[作品提交] 【Follow me第二季第2期】进阶任务

qzc飘曳   2024-9-10 22:45 楼主
        通过Wi-Fi,利用MQTT协议接入到开源的智能家居平台HA(HomeAssistant)。
        实际上我们通过在HA系统中注册设备和实体后,只要通过固定的接口按照规则发送数据就能实现整个正常的解析和显示了。
        我们打开HA,配置MQTT模块:
wd_224308bo0qjhjooftq0vey.png
        主要是IP地址要和你的HA系统的IP地址相一致;
        然后通过MQTT模块的自发现功能,使用MQTT模拟器进行连接注册,首先要连接到我们的HA:
wd_224308nzi8tr8it1dq45qm.png
        设备注册通过下面语句进行(config topic):
homeassistant/sensor/sensorsth40tem/config

        如果为空则是删除对应的设备,否则需要添加配置项:

{
    "name":"tem",
    "device_class":"temperature",
    "state_topic":"homeassistant/sensor/sensorsth40/state",
"value_template":"{{ value_json.tem}}",
    "unit_of_measurement":"C",
    "unique_id":"sth40-001-tem",
    "device":{
        "identifiers":[
            "STH40"
        ],
        "name":"SHT40-Sensor",
        "manufacturer": "Arduino",
        "model": "UNO R4 WiFi"
    }
}

        同理创建了同样的设备下的3个实体:

wd_224308h31xrjegnn1qppe3.png
        其中cnt用于显示上报次数,这个在我们没有进行传感器采集的时候用于进行实物测试,其实这个时候说明已经实现了HA系统的打通,不过我们还是使用模拟器进行一下具体数据传的测试:
        发送:
homeassistant/sensor/sensorsth40/state
{ "tem": 23.20, "hum": 43.70 ,"cnt":1}

        输出结果符合预期:

wd_224308r3q4kvg4094s4qag.png
        以上内容我们都是通过PC软件实现的,接下来我们使用开发板进行上述功能的实现。
        这里主要设计wifi连接和MQTT协议的内容:
#include <ArduinoMqttClient.h>
#include <WiFiS3.h>
#include <WiFiClient.h>
#include <Arduino_JSON.h>
char ssid[] = "xxx";        
char pass[] = "xxx";  
const char broker[] = "192.168.72.127";
int        port     = 1883;
const char state_topic2[]  = "homeassistant/sensor/sensorsth40/state";
WiFiClient wifiClient;
MqttClient mqttClient(wifiClient);
JSONVar dataObj;
const long interval = 1000;
unsigned long previousMillis = 0;
int count = 0;
void setup() {
  Serial.begin(115200);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }
  Serial.println("HA com test");
  Serial.println("connect to WPA SSID: ");
  Serial.println(ssid);
  // attempt to connect to WiFi network:
  while (WiFi.begin(ssid, pass) != WL_CONNECTED) {
    Serial.print("......");
    delay(5000);
  }
  Serial.print("connect wifi succeed!");
  Serial.println();
  Serial.println(WiFi.localIP());
  // You can provide a unique client ID, if not set the library uses Arduino-millis()
  // Each client must have a unique client ID
   mqttClient.setId("clientId");
  // You can provide a username and password for authentication
   mqttClient.setUsernamePassword("admin", "admin");
  Serial.print("connect to the MQTT broker: ");
  Serial.println(broker);
  if (!mqttClient.connect(broker, port)) {
    Serial.print("MQTT connection failed! Error code = ");
    Serial.println(mqttClient.connectError());
    while (1);
  }
  Serial.println("connected to the MQTT succeed!");
  Serial.println();
}
void loop() {
  // put your main code here, to run repeatedly:
  mqttClient.poll(); 
  unsigned long currentMillis = millis();
  if (currentMillis - previousMillis >= interval) {
    // save the last time a message was sent
    previousMillis = currentMillis;
    dataObj["cnt"] = count;
    String jsonString = JSON.stringify(dataObj);
    // send message, the Print interface can be used to set the message contents
    mqttClient.beginMessage(state_topic);
    mqttClient.print(jsonString);
    mqttClient.endMessage();
    count++;
    if(count>=90)
      count = 0;
    delay(1000);
  }
}

    串口打印状态:

wd_224308dky5zdnqprpqkip1.png
        HA系统中的效果展示参见最终的效果视频-进阶任务。

回复评论 (2)

做的很好啊,效果很炫酷的,而且MQTT我觉得还是比较方便好用的,主要是在于订阅这种,不用长连接

点赞  2024-9-11 11:50
引用: yangjiaxu 发表于 2024-9-11 11:50 做的很好啊,效果很炫酷的,而且MQTT我觉得还是比较方便好用的,主要是在于订阅这种,不用长连接

主要是这些集成库很好用,直接配置好了,直接发送就行 

点赞  2024-10-3 13:05
电子工程世界版权所有 京B2-20211791 京ICP备10001474号-1 京公网安备 11010802033920号
    写回复