Ernesto in Discussions
上次活动时间: 2025-7-19

Hi! I'm having trouble sending data to a channel using MQTT. I'm using a program that was working perfectly until just a few days ago, but after making some minor changes yesterday, it stopped working. I’ve also tested it manually using the MQTTX client. If I send data using CURL and GET, it works fine. It’s a bit strange... Thankfully, Ernesto. Is the MQTT server experiencing any problems? same here, publish via mqtt stopped working 11 hours ago.. thanks Also having issues. Have different location and devices. All stopped working basically about 24 hours ago. It is only those that publish on the mqtt server. The one that is on restful is working. Thanks Jacques Can you please try again. A subset of MQTT devices seems to have seen an issue publishing. We've restarted nodes in the system and can confirm things are back to 100% from our dashboards. Now is working for me Working again. Thank you. Can you explain how this problem occurred? Unplanned updates on the server instances fronting ThingSpeak's MQTT API caused some nodes in ThingSpeak's high-availability MQTT cluster to get into a bad state. These changes were unrelated to ThingSpeak application code, as evidenced by the REST API working faultlessly in @Ernesto's post. We worked with the platform provider to address the issue and have confirmed things are working correctly again for all clients of the MQTT API. This issue has occurred again and has lasted for 30 minutes. not for me, all ok after they restarted nodes yea thx The additional monitoring we put in place didn't see any issues on any nodes. Did you see any effects on multiple devices? If so, can you please send me an email with the channel numbers? mqtt
MathWorks Support Team in MATLAB Answers
上次活动时间: 2024-12-17

When using the Industrial Communication Toolbox's mqtt function, one of the input arguments is a file path to a root certificate. Where can I download this root certificate? Which one should I download? kA03q000000sw3QCAQ 000320069
Dylan in MATLAB Answers
上次活动时间: 2024-9-19

I set up a subscription connection to the mqtt broker for a public channel that I've already added my device to. I'm confident that all of my username, password, client_id, and topic configurations have been set correctly. When I connect using MQTTX or mosquitto_sub, I don't receive any data. It says that my connection is successful, but proceeds to sit endlessly with no data being received. I'm at a dead end here. Does anyone know what I could be doing wrong?
Joyeeta Chatterjee in MATLAB Answers
上次活动时间: 2024-8-6

I want to publish MQTT messages from my model in Simulink to the mosquitto broker. So far I have been able to publish messages successfully from MATLAB script to the mosquitto broker using the MQTT in MATLAB toolbox. I would like to do the same through my Simulink model. I understand that there is a MQTT Publish block in Simulink for Raspberry Pi that publishes message to a ThingSpeak broker. Is there a way to use this block for any other Simulink model (that does not use Raspberry Pi) and also for any other broker like mosquitto in my case? If the MQTT Publish block cannot be used for this purpose, should I use a MATLAB function block and write the MATLAB code for MQTT in a .m file and include it in Simulink? Is there any other way to implement MQTT Publish in Simulink models (without Raspberry Pi and for brokers other than ThingSpeak)?
Anam Amjad in MATLAB Answers
上次活动时间: 2024-8-1

Here is my piece of code, I am following the steps of the tutorial https://www.mathworks.com/help/icomm/ug/get-started-with-mqtt.html clientID = "client id"; userName = "user name"; password = "password"; rootCert = "Path"; brokerAddress = "ssl://mqtt3.thingspeak.com"; port = 8883; mqClient = mqttclient(brokerAddress, Port = port, ClientID = clientID,... Username = userName, Password = password, CARootCertificate = rootCert); upon reaching the mqClient, the following error occurs ThingSpeakMQTT Error: File: ThingSpeakMQTT.m Incorrect use of '=' operator. To assign a value to a variable, use '='. To compare values for equality, use '=='. Please someone guide me on this.
Anam Amjad in MATLAB Answers
上次活动时间: 2024-6-4

Hi, I am using MQTT for ThingSpeak. I am following the tutorial on the given link. https://www.mathworks.com/help/icomm/ug/get-started-with-mqtt.html#GetStartedWithMQTTExample-1 the issue is, as written in the example, root certificate needs to be downloaded from thingspeak.com (screenshot also attached) but I am unable to find it on thingspeak.com website. Please help how can i get this?
Marco in Discussions
上次活动时间: 2024-5-13

