6 Commits

Author SHA1 Message Date
Emanuele Trabattoni
b7881355a2 Config class as singleton with initializer in setup 2025-07-17 20:57:50 +02:00
Emanuele Trabattoni
92de57a760 Implemented config file and save to memory using ffat 2025-07-17 18:01:03 +02:00
Emanuele Trabattoni
0b5d725d3a Added Buzzer and RGB led drivers 2025-07-16 20:42:11 +02:00
Emanuele Trabattoni
30ed0d283a Fixed time format conversion to be static 2025-07-16 20:41:57 +02:00
Emanuele Trabattoni
3923aa3c05 Added power factor register 2025-07-16 20:41:38 +02:00
Emanuele Trabattoni
53b82c32c3 DebugLog level in every header 2025-07-14 11:35:19 +02:00
21 changed files with 703 additions and 59 deletions

3
data/example.json Normal file
View File

@@ -0,0 +1,3 @@
{
"data": "value"
}

6
fatfs_partition.csv Normal file
View File

@@ -0,0 +1,6 @@
# Name, Type, SubType, Offset, Size, Flags
nvs, data, nvs, 0x9000, 0x5000,
otadata, data, ota, 0xe000, 0x2000,
app0, app, ota_0, 0x10000, 0x300000,
app1, app, ota_1, 0x310000,0x300000,
ffat, data, fat, 0x610000,0x9E0000,
1 # Name Type SubType Offset Size Flags
2 nvs data nvs 0x9000 0x5000
3 otadata data ota 0xe000 0x2000
4 app0 app ota_0 0x10000 0x300000
5 app1 app ota_1 0x310000 0x300000
6 ffat data fat 0x610000 0x9E0000

View File

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

View File

@@ -0,0 +1,70 @@
#include <BUZZER_Driver.h>
#define TASK_PRIORITY 20
#define TASK_STACK 2048
#define OCTAVE 6
namespace drivers
{
Buzzer::Buzzer()
{
LOG_INFO("Initializing Beeper");
pinMode(buzzerPin, OUTPUT);
ledcAttach(buzzerPin, 1000, 8);
m_bp.pin = buzzerPin;
m_bp.beeperTask = NULL;
beep(50, NOTE_G);
}
Buzzer::~Buzzer()
{
beepStop();
ledcDetach(buzzerPin);
pinMode(buzzerPin, INPUT);
}
void Buzzer::beep(const uint16_t tBeep, const note_t note)
{
beepStop();
m_bp.tOn = tBeep;
m_bp.tOff = 0;
m_bp.note = note;
xTaskCreate(beepTask, "beeper", TASK_STACK, static_cast<void *>(&m_bp), TASK_PRIORITY, &m_bp.beeperTask);
}
void Buzzer::beepRepeat(const uint16_t tOn, const uint16_t tOff, const note_t note)
{
beepStop();
m_bp.tOn = tOn;
m_bp.tOff = tOff;
m_bp.note = note;
xTaskCreate(beepTask, "beeper", TASK_STACK, static_cast<void *>(&m_bp), TASK_PRIORITY, &m_bp.beeperTask);
}
void Buzzer::beepStop()
{
if (m_bp.beeperTask != NULL)
vTaskDelete(m_bp.beeperTask);
ledcWriteTone(m_bp.pin, 0); // off
m_bp.beeperTask = NULL;
}
void Buzzer::beepTask(void *params)
{
LOG_DEBUG("Beeper Task Created");
beep_params_t *bPar = static_cast<beep_params_t *>(params);
while (true)
{
ledcWriteNote(bPar->pin, bPar->note, OCTAVE); // on with selected note
vTaskDelay(pdMS_TO_TICKS(bPar->tOn));
ledcWriteTone(bPar->pin, 0); // off
if (bPar->tOff == 0)
break;
vTaskDelay(pdMS_TO_TICKS(bPar->tOff));
}
LOG_DEBUG("Beeper Task Ended");
bPar->beeperTask = NULL;
vTaskDelete(NULL);
}
}

38
lib/GPIO/BUZZER_Driver.h Normal file
View File

@@ -0,0 +1,38 @@
#pragma once
#include <Arduino.h>
#define DEBUGLOG_DEFAULT_LOG_LEVEL_INFO
#include <DebugLog.h>
namespace drivers
{
class Buzzer
{
const uint8_t buzzerPin = 46; // hardware assigned
typedef struct
{
note_t note;
uint8_t pin;
uint16_t tOn;
uint16_t tOff;
TaskHandle_t beeperTask;
} beep_params_t;
public:
Buzzer();
~Buzzer();
void beep(const uint16_t tBeep, const note_t note);
void beepRepeat(const uint16_t tOn, const uint16_t tOff, const note_t note);
void beepStop();
private:
static void beepTask(void *params);
private:
beep_params_t m_bp;
};
}

