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个实体:
homeassistant/sensor/sensorsth40/state
{ "tem": 23.20, "hum": 43.70 ,"cnt":1}
输出结果符合预期:
#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);
}
}
串口打印状态:
引用: yangjiaxu 发表于 2024-9-11 11:50 做的很好啊,效果很炫酷的,而且MQTT我觉得还是比较方便好用的,主要是在于订阅这种,不用长连接
主要是这些集成库很好用,直接配置好了,直接发送就行