Application develop start

This commit is contained in:
Emanuele Trabattoni
2025-07-24 22:46:31 +02:00
parent bea42c9a36
commit bb0832ad4f
12 changed files with 237 additions and 123 deletions

View File

@@ -189,12 +189,12 @@ private:
mqtt["clientName"] = m_mqttClientName; mqtt["clientName"] = m_mqttClientName;
mqtt["retries"] = m_mqttRetries; mqtt["retries"] = m_mqttRetries;
auto publish = mqtt["publish"].to<ArduinoJson::JsonObject>(); auto publish = mqtt["publish"].to<ArduinoJson::JsonObject>();
for (auto v : m_mqttSubscribe) for (auto v : m_mqttPublish)
{ {
publish[v.first] = v.second; publish[v.first] = v.second;
} }
auto subscribe = mqtt["subscribe"].to<ArduinoJson::JsonObject>(); auto subscribe = mqtt["subscribe"].to<ArduinoJson::JsonObject>();
for (auto v : m_mqttPublish) for (auto v : m_mqttSubscribe)
{ {
subscribe[v.first] = v.second; subscribe[v.first] = v.second;
} }
@@ -275,7 +275,7 @@ private:
public: public:
// Globals // Globals
std::uint16_t m_globalLoopDelay = 1000; // in milliseconds std::uint16_t m_globalLoopDelay = 5000; // in milliseconds
// Ethernet // Ethernet
std::string m_ethHostname = "ETcontroller_PRO"; std::string m_ethHostname = "ETcontroller_PRO";
@@ -308,9 +308,10 @@ public:
std::string m_mqttClientName = "etcontrollerPRO"; std::string m_mqttClientName = "etcontrollerPRO";
std::map<const std::string, std::string> m_mqttSubscribe = { std::map<const std::string, std::string> m_mqttSubscribe = {
{"commands", "test/etcontroller/commands"}}; {"commands", "etcontroller/hw/commands"}};
std::map<const std::string, std::string> m_mqttPublish = { std::map<const std::string, std::string> m_mqttPublish = {
{"heatpump", "test/etcontroller/heatpump"}, {"answers", "etcontroller/hw/answers"},
{"temperature", "test/etcontroller/temperatures"}, {"heatpump", "etcontroller/hw/heatpump"},
{"irrigation", "test/etcontroller/irrigation"}}; {"temperatures", "etcontroller/hw/temperatures"},
}; {"irrigation", "etcontroller/hw/irrigation"}};
};

View File

@@ -14,7 +14,7 @@ namespace drivers
ledcAttach(c_buzzerPin, 1000, 8); ledcAttach(c_buzzerPin, 1000, 8);
m_bp.pin = c_buzzerPin; m_bp.pin = c_buzzerPin;
m_bp.beeperTask = NULL; m_bp.beeperTask = NULL;
beep(50, NOTE_G); beep(50, NOTE_C);
} }
Buzzer::~Buzzer() Buzzer::~Buzzer()

View File

@@ -23,7 +23,7 @@ namespace drivers
void Led::setColor(const color_t color) void Led::setColor(const color_t color)
{ {
blinkStop(); blinkStop();
rgbLedWrite(c_ledPin, color.r, color.g, color.b); rgbLedWrite(c_ledPin, color.g, color.r, color.b);
} }
void Led::blinkColor(const uint16_t tOn, const uint16_t tOff, const color_t color) void Led::blinkColor(const uint16_t tOn, const uint16_t tOff, const color_t color)

View File