75
lib/GPIO/LED_Driver.cpp Normal file
View File

@@ -0,0 +1,75 @@
#include <LED_Driver.h>
#define TASK_PRIORITY 20
#define TASK_STACK 2048
namespace drivers
{
Led::Led()
{
LOG_INFO("Inizializing RGB Led");
pinMode(ledPin, OUTPUT);
m_lp.pin = ledPin;
m_lp.blinkTask = NULL;
}
Led::~Led()
{
setColor({0, 0, 0});
pinMode(ledPin, INPUT);
}
void Led::setColor(const color_t color)
{
blinkStop();
rgbLedWrite(ledPin, color.r, color.g, color.b);
}
void Led::blinkColor(const uint16_t tOn, const uint16_t tOff, const color_t color)
{
blinkStop();
m_lp.color1 = color;
m_lp.color2 = {0, 0, 0};
m_lp.tOn = tOn;
m_lp.tOff = tOff;
xTaskCreate(blinkTask, "blinker", TASK_STACK, static_cast<void *>(&m_lp), TASK_PRIORITY, &m_lp.blinkTask);
}
void Led::blinkAlternate(const uint16_t tOn, const uint16_t tOff, const color_t color1, const color_t color2)
{
{
blinkStop();
m_lp.color1 = color1;
m_lp.color2 = color2;
m_lp.tOn = tOn;
m_lp.tOff = tOff;
xTaskCreate(blinkTask, "blinker", TASK_STACK, static_cast<void *>(&m_lp), TASK_PRIORITY, &m_lp.blinkTask);
}
}
void Led::blinkStop()
{
if (m_lp.blinkTask != NULL)
vTaskDelete(m_lp.blinkTask);
m_lp.blinkTask = NULL;
}
void Led::blinkTask(void *params)
{
LOG_DEBUG("Blinker Task Created");
led_params_t *lPar = static_cast<led_params_t *>(params);
while (true)
{
rgbLedWrite(lPar->pin, lPar->color1.g, lPar->color1.r, lPar->color1.b);
vTaskDelay(pdMS_TO_TICKS(lPar->tOn));
rgbLedWrite(lPar->pin, lPar->color2.g, lPar->color2.r, lPar->color2.b); // off
if (lPar->tOff == 0)
break;
vTaskDelay(pdMS_TO_TICKS(lPar->tOff));
}
LOG_DEBUG("Blinker Task Ended");
lPar->blinkTask = NULL;
vTaskDelete(NULL);
}
}

50
lib/GPIO/LED_Driver.h Normal file
View File

@@ -0,0 +1,50 @@
#pragma once
#include <Arduino.h>
#define DEBUGLOG_DEFAULT_LOG_LEVEL_INFO
#include <DebugLog.h>
namespace drivers
{
class Led
{
const uint8_t ledPin = 38;
public:
typedef struct
{
uint8_t r;
uint8_t g;
uint8_t b;
} color_t;
private:
typedef struct
{
color_t color1;
color_t color2;
uint8_t pin;
uint16_t tOn;
uint16_t tOff;
TaskHandle_t blinkTask;
} led_params_t;
public:
Led();
~Led();
void setColor(const color_t color);
void blinkColor(const uint16_t tOn, const uint16_t tOff, const color_t color);
void blinkAlternate(const uint16_t tOn, const uint16_t tOff, const color_t color1, const color_t color2);
void blinkStop();
private:
static void blinkTask(void *params);
private:
led_params_t m_lp;
};
}

View File

@@ -1,4 +1,8 @@
#pragma once #pragma once
#define DEBUGLOG_DEFAULT_LOG_LEVEL_INFO
#include <DebugLog.h>
#include "I2C_Driver.h" #include "I2C_Driver.h"
/****************************************************** The macro defines the TCA9554PWR information ******************************************************/ /****************************************************** The macro defines the TCA9554PWR information ******************************************************/

View File

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

View File

@@ -1,6 +1,6 @@
#pragma once #pragma once
// #define DEBUGLOG_DEFAULT_LOG_LEVEL_TRACE #define DEBUGLOG_DEFAULT_LOG_LEVEL_INFO
#include <DebugLog.h> #include <DebugLog.h>
#include <Arduino.h> #include <Arduino.h>

View File