I isolated a var that I'm interested in, and I want to connect Node-RED to thingspeak to show the values on the graph. The problem is the node "mqttout": I connected it to the server mqtt3.thingspeak.com and the port 1883, and with the device with right username and password. It shows "connected", but the graph is still the same, I can not upload the varabiles. mqtt connection problem Have you created an MQTT device in ThingSpeak and given permissions for MQTT to write to the channel? See the instructions in the MQTT Basics. Yes I have it, I don't know why it doesn't work I reccomend troubleshooting using the desktop client. You can see instructions in the help link I send above. Also , a common casue of not seing data on the field plots is sending non numeric data by accident. Make sure to export the recent data in your channel to be sure its not there but in an unexpected format. mqtt connection node-red upload
Sébastien Trocherie in MATLAB Answers
上次活动时间: 2024-5-2

Hi, I'm using the STM32F746NG discovery board to connect to the thingspeak MQTT broker. However I can't connect to the server, i'm using dns to get the server ip adres which I then use in the mqtt_client_connect function. When I get to the callback function the status is 256 (MQTT_CONNECT_DISCONNECTED). I've had this problem before with a local MQTT broker (mosquitto 2.0), I was able to solve this problem by installing an older version (mosquitto 1.161a). I'm using the correct credentials because they work in the mqtt_spy application. Has anyone had this problem before or a sollution for this problem? With kind regards Sébastien
Hoang Bach in Discussions
上次活动时间: 2024-4-16

Hey, so I have a simple air quality measurement IoT system but the values are not arriving in my ThingSpeak channel. I use basic tutorials for it and tried some kind of variation but the code is so simple, I don't see any problem code-wise. Maybe someone here can help me? I am working with a Raspberry Pi 3 and the following code for a SDS011 sensor: import time from datetime import datetime import paho.mqtt.publish as publish import paho.mqtt.client as mqtt import psutil from sds011 import * import aqi sensor = SDS011("/dev/ttyUSB0", use_query_mode=True) def get_data(n=3): sensor.sleep(sleep=False) pmt_2_5 = 0 pmt_10 = 0 time.sleep(10) for i in range (n): x = sensor.query() pmt_2_5 = pmt_2_5 + x[0] pmt_10 = pmt_10 + x[1] time.sleep(2) pmt_2_5 = round(pmt_2_5/n, 1) pmt_10 = round(pmt_10/n, 1) sensor.sleep(sleep=True) time.sleep(2) return pmt_2_5, pmt_10 def conv_aqi(pmt_2_5, pmt_10): aqi_2_5 = aqi.to_iaqi(aqi.POLLUTANT_PM25, str(pmt_2_5)) aqi_10 = aqi.to_iaqi(aqi.POLLUTANT_PM10, str(pmt_10)) return aqi_2_5, aqi_10 def save_log(): with open("/YOUR PATH/air_quality.csv", "a") as log: dt = datetime.now() log.write("{},{},{},{},{}\n".format(dt, pmt_2_5, aqi_2_5, pmt_10, aqi_10)) log.close() channelID = "YOUR CHANNEL ID" apiKey = "YOUR WRITE KEY" clientID = "YOUR CLIENT ID" tUsername = "YOUR USERNAME" tPassword = "YOUR PASSWORD" topic = "channels/" + channelID + "/publish/" + apiKey mqttHost = "mqtt3.thingspeak.com" tTransport = "tcp" tPort = 1883 tTLS = None tProtocol = mqtt.MQTTv311 while True: pmt_2_5, pmt_10 = get_data() aqi_2_5, aqi_10 = conv_aqi(pmt_2_5, pmt_10) print ("AQI2.5 =", aqi_2_5," AQI10 =", aqi_10) tPayload = "field1=" + str(pmt_2_5)+ "&field2=" + str(aqi_2_5)+ "&field3=" + str(pmt_10)+ "&field4=" + str(aqi_10) try: publish.single(topic, payload=tPayload, hostname=mqttHost, port=tPort, client_id=clientID, auth={'username':tUsername, 'password':tPassword}, tls=tTLS, transport=tTransport, protocol=tProtocol) print ("[INFO] Published data") save_log() time.sleep(60) except Exception as e: print ("[INFO] Failure in sending data") print (e) time.sleep(60) Publish via Paho-MQTT publish.single but data is not arriving? Have a look at the documentation for MQTT and the provided examples. You are using syntax from the old broker, which was replaced in July 2021 and deprecated in April. Here is the new publish syntax for publish. The topic you are publishing to is incorrect. Take a look at the examples Christopher has linked to. So is this page in your documentation outdated then: https://se.mathworks.com/help/thingspeak/use-raspberry-pi-board-that-runs-python-websockets-to-publish-to-a-channel.html? Is there any way to use paho_mqtt to publish data in ThingSpeak or is the only option to use MQTT X? The code you reference should work. You can definitely still use paho, im pretty sure ive done it already on a pi. Just set up am MQTT device on the thingSpeak web UI, enable publishing from that device to your channel of interest, and copy the credentials to the pi. Can you tell us where it is failing for you? Now I found it: one extra /. Had f"channels/{channel_ID}/publish/ instead of f"channels/{channel_ID}/publish Damn, it was hard to find it. :P Thanks for help anyway! Ive had that one before, sorry I didnt look close enough to see that. We appreciate you sharing the solution! If its working, can you share an interesting plot from your monitor to inspire others who see this discussion? publish mqtt paho-mqtt air-quality sds011 raspberry pi 3
Milan Tomin in MATLAB Answers
上次活动时间: 2024-4-8

