本文代码用platform IO编写,这部分代码用到了两个库,WiFi.h 和PubSubClient.h
#include<WiFi.h>
#include<PubSubClient.h>
const char* ssid ="vivo";//wifi名
const char*password ="12345678";//wifi密码
const char*mqttHostUrl = "a1mBx3d4zsb.iot-as-mqtt.cn-shanghai.aliyuncs.com";//阿里云服务器域名
const int mqttPort =1883;//端口号
const char*mqttUser = "device&a1mBx3d4zsb";//username
const char*mqttPassword = "9599201fb682d4d838a6f8f36d8daa5093c1b047e4d24507f5f2b2c8285df11f";//密钥
const char*clientId = "a1mBx3d4zsb.device|securemode=2,signmethod=hmacsha256,timestamp=1722159382775|" ;//连接id
#define PRODUCT_KEY "a1mBx3d4zsb"
#define DEVICE_NAME "device"
//下面组包用{{\"id\":1718790269227,\"params\":{\"LEDSwitch\":%d,\"temperature\":%f,\"HCHO\":%f,\"Humidity\":%d,\"SmokeSensorState\":%d,\"LightLux\":%d,\"TVOC\":%f,\"co2\":%d},\"version\":\"1.0\",\"method\":\"thing.event.property.post\"}"}
//#define ALINK_BODY_FORMAT "{\"id\":\"level\",\"version\":\"1.0\",\"method\":\"thing.event.property.post\",\"params\":%s}"
#define ALINK_BODY_FORMAT "{\"id\":1718790269227,\"params\":{\"LEDSwitch\":%d,\"temperature\":%f,\"HCHO\":%f,\"Humidity\":%d,\"SmokeSensorState\":%d,\"LightLux\":%d,\"TVOC\":%f,\"co2\":%d},\"version\":\"1.0\",\"method\":\"thing.event.property.post\"}"
#define ALINK_TOPIC_PROP_POST "/sys/a1mBx3d4zsb/device/thing/event/property/post"
unsigned long lastMs = 0;
WiFiClient espClient;
PubSubClient client(espClient);
//连接wifi
void wifiInit()
{
WiFi.begin(ssid,password);
while (WiFi.status()!= WL_CONNECTED) {
delay(500);
Serial.println("Connectingto WiFi..");
}
Serial.println("Connectedto the WiFi network");
}
//mqtt连接
void mqttCheckConnect()
{
client.setServer(mqttHostUrl,mqttPort);
while (!client.connected()){
Serial.println("Connectingto MQTT...");
if (client.connect(clientId,mqttUser, mqttPassword )) {
Serial.println("connected");
}else {
Serial.print("failedwith state ");
Serial.print(client.state());
delay(2000);
}
}
}
//组数据帧并发送
void mqttIntervalPost()
{
char param[32];
char jsonBuf[600];
sprintf(jsonBuf, ALINK_BODY_FORMAT, 1,1.0,1.0,1,1,1,1.0,1);
Serial.println(jsonBuf);
client.publish(ALINK_TOPIC_PROP_POST, jsonBuf);
}
void setup() {
Serial.begin(115200);
wifiInit();//连接wifi
mqttCheckConnect();//连接阿里云
}
void loop() {
client.loop();
if (millis() - lastMs >= 5000)
{//定时检查或上报数据
lastMs = millis();
mqttCheckConnect();
// 上报
mqttIntervalPost();
}
}