@@ -20,6 +20,17 @@ namespace drivers
uint8_t b; uint8_t b;
} color_t; } color_t;
const color_t COLOR_RED = {255, 0, 0};
const color_t COLOR_ORANGE = {255, 127, 0};
const color_t COLOR_YELLOW = {255, 255, 0};
const color_t COLOR_CHARTREUSE = {127, 255, 0};
const color_t COLOR_GREEN = {0, 255, 0};
const color_t COLOR_CYAN = {0, 255, 255};
const color_t COLOR_SKYBLUE = {0, 127, 255};
const color_t COLOR_BLUE = {0, 0, 255};
const color_t COLOR_VIOLET = {127, 0, 255};
const color_t COLOR_MAGENTA = {255, 0, 255};
private: private:
typedef struct typedef struct
{ {

View File

@@ -87,7 +87,7 @@ namespace drivers
auto now = millis(); auto now = millis();
if ((now - m_lastAccess) < c_minDelay) // fixed milliseconds delay between commands to different devices if ((now - m_lastAccess) < c_minDelay) // fixed milliseconds delay between commands to different devices
{ {
LOG_WARN("MODBUS access delay", (now - m_lastAccess), "device", device); LOG_DEBUG("MODBUS access delay", (now - m_lastAccess), "device", device);
delay(now - m_lastAccess); delay(now - m_lastAccess);
} }
m_lastDevice = device; m_lastDevice = device;

49
src/commands.cpp Normal file
View File

@@ -0,0 +1,49 @@
#include <commands.h>
namespace commands
{
const ArduinoJson::JsonDocument Commands::setHPlimit(const devices_t &dev, const ArduinoJson::JsonDocument &params)
{
ArduinoJson::JsonDocument response;
if (!params["level"].is<std::string>())
{
LOG_ERROR("setHPlimit incorrect parameters");
return response;
}
const auto level = params["level"].as<std::string>();
if (!c_hpLimitsMap.contains(level))
{
LOG_ERROR("setHPlimit invalid level", level.c_str());
return response;
}
for (auto k : c_hpLimitsMap)
{
if (level == k.first && level != "UNLIMITED")
dev.io.digitalOutWrite(k.second, true);
else
dev.io.digitalOutWrite(k.second, false);
}
LOG_INFO("setHPlimit -> level", level.c_str());
return response;
}
const ArduinoJson::JsonDocument Commands::getHPpower(const devices_t &dev, const ArduinoJson::JsonDocument &params)
{
ArduinoJson::JsonDocument response;
const auto pinfo = dev.seneca.getAll();
response["cmd"] = "getHPpower";
auto values = response["params"].to<JsonObject>();
values["power"] = pinfo.pAct;
values["current"] = pinfo.a;
values["energy"] = pinfo.whPar;
LOG_INFO("getHPpower -> power", pinfo.pAct, "current", pinfo.a, "energy", pinfo.whPar);
return response;
}
const ArduinoJson::JsonDocument Commands::setHeating(const devices_t &dev, const ArduinoJson::JsonDocument &params)
{
ArduinoJson::JsonDocument response;
LOG_WARN("setHeating not yet implemented");
return response;
}
}

63
src/commands.h Normal file
View File

@@ -0,0 +1,63 @@
#pragma once
#include <DebugLog.h>
#include <Arduino.h>
#include <ArduinoJson.h>
#include <devices.h>
namespace commands
{
enum RO
{
P1,
P2,
P3,
P4,
NC_1,
NC_2,
PUMP_HT,
GND_FLOOR,
FR_FLOOR,
IRR_PUMP,
Z1,
Z2,
Z3,
AUX,
RETURN,
NC_3,
NC_4
};
const std::map<const std::string, uint8_t> c_hpLimitsMap = {{"P1", RO::P1},
{"P2", RO::P2},
{"P3", RO::P3},
{"P4", RO::P4},
{"UNLIMITED", RO::P1}};
const std::map<const std::string, uint8_t> c_heatingValveMap = {{"pump", RO::PUMP_HT},
{"first", RO::FR_FLOOR},
{"ground", RO::GND_FLOOR}};
const std::map<const std::string, uint8_t> c_irrigationValveMap = {{"ricircolo", RO::RETURN},
{"1", RO::Z1},
{"2", RO::Z2},
{"3", RO::Z3},
{"rubinetti", RO::AUX}};
class Commands
{
Commands() = delete;
public:
static const ArduinoJson::JsonDocument setHPlimit(const devices_t &dev, const ArduinoJson::JsonDocument &params);
static const ArduinoJson::JsonDocument getHPpower(const devices_t &dev, const ArduinoJson::JsonDocument &params);
static const ArduinoJson::JsonDocument setHeating(const devices_t &dev, const ArduinoJson::JsonDocument &params);
};
static const std::map<const std::string, std::function<const ArduinoJson::JsonDocument(const devices_t &, const ArduinoJson::JsonDocument &)>> commandMap = {
{"setHPlimit", Commands::setHPlimit},
{"getHPpower", Commands::getHPpower},
{"setHeating", Commands::setHeating}};
}

19
src/devices.h Normal file
View File

@@ -0,0 +1,19 @@
#pragma once
#include <PCF85063_Driver.h>
#include <R4DCB08_Driver.h>
#include <S50140_Driver.h>
#include <BUZZER_Driver.h>
#include <LED_Driver.h>
#include <ETH_Driver.h>
#include <digitalIO.h>
typedef struct
{
drivers::PCF85063 &rtc;
drivers::R4DCB08 &tmp;
drivers::S50140 &seneca;
drivers::Buzzer &buzzer;
drivers::Led &led;
digitalIO &io;
} devices_t;

View File

@@ -76,7 +76,7 @@ const std::vector<bool> digitalIO::digitalOutReadPort()
rv.reserve(getOutNum()); rv.reserve(getOutNum());
rv.insert(rv.begin(), locals.begin(), locals.end()); rv.insert(rv.begin(), locals.begin(), locals.end());
rv.insert(rv.end(), remotes.begin(), remotes.end()); rv.insert(rv.end(), remotes.begin(), remotes.end());
return std::move(rv); return rv;
} }
const bool digitalIO::digitalInRead(const uint8_t ch) const bool digitalIO::digitalInRead(const uint8_t ch)
@@ -104,7 +104,7 @@ const std::vector<bool> digitalIO::digitalInReadPort()
rv.reserve(getInNum()); rv.reserve(getInNum());
rv.insert(rv.begin(), locals.begin(), locals.end()); rv.insert(rv.begin(), locals.begin(), locals.end());
rv.insert(rv.end(), remotes.begin(), remotes.end()); rv.insert(rv.end(), remotes.begin(), remotes.end());
return std::move(rv); return rv;
} }
void digitalIO::reset() void digitalIO::reset()

