aboutsummaryrefslogtreecommitdiff
path: root/platformio/common/libs/mqtt_module_relay/homekit/mqtt/module/relay.cpp
blob: ab407275ebf2f45c530fa88dedce42e6899363bb (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
#include "./relay.h"
#include <homekit/relay.h>
#include <homekit/logging.h>

namespace homekit::mqtt {

static const char TOPIC_RELAY_SWITCH[] = "relay/switch";

void MqttRelayModule::init(Mqtt &mqtt) {
	String topic(TOPIC_RELAY_SWITCH);
	mqtt.subscribeModule(topic, this, 1);
}

void MqttRelayModule::tick(homekit::mqtt::Mqtt& mqtt) {}

void MqttRelayModule::handlePayload(Mqtt& mqtt, String& topic, uint16_t packetId, const uint8_t *payload, size_t length, size_t index, size_t total) {
	if (topic != TOPIC_RELAY_SWITCH)
		return;

	if (length != sizeof(MqttRelaySwitchPayload)) {
        PRINTF("error: size of payload (%ul) does not match expected (%ul)\n",
               length, sizeof(MqttRelaySwitchPayload));
        return;
    }

    auto pd = reinterpret_cast<const struct MqttRelaySwitchPayload*>(payload);
    if (strncmp(pd->secret, MQTT_SECRET, sizeof(pd->secret)) != 0) {
        PRINTLN("error: invalid secret");
        return;
    }

    if (pd->state == 1) {
        PRINTLN("mqtt: turning relay on");
        relay::on();
    } else if (pd->state == 0) {
        PRINTLN("mqtt: turning relay off");
        relay::off();
    } else {
        PRINTLN("error: unexpected state value");
    }
}

}