Merge branch 'doorbell' into huzzah

This commit is contained in:
Nicu Hodos 2024-05-19 18:11:28 +02:00
commit 4096bfc83a
10 changed files with 183 additions and 101 deletions

View File

@ -2,15 +2,24 @@
#include <ArduinoJson.h>
#include <RCSwitch.h>
using namespace std;
class Protocol {
protected:
unsigned int protocol;
unsigned int no;
public:
static unordered_map<unsigned int, Protocol*> mapProtocols;
Protocol(unsigned int protocol) {
this->protocol = protocol;
no = protocol;
mapProtocols.insert({ no, this });
}
Protocol& setProtocol(unsigned int p) {
no = p;
return *this;
}
virtual ~Protocol() {}
virtual void fromJson(JsonObjectConst& rcSwitch, RCSwitch& rcDevice) {
unsigned int protocol = rcSwitch["protocol"];
@ -20,8 +29,9 @@ public:
virtual void toJson(unsigned long value, JsonDocument& jsonDoc) {
JsonObject rcSwitch = jsonDoc.createNestedObject("rcSwitch");
rcSwitch["protocol"] = protocol;
rcSwitch["protocol"] = no;
rcSwitch["value"] = value;
}
};
};
unordered_map<unsigned int, Protocol*> Protocol::mapProtocols;
Protocol fallbackProtocol{ 0 };

View File

@ -5,8 +5,7 @@
class Protocol_1 : public Protocol {
public:
Protocol_1() : Protocol(1) {
}
Protocol_1() : Protocol(1) {}
void fromJson(JsonObjectConst& rcSwitch, RCSwitch& rcDevice) override {
unsigned int protocol = rcSwitch["protocol"];
@ -18,7 +17,7 @@ public:
void toJson(unsigned long value, JsonDocument& jsonDoc) override {
JsonObject rcSwitch = jsonDoc.createNestedObject("rcSwitch");
rcSwitch["protocol"] = protocol;
rcSwitch["protocol"] = no;
RcDecoder decoder;
decoder.decode(value);
rcSwitch["state"] = decoder.state;
@ -32,4 +31,4 @@ public:
sprintf(uId, "%s_%d", group, channel);
return std::string{ uId };
}
};
} protocol1;

View File

@ -5,8 +5,7 @@
class Protocol_2 : public Protocol {
public:
Protocol_2() : Protocol(2) {
}
Protocol_2() : Protocol(2) {}
void toJson(unsigned long value, JsonDocument& jsonDoc) override {
switch (value) {
@ -33,4 +32,4 @@ public:
}
}
};
} protocol2;

View File

@ -0,0 +1,64 @@
#pragma once
#include "Protocol.h"
#define BIT_LENGTH 40
#define BIT_LENGTH_3 BIT_LENGTH*3
#define TX_DELAY 620
class Protocol_Doorbell : public Protocol {
public:
Protocol_Doorbell() : Protocol(16) {}
void ring() {
preamble();
for (int i = 0; i < 7; i++) {
delayMicroseconds(TX_DELAY);
code("00000000110100101000100");
}
}
void fromJson(JsonObjectConst& rcSwitch, RCSwitch& rcDevice) override {
}
void toJson(unsigned long value, JsonDocument& jsonDoc) override {
}
private:
void transmitBit(uint8_t value) {
digitalWrite(SEND_PIN, value);
delayMicroseconds(BIT_LENGTH);
digitalWrite(SEND_PIN, LOW);
}
void transmitHigh() {
digitalWrite(SEND_PIN, HIGH);
delayMicroseconds(BIT_LENGTH_3);
digitalWrite(SEND_PIN, LOW);
delayMicroseconds(BIT_LENGTH);
}
void transmitLow() {
digitalWrite(SEND_PIN, HIGH);
delayMicroseconds(BIT_LENGTH);
digitalWrite(SEND_PIN, LOW);
delayMicroseconds(BIT_LENGTH_3);
}
void preamble() {
noInterrupts();
for (int i = 0; i < 370; i++) {
transmitBit(HIGH);
transmitBit(LOW);
}
interrupts();
}
void code(const char* value) {
noInterrupts();
for (const char* p = value; *p; p++) {
*p == '1' ? transmitHigh() : transmitLow();
}
interrupts();
}
} doorbell;

View File