Having a bizarre problem subscribing to topic with sim7600 hat on raspberry pi. When i try subscribing i get: the following: OK CMQTTSUB: 0,6 CMQTTCONNLOST: 0,1. Code 6 in the CMQTTSUB means failed to receive message. Code 0 in CMQTTCONNLOST means socket closed passively. Why tho? Mqtt actions with sim7600 such as Acquire client, connect, and even publish works without any difficulties in the same project, sub however does not. I'm using thingspeak as a broker, and have tried broker.emqx.io to subscribe to and... it worked without any problem. Has anyone had any similar problem? I've tried subscribing to one or multiple fields, still no dice. Topic strings i've tried: channels/2429193/subscribe/fields/field1 channels/2429193/subscribe/fields/+ channels/2429193/subscribe I provide the code: def setup(self): isSerial2Available = True self.SentMessage('AT+CMQTTDISC=0,60\r\n') time.sleep(0.5) self.SentMessage('AT+CMQTTREL=0\r\n') time.sleep(0.5) self.SentMessage('AT+CMQTTSTART\r\n') # Enable MQTT service. time.sleep(1) connect_cmd = 'AT+CMQTTACCQ=0,"'+ self.ID +'",0,4' # Apply for MQTT client with client ID. self.SentMessage(connect_cmd + '\r\n') time.sleep(1) connect_cmd = 'AT+CMQTTCONNECT=0,"tcp://mqtt3.thingspeak.com",60,1,"'+ self.username +'","'+ self.password +'"' # Send MQTT connection request to the server. self.SentMessage(connect_cmd + '\r\n') time.sleep(2) dataLength = str(len(self.pub)) connect_cmd = "AT+CMQTTTOPIC=0,{}".format(dataLength) # Publish to the inputed topic. self.input_message(connect_cmd, self.pub) time.sleep(1.5) dataLength = str(len('channels/2429193/subscribe')) connect_cmd = "AT+CMQTTSUBTOPIC=0,{},0".format(dataLength) # Subscribe to the inputed topic. self.input_message(connect_cmd, "channels/2429193/subscribe") time.sleep(0.5) self.SentMessage('AT+CMQTTSUB=0\r\n') def SentMessage(self, p_char): global isSerial2Available towrite = p_char.encode() self.ser.write(towrite) time.sleep(1) response = self.ser.read_all().decode() print(response) responses = response.split('\r\n') for resp in responses: if "+CREG: 0," in resp: status = int(resp.split("+CREG: 0,")[1]) # Check if connected to the network. if status == 6: isSerial2Available = False print("\nNetWork Connected") elif "+CMQTTCONNECT: 0," in resp: status = int(resp.split("+CMQTTCONNECT: 0,")[1]) # Check if the client is connected. if status == 0: isSerial2Available = False print("\nMqtt Connected") elif resp == "+CMQTTSTART: 23": isSerial2Available = False print("\nMqtt is already Connected") def input_message(self, p_char, p_data): global startSent self.ser.write(p_char.encode() + b'\r\n') time.sleep(0.2) encodedstr = p_data.encode() + b'\r\n' self.ser.write(p_data.encode() + b'\r\n') time.sleep(1) response = self.ser.read_all().decode() responses = response.split('\r\n') for resp in responses: if "+CMQTTSUB: 0," in resp: status = int(resp.split("+CMQTTSUB: 0,")[1]) if status == 0: print("\nSubTopic Sub") startSent = True self.subThreadStart() def publishData(self, updateMsn): dataLength = str(len(self.pub)) connect_cmd = "AT+CMQTTTOPIC=0,{}".format(dataLength) # Publish to the inputed topic. self.input_message(connect_cmd, self.pub) dataLength = str(len(str(updateMsn))) connect_cmd = "AT+CMQTTPAYLOAD=0,{}".format(dataLength) # Input the publish message self.input_message(connect_cmd, str(updateMsn)) time.sleep(0.5) self.ser.write(b'AT+CMQTTPUB=0,0,120\r\n')
Levani Meskhiya in MATLAB Answers
上次活动时间: 2024-3-2