@@ -164,7 +164,7 @@ namespace drivers
return datetime2str(dt); return datetime2str(dt);
} }
PCF85063::datetime_t PCF85063::fromEpoch(time_t currentTime) const PCF85063::datetime_t PCF85063::fromEpoch(const time_t currentTime)
{ {
PCF85063::datetime_t tm; PCF85063::datetime_t tm;
struct tm *localTime = std::localtime(&currentTime); struct tm *localTime = std::localtime(&currentTime);
@@ -178,7 +178,7 @@ namespace drivers
return tm; return tm;
} }
const std::string PCF85063::datetime2str(datetime_t &datetime) const std::string PCF85063::datetime2str(const datetime_t &datetime)
{ {
tm dtime; tm dtime;
dtime.tm_sec = datetime.second; dtime.tm_sec = datetime.second;
@@ -188,7 +188,8 @@ namespace drivers
dtime.tm_mday = datetime.day; dtime.tm_mday = datetime.day;
dtime.tm_mon = datetime.month - 1; dtime.tm_mon = datetime.month - 1;
dtime.tm_year = datetime.year - 1900; // time offset in structure according cpp reference dtime.tm_year = datetime.year - 1900; // time offset in structure according cpp reference
return std::string(std::asctime(&dtime)); const std::string buf(std::asctime(&dtime));
return buf.substr(0, std::min(buf.find('\n'),buf.find('\r')));
} }
const uint8_t PCF85063::decToBcd(const int val) const uint8_t PCF85063::decToBcd(const int val)

View File

@@ -1,5 +1,8 @@
#pragma once #pragma once
#define DEBUGLOG_DEFAULT_LOG_LEVEL_INFO
#include <DebugLog.h>
#include "I2C_Driver.h" #include "I2C_Driver.h"
#include <string> #include <string>
@@ -130,10 +133,10 @@ namespace drivers
const bool readAlarm(datetime_t &time); const bool readAlarm(datetime_t &time);
const bool getAlarmFlag(uint8_t &flags); const bool getAlarmFlag(uint8_t &flags);
const std::string datetime2str(datetime_t &datetime);
const std::string getTimeStr(); const std::string getTimeStr();
static PCF85063::datetime_t fromEpoch(time_t currentTime); static const std::string datetime2str(const datetime_t &datetime);
static const PCF85063::datetime_t fromEpoch(const time_t currentTime);
private: private:
const uint8_t decToBcd(const int val); const uint8_t decToBcd(const int val);

View File

