summaryrefslogtreecommitdiff
path: root/include/pio/libs/mqtt_module_ota/homekit/mqtt/module/ota.h
blob: df4f7ce101a5b17365336f6d76f119ef08b2d95c (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
#ifndef HOMEKIT_LIB_MQTT_MODULE_OTA_H
#define HOMEKIT_LIB_MQTT_MODULE_OTA_H

#include <stdint.h>
#include <Ticker.h>
#include <homekit/mqtt/module.h>

namespace homekit::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;
    }
};

struct MqttOtaResponsePayload {
    OtaResult status;
    uint8_t error_code;
} __attribute__((packed));


class MqttOtaModule: public MqttModule {
private:
    OtaStatus ota;
    Ticker restartTimer;

    uint16_t sendResponse(Mqtt& mqtt, OtaResult status, uint8_t error_code = 0) const;

public:
    MqttOtaModule() : MqttModule(0, true, true) {}

    void onConnect(Mqtt& mqtt) override;
	void onDisconnect(Mqtt& mqtt, espMqttClientTypes::DisconnectReason reason) override;

    void tick(Mqtt& mqtt) override;
	
    void handlePayload(Mqtt& mqtt, String& topic, uint16_t packetId, const uint8_t *payload, size_t length, size_t index, size_t total) override;
    void handleOnPublish(uint16_t packetId) override;

    inline bool isReadyToRestart() const {
        return ota.readyToRestart;
    }
};

}

#endif //HOMEKIT_LIB_MQTT_MODULE_OTA_H