Hello, I have a problem with the connection to thingspeak MQTT broker using MQTT x client. After pressing the "Connect" button after a few seconds connection is not set. I have followed the instructions described in: https://de.mathworks.com/help/thingspeak/use-desktop-mqtt-client-to-publish-to-a-channel.html. Below you can see the settings in the MQTT X client. ClientID, Username and Password I took from the credentials file which was created when I add a new MQTT device in thingspeak. I have already checked the discussion with a similar problem, but I can not figure out what could be the source of the problem. I would like to ask your help with this problem. Thank you, Levani Meskhiya
Matteo in Discussions
上次活动时间: 2023-12-7

Buongiorno, non mi è possibile connetermi al canale di thingspeak che ho creato, per passare i dati tramite MQTT. Il codice segue la libreria PubSubClient su arduino ide, l'errore restituito dal serial monitor dell'ide é: -4 : MQTT_CONNECTION_TIMEOUT - the server didn't respond within the keepalive time. Allego il codice per eventuali verifiche: Grazie per a disponibilità #include "PubSubClient.h" #include <ESP8266WiFi.h> #include "secrets.h" bool DEBUG = false; // true=serial message of debug enabled char* server = "mqtt.thingspeak.com"; WiFiClient wifiClient; PubSubClient client(server, 1883, wifiClient); String payload; // BME280 Setting #include <Wire.h> #include <Adafruit_BME280.h> //#define SEALEVELPRESSURE_HPA (1013.25) Adafruit_BME280 bme; // I2C bool BMEStatus; ADC_MODE(ADC_VCC); // Set ADC for read Vcc // Update time in seconds. Min with Thingspeak is ~20 seconds const int UPDATE_INTERVAL_SECONDS = 3600; //il clock interno ha un errore del 5% questo valore va tarato sperimentalmente //const int UPDATE_INTERVAL_SECONDS = 60; // caricamento ogni minuto solo per test void setup() { // Connect BME280 GND TO pin14 OR board's GND pinMode(14, OUTPUT); digitalWrite(14, LOW); Serial.begin(115200); delay(10); // BME280 Initialise I2C communication as MASTER Wire.begin(13, 12); //Wire.begin([SDA], [SCL]) BMEStatus = bme.begin(); if (!BMEStatus) { if (DEBUG) { Serial.println("Could not find BME280!"); } //while (1); } // Weather monitoring See chapter 3.5 Recommended modes of operation bme.setSampling(Adafruit_BME280::MODE_FORCED, Adafruit_BME280::SAMPLING_X1, // temperature Adafruit_BME280::SAMPLING_X1, // pressure Adafruit_BME280::SAMPLING_X1, // humidity Adafruit_BME280::FILTER_OFF ); // read values from the sensor float temperature, humidity, pressure; if (BMEStatus) { temperature = bme.readTemperature(); humidity = bme.readHumidity(); pressure = bme.readPressure() / 100.0F; } else { if (DEBUG) Serial.println("Could not find BME280!"); temperature=0; humidity=0; pressure=0; } float voltage = ESP.getVcc(); voltage = voltage/1024.0; //volt if (DEBUG) { Serial.println("T= " + String(temperature) + "°C H= " + String(humidity) + "% P=" + String(pressure) + "hPa V=" + voltage + "V"); } // Construct MQTT payload payload="field1="; payload+=temperature; payload+="&field2="; payload+=humidity; payload+="&field3="; payload+=pressure; payload+="&field4="; payload+=voltage; payload+="&status=MQTTPUBLISH"; //Connect to Wifi if (DEBUG) { Serial.println(); Serial.print("\nConnecting to WiFi SSID "); Serial.print(SECRET_SSID); } WiFi.begin(SECRET_SSID, SECRET_PASS); int timeOut=10; // Time out to connect is 10 seconds while ((WiFi.status() != WL_CONNECTED) && timeOut>0) { delay(1000); if (DEBUG) { Serial.print("."); } timeOut--; } if (timeOut==0) //No WiFi! { if (DEBUG) Serial.println("\nTimeOut Connection, go to sleep!\n\n"); ESP.deepSleep(1E6 * UPDATE_INTERVAL_SECONDS); } if (DEBUG) // Yes WiFi { Serial.print("\nWiFi connected with IP address: "); Serial.println(WiFi.localIP()); } // Reconnect if MQTT client is not connected. if (!client.connected()) { reconnect(); } mqttpublish(); delay(200); // Waiting for transmission to complete!!! (ci vuole) WiFi.disconnect( true ); delay( 1 ); if (DEBUG) { Serial.println("Go to sleep!\n\n"); } // Sleep ESP and disable wifi at wakeup ESP.deepSleep( 1E6 * UPDATE_INTERVAL_SECONDS, WAKE_RF_DISABLED ); } void loop() { //there's nothing to do } void mqttpublish() { // read values from the sensor float temperature, humidity, pressure; if (DEBUG) { Serial.print("Sending payload: "); Serial.println(payload); } // Create a topic string and publish data to ThingSpeak channel feed. String topicString ="channels/" + String( channelID ) + "/publish/"+String(writeAPIKey); unsigned int length=topicString.length(); char topicBuffer[length]; topicString.toCharArray(topicBuffer,length+1); if (client.publish(topicBuffer, (char*) payload.c_str())) { if (DEBUG) Serial.println("Publish ok"); } else { if (DEBUG) Serial.println("Publish failed"); } } void reconnect() { String clientName="MY-ESP"; // Loop until we're reconnected while (!client.connected()) { if (DEBUG) Serial.println("Attempting MQTT connection..."); // Try to connect to the MQTT broker if (client.connect((char*) clientName.c_str())) { if (DEBUG) Serial.println("Connected"); } else { if (DEBUG) { Serial.print("failed, try again"); // Print to know why the connection failed. // See http://pubsubclient.knolleary.net/api.html#state for the failure code explanation. Serial.print(client.state()); Serial.println(" try again in 2 seconds"); } delay(2000); } } } Difficoltà di connessione con il client MQTT al server di thingspeak Your code is using the deprecated MQTT format. Have a look at the MQTT doc for the new format, and see the examples for some code. You will have to make an MQTT devicein ThingSepak and add the channel that you want to be able to interact with to th device for publish and subscribe. thingspeak mqtt
Haydar Jawad in Discussions
上次活动时间: 2023-11-2

