rc-gateway/include/huzzah.h

119 lines
2.9 KiB
C++

#include <TaskScheduler.h>
#define MQTT_HOST IPAddress(192, 168, 5, 11)
#define MQTT_PORT 1883
using namespace std;
Scheduler ts;
#include "devices.h"
#include "mqtt.h"
#include "ota.h"
#include "wifi.h"
#include "webserver.h"
namespace Board {
Task tReadCommand(TASK_IMMEDIATE, TASK_FOREVER, [](){
if (serialReader.readLine(Serial) > 0) {
char* cmd = serialReader.getBuffer();
if (strcmp("reset", cmd) == 0) {
Serial.println("resetting...");
ESP.restart();
Serial.println("resetting failed");
}
runJsonCommand(cmd);
}
}, &ts);
void turnLed(uint8_t led, bool on = true) {
on ? digitalWrite(led, LOW) : digitalWrite(led, HIGH);
}
void setup() {
// Serial.begin(9600, SERIAL_8N1, SERIAL_TX_ONLY);
pinMode(RED_LED, OUTPUT);
pinMode(BLUE_LED, OUTPUT);
turnLed(RED_LED, false);
turnLed(BLUE_LED);
Mqtt::setup(&ts,
[] {turnLed(BLUE_LED, false);},
[] {turnLed(BLUE_LED);}
);
Wifi::setup(ts,
[] {
Ota::tLoop.enable();
Mqtt::tReConnect.enable();
WebServer::setup();
},
[] {
Ota::tLoop.disable();
Mqtt::tReConnect.disable();
WebServer::stop();
}
);
Ota::setup(
[] {
Mqtt::publishCleanupConfig();
delay(2000);
Mqtt::disconnect();
WebServer::stop();
});
tReadCommand.enable();
}
void loop() {
ts.execute();
}
void parseSwitches(JsonDocument& jsonDoc) {
JsonObjectConst rcSwitch = jsonDoc["rcSwitch"];
switch ((unsigned int)rcSwitch["protocol"]) {
case 1: {
string id = Protocol_1::buildId((const char*)rcSwitch["group"], (int)rcSwitch["channel"]);
Ha::Switch* el = p1Switches[id];
if (el) el->updateState((bool)rcSwitch["state"]);
break;
}
case 2:
break;
default: {
unsigned long value = rcSwitch["value"];
auto range = onSwitches.equal_range(value);
for_each(range.first, range.second, [](mapswitches::value_type& x){
x.second->updateState(true);
});
range = offSwitches.equal_range(value);
for_each(range.first, range.second, [](mapswitches::value_type& x){
x.second->updateState(false);
});
}
}
}
void parseSensors(JsonDocument& jsonDoc, char* message) {
JsonObjectConst json = jsonDoc["sensor"];
string id = to_string((unsigned int)json["id"]);
auto sensor = GenericSensor::mapSensors[id];
if (sensor) sensor->updateState(message);
}
void publishResponse(JsonDocument& jsonDoc) {
char message[255];
serializeJson(jsonDoc, message);
Mqtt::publish("homeassistant/sensor/rc-gateway/raw", message);
if (jsonDoc.containsKey("rcSwitch")) parseSwitches(jsonDoc);
if (jsonDoc.containsKey("sensor")) parseSensors(jsonDoc, message);
}
void handleJsonError(JsonDocument& jsonError) {
char message[255];
serializeJson(jsonError, message);
Mqtt::publish("homeassistant/sensor/rc-gateway/raw", message);
}
}
// {"rcSwitch":{"protocol":1,"state":false,"group":"11111","channel":4}}