add support for restart over MQTT

This commit is contained in:
Nicu Hodos 2022-11-10 21:16:30 +01:00
parent a888a1fd1f
commit 55782b7538
2 changed files with 25 additions and 0 deletions

View File

@ -67,4 +67,13 @@ namespace Ha {
jsonDoc["value_template"] = config.valueTemplate;
serializeJson(jsonDoc, output);
}
void buildRestartConfig(char(&output)[JSON_SIZE], const char* topic) {
StaticJsonDocument<JSON_SIZE> jsonDoc;
buildDeviceConfig(jsonDoc);
jsonDoc["name"] = "Restart";
jsonDoc["unique_id"] = "esp_clock_restart";
jsonDoc["command_topic"] = topic;
serializeJson(jsonDoc, output);
}
}

View File

@ -35,6 +35,7 @@ namespace Mqtt {
} commands;
const char* bmpTopic = "homeassistant/sensor/esp_clock/state";
const char* restartTopic = "homeassistant/button/esp_clock/restart";
void connect() {
client.connect();
@ -62,10 +63,18 @@ namespace Mqtt {
client.publish("homeassistant/sensor/esp_clock/altitude/config", 0, true, message);
}
void publishRestartConfig() {
char message[JSON_SIZE];
Ha::buildRestartConfig(message, restartTopic);
client.publish("homeassistant/button/esp_clock/restart/config", 0, true, message);
}
void publishConfig() {
publishTempConfig();
publishPressureConfig();
publishAltitudeConfig();
publishRestartConfig();
client.subscribe(restartTopic, 0);
ts.deleteTask(tPublishConfig);
}
@ -92,6 +101,12 @@ namespace Mqtt {
}
}
void onMessage(char* topic, char* payload, AsyncMqttClientMessageProperties properties, size_t len, size_t index, size_t total) {
if (String{ restartTopic }.equals(topic) && String { payload }.equals("PRESS")) {
ESP.restart();
}
}
void setup() {
client.onConnect([](bool sessionPresent) {
tPublishConfig.enable();
@ -106,6 +121,7 @@ namespace Mqtt {
tPublishBmp.disable();
Serial.println("Disconnected from MQTT");
});
client.onMessage(onMessage);
client.setServer(MQTT_HOST, MQTT_PORT);
Serial.println("Connecting to MQTT...");
}