Hi, i wonder if any one experiencing the same, but in my thing sepak profiel i can only see : 1- User API Key 2- Alert API Key but no MQTT API key? not sure why Thank you MQTT API is not in my profile We are so glad you asked! ThingSpeak has a new MQTT interface that does not require an API key. Check out the <https://blogs.mathworks.com/iot/2021/07/21/thingspeak-mqtt-update-access-control-and-iot-device-management/ recent blog post> and the <https://www.mathworks.com/help/thingspeak/mqtt-api.html doc> . (edit: links added) Please let us know what you think if you get a chance. Thank you Chris, I actually found out after searching the topics. It works great i am testing now with multiple MCUs! All good so far. Still please post the links just in case i see something useful well. Thank you again Hello there Mr. @Christopher Stapels I have some struggles with Thingspeak new MQTT interface. I want to connect dragino LG-02 LoRa Gateway to Thingspeak channel. When thingspeak used to have MQTT API key it will be the Password of MQTT client and it's fairly easy to connect it to Thingspeak. And now with the new interface I am unable to connect gateway to Thingspeak channel. I have filled User ID with Thingspeak MQTT username, Client ID with Thingspeak MQTT Client ID, and password with Thingspeak MQTT password, but it still don't work. Do you have any idea with this case? Thank you in advance ! Have you created a device in your mqtt devices? We suggest using the desktop client to debug, see the documentation for how to test with mqttx. It has been solved sir, I notice that the MQTT topic template changed a bit since last time I used the gateway May I know how you solved? I have the same problem. Thank you. They solved the problem by using the correct syntax for the MQTT API. If you look in the documentation, you can se the proper syntax. Hello , how you resolve the problem? HI. Can you tell me how you solved it? Thank you. In the original post, the user is using the old syntax for the MQTT service that was depricated quite some time ago. The new syntax is in the links I provided above. If you are having an issue that you cannot fix, please feel free to start a new thread with the question on MATLAB answers, with the tag ThingSepak. Please!!!! @Christopher Stapels please sir help me finding the mqtt api key ThingSpeak has an MQTT interface that does not require an API key. Check out the blog post and the doc. Please let us know what you think if you get a chance. mqtt api key
Riley Dickert in Discussions
上次活动时间: 2023-2-21

Not able to display password by copying to clipboard or by clicking the unhide icon - have tried multiple computers. Anyone else had this problem with mqtt? Not able to get password for MQTT connection The password is only available at device creation time for security. You will have to create a new device to get a new password. The interface will allow you to download and save the credentials. password mqtt clipboard
Mohamed Tawfik in Discussions
上次活动时间: 2023-2-19

I try to use MQTT Explorer to subscribe to the channel using the settings in the photo , but it always gives me connection erorr so any recommendation about how i can use it to subscribe or it's a must to use MQTTX can't connect using MQTT Explorer mqtt mqtt explorer mqtt subscribe
Simo Rounela in MATLAB Answers
上次活动时间: 2023-2-11