@@ -3,7 +3,7 @@
namespace drivers namespace drivers
{ {
S50140::S50140(drivers::MODBUS &bus, const uint8_t address) : m_bus(bus), m_address(address) S50140::S50140(drivers::MODBUS &bus, const uint8_t address) : m_bus(bus), m_address(address), m_lastRequest(millis())
{ {
} }
S50140::~S50140() S50140::~S50140()
@@ -18,6 +18,7 @@ namespace drivers
info.pAct = getPact(); info.pAct = getPact();
info.pApp = getPapp(); info.pApp = getPapp();
info.pRea = getPrea(); info.pRea = getPrea();
info.pf = getPf();
info.f = getF(); info.f = getF();
info.whTot = getWhTot(); info.whTot = getWhTot();
info.whPar = getWhPar(); info.whPar = getWhPar();
@@ -44,6 +45,10 @@ namespace drivers
{ {
return readFloatReg(REG_Prea); return readFloatReg(REG_Prea);
} }
const float_t S50140::getPf()
{
return readFloatReg(REG_Pf);
}
const float_t S50140::getF() const float_t S50140::getF()
{ {
return readFloatReg(REG_Freq); return readFloatReg(REG_Freq);
@@ -61,8 +66,8 @@ namespace drivers
{ {
auto now = millis(); auto now = millis();
if ((now - m_lastRequest) < minDelay) if ((now - m_lastRequest) < minDelay)
{ // minimum 500ms between requests { // minimum m_lastRequest between requests
delay(now - m_lastRequest); vTaskDelay(pdMS_TO_TICKS(now - m_lastRequest));
} }
m_lastRequest = now; m_lastRequest = now;
} }
@@ -90,21 +95,22 @@ namespace drivers
void S50140::resetPartialCounters() void S50140::resetPartialCounters()
{ {
uint8_t retries(0); uint8_t retries(0);
const uint16_t resetAll = 0x0A03; constexpr uint16_t nullVal = 0x0000;
const uint16_t stopAll = 0x0A02; constexpr uint16_t resetAll = 0x0A03;
const uint16_t startAll = 0x0A01; constexpr uint16_t stopAll = 0x0A02;
constexpr uint16_t startAll = 0x0A01;
while (retries++ < maxRetries) while (retries++ < maxRetries)
{ {
bool ok(true); bool ok(true);
delayRequest(); delayRequest();
LOG_WARN("Powermeter Counter STOP"); LOG_WARN("Powermeter Counter STOP");
ok &= m_bus.writeRegisters(m_address, REG_PartCount, {0x0000, stopAll}); ok &= m_bus.writeRegisters(m_address, REG_PartCount, {nullVal, stopAll});
delayRequest(); delayRequest();
LOG_WARN("Powermeter Counter RESET"); LOG_WARN("Powermeter Counter RESET");
ok &= m_bus.writeRegisters(m_address, REG_PartCount, {0x0000, resetAll}); ok &= m_bus.writeRegisters(m_address, REG_PartCount, {nullVal, resetAll});
delayRequest(); delayRequest();
LOG_WARN("Powermeter Counter START"); LOG_WARN("Powermeter Counter START");
ok &= m_bus.writeRegisters(m_address, REG_PartCount, {0x0000, startAll}); ok &= m_bus.writeRegisters(m_address, REG_PartCount, {nullVal, startAll});
if (ok) if (ok)
return; return;
LOG_ERROR("Unable to Reset Powermeter Partial Counters, device", m_address); LOG_ERROR("Unable to Reset Powermeter Partial Counters, device", m_address);

View File

@@ -1,5 +1,7 @@
#pragma once #pragma once
#define DEBUGLOG_DEFAULT_LOG_LEVEL_INFO
#include <DebugLog.h> #include <DebugLog.h>
#include <RS485_Driver.h> #include <RS485_Driver.h>
@@ -19,6 +21,7 @@ namespace drivers
const uint16_t REG_Papp = 0x102E; const uint16_t REG_Papp = 0x102E;
const uint16_t REG_Prea = 0x1036; const uint16_t REG_Prea = 0x1036;
const uint16_t REG_Freq = 0x1038; const uint16_t REG_Freq = 0x1038;
const uint16_t REG_Pf = 0x101E;
const uint16_t REG_WhTot = 0x1106; const uint16_t REG_WhTot = 0x1106;
const uint16_t REG_WhPart = 0x1400; const uint16_t REG_WhPart = 0x1400;
const uint16_t REG_Serial = 0x0500; const uint16_t REG_Serial = 0x0500;
@@ -43,6 +46,7 @@ namespace drivers
float_t pAct; float_t pAct;
float_t pApp; float_t pApp;
float_t pRea; float_t pRea;
float_t pf;
float_t f; float_t f;
float_t whTot; float_t whTot;
float_t whPar; float_t whPar;
@@ -59,6 +63,7 @@ namespace drivers
const float_t getPact(); const float_t getPact();
const float_t getPapp(); const float_t getPapp();
const float_t getPrea(); const float_t getPrea();
const float_t getPf();
const float_t getF(); const float_t getF();
const float_t getWhTot(); const float_t getWhTot();
const float_t getWhPar(); const float_t getWhPar();
@@ -75,6 +80,6 @@ namespace drivers
private: private:
const uint8_t m_address; const uint8_t m_address;
drivers::MODBUS &m_bus; drivers::MODBUS &m_bus;
uint64_t m_lastRequest = 0; uint64_t m_lastRequest;
}; };
} }

View File

@@ -1,5 +1,7 @@
#pragma once #pragma once
#define DEBUGLOG_DEFAULT_LOG_LEVEL_INFO
#include <DebugLog.h> #include <DebugLog.h>
#include <RS485_Driver.h> #include <RS485_Driver.h>

View File

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

View File

@@ -18,6 +18,11 @@ lib_deps =
knolleary/PubSubClient@^2.8 knolleary/PubSubClient@^2.8
robtillaart/CRC@^1.0.3 robtillaart/CRC@^1.0.3
hideakitai/DebugLog@^0.8.4 hideakitai/DebugLog@^0.8.4
build_type = release
board_build.filesystem = ffat
board_build.partitions = fatfs_partition.csv ; se stai usando uno custom
[env:esp32-s3-waveshare8-debug] [env:esp32-s3-waveshare8-debug]
platform = ${env:esp32-s3-waveshare8.platform} platform = ${env:esp32-s3-waveshare8.platform}
@@ -38,3 +43,6 @@ build_flags =
-fno-ipa-sra -fno-ipa-sra
-fno-tree-sra -fno-tree-sra
-fno-builtin -fno-builtin
board_build.filesystem = ffat
board_build.partitions = fatfs_partition.csv ; se stai usando uno custom

316
src/config.h Normal file
View File

@@ -0,0 +1,316 @@
#pragma once
#define DEBUGLOG_DEFAULT_LOG_LEVEL_DEBUG
#include <DebugLog.h>
#include <Arduino.h>
#include <ArduinoJson.h>
#include <FFat.h>
#include <mutex>
class FSmount
{
public:
FSmount()
{
if (!FFat.begin(false))
{
LOG_ERROR("Unable to mount filesystem without formatting");
if (!FFat.begin(true))
{
LOG_ERROR("Formatted and mounted filesystem");
}
}
LOG_INFO("Local Filesystem Mounted Correctly");
const auto totalBytes = FFat.totalBytes();
const auto freeBytes = FFat.freeBytes();
const auto usedBytes = FFat.usedBytes();
const auto mountPoint = FFat.mountpoint();
LOG_INFO("Local filesystem, total", totalBytes / 1024, "KB - used", usedBytes / 1024, "KB - free", freeBytes / 1024, "KB");
LOG_INFO("Local filesystem, mountpoint", mountPoint);
}
~FSmount()
{
FFat.end(); // unmout filesystem to avoid corruption
LOG_INFO("Local Filesystem Unmounted Correctly");
}
};
class Config
{
public:
static Config &getInstance()
{
static Config instance;
return instance;
}
private:
Config() = default;
Config(const Config &) = delete;
Config &operator=(const Config &) = delete;
public:
void init()
{
FSmount mount; // scoped mount of the filesystem
// Initialize and mount filesystem
LOG_INFO("Initializing Config");
if (!FFat.exists("/config.json"))
{
LOG_WARN("Initializing default config");
saveConfig();
}
File file = FFat.open("/config.json", FILE_READ, false);
if (!file)
{
LOG_ERROR("Unable to open config.json");
return;
}
if (ArduinoJson::deserializeJson(m_configJson, file) != ArduinoJson::DeserializationError::Ok)
{
LOG_ERROR("Unable to load config.json");
}
std::string loadedConf;
ArduinoJson::serializeJsonPretty(m_configJson, loadedConf);
LOG_INFO("Loaded Configuration\n", loadedConf.c_str());
deserialize(); // convert from json format to class members
file.close(); // close config file before unmounting filesystem
};
void updateConfig(ArduinoJson::JsonDocument &json)
{
std::lock_guard<std::mutex> lock(m_mutex);
{
FSmount mount;
m_configJson = json;
deserialize();
saveConfig();
}; // filesystem is unmounted here
delay(500);
esp_restart(); // configuration updates trigger a cpu restart
}
void resetConfig()
{
std::lock_guard<std::mutex> lock(m_mutex);
{
FSmount mount;
LOG_WARN("Removing config.json");
if (!FFat.remove("/config.json"))
{
LOG_ERROR("Unable to remove config.json");
}
LOG_WARN("Configuration reset, Restarting");
}; // filesystem is unmounted here
delay(500);
esp_restart();
}
private:
void saveConfig() // write configuration to flash memory
{
File file = FFat.open("/config.json", FILE_WRITE, true);
if (!file)
{
LOG_ERROR("Unable to open config.json for writing");
return;
}
serialize(); // serialize default configuration
if (ArduinoJson::serializeJson(m_configJson, file) == 0)
{
LOG_ERROR("Serialization Failed");
}
file.close();
}
//////////////////////////////////////////////////////////////
////////////// SERIALIZATION + DESERIALIZATION ///////////////
//////////////////////////////////////////////////////////////
void serialize()
{
// form class members to json document
{
auto globals = m_configJson["globals"].to<ArduinoJson::JsonObject>();
globals["loopDelay"] = m_globalLoopDelay;
};
{
auto ethernet = m_configJson["ethernet"].to<ArduinoJson::JsonObject>();
ethernet["hostname"] = m_ethHostname;
ethernet["ipAddr"] = m_ethIpAddr;
ethernet["netmask "] = m_ethNetmask;
ethernet["gateway "] = m_ethGateway;
};
{
auto modbus = m_configJson["modbus"].to<ArduinoJson::JsonObject>();
modbus["relayAddr"] = m_modbusRelayAddr;
modbus["temperatureAddr"] = m_modbusTemperatureAddr;
modbus["senecaAddr"] = m_modbusSenecaAddr;
modbus["flowmeterAddr"] = m_modbusFlowmeterAddr;
modbus["tankLevelAddr"] = m_modbusTankLevelAddr;
};
{
auto temperature = m_configJson["temperature"].to<ArduinoJson::JsonObject>();
temperature["expectedSensors"] = m_tempExpectedSensors;
auto values = temperature["correctionValues"].to<ArduinoJson::JsonArray>();
for (auto v : m_tempCorrectionValues)
{
values.add(v);
}
};
{
auto ntp = m_configJson["ntp"].to<ArduinoJson::JsonObject>();
ntp["pool"] = m_ntpPool;
ntp["timezone"] = m_ntpTimezone;
ntp["updateInterval"] = m_ntpUpdateInterval;
ntp["retries"] = m_ntpRetries;
};
{
auto mqtt = m_configJson["mqtt"].to<ArduinoJson::JsonObject>();
mqtt["host"] = m_mqttHost;
mqtt["port"] = m_mqttPort;
mqtt["loopTime"] = m_mqttLoopTime;
mqtt["clientName"] = m_mqttClientName;
mqtt["retries"] = m_mqttRetries;
auto publish = mqtt["publish"].to<ArduinoJson::JsonObject>();
for (auto v : m_mqttSubscribe)
{
publish[v.first] = v.second;
}
auto subscribe = mqtt["subscribe"].to<ArduinoJson::JsonObject>();
for (auto v : m_mqttPublish)
{
subscribe[v.first] = v.second;
}
};
};
void deserialize()
{ // from json document to class members
if (m_configJson.isNull())
{
LOG_ERROR("NUll config document");
return;
}
{
auto globals = m_configJson["globals"];
m_globalLoopDelay = globals["loopDelay"].as<uint16_t>();
};
{
auto ethernet = m_configJson["ethernet"];
m_ethHostname = ethernet["hostname"].as<std::string>();
m_ethIpAddr = ethernet["ipAddr"].as<std::string>();
m_ethNetmask = ethernet["netmask"].as<std::string>();
m_ethGateway = ethernet["gateway"].as<std::string>();
};
{
auto modbus = m_configJson["modbus"];
m_modbusRelayAddr = modbus["relayAddr"].as<uint8_t>();
m_modbusTemperatureAddr = modbus["temperatureAddr"].as<uint8_t>();
m_modbusSenecaAddr = modbus["senecaAddr"].as<uint8_t>();
m_modbusFlowmeterAddr = modbus["flowmeterAddr"].as<uint8_t>();
m_modbusTankLevelAddr = modbus["tankLevelAddr"].as<uint8_t>();
};
{
auto temperature = m_configJson["temperature"];
m_tempExpectedSensors = temperature["expectedSensors"].as<uint8_t>();
auto values = temperature["correctionValues"].as<JsonArray>();
m_tempCorrectionValues.reserve(values.size());
for (auto v : values)
{
m_tempCorrectionValues.push_back(v.as<float>());
}
};
{
auto ntp = m_configJson["ntp"];
m_ntpPool = ntp["pool"].as<std::string>();
m_ntpTimezone = ntp["timezone"].as<uint16_t>();
m_ntpUpdateInterval = ntp["updateInterval"].as<uint16_t>();
m_ntpRetries = ntp["retries"].as<uint8_t>();
};
{
auto mqtt = m_configJson["mqtt"];
m_mqttHost = mqtt["host"].as<std::string>();
m_mqttPort = mqtt["port"].as<uint16_t>();
m_mqttLoopTime = mqtt["loopTime"].as<uint16_t>();
m_mqttRetries = mqtt["retries"].as<uint16_t>();
auto subscribe = mqtt["subsribe"].as<ArduinoJson::JsonObject>();
for (auto v : subscribe)
{
m_mqttSubscribe[v.key().c_str()] = v.value().as<std::string>();
}
auto publish = mqtt["publish"].as<ArduinoJson::JsonObject>();
for (auto v : publish)
{
m_mqttPublish[v.key().c_str()] = v.value().as<std::string>();
}
};
};
private:
ArduinoJson::JsonDocument m_configJson;
std::mutex m_mutex;
public:
// Globals
std::uint16_t m_globalLoopDelay = 1000; // in milliseconds
// Ethernet
std::string m_ethHostname = "ETcontroller_PRO";
std::string m_ethIpAddr = "10.0.2.251";
std::string m_ethNetmask = "255.255.255.0";
std::string m_ethGateway = "10.0.2.1";
// MODBUS
uint8_t m_modbusRelayAddr = 0x01;
uint8_t m_modbusTemperatureAddr = 0xAA;
uint8_t m_modbusSenecaAddr = 0xBB;
uint8_t m_modbusFlowmeterAddr = 0xCC;
uint8_t m_modbusTankLevelAddr = 0xDD;
// Temperature Board
uint8_t m_tempExpectedSensors = 1;
std::vector<float> m_tempCorrectionValues = std::vector<float>(8, 0.0f);
// NTP
std::string m_ntpPool = "pool.ntp.org";
uint16_t m_ntpTimezone = 3600; // GTM +1
uint16_t m_ntpUpdateInterval = 3600; // every hour
uint8_t m_ntpRetries = 5;
// MQTT
std::string m_mqttHost = "10.0.2.249";
uint16_t m_mqttPort = 1883;
uint16_t m_mqttLoopTime = 100; // in milliseconds
uint8_t m_mqttRetries = 5;
std::string m_mqttClientName = "etcontrollerPRO";
std::map<const std::string, std::string> m_mqttSubscribe = {
{"commands", "test/etcontroller/commands"}};
std::map<const std::string, std::string> m_mqttPublish = {
{"heatpump", "test/etcontroller/heatpump"},
{"temperature", "test/etcontroller/temperatures"},
{"irrigation", "test/etcontroller/irrigation"}};
};

View File

@@ -1,7 +1,10 @@
#pragma once #pragma once
#define DEBUGLOG_DEFAULT_LOG_LEVEL_INFO
#include <DebugLog.h> #include <DebugLog.h>
#include <Arduino.h> #include <Arduino.h>
#include <remoteIO.h> #include <remoteIO.h>
#include <TCA9554PWR_Driver.h> #include <TCA9554PWR_Driver.h>

View File

@@ -2,18 +2,26 @@
#include <DebugLog.h> #include <DebugLog.h>
#include <DebugLogEnable.h> #include <DebugLogEnable.h>
#include <Arduino.h> #include <Arduino.h>
#include <PubSubClient.h> #include <PubSubClient.h>
#include <config.h>
#include <PCF85063_Driver.h> #include <PCF85063_Driver.h>
#include <R4DCB08_Driver.h> #include <R4DCB08_Driver.h>
#include <S50140_Driver.h> #include <S50140_Driver.h>
#include <BUZZER_Driver.h>
#include <LED_Driver.h>
#include <ETH_Driver.h> #include <ETH_Driver.h>
#include <digitalIO.h> #include <digitalIO.h>
#include "utils.h" #include "utils.h"
/////////////// GLOBALS ///////////////
Config& conf = Config::getInstance();
/////////////// GLOBALS ///////////////
void callback(char *topic, uint8_t *payload, unsigned int length) void callback(char *topic, uint8_t *payload, unsigned int length)
{ {
std::string pl; std::string pl;
@@ -34,61 +42,81 @@ void myTask(void *mqtt)
vTaskDelete(NULL); // delete the current task vTaskDelete(NULL); // delete the current task
}; };
/////////////// GLOBALS ///////////////
void setup() void setup()
{ {
Serial.begin(9600); Serial.begin(9600);
LOG_ATTACH_SERIAL(Serial); LOG_ATTACH_SERIAL(Serial);
conf.init();
} }
void loop() void loop()
{ {
const uint8_t tempBoardAddr(0xAA);
const uint8_t relayBoardAddr(0x01);
const uint8_t senecaMeterAddr(0xBB);
const uint8_t baseRegister(0x00); const uint8_t baseRegister(0x00);
uint16_t k(0); uint16_t k(0);
uint8_t ethRetries(0);
uint8_t sensors(0); uint8_t sensors(0);
bool buzzing(false);
//////////////// DEVICES //////////////// //////////////// DEVICES ////////////////
// Declared here to keep devices local to the main loop otherwise the kernel crashes // // Declared here to keep devices local to the main loop otherwise the kernel crashes //
auto i2c = drivers::I2C(); auto i2c = drivers::I2C();
auto bus = drivers::MODBUS(9600, SERIAL_8N1); auto bus = drivers::MODBUS(9600, SERIAL_8N1);
auto rtc = drivers::PCF85063(i2c, PCF85063_ADDRESS); auto rtc = drivers::PCF85063(i2c, PCF85063_ADDRESS);
auto eth = drivers::Ethernet("waveshare-test"); auto eth = drivers::Ethernet(conf.m_ethHostname);
auto tmp = drivers::R4DCB08(bus, tempBoardAddr); auto tmp = drivers::R4DCB08(bus, conf.m_modbusTemperatureAddr);
delay(100); delay(100);
auto io = digitalIO(i2c, bus, {relayBoardAddr}); auto io = digitalIO(i2c, bus, {conf.m_modbusRelayAddr});
delay(100); delay(100);
auto seneca = drivers::S50140(bus, senecaMeterAddr); auto seneca = drivers::S50140(bus, conf.m_modbusSenecaAddr);
auto buzzer = drivers::Buzzer();
Network.onEvent([&eth](arduino_event_id_t event, arduino_event_info_t info) auto led = drivers::Led();
{ eth.onEvent(event, info); }); //////////////// DEVICES ////////////////
while (!eth.isConnected() && ethRetries++ < 5)
{
LOG_WARN("Waiting for Ethernet retry", ethRetries);
delay(1000);
}
// Initialize temperature sensors // Initialize temperature sensors
sensors = tmp.getNum(); sensors = tmp.getNum();
LOG_INFO("Temperature sensors connected ->", sensors); LOG_INFO("Temperature sensors connected ->", sensors);
// Get RTC time at startup //////////////// NETWORK ////////////////
time_t ntpTime; // MQTT Test //
drivers::PCF85063::datetime_t dt;
// MQTT Test
NetworkClient tcp; NetworkClient tcp;
PubSubClient mqtt(tcp); PubSubClient mqtt(tcp);
mqtt.setServer(conf.m_mqttHost.c_str(), conf.m_mqttPort);
mqtt.setServer("10.0.2.249", 1883);
mqtt.setCallback(callback); mqtt.setCallback(callback);
mqtt.connect("esp32-client"); //////////////// NETWORK ////////////////
//////////////// NETWORK ////////////////
/////////////// CALLBACK ////////////////
Network.onEvent(
[&eth, &rtc, &mqtt, &buzzer, &led](arduino_event_id_t event, arduino_event_info_t info) -> void
{
eth.onEvent(event, info); // Arduino Ethernet event handler
if (!eth.isConnected())
return;
// Get RTC time at ethernet connection
time_t ntpTime;
uint8_t timeRetries(0);
uint8_t mqttRetries(0);
while (timeRetries++ < conf.m_ntpRetries)
{
if (eth.getNtpTime(ntpTime) && rtc.setDatetime(drivers::PCF85063::fromEpoch(ntpTime)))
{
buzzer.beep(250, NOTE_F);
led.setColor({255, 255, 0});
const drivers::PCF85063::datetime_t dt(drivers::PCF85063::fromEpoch(ntpTime));
LOG_INFO("NTP Time: ", drivers::PCF85063::datetime2str(dt).c_str());
delay(100);
}
break;
}
while (mqttRetries++ < conf.m_mqttRetries)
{
if (!mqtt.connected() && mqtt.connect(conf.m_mqttClientName.c_str()))
{
mqtt.subscribe("test/esp32-in"); mqtt.subscribe("test/esp32-in");
xTaskCreatePinnedToCore(myTask, "mqttLoop", 4096, &mqtt, 2, NULL, 1); xTaskCreatePinnedToCore(myTask, "mqttLoop", 4096, &mqtt, 2, NULL, 1);
break;
}
delay(100);
}
});
//////////////////////////////////////// ////////////////////////////////////////
///////// MAIN LOOP INSIDE LOOP //////// ///////// MAIN LOOP INSIDE LOOP ////////
@@ -98,11 +126,9 @@ void loop()
{ {
LOG_INFO("[", k++, "] Loop"); LOG_INFO("[", k++, "] Loop");
eth.getNtpTime(ntpTime); const std::string timeStr(rtc.getTimeStr());
dt = drivers::PCF85063::fromEpoch(ntpTime); LOG_INFO("Current Datetime", timeStr.c_str());
LOG_INFO("Network Datetime", rtc.datetime2str(dt).c_str()); mqtt.publish("test/esp32-out", ("[" + std::to_string(k) + "] -> " + timeStr).c_str());
LOG_INFO("Current Datetime", rtc.getTimeStr().c_str());
mqtt.publish("test/esp32-out", ("[" + std::to_string(k) + "] -> " + rtc.getTimeStr()).c_str());
uint8_t i(0); uint8_t i(0);
for (auto v : tmp.getTempAll()) for (auto v : tmp.getTempAll())
@@ -116,16 +142,11 @@ void loop()
LOG_INFO("Temperature correction channel", i++, "tc", v); LOG_INFO("Temperature correction channel", i++, "tc", v);
} }
for (auto j(0); j < io.getOutNum(); j++) delay(100);
{
LOG_INFO("Input", j, io.digitalIORead(j) ? "True" : "False");
delay(50);
}
drivers::S50140::powerinfo_t pinfo = seneca.getAll(); drivers::S50140::powerinfo_t pinfo = seneca.getAll();
LOG_INFO("Power Info ==> V:", pinfo.v, "- A:", pinfo.a, "- W:", pinfo.pAct, "- F:", pinfo.f, "- Wh_t:", pinfo.whTot, "- Wh_p:", pinfo.whPar); LOG_INFO("Power Info ==> V:", pinfo.v, "- A:", pinfo.a, "- W:", pinfo.pAct, "- F:", pinfo.f, "- Wh_t:", pinfo.whTot, "- Wh_p:", pinfo.whPar);
if (io.digitalIORead(0)) if (io.digitalIORead(0)) // rosso
{ {
uint8_t regset(seneca.getRegset()); uint8_t regset(seneca.getRegset());
uint16_t countStat(seneca.getCounterStatus()); uint16_t countStat(seneca.getCounterStatus());
@@ -133,8 +154,33 @@ void loop()
LOG_INFO("Counter Status: ", countStat); LOG_INFO("Counter Status: ", countStat);
seneca.resetPartialCounters(); seneca.resetPartialCounters();
} }
delay(100);
if (io.digitalIORead(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");
}
delay(2000); if(io.digitalIORead(9)) { // verde
conf.resetConfig();
}
if(io.digitalIORead(10)) { // giallo
esp_restart();
}
delay(conf.m_globalLoopDelay);
} }
//////////////////////////////////////// ////////////////////////////////////////

View File

@@ -1,5 +1,7 @@
#pragma once #pragma once
#define DEBUGLOG_DEFAULT_LOG_LEVEL_INFO
#include <DebugLog.h> #include <DebugLog.h>
#include <RS485_Driver.h> #include <RS485_Driver.h>