69 lines
2.0 KiB
C++
69 lines
2.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);
|
|
}
|
|
|
|
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");
|
|
turnLed(BLUE_LED, false);
|
|
});
|
|
client.onDisconnect([](AsyncMqttClientDisconnectReason reason) {
|
|
tReConnect.enableDelayed();
|
|
Serial.println("Disconnected from MQTT");
|
|
turnLed(BLUE_LED);
|
|
});
|
|
client.onMessage(onMessage);
|
|
client.setServer(MQTT_HOST, MQTT_PORT);
|
|
}
|
|
}
|