发一个EPS-04通过MQTT连接OneNet的程序,之前写的程序。里面用了WiFiManager库,可以通过手机配置Wifi,程序部分如下,如果想看详细的过程可以查看文末的文章。
#include <ESP8266WiFi.h>
#include <DNSServer.h>
#include <ESP8266WebServer.h>
#include <WiFiManager.h>
#include <PubSubClient.h>
#include <ArduinoJson.h>
const char* mqtt_server = "183.230.40.39"; //服务器地址
const char* DeviceID = ""; //修改为自己的设备号
const char* ProductID = ""; //修改为自己的产品号
const char* AuthInfo = ""; //修改为自己的鉴权信息
WiFiClient espClient;
PubSubClient client(espClient);
long lastMsg = 0;
char msg_buf[200];
char dataTemplete[] = "{\"temperature\":%d}"; //数据流信息
char msgJson[75];
unsigned short json_len = 0;
char comdata[20]; //串口接收字符串暂存器
char rc_len ;
//数据接收回掉函数
void callback(char* topic, byte* payload, unsigned int length) {
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
for (int i = 0; i < length; i++) {
Serial.print((char)payload[i]);
}
Serial.println();
}
//设备重连
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Create a random client ID
String clientId = "ESP8266Client-";
clientId += String(random(0xffff), HEX);
// Attempt to connect
if (client.connect(DeviceID, ProductID, AuthInfo)) {
Serial.println("connected");
// Once connected, publish an announcement...
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
WiFiManager wifiManager;
wifiManager.setTimeout(180);
if (!wifiManager.autoConnect("AutoConnectAP")) {
Serial.println("failed to connect and hit timeout");
delay(3000);
ESP.reset();
delay(5000);
}
client.setServer(mqtt_server, 6002);
client.connect(DeviceID, ProductID, AuthInfo);
client.setCallback(callback);
}
uint16_t Temp ;
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
long now = millis();
//上传周期为4秒
if (now - lastMsg > 4000) {
lastMsg = now;
Publish_Msg(Temp);
}
while (Serial.available() > 0) {
comdata[rc_len++] = char(Serial.read()); //每次读一个char字符,并相加
delay(2);
}
if (rc_len > 0) {
//Serial.println(comdata);
Temp = comdata[0] << 8 | comdata[1] ;
rc_len = 0 ;
}
}
//上传数据到OneNET
void Publish_Msg(uint16_t value)
{
snprintf(msgJson, 40, dataTemplete, value);
json_len = strlen(msgJson); //packet length count the end char '\0'
msg_buf[0] = char(0x03); //palyLoad packet byte 1, one_net mqtt Publish packet payload byte 1, type3 , json type2
msg_buf[1] = char(json_len >> 8); //high 8 bits of json_len (16bits as short int type)
msg_buf[2] = char(json_len & 0xff); //low 8 bits of json_len (16bits as short int type)
// snprintf(msg_buf+3,40,dataTemplete,value);
memcpy(msg_buf + 3, msgJson, strlen(msgJson));
msg_buf[3 + strlen(msgJson)] = 0;
Serial.print("Publish message: ");
Serial.println(msgJson);
client.publish("$dp", (const uint8_t*)msg_buf, 3 + strlen(msgJson), false); // msg_buf as payload length which may have a "0x00"byte
}