ESP32连接阿里云(MQTT协议)

本文代码用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();
    }
}

  • 7
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值