Hi! I'm using Advanticsys UCM-316 IoT gateway, with integrated analog inputs. It supports MQTT data upload, but I can't get it working with ThingSpeak MQTT server. There is username (not needed / blaablaa?) and password (Write API Key) authentication. No DNS server support, so broker URL 34.206.80.227 (mqtt.thingspeak.com), port 1883, subscriber identifier "ucm316". After IO configurations, it will make JSON message to be sent. It's fixed formation, cannot change it. Example: { "SN":"86004", "name":"ucm316", "header":{ "startTime":"2016-02-07T15:06:00.000Z", "endTime":"2016-02-07T15:06:00.000Z", "recordCount":2, "columns":{ "0":{ "id":"0", "name":"relay1", "dataType": "NUMBER", "format":"unsigned short" } }, "data":[ { "ts":"2016-02-07T15:06:00.000Z", "f":{ "0":{"v":0} } } ] } *This message is copied from manual, because user cannot access the actual JSON message.* There is no error log available. In the end, nothing happens. Most probably, because MQTT message formation is not correct. - Is there any way I could use this message structure with Thingspeak? And in case it's not visible, I'm not really a pro with MQTT yet =)
Mauro Emme in MATLAB Answers
上次活动时间: 2023-2-10

Hi, I've used the service since 2018 and I'm very happy with it. In these days I've added some sensors (Shelly) to my project and I'm trying to switch to MQTT since they suppport it: I've configured all for ThingS. side and tried to send data via MQTT with a manual client to see if it runs. Done. It runs. The problem is that Shelly sensors use their specifi topics: shellies/shellyem-<deviceid>/emeter/<i>/energy energy counter in Watt-minute shellies/shellyem-<deviceid>/emeter/<i>/returned_energy energy returned to the grid in Watt-minute shellies/shellyem-<deviceid>/emeter/<i>/total total energy in Wh (accumulated in device's non-volatile memory) shellies/shellyem-<deviceid>/emeter/<i>/power instantaneous active power in Watts shellies/shellyem-<deviceid>/emeter/<i>/reactive_power instantaneous reactive power in Watts shellies/shellyem-<deviceid>/emeter/<i>/voltage grid voltage in Volts shellies/shellyem-<deviceid>/emeter/<i>/pf power factor (dimensionless) shellies/shellyem-<deviceid>/relay/0 reports status: on, off or overpower and, as I can see, they could not been changed. On the other side, ThingS has his own topic stucture: channels/619092/publish/fields/field1 Is there a way by ThingsSpeak side to "translate" or "bridge" or something else 1 topic to another one? Any idea would be appreciated.
Manira in MATLAB Answers
上次活动时间: 2023-2-3

I have used the following code in Raspi 4. When I run the code it displays field1 and field2 on the screen. However my channel is not receiving any data. Writing Payload = field1=6.6&field2=17.2 to host: mqtt3.thingspeak.com clientID= xxxxxxxxxxxxxxxxxxxx User xxxxxxxxx PWD xxxxxxxxxxxxxxxx import paho.mqtt.publish as publish import psutil import string # The ThingSpeak Channel ID. # Replace <YOUR-CHANNEL-ID> with your channel ID. channel_ID = "xxxxxxxx" # The hostname of the ThingSpeak MQTT broker. mqtt_host = "mqtt3.thingspeak.com" # Your MQTT credentials for the device mqtt_client_ID = "xxxxxxxxxxxxxxxx" mqtt_username = "xxxxxxxxxxxxx" mqtt_password = "xxxxxxxxxxxxx" t_transport = "websockets" t_port = 80 # Create the topic string. topic = "channels/" + channel_ID + "/publish" while (True): # get the system performance data over 20 seconds. cpu_percent = psutil.cpu_percent(interval=20) ram_percent = psutil.virtual_memory().percent # build the payload string. payload = "field1=" + str(cpu_percent) + "&field2=" + str(ram_percent) # attempt to publish this data to the topic. try: print ("Writing Payload = ", payload," to host: ", mqtt_host, " clientID= ", mqtt_client_ID, " User ", mqtt_username, " PWD ", mqtt_password) publish.single(topic, payload, hostname=mqtt_host, transport=t_transport, port=t_port, client_id=mqtt_client_ID, auth={'username':mqtt_username,'password':mqtt_password}) except (keyboardInterrupt): break except Exception as e: print (e)
Silvia Booij in MATLAB Answers
上次活动时间: 2023-1-22