View File

@@ -1,36 +1,23 @@
#define DEBUGLOG_DEFAULT_LOG_LEVEL_DEBUG
#include <Arduino.h> #include <Arduino.h>
#include <DebugLog.h> #include <DebugLog.h>
#include <DebugLogEnable.h> #include <DebugLogEnable.h>
#include <config.h> #include <config.h>
#include <PCF85063_Driver.h> #include <commands.h>
#include <R4DCB08_Driver.h>
#include <S50140_Driver.h>
#include <BUZZER_Driver.h>
#include <LED_Driver.h>
#include <ETH_Driver.h>
#include <digitalIO.h>
#include <mqtt.h> #include <mqtt.h>
#include <devices.h>
#include "utils.h" #include "utils.h"
/////////////// GLOBALS /////////////// /////////////// GLOBALS ///////////////
Config &conf = Config::getInstance(); Config &conf = Config::getInstance();
/////////////// GLOBALS /////////////// /////////////// GLOBALS ///////////////
void testAction(const ArduinoJson::JsonDocument &doc)
{
std::string message;
ArduinoJson::serializeJsonPretty(doc, message);
LOG_INFO("Received on testAction\n", message.c_str());
}
void setup() void setup()
{ {
Serial.begin(9600); Serial.begin(9600);
LOG_ATTACH_SERIAL(Serial); LOG_ATTACH_SERIAL(Serial);
LOG_SET_LEVEL(DebugLogLevel::LVL_INFO);
conf.init(); // read the configuration from internal flash conf.init(); // read the configuration from internal flash
} }
@@ -54,44 +41,54 @@ void loop()
auto io = digitalIO(i2c, bus, {conf.m_modbusRelayAddr}); auto io = digitalIO(i2c, bus, {conf.m_modbusRelayAddr});
// Initialize temperature sensors // Initialize temperature sensors
sensors = tmp.getNum(); sensors = tmp.getNum();
tmp.setCorrection(conf.m_tempCorrectionValues);
LOG_INFO("Temperature sensors connected ->", sensors); LOG_INFO("Temperature sensors connected ->", sensors);
// Create device structure to pass all devices in the callbacks as needed
devices_t devices(rtc, tmp, seneca, buzzer, led, io);
//////////////// DEVICES //////////////// //////////////// DEVICES ////////////////
//////////////// NETWORK //////////////// //////////////// NETWORK ////////////////
auto mqtt = MQTTwrapper(); auto mqtt = MQTTwrapper();
//////////////// NETWORK //////////////// //////////////// NETWORK ////////////////
std::function<void(const ArduinoJson::JsonDocument &)> mycallback = //////////////// MQTT ////////////////
[&io](const ArduinoJson::JsonDocument &doc) /////////////// CALLBACK //////////////
std::function<void(const ArduinoJson::JsonDocument &)> commandsCallback =
[&mqtt, &devices](const ArduinoJson::JsonDocument &doc)
{ {
std::vector<bool> v1 = {1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0}; if (!doc["cmd"].is<std::string>() || !doc["params"].is<ArduinoJson::JsonObject>())
std::vector<bool> v2 = {0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1}; {
std::vector<bool> v0(io.getOutNum(), 0); LOG_ERROR("Invalid Json Command");
return;
LOG_INFO("SET Digital Outputs V1: ", printBoolVec(v1).c_str()); }
io.digitalOutWritePort(v1); const std::string cmd = doc["cmd"].as<std::string>();
delay(100); ArduinoJson::JsonDocument params = doc["params"];
LOG_INFO("GET Digital Outputs V1: ", printBoolVec(io.digitalOutReadPort()).c_str()); if (commands::commandMap.contains(cmd))
delay(2000); { // call command from command map in this same thread (the MQTT thread)
LOG_INFO("Executing command", cmd.c_str());
LOG_INFO("SET Digital Outputs V2: ", printBoolVec(v2).c_str()); auto answer = std::move(commands::commandMap.at(cmd)(devices, params));
io.digitalOutWritePort(v2); if (answer.isNull())
delay(100); return;
LOG_INFO("GET Digital Outputs V2: ", printBoolVec(io.digitalOutReadPort()).c_str()); mqtt.publish(conf.m_mqttPublish["answers"], answer);
delay(2000); }
else
LOG_INFO("GET Digital Inputs: ", printBoolVec(io.digitalInReadPort()).c_str()); {
io.digitalOutWritePort(v0); LOG_ERROR("Unknown command", cmd.c_str());
}
}; };
//////////////// NETWORK //////////////// //////////////// NETWORK ////////////////
/////////////// CALLBACK //////////////// /////////////// CALLBACK ////////////////
Network.onEvent( Network.onEvent(
[&eth, &rtc, &mqtt, &buzzer, &led, &mycallback](arduino_event_id_t event, arduino_event_info_t info) -> void [&](arduino_event_id_t event, arduino_event_info_t info) -> void
{ {
eth.onEvent(event, info); // Arduino Ethernet event handler eth.onEvent(event, info); // Arduino Ethernet event handler
if (!eth.isConnected()) if (!eth.isConnected())
{
led.setColor(led.COLOR_RED);
return; return;
}
// Get RTC time at ethernet connection // Get RTC time at ethernet connection
time_t ntpTime; time_t ntpTime;
uint8_t timeRetries(0); uint8_t timeRetries(0);
@@ -100,20 +97,20 @@ void loop()
{ {
if (eth.getNtpTime(ntpTime) && rtc.setDatetime(drivers::PCF85063::fromEpoch(ntpTime))) if (eth.getNtpTime(ntpTime) && rtc.setDatetime(drivers::PCF85063::fromEpoch(ntpTime)))
{ {
// buzzer.beep(250, NOTE_F); buzzer.beep(250, NOTE_A);
led.setColor({255, 255, 0}); led.setColor(led.COLOR_ORANGE);
const drivers::PCF85063::datetime_t dt(drivers::PCF85063::fromEpoch(ntpTime)); const drivers::PCF85063::datetime_t dt(drivers::PCF85063::fromEpoch(ntpTime));
LOG_INFO("NTP Time: ", drivers::PCF85063::datetime2str(dt).c_str()); LOG_INFO("NTP Time Update: ", drivers::PCF85063::datetime2str(dt).c_str());
delay(100); break;
} }
break; delay(100);
} }
while (mqttRetries++ < conf.m_mqttRetries) while (mqttRetries++ < conf.m_mqttRetries)
{ {
if (mqtt.connect()) if (mqtt.connect())
{ {
mqtt.subscribe("test/esp32-in", testAction); led.setColor(led.COLOR_GREEN);
mqtt.subscribe("test/esp32-functional", mycallback); mqtt.subscribe(conf.m_mqttSubscribe["commands"], commandsCallback);
break; break;
} }
delay(100); delay(100);
@@ -126,81 +123,57 @@ void loop()
while (true) while (true)
{ {
LOG_INFO("[", k++, "] Loop");
const std::string timeStr(rtc.getTimeStr()); const std::string timeStr(rtc.getTimeStr());
LOG_INFO("Current Datetime", timeStr.c_str()); LOG_INFO("[", k++, "] Loop - Current Datetime", timeStr.c_str());
ArduinoJson::JsonDocument ts;
ts["loopIterator"] = k;
ts["currentTime"] = timeStr;
mqtt.publish("test/esp32-out", ts);
uint8_t i(0);
for (auto v : tmp.getTempAll())
{ {
LOG_INFO("Temperature channel", i++, "->", v); ArduinoJson::JsonDocument poll;
poll["cmd"] = "POLL";
auto params = poll["params"].to<ArduinoJson::JsonObject>();
params["time"] = timeStr;
params["number"] = k;
mqtt.publish(conf.m_mqttPublish["answers"], poll);
};
{
ArduinoJson::JsonDocument ti;
auto tempinfo = tmp.getTempAll();
ti["solar"] = tempinfo.at(0);
ti["acs"] = tempinfo.at(0);
ti["heating"] = tempinfo.at(0);
mqtt.publish(conf.m_mqttPublish["temperatures"], ti);
};
{
ArduinoJson::JsonDocument pi;
auto powerinfo = seneca.getAll();
pi["power"] = powerinfo.pAct;
pi["current"] = powerinfo.a;
pi["energy"] = powerinfo.whPar;
pi["voltage"] = powerinfo.v;
mqtt.publish(conf.m_mqttPublish["heatpump"], pi);
} }
LOG_INFO("Read Red"); if (io.digitalInRead(0)) // ROSSO - Config Reset
if (io.digitalInRead(0)) // rosso
{ {
std::vector<bool> v1 = {1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0}; LOG_WARN("Config RESET!");
std::vector<bool> v2 = {0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1}; buzzer.beep(450, NOTE_E);
std::vector<bool> v0(16, 0); delay(500);
LOG_INFO("SET Digital Outputs V1: ", printBoolVec(v1).c_str());
io.digitalOutWritePort(v1);
LOG_INFO("GET Digital Outputs V1: ", printBoolVec(io.digitalOutReadPort()).c_str());
delay(2000);
LOG_INFO("SET Digital Outputs V2: ", printBoolVec(v2).c_str());
io.digitalOutWritePort(v2);
LOG_INFO("GET Digital Outputs V2: ", printBoolVec(io.digitalOutReadPort()).c_str());
delay(2000);
LOG_INFO("GET Digital Inputs: ", printBoolVec(io.digitalInReadPort()).c_str());
delay(2000);
io.digitalOutWritePort(v0);
delay(2000);
}
LOG_INFO("Read Blue");
if (io.digitalInRead(8)) // blu
{
if (!buzzing)
{
buzzing = true;
buzzer.beepRepeat(100, 1000, NOTE_C);
led.blinkColor(100, 500, {255, 0, 255});
}
else
{
buzzer.beepStop();
led.blinkAlternate(500, 500, {255, 255, 0}, {0, 255, 255});
buzzing = false;
}
LOG_INFO("Buzzing -> ", buzzing ? "True" : "False");
}
LOG_INFO("Read Green");
if (io.digitalInRead(9))
{ // verde
conf.resetConfig(); conf.resetConfig();
} }
LOG_INFO("Read Yellow"); if (io.digitalInRead(1)) // GIALLO - Restart
if (io.digitalInRead(10)) {
{ // giallo LOG_WARN("RESTART!");
buzzer.beep(450, NOTE_D);
delay(100);
esp_restart(); esp_restart();
} }
drivers::S50140::powerinfo_t pinfo = seneca.getAll(); delay(conf.m_globalLoopDelay); // to avoid too fast loop
LOG_INFO("Power Info ==> V:", pinfo.v, "- A:", pinfo.a, "- W:", pinfo.pAct, "- F:", pinfo.f, "- Wh_t:", pinfo.whTot, "- Wh_p:", pinfo.whPar);
delay(conf.m_globalLoopDelay);
} }
//////////////////////////////////////// ////////////////////////////////////////
///////// MAIN LOOP INSIDE LOOP //////// ///////// MAIN LOOP INSIDE LOOP ////////
//////////////////////////////////////// ////////////////////////////////////////

View File

@@ -1,6 +1,6 @@
#include <mqtt.h> #include <mqtt.h>
#define STACK_DEPTH 4096 #define STACK_DEPTH 8192
#define PRIOTITY 2 #define PRIOTITY 2
MQTTwrapper::MQTTwrapper() : m_config(Config::getInstance()), m_tcp(NetworkClient()), m_client(PubSubClient(m_tcp)), m_loopHandle(NULL) MQTTwrapper::MQTTwrapper() : m_config(Config::getInstance()), m_tcp(NetworkClient()), m_client(PubSubClient(m_tcp)), m_loopHandle(NULL)

View File

@@ -1,7 +1,5 @@
#pragma once #pragma once
#define DEBUGLOG_DEFAULT_LOG_LEVEL_DEBUG
#include <DebugLog.h> #include <DebugLog.h>
#include <Arduino.h> #include <Arduino.h>
#include <ArduinoJson.h> #include <ArduinoJson.h>