summaryrefslogtreecommitdiff
path: root/include/pio/libs/mqtt_module_diagnostics/homekit/mqtt/module/diagnostics.cpp
blob: e0f797eae10301ff60015e9ca86e93e333c9e434 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#include "./diagnostics.h"
#include <homekit/wifi.h>
#include <ESP8266WiFi.h>

namespace homekit::mqtt {

static const char TOPIC_DIAGNOSTICS[] = "diag";
static const char TOPIC_INITIAL_DIAGNOSTICS[] = "d1ag";

void MqttDiagnosticsModule::onConnect(Mqtt &mqtt) {
    sendDiagnostics(mqtt);
}

void MqttDiagnosticsModule::onDisconnect(Mqtt &mqtt, espMqttClientTypes::DisconnectReason reason) {
    initialSent = false;
}

void MqttDiagnosticsModule::tick(Mqtt& mqtt) {
    if (!tickElapsed())
        return;
    sendDiagnostics(mqtt);
}

void MqttDiagnosticsModule::sendDiagnostics(Mqtt& mqtt) {
    auto cfg = config::read();

    if (!initialSent) {
        MqttInitialDiagnosticsPayload stat{
                .ip = wifi::getIPAsInteger(),
                .fw_version = CONFIG_FW_VERSION,
                .rssi = wifi::getRSSI(),
                .free_heap = ESP.getFreeHeap(),
                .flags = DiagnosticsFlags{
                        .state = 1,
                        .config_changed_value_present = 1,
                        .config_changed = static_cast<uint8_t>(cfg.flags.node_configured ||
                                                               cfg.flags.wifi_configured ? 1 : 0)
                }
        };
        mqtt.publish(TOPIC_INITIAL_DIAGNOSTICS, reinterpret_cast<uint8_t*>(&stat), sizeof(stat));
        initialSent = true;
    } else {
        MqttDiagnosticsPayload stat{
                .rssi = wifi::getRSSI(),
                .free_heap = ESP.getFreeHeap(),
                .flags = DiagnosticsFlags{
                        .state = 1,
                        .config_changed_value_present = 0,
                        .config_changed = 0
                }
        };
        mqtt.publish(TOPIC_DIAGNOSTICS, reinterpret_cast<uint8_t*>(&stat), sizeof(stat));
    }
}

}