MQTT模板
一个好的模板将极大的提高编程效率
传感器 发送数据
以超声波为例
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <string.h>
#include <SoftwareSerial.h>
#include <ArduinoJson.h>
#include <SPI.h> // Only needed for Arduino 1.6.5 and earlier
//Wifi Configuration
#define MQTT_VERSION MQTT_VERSION_3_1_1
const char* WIFI_SSID = "wifi ssid";
const char* WIFI_PASSWORD = "wifi password";
const PROGMEM char* MQTT_PUBLISH_TOPIC = "topic";
const PROGMEM char* MQTT_CLIENT_ID = "client id";
const PROGMEM char* MQTT_SERVER_IP = "IP";
const PROGMEM uint16_t MQTT_SERVER_PORT = port;
const PROGMEM char* MQTT_USER = "user";
const PROGMEM char* MQTT_PASSWORD = "password";
unsigned int HighLen = 0;
unsigned int LowLen = 0;
unsigned int Len_mm = 0;
SoftwareSerial us100(D1,D2);//Rx,Tx
WiFiClient wifiClient;
PubSubClient client(wifiClient);
void callback(char* p_topic, byte* p_payload, unsigned int p_length) {
// concat the payload into a string
String payload;
for (uint8_t i = 0; i < p_length; i++) {
payload.concat((char)p_payload[i]);
}
}
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("INFO: Attempting MQTT connection...");
// Attempt to connect
if (client.connect(MQTT_CLIENT_ID, MQTT_USER, MQTT_PASSWORD)) {
Serial.println("INFO: connected");
// Once connected, publish an announcement...
} else {
Serial.print("ERROR: failed, rc=");
Serial.print(client.state());
Serial.println("DEBUG: try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
void publishData(float dist) {
// create a JSON object
// doc : https://github.com/bblanchon/ArduinoJson/wiki/API%20Reference
StaticJsonBuffer<200> jsonBuffer;
JsonObject& root = jsonBuffer.createObject();
// INFO: the data must be converted into a string; a problem occurs when using floats...
root["distance"] = (String)dist;
root.prettyPrintTo(Serial);
/*
{
"temperature": "23.20" ,
"humidity": "43.70"
}
*/
char data[200];
root.printTo(data, root.measureLength() + 1);
client.publish(MQTT_PUBLISH_TOPIC, data, true);
}
void setup() {
// set baudrate as 9600bps.
us100.begin(9600);
Serial.begin(9600);
// init the WiFi connection
Serial.println();
Serial.println();
Serial.print("INFO: Connecting to ");
WiFi.mode(WIFI_STA);
Serial.println(WIFI_SSID);
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("INFO: WiFi connected");
Serial.print("INFO: IP address: ");
Serial.println(WiFi.localIP());
// init the MQTT connection
client.setServer(MQTT_SERVER_IP, MQTT_SERVER_PORT);
client.setCallback(callback);
}
void loop() {
if (!client.connected()) {
reconnect();
}
us100.flush(); // clear receive buffer of serial port
us100.write(0X55); // trig US-100 begin to measure the distance
delay(500); //delay 500ms to wait result
if(us100.available() >= 2) { //when receive 2 bytes
HighLen = us100.read(); //High byte of distance
LowLen = us100.read(); //Low byte of distance
Len_mm = HighLen*256 + LowLen; //Calculate the distance
Serial.print("Distance is: "); //output the result to serial monitor
Serial.print(Len_mm); //output the result to serial monitor
Serial.println("mm");
publishData((float)Len_mm);
}
delay(500);
client.loop();
}
仅需通过修改头部配置信息 publishData()函数 与 loop循环即可. esp8266将以JSON的数据格式向Broker发送数据
执行器 接收数据
以继电器为例
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <ArduinoJson.h>
#define MQTT_VERSION MQTT_VERSION_3_1_1
//Wifi Configuration
const char* WIFI_SSID = "wifi ssid";
const char* WIFI_PASSWORD = "wifi password";
const PROGMEM char* MQTT_SUBSCRIBE_TOPIC = "relay";
const PROGMEM char* MQTT_CLIENT_ID = "relay";
const PROGMEM char* MQTT_SERVER_IP = "mqtt server ip";
const PROGMEM uint16_t MQTT_SERVER_PORT = 1883;
const PROGMEM char* MQTT_USER = "mqtt user";
const PROGMEM char* MQTT_PASSWORD = "mqtt password";
//relay
int relay = D0;
WiFiClient wifiClient;
PubSubClient client(wifiClient);
void callback(char* p_topic, byte* p_payload, unsigned int p_length) {
String payload;
for (uint8_t i = 0; i < p_length; i++) {
payload.concat((char)p_payload[i]);
}
StaticJsonBuffer<200> jsonBuffer;
// doc : https://github.com/bblanchon/ArduinoJson/wiki/API%20Reference
JsonObject& mBuffer = jsonBuffer.parseObject(payload);
const char* state = mBuffer["state"];
if(state == "on"){
digitalWrite(relay, HIGH);
}else if(state == "off"){
digitalWrite(relay, LOW);
}
}
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("INFO: Attempting MQTT connection...");
// Attempt to connect
if (client.connect(MQTT_CLIENT_ID, MQTT_USER, MQTT_PASSWORD)) {
Serial.println("INFO: connected");
client.subscribe(MQTT_SUBSCRIBE_TOPIC);
} else {
Serial.print("ERROR: failed, rc=");
Serial.print(client.state());
Serial.println("DEBUG: try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
void setup() {
Serial.begin(115200);
Serial.println();
Serial.println();
Serial.print("INFO: Connecting to ");
WiFi.mode(WIFI_STA);
Serial.println(WIFI_SSID);
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("INFO: WiFi connected");
Serial.print("INFO: IP address: ");
Serial.println(WiFi.localIP());
// init the MQTT connection
client.setServer(MQTT_SERVER_IP, MQTT_SERVER_PORT);
client.setCallback(callback);
pinMode(relay, OUTPUT);
}
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
}
仅修改callback()函数即可 通过mBuffer["键"]取值
上位机数据发送示例
{"sensor":"gps","time":1351824120,"data":[48.756080,2.302038]}
注意防转义 两边的双引号
网友评论