86 lines
3.0 KiB
C++
86 lines
3.0 KiB
C++
#pragma once
|
|
|
|
#include <AsyncMqttClient.h>
|
|
#include <ArduinoJson.h>
|
|
#include "devices.h"
|
|
|
|
|
|
#define MQTT_HOST IPAddress(192, 168, 5, 11)
|
|
#define MQTT_PORT 1883
|
|
|
|
namespace Mqtt {
|
|
|
|
AsyncMqttClient client;
|
|
|
|
Task tReConnect(5 * TASK_MINUTE, TASK_FOREVER, []() {
|
|
Serial.println("Connecting to MQTT...");
|
|
client.connect();
|
|
}, &ts);
|
|
void publishInit();
|
|
Task tPublishInit(TASK_IMMEDIATE, TASK_ONCE, publishInit, &ts);
|
|
|
|
const char* mainTopic = "homeassistant/+/rc-gateway/#";
|
|
|
|
void disconnect() {
|
|
client.unsubscribe(mainTopic);
|
|
client.disconnect();
|
|
}
|
|
|
|
uint16_t publish(const char* topic, const char* message) {
|
|
return client.publish(topic, 0, true, message);
|
|
}
|
|
|
|
Command* commands[] = {
|
|
Builder<Button>::instance(new Button{"Restart", "restart",
|
|
[](const char* msg) {
|
|
if (strcmp("PRESS", msg) == 0) ESP.restart();
|
|
}
|
|
}).asDevice(gatewayDevice).build(),
|
|
(new EasyHomeSwitch{"FritzBox", "easy_home_a", (unsigned long[4]) { 4483136, 4626800, 4661552, 4819632 }, (unsigned long[4]) { 4326544, 4537104, 4767520, 4972704 }, "Basement"})->withStateTopic(),
|
|
(new EasyHomeSwitch{"Outside", "easy_home_b", (unsigned long[4]) { 4483140, 4626804, 4661556, 4819636 }, (unsigned long[4]) { 4326548, 4537108, 4767524, 4972708 }, "Basement"})->withStateTopic(),
|
|
(new PollinSwitch{"Meeting sensor", "00001", 1, "Dining room"})->withStateTopic(),
|
|
(new PollinSwitch{"Fire Tv", "00001", 2, "Living room"})->withStateTopic(),
|
|
(new PollinSwitch{"Diningroom player", "00001", 3, "Dining room"})->withStateTopic(),
|
|
(new PollinSwitch{"Train", "11111", 4, "Playroom"})->withStateTopic()
|
|
};
|
|
|
|
Sensor* sensors[] = {
|
|
OilTank::buildRoomSensor("4"),
|
|
OilTank::buildTankSensor("7")
|
|
};
|
|
|
|
void publishInit() {
|
|
Ha::publisher = publish;
|
|
Component::components.forEach([](Component* c) { c->publishConfig(); });
|
|
AbstractBuilder::deleteAll();
|
|
ts.deleteTask(tPublishInit);
|
|
}
|
|
|
|
void publishCleanupConfig() {
|
|
Component::components.forEach([](Component* c) { c->publishCleanupConfig(); });
|
|
}
|
|
|
|
void onMessage(char* topic, char* payload, AsyncMqttClientMessageProperties properties, size_t len, size_t index, size_t total) {
|
|
char msg[len + 1];
|
|
memcpy(msg, payload, len);
|
|
msg[len] = 0;
|
|
Command* cmd = Command::mapCommands[string{ topic }];
|
|
if (cmd) cmd->onCommand(msg);
|
|
}
|
|
|
|
void setup() {
|
|
client.onConnect([](bool sessionPresent) {
|
|
tPublishInit.enable();
|
|
client.subscribe(mainTopic, 0);
|
|
tReConnect.disable();
|
|
Serial.println("Connected to MQTT");
|
|
});
|
|
client.onDisconnect([](AsyncMqttClientDisconnectReason reason) {
|
|
tReConnect.enableDelayed();
|
|
Serial.println("Disconnected from MQTT");
|
|
});
|
|
client.onMessage(onMessage);
|
|
client.setServer(MQTT_HOST, MQTT_PORT);
|
|
}
|
|
}
|