My MQTT client sends different sensor data to thingspeak MQTT broker via a single MQTT device. Following the MQTT device procedure found on the Mathworks website. My MQTT client reports back no errors (100% succesfull MQTT data transmission). But I cannot figure out how to select which data to make visible in the different ThingSpeak fields. At this moment the field in the selected channel has the name of the datafield in the MQTT message, but no data appears. And I do not see any data when I download the Channel's feeds in CSV format. The only work around I can think of is create via an ESP another MQTT server who retrieves the data from ThingsSpeak and sends it back to the ThingSpeak channel without using the MQTT channel (as I do with the non-MQTT devices), but this sounds silly. What is the normal method to make MQTT data visible without adding other hardware?
Christopher Stapels in Discussions
上次活动时间: 2022-8-4

The ThingSpeak certificate was updated recently. If you are using secure communication for your devices, you may need to update the certificate or certificate fingerprint on your devices. Secure ThingSpeak communications and security certificate If anyone find a working with ThingSpeak root certificat for Arduino ESP32 programmation, I'd be interrested, something like : const char* rootCACertificate = "-----BEGIN CERTIFICATE-----\n" ... here should be what I need ... "-----END CERTIFICATE-----"; for Arduino code: WiFiClientSecure client; client.setCACert(rootCACertificate); Thanks, TC This post might help. Hi, Thanks, but I already tried the one exported and download from ThingSpeak.com, still not working. I try also the one from Digicert and two others, none are working. I am hoping somehting from the other post... TT Use firefox Got to thingspeak.com. Click on the lock icon Click on Connection secure -> More information Click on view certificate Click on "DigiCert Global Root CA" in the tab Click on PEM(cert) under Miscellaneous Right click on the downloaded file. Open with any editor. In Chrome, I think its similar, but you want to save it with base64 encoding. I was able to use the thingspeak library secure connection with esp32 with this cert, but you need to add the line you mentioned. in secrets.h: client.setCACert(SECRET_TS_ROOT_CA); #define SECRET_TS_ROOT_CA "-----BEGIN CERTIFICATE-----\n" \ ... "-----END CERTIFICATE-----\n" in main file: const char* certificate = SECRET_TS_ROOT_CA; % in setup fucntion client.setCACert(certificate); // Set Root Certificate for authenticity check http mqtt secure certificat
Ismet Perona in Discussions
上次活动时间: 2022-7-27

