Added homeassistant auto-discovery via MQTT.

This commit is contained in:
2020-07-09 06:41:21 +02:00
parent 209140cfb7
commit fd44b217a7
2 changed files with 21 additions and 2 deletions

View File

@ -23,7 +23,7 @@ void mqtt_callback(char* original_topic, byte* pl, unsigned int length) {
pl[length] = '\0';
String payload((char*)pl);
String topic (original_topic);
if (topic.equals(MQTT_TOPIC "log") || topic.equals(MQTT_TOPIC "status") || topic.startsWith(MQTT_TOPIC "metrics")) {
if (topic.equals(MQTT_TOPIC "log") || topic.equals(MQTT_TOPIC "status") || topic.equals(MQTT_TOPIC "status_details") || topic.startsWith(MQTT_TOPIC "metrics")) {
// Return our own messages
return;
}
@ -98,15 +98,33 @@ void mqtt_callback(char* original_topic, byte* pl, unsigned int length) {
boolean mqtt_connect() {
LOGln("MQTT * Connecting to MQTT server with client id %s", hostname);
mqtt_client.setBufferSize(350);
if (mqtt_client.connect(hostname, MQTT_USER, MQTT_PASS, MQTT_TOPIC "status", 0, true, "OFFLINE", true)) {
LOGln("MQTT * Connected.");
LOGln("Core * Flash chip id: 0x%X. Size: %d bytes. 'Real' size: %d bytes.", ESP.getFlashChipId(), ESP.getFlashChipSize(), ESP.getFlashChipRealSize());
char buffer[40];
snprintf(buffer, 40, "ONLINE %s %s", hostname, WiFi.localIP().toString().c_str());
mqtt_client.publish(MQTT_TOPIC "status", buffer, true);
mqtt_client.publish(MQTT_TOPIC "status", "ONLINE", true);
mqtt_client.publish(MQTT_TOPIC "status_details", buffer, true);
mqtt_client.subscribe(MQTT_TOPIC "+");
mqtt_client.subscribe(MQTT_TOPIC_WEATHER "#");
mqtt_client.subscribe(MQTT_TOPIC_TIMER);
#ifdef MQTT_TOPIC_HOMEASSISTANT
// Set MQTT values for homeassistant auto device discovery
String topic = MQTT_TOPIC_HOMEASSISTANT "/light/";
topic += hostname;
topic += "/config";
String message = "{\"~\":\"" MQTT_TOPIC "\",\"opt\":1,\"avty_t\":\"~status\",\"pl_avail\":\"ONLINE\",\"pl_not_avail\":\"OFFLINE\",";
message += "\"bri_cmd_t\": \"~brightness\",\"bri_scl\":255,\"fx_cmd_t\":\"~modus\",\"name\":\"Pitrix\",\"uniq_id\":\"";
message += hostname;
message += "\",";
message += "\"stat_t\":\"~modus\",\"cmd_t\":\"~modus\",\"pl_on\":\"cycle\",\"pl_off\":\"night_clock\"}";
mqtt_client.publish(topic.c_str(), message.c_str(), true);
DBG("MQTT * Homeassistant data:");
DBG("MQTT * Topic: %s", topic.c_str());
DBG("MQTT * Data: %s", message.c_str());
#endif
}
return mqtt_client.connected();
}