summaryrefslogtreecommitdiff
path: root/platformio/temphum/src/mqtt.h
blob: 84df5b13d630fd342afde0ce77c1aacee45c7688 (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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
#ifndef HOMEKIT_TEMPHUM_MQTT_H
#define HOMEKIT_TEMPHUM_MQTT_H

#include <ESP8266WiFi.h>
#include <espMqttClient.h>
#include <Ticker.h>

#include <homekit/stopwatch.h>
#include <homekit/mqtt.h>

namespace homekit { namespace mqtt {

enum class OTAResult: uint8_t {
    OK = 0,
    UPDATE_ERROR = 1,
    WRITE_ERROR = 2,
};

struct OTAStatus {
    uint16_t dataPacketId;
    uint16_t publishResultPacketId;
    bool finished;
    bool readyToRestart;
    size_t written;

    OTAStatus()
        : dataPacketId(0)
        , publishResultPacketId(0)
        , finished(false)
        , readyToRestart(false)
        , written(0)
    {}

    inline void clean() {
        dataPacketId = 0;
        publishResultPacketId = 0;
        finished = false;
        readyToRestart = false;
        written = 0;
    }

    inline bool started() const {
        return dataPacketId != 0;
    }
};

class MQTT {
private:
    String homeId;
    WiFiClientSecure httpsSecureClient;
    espMqttClientSecure client;
    Ticker reconnectTimer;
    Ticker restartTimer;

    void handleAdminOtaPayload(uint16_t packetId, const uint8_t* payload, size_t length, size_t index, size_t total);

    uint16_t publish(const String& topic, uint8_t* payload, size_t length);
    uint16_t subscribe(const String& topic, uint8_t qos = 0);

    void sendInitialDiagnostics();
    uint16_t sendOtaResponse(OTAResult status, uint8_t error_code = 0);

public:
    StopWatch diagnosticsStopWatch;
    OTAStatus ota;

    MQTT();
    void connect();
    void disconnect();
    void reconnect();
    void loop();
    void sendDiagnostics();
    void sendTempHumData(double temp, double rh);
};

struct DiagnosticsFlags {
    uint8_t state: 1;
    uint8_t config_changed_value_present: 1;
    uint8_t config_changed: 1;
    uint8_t reserved: 5;
} __attribute__((packed));

struct InitialDiagnosticsPayload {
    uint32_t ip;
    uint8_t fw_version;
    int8_t rssi;
    uint32_t free_heap;
    DiagnosticsFlags flags;
} __attribute__((packed));

struct DiagnosticsPayload {
    int8_t rssi;
    uint32_t free_heap;
    DiagnosticsFlags flags;
} __attribute__((packed));

struct PowerPayload {
    char secret[12];
    uint8_t state;
} __attribute__((packed));

struct TempHumDataPayload {
    double temp;
    double rh;
} __attribute__((packed));

struct OTAResponse {
    OTAResult status;
    uint8_t error_code;
} __attribute__((packed));

} }

#endif //HOMEKIT_TEMPHUM_MQTT_H