@ -6,44 +6,50 @@
using namespace Ha;
DeviceConfig* gatewayDevice = (new DeviceConfig{MAIN_DEVICE_ID})->withName("RC Gateway")->withManufacturer("Adafruit")->withModel("Huzzah Esp8266");
typedef unordered_multimap<unsigned long, Ha::Switch*> mapswitches;
mapswitches onSwitches;
mapswitches offSwitches;
unordered_map<string, Ha::Switch*> p1Switches;
auto gatewayDevice = &DeviceConfig::create(MAIN_DEVICE_ID).withName("RC Gateway").withManufacturer("Adafruit").withModel("Huzzah Esp8266");
namespace OilTank {
Sensor* buildRoomSensor(const char* id) {
auto device = DeviceConfig::create(id)
->withName("Oil tank room")
->withManufacturer("Atmel")
->withModel("AtTiny85")
->withArea("Basement")
->withParent(gatewayDevice);
DeviceConfig* device = &DeviceConfig::create(id)
.withName("Oil tank room")
.withManufacturer("Atmel")
.withModel("AtTiny85")
.withArea("Basement")
.withParent(gatewayDevice);
return Builder<TemperatureSensor>::instance(id)
.asDevice(device)
.withValueTemplate("{{ value_json.sensor.temperature }}")
.withDiagnostic(new VoltageSensor{id, "Battery voltage", "{{ value_json.sensor.diagnostic.voltage }}"})
.withDiagnostic(new BatterySensor{id, "Battery level", "{{ ((states('sensor.oil_tank_room_battery_voltage')|float-2.5)|round(2)*100/2)|int }}"})
.asDiagnostic(new VoltageSensor{id, "Battery voltage", "{{ value_json.sensor.diagnostic.voltage }}"})
.asDiagnostic(new BatterySensor{id, "Battery level", "{{ ((states('sensor.oil_tank_room_battery_voltage')|float-2.5)|round(2)*100/2)|int }}"})
.build();
}
Sensor* buildTankSensor(const char* id) {
auto device = DeviceConfig::create(id)
->withName("Oil tank")
->withManufacturer("Arduino")
->withModel("Pro Mini")
->withArea("Basement")
->withParent(gatewayDevice);
DeviceConfig* device = &DeviceConfig::create(id)
.withName("Oil tank")
.withManufacturer("Arduino")
.withModel("Pro Mini")
.withArea("Basement")
.withParent(gatewayDevice);
return Builder<Sensor>::instance(new Sensor{ "Depth", id })
.asDevice(device)
.withDeviceClass("distance")
.withUnitMseasure("cm")
.withValueTemplate("{{ value_json.sensor.value }}")
.withSecondary(
.asSecondary(
Builder<Sensor>::instance(new Sensor{ "Level", id })
.withUnitMseasure("%")
.withValueTemplate("{{ 100 - ((value_json.sensor.value-7)|float*100/110)|round(2) }}")
.build()
)
.withDiagnostic(new VoltageSensor{id, "Battery voltage", "{{ value_json.sensor.diagnostic.voltage }}"})
.withDiagnostic(new BatterySensor{id, "Battery level", "{{ ((states('sensor.oil_tank_battery_voltage')|float-3.6)|round(2)*100/1.6)|int }}"})
.asDiagnostic(new VoltageSensor{id, "Battery voltage", "{{ value_json.sensor.diagnostic.voltage }}"})
.asDiagnostic(new BatterySensor{id, "Battery level", "{{ ((states('sensor.oil_tank_battery_voltage')|float-3.6)|round(2)*100/1.6)|int }}"})
.build();
}
}
@ -60,7 +66,7 @@ struct PollinSwitch : Switch {
strcpy(uId, s.c_str());
return uId;
}()), group(group), channel(channel) {
mainDevice = (new DeviceConfig{id})->withName(name)->withManufacturer("Pollin")->withArea(area)->withParent(gatewayDevice);
mainDevice = &DeviceConfig::create(id).withName(name).withManufacturer("Pollin").withArea(area).withParent(gatewayDevice);
deviceClass = "outlet";
p1Switches.insert({ string(id), this });
}
@ -80,7 +86,7 @@ struct EasyHomeSwitch : Switch {
: Switch(name, id) {
memcpy(&this->on[4], on, 4 * sizeof(unsigned long));
memcpy(&this->off[4], off, 4 * sizeof(unsigned long));
mainDevice = (new DeviceConfig{id})->withName(name)->withManufacturer("Intertek")->withModel("Easy Home")->withArea(area)->withParent(gatewayDevice);
mainDevice = &DeviceConfig::create(id).withName(name).withManufacturer("Intertek").withModel("Easy Home").withArea(area).withParent(gatewayDevice);
deviceClass = "outlet";
for (int i = 0; i < 8; i++) {
onSwitches.insert({ this->on[i], this });
@ -101,6 +107,19 @@ Command* commands[] = {
if (strcmp("PRESS", msg) == 0) ESP.restart();
}
}).asDevice(gatewayDevice).build(),
Builder<Button>::instance(new Button{"Front door", "doorbell_front",
[](const char* msg) {
if (strcmp("PRESS", msg) == 0) doorbell.ring();
}
})
.asDevice(
&DeviceConfig::create("doorbell")
.withName("Doorbell")
.withManufacturer("Thomson")
.withModel("Kinetic Halo")
.withParent(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(),

View File

@ -16,12 +16,10 @@ namespace Ha {
const char* model = nullptr;
const char* manufacturer = nullptr;
const char* area = nullptr;
DeviceConfig* parent = nullptr;
const DeviceConfig* parent = nullptr;
DeviceConfig(const char* id) : id(id) {}
static DeviceConfig* create(const char* id) {
return new DeviceConfig{ id };
static DeviceConfig& create(const char* id) {
return *(new DeviceConfig{ id });
}
void buildConfig(JsonDocument& jsonDoc) {
@ -35,30 +33,33 @@ namespace Ha {
identifiers.add(id);
}
DeviceConfig* withName(const char* value) {
DeviceConfig& withName(const char* value) {
name = value;
return this;
return *this;
}
DeviceConfig* withModel(const char* value) {
DeviceConfig& withModel(const char* value) {
model = value;
return this;
return *this;
}
DeviceConfig* withManufacturer(const char* value) {
DeviceConfig& withManufacturer(const char* value) {
manufacturer = value;
return this;
return *this;
}
DeviceConfig* withArea(const char* value) {
DeviceConfig& withArea(const char* value) {
area = value;
return this;
return *this;
}
DeviceConfig* withParent(DeviceConfig* deviceConfig) {
DeviceConfig& withParent(const DeviceConfig* deviceConfig) {
parent = deviceConfig;
return this;
return *this;
}
protected:
DeviceConfig(const char* id) : id(id) {}
};
struct Component {
@ -108,7 +109,6 @@ namespace Ha {
publisher(configTopic, "");
}
};
List<Component> Component::components;
struct AbstractBuilder {
static List<AbstractBuilder> builders;
@ -122,7 +122,6 @@ namespace Ha {
builders.empty();
}
};
List<AbstractBuilder> AbstractBuilder::builders;
template <class T>
struct Builder : AbstractBuilder {
@ -161,15 +160,14 @@ namespace Ha {
return *this;
}
Builder& withSecondary(Component* c) {
c->mainDevice = new DeviceConfig{ cmp->id };
Builder& asSecondary(Component* c) {
c->mainDevice = &DeviceConfig::create(cmp->id);
return *this;
}
Builder& withDiagnostic(Component* c) {
Builder& asDiagnostic(Component* c) {
c->entityCategory = "diagnostic";
c->mainDevice = new DeviceConfig{ cmp->id };
return *this;
return asSecondary(c);
}
Builder& asDevice(DeviceConfig* deviceConfig) {
@ -198,7 +196,6 @@ namespace Ha {
}
};
unordered_map<string, Command*> Command::mapCommands;
struct Button : Command {
@ -227,7 +224,7 @@ namespace Ha {
if (stateTopic[0]) jsonDoc["state_topic"] = stateTopic;
}
void publishState(bool state) {
void updateState(bool state) {
publisher(stateTopic, state ? "ON" : "OFF");
}
};
@ -235,13 +232,11 @@ namespace Ha {
struct Sensor : Component, StateConfig<Sensor> {
const char* unitMeasure = nullptr;
const char* valueTemplate = nullptr;
Sensor() : Component(name, id, "sensor") {
withStateTopic();
}
static unordered_map<string, Sensor*> mapSensors;
Sensor(const char* name, const char* id) : Component(name, id, "sensor") {
withStateTopic();
mapSensors.insert({ id, this });
}
void buildUniqueId(char* uniqueId) override {
@ -267,6 +262,10 @@ namespace Ha {
jsonDoc["state_topic"] = stateTopic;
jsonDoc["suggested_display_precision"] = 2;
}
void updateState(const char* message) {
publisher(stateTopic, message);
}
};
struct TemperatureSensor : Sensor {
@ -307,4 +306,9 @@ namespace Ha {
// valueTemplate = "{{ value_json.sensor.pressure }}";
}
};
List<Component> Component::components;
List<AbstractBuilder> AbstractBuilder::builders;
unordered_map<string, Command*> Command::mapCommands;
unordered_map<string, Sensor*> Sensor::mapSensors;
}

View File

@ -1,22 +1,9 @@
#include <TaskScheduler.h>
#define SEND_PIN 14
#define RECEIVE_PIN 12
#define RED_LED LED_BUILTIN
#define BLUE_LED 2
using namespace std;
Scheduler ts;
namespace Ha {
struct Switch;
}
typedef unordered_multimap<unsigned long, Ha::Switch*> mapswitches;
mapswitches onSwitches;
mapswitches offSwitches;
unordered_map<string, Ha::Switch*> p1Switches;
void turnLed(uint8_t led, bool on = true) {
on ? digitalWrite(led, LOW) : digitalWrite(led, HIGH);
}
@ -57,7 +44,7 @@ namespace Board {
case 1: {
string id = Protocol_1::buildId((const char*)rcSwitch["group"], (int)rcSwitch["channel"]);
Ha::Switch* el = p1Switches[id];
if (el) el->publishState((bool)rcSwitch["state"]);
if (el) el->updateState((bool)rcSwitch["state"]);
break;
}
case 2:
@ -66,11 +53,11 @@ namespace Board {
unsigned long value = rcSwitch["value"];
auto range = onSwitches.equal_range(value);
for_each(range.first, range.second, [](mapswitches::value_type& x){
x.second->publishState(true);
x.second->updateState(true);
});
range = offSwitches.equal_range(value);
for_each(range.first, range.second, [](mapswitches::value_type& x){
x.second->publishState(false);
x.second->updateState(false);
});
}
}
@ -79,10 +66,8 @@ namespace Board {
void parseSensors(JsonDocument& jsonDoc, char* message) {
JsonObjectConst json = jsonDoc["sensor"];
string id = to_string((unsigned int)json["id"]);
char stateTopic[TOPIC_SIZE];
sprintf(stateTopic, "homeassistant/sensor/%s/%s/state", MAIN_DEVICE_ID, id.c_str());
Mqtt::publish(stateTopic, message);
auto sensor = Sensor::mapSensors[id];
if (sensor) sensor->updateState(message);
}
void publishResponse(JsonDocument& jsonDoc) {

12
gateway/include/pins.h Normal file
View File

@ -0,0 +1,12 @@
#pragma once
#if defined(ESP8266)
#define SEND_PIN 14
#define RECEIVE_PIN 12
#define RED_LED LED_BUILTIN
#define BLUE_LED 2
#else
#define RESET_PIN 10
#define SEND_PIN 11
#define RECEIVE_PIN 2
#endif

View File

@ -1,9 +1,5 @@
#include "output.h"
#define RESET_PIN 10
#define SEND_PIN 11
#define RECEIVE_PIN 2
namespace Board {
void setup() {

View File

@ -1,9 +1,11 @@
#include <Arduino.h>
#include <RCSwitch.h>
#include <SerialReader.h>
#include "pins.h"
#include "Dht.h"
#include "Protocol_1.h"
#include "Protocol_2.h"
#include "Protocol_Doorbell.h"
RCSwitch mySwitch;
SerialReader<200> serialReader;
@ -29,15 +31,9 @@ void setup() {
delay(1000);
}
Protocol* findProtocol(unsigned int protocol) {
switch (protocol) {
case 1:
return new Protocol_1();
case 2:
return new Protocol_2();
default:
return new Protocol(protocol);
}
Protocol& findProtocol(unsigned int protocol) {
auto p = Protocol::mapProtocols[protocol];
return p ? *p : fallbackProtocol.setProtocol(protocol);
}
void readRcSwitch() {
@ -52,9 +48,8 @@ void readRcSwitch() {
mySwitch.resetAvailable();
StaticJsonDocument<128> jsonDoc;
Protocol* p = findProtocol(mySwitch.getReceivedProtocol());
p->toJson(value, jsonDoc);
delete p;
Protocol& p = findProtocol(mySwitch.getReceivedProtocol());
p.toJson(value, jsonDoc);
if (!jsonDoc.isNull()) {
serializeJson(jsonDoc, Serial);
Serial.println();
@ -75,14 +70,13 @@ void handleJsonError(DeserializationError err, const char* cmd) {
}
void runJsonCommand(char* cmd) {
StaticJsonDocument<50> jsonDoc;
StaticJsonDocument<128> jsonDoc;
DeserializationError err = deserializeJson(jsonDoc, cmd);
if (err == DeserializationError::Ok) {
if (jsonDoc.containsKey("rcSwitch")) {
JsonObjectConst rcSwitch = jsonDoc["rcSwitch"];
Protocol* p = findProtocol(rcSwitch["protocol"]);
p->fromJson(rcSwitch, mySwitch);
delete p;
Protocol& p = findProtocol(rcSwitch["protocol"]);
p.fromJson(rcSwitch, mySwitch);
serializeJson(jsonDoc, Serial);
Serial.println();
Board::publishResponse(jsonDoc);