Hi Everyone, I'm a novice when it comes to programming and i'm trying to figure out why my weather data is not loading into my channel. I've had the code working previously before thingspeak went from MQTT to MQTT3. I'm having issues around the publish.single(). import subprocess import paho.mqtt.publish as publish import psutil import string import json from statistics import median from pms5003 import PMS5003 #weather_iot import requests import time from datetime import datetime from csv import writer import math import paho.mqtt.publish as publish #Thingspeak channel and MQQT protocol mqtt_client_ID = "detail removed" mqtt_username = "detail removed" mqtt_password = "detail removed" channelID = "detail removed" apiKey = "detail removed" topic = "channels/" + channelID + "/publish/" mqttHost = "mqtt3.thingspeak.com" tTransport = "websockets" useSSLWebsockets = False tTLS = None tPort = 80 def csv(): List=[now, Temperature1, IAQ1, Pressure1, Humidity1, PM1_0, PM2_5, PM10] with open('Weather.csv', 'a') as f_object: writer_object = writer(f_object) writer_object.writerow(List) f_object.close() return #PM sensor configuration pms5003 = PMS5003( device='/dev/ttyAMA0', baudrate=9600, pin_enable=22, pin_reset=27 ) #Open C File proc = subprocess.Popen(['./bsec_bme680'], stdout=subprocess.PIPE) listIAQ_Accuracy = [ ] listPressure = [ ] listGas = [ ] listTemperature = [ ] listIAQ = [ ] listHumidity = [ ] listStatus = [ ] for line in iter(proc.stdout.readline, ''): lineJSON = json.loads(line.decode("utf-8")) # process line-by-line lineDict = dict(lineJSON) listIAQ_Accuracy.append(int(lineDict['IAQ_Accuracy'])) listPressure.append(float(lineDict['Pressure'])) listGas.append(int(lineDict['Gas'])) listTemperature.append(float(lineDict['Temperature'])) listIAQ.append(float(lineDict['IAQ'])) listHumidity.append(float(lineDict['Humidity'])) listStatus.append(int(lineDict['Status'])) if len(listIAQ_Accuracy) == 20: #generate the median for each value IAQ_Accuracy = median(listIAQ_Accuracy) Pressure = median(listPressure) Gas = median(listGas) Temperature = median(listTemperature) IAQ = median(listIAQ) Humidity = median(listHumidity) Status = median(listStatus) #clear lists listIAQ_Accuracy.clear() listPressure.clear() listGas.clear() listTemperature.clear() listIAQ.clear() listHumidity.clear() listStatus.clear() #Temperature Offset Temperature = Temperature + 2 IAQ1 = round(IAQ,1) Temperature1 = round(Temperature, 1) Humidity1 = round(Humidity, 1) Pressure1 = round(Pressure, 1) data = pms5003.read() if Humidity1 < 80: CF = 1 else: CF = (Humidity1/100)*1.3 PM1_0 = format(data.pm_ug_per_m3(1.0)) PM2_5 = format(data.pm_ug_per_m3(2.5)) PM10 = format(data.pm_ug_per_m3(10)) PM1_0 = round(int(PM1_0) / CF,) PM2_5 = round((int(PM2_5)/CF/25) * 100,) PM10 = round((int(PM10)/CF/50) * 100,) now = datetime.now() tPayload = "field1=" + str(Temperature1)+ "&field2=" + str(IAQ1)+ "&field3=" + str(Pressure1)+ "&field4=" + str(Humidity1)+ "&field5=" + str(PM1_0)+ "&field6=" + str(PM2_5)+ "&field7=" + str(PM10) try: print ("[INFO] Data prepared to be uploaded") publish.single(topic, payload=tPayload, hostname=mqttHost, transport=tTransport, port=tPort, tls=tTLS, client_id=mqtt_client_ID, auth={'username':mqtt_username,'password':mqtt_password}) print ("[INFO] Data sent for 7 fields: ", Temperature1, IAQ1, Pressure1, Humidity1, PM1_0, PM2_5, PM10) except (KeyboardInterrupt): break except: print ("[INFO] Failure in sending data") csv() Raspberry Pi Weather Station MQTT Can you publish successfully from a desktop app like mqttx or MATLAB? Make sure you have added the permissions for the device to write to the correct channel. What error do you see? Hi Chris, I don't receive any errors. I tried connecting using my creddentials in MQTTX using port 80 and it didn't establish a connection. If I change this to port 1883 it establishes a connection. I only have one channel setup so the details should be correct. Does this part of the program look correct to you? mqtt_client_ID = "detail removed" #same as mqtt_username mqtt_username = "detail removed" mqtt_password = "detail removed" channelID = "detail removed" apiKey = "detail removed" topic = "channels/" + channelID + "/publish/" mqttHost = "mqtt3.thingspeak.com" tTransport = "websockets" useSSLWebsockets = False tTLS = None tPort = 80 publish.single(topic, payload=tPayload, hostname=mqttHost, transport=tTransport, port=tPort, tls=tTLS, client_id=mqtt_client_ID, auth={'username':mqtt_username,'password':mqtt_password}) it looks very similar to the code I tested that is in our doc example. To make sure you have the permissions for the device correct, I would try using mqttx, or MATLAB to publish to the channel. You need to specifically allow an MQTT device to publish to a channel. python mqtt
Andrew Dumbill in MATLAB Answers
上次活动时间: 2022-5-25

I created a new MQTT device attached to my existing ThingSpeak channel. Then modified my application to use the mqtt3.thingspeak.com server, following the python example given. The application appears to publish data to the server successfully without any exception. However, the channel fields do not appear to update. The old app using the original MQTT server still appears to work for a while and then stops updating. Do I need to remove the old channel and create a completely new one and create a new device before linking them?In other words do I have to completely unlink the old channel before I can publish my data and use it invisualisations?
stev1088 in MATLAB Answers
上次活动时间: 2022-3-15

I am working on a IoT application using gateways that publish data using the MQTT protocol and I am wondering if I can publish MQTT directly to MATLAB through a data broker?
Siddharth Lotia in MATLAB Answers
上次活动时间: 2022-3-1

Hi , I am doing this excample , I have configured MQTT X client , it gets connected to my channel . But when I am doing subscribe , it get's disconnected , says client not connected? Also even after entering the required data in topic as per the excample it still says topic required, why it is so? Someone kindly suggest what I am doing wrong in these two steps?
S SIn in MATLAB Answers
上次活动时间: 2022-2-15

I have created a mqtt device from thingspeak platform and obtained the MQTT Credentials (clientid, username and password). I download the Iot extension to my microbit plaform to be used for my elecfreak iot:bit board and try to use its MQTT function. However I failed to subscribe data from and publish data to the topics from thingspeak mqtt broker.

关于 ThingSpeak

The community for students, researchers, and engineers looking to use MATLAB, Simulink, and ThingSpeak for Internet of Things applications. You can find the latest ThingSpeak news, tutorials to jump-start your next IoT project, and a forum to engage in a discussion on your latest cloud-based project. You can see answers to problems other users have solved and share how you solved a problem.