!!!!!!!!!!!!!使用PubSubClient2.8.0!!!!!!!!!!!!!!
替换三元组和服务ID即可连接
参考:【代码分享】ESP32接入华为云物联网平台完成属性定时上报(Arduino IDE开发)_adrunioide连接华为云-CSDN博客
//ESP32接入华为云物联网平台完成属性定时上报
#include <WiFi.h>
#include <PubSubClient.h> //使用PubSubClient2.8.0
WiFiClient espClient;
PubSubClient client(espClient);
const char* ssid = "X50"; //wifi名称
const char* password = "12345678"; //wifi密码
const char* mqttServer = "140cb684fa.st1.iotda-device.cn-south-1.myhuaweicloud.com"; //例如iot-mqtts.cn-north-4.myhuaweicloud.com,详情参考华为云控制台
const int mqttPort = 1883; //华为MQTT地址1883)
//三元组:三元组生成链接:https://iot-tool.obs-website.cn-north-4.myhuaweicloud.com/
const char* ClientId ="xxx";
const char* mqttUser ="xxx";
const char* mqttPassword = "xxx";
//注册设备的ID和密钥
#define device_id "xx"
#define secret "xx"
//注意修改自己的服务ID
#define Iot_link_Body_Format "{\"services\":[{\"service_id\":\"Dev_data\",\"properties\":{%s"
//参考上报格式:{"services":[{"service_id":"Dev_data","properties":{"temp": 39}}]}
//设备属性上报
#define Iot_link_MQTT_Topic_Report "$oc/devices/"device_id"/sys/properties/report"
int data_temp=1; //模拟上报的温度值
long lastMsg = 0;
void setup() {
//wifi初始化
Serial.begin(115200);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.println("Connecting to WiFi..");
}
Serial.println("Connected to the WiFi network");
//MQTT初始化
MQTT_Init();
//更多资料欢迎关注微信公众号“IOT趣制作”
}
void loop() {
if (!client.connected()){
MQTT_Init();
}
else client.loop();
long now = millis();
if (now - lastMsg > 5000)//定时上报
{
lastMsg = now;
MQTT_POST();
data_temp++;
}
}
void MQTT_Init()
{
client.setServer(mqttServer, mqttPort);
client.setKeepAlive(60);
while (!client.connected())
{
Serial.println("Connecting to MQTT...");
if (client.connect(ClientId, mqttUser, mqttPassword ))
{
Serial.println("connected");
}
else
{
Serial.print("failed with state ");
Serial.print(client.state());
delay(3000);
}
}
}
void MQTT_POST()
{
char properties[32];
char jsonBuf[128];
sprintf(properties,"\"temp\":%d}}]}",data_temp);
sprintf(jsonBuf,Iot_link_Body_Format,properties);
client.publish(Iot_link_MQTT_Topic_Report, jsonBuf);
Serial.println(Iot_link_MQTT_Topic_Report);
Serial.println(jsonBuf);
Serial.println("MQTT Publish OK!");
}