使用粒子设备客户端通过 MQTT 发布到 ThingSpeak 通道
此示例演示如何使用硼、氩、光子或电子等粒子设备通过 MQTT 将测量值发布到 ThingSpeak通道。如果您有多个值要发送到 ThingSpeak,您可以将多个值发布到通道源。或者,如果您只有一个传感器,则可以将单个值发布到通道字段。
设置
1)新建一个通道,如图Collect Data in a New Channel所示。请务必启用您计划使用的所有字段。
2) 点击“设备”创建 MQTT 设备>ThingSpeak 页面顶部的“MQTT”,然后是“添加设备”。设置设备并将新通道添加到其授权列表时,点击“下载凭据”> “ 纯文本 ” 。使用下面代码部分中保存的凭据。详情请参见创建 ThingSpeak MQTT 设备。
3) 在您的 Particle IDE 中包含库 MQTT/MQTT.h
。
代码
1) 定义用于与 ThingSpeak 通信的变量。编辑您自己的 ID 和凭据的代码。
// This #include statement is automatically added by the Particle IDE. #include <MQTT.h> const long channelId = YOUR_THINGSPEAK_CHANNEL_NUMBER; // Change this to your ThingSpeak channel number. String clientId = "MQTT_CLIENDID_FROM_THINGSPEAK"; String username = "MQTT_USERNAME_FROM_THINGSPEAK"; String password = "MQTT_PASSWORD_FROM_THINGSPEAK"; char server[] = "mqtt3.thingspeak.com";
2) 跟踪上次连接时间并使用全局变量定义发布数据时间间隔。初始化 MQTT 客户端。
unsigned long lastConnectionTime = 0; const unsigned long postingInterval = 20L * 1000L; // Post data every 20 seconds. int strength = WiFi.RSSI(); int power = 10^(strength/10); MQTT client(server, 1883, callback); // Initialize the MQTT client.
3) 定义MQTT客户端的回调函数。在本例中,setup
函数故意为空。
// Define a callback function to initialize the MQTT client. void callback(char* topic, byte* payload, unsigned int length) { } void setup() { }
4) 在loop
主函数中建立MQTT连接并定期向通道发布数据。
void loop() { // If MQTT client is not connected then reconnect. if (!client.isConnected()) { reconnect(); } // Call the loop continuously to establish connection to the server. client.loop(); if (millis() - lastConnectionTime > postingInterval) { mqttpublish(); } }
5) 使用 mqttpublish
方法将传感器数据发布到 ThingSpeak通道源。如果您要发布到通道源,则可以一次发布到多个字段。如果您只有一个传感器,则可以直接发布到单个字段。根据需要更改以下代码中的行注释。
void mqttpublish() { //Get SSID signal strength strength = WiFi.RSSI(); //Power in milliwatts power = 10^(strength/10); // Create a data string to send data to ThingSpeak. // Use these lines to publish to a channel feed, which allows multiple fields to be updated simultaneously. // String data = String("field1=" + String(strength) + "&field2=" + String(power) ); // String topic = String("channels/"+String(channelId)+ "/publish"); // Use the next two to publish to a single channel field directly. String data = String(strength); String topic = String("channels/"+String(channelId)+ "/publish/fields/field1"); client.publish(topic,data); lastConnectionTime = millis(); }
6) 生成唯一的客户端 ID,并使用 reconnect
函数将 Particle Photon MQTT 客户端连接到 ThingSpeak MQTT 代理。
void reconnect(){ Particle.publish("Attempting MQTT connection"); // Connect to the ThingSpeak MQTT broker. if (client.connect(clientId,username,password)) { // Track the connection with particle console. Particle.publish("Conn:"+ String(server) + " cl: " + String(clientId)+ " Uname:" + String(username)); } else { Particle.publish("Failed to connect. Trying to reconnect in 2 seconds"); delay(2000); } }
另请参阅
Publish to a Channel Field Feed | Publish to a Channel Feed