Compare commits
40 Commits
mqtt-wrapp
...
pro-develo
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1457c6f1d2 | ||
|
|
d07ee18a22 | ||
|
|
9a0bc4c03f | ||
|
|
df66a9d076 | ||
|
|
145698d3b9 | ||
|
|
0952be3141 | ||
|
|
6a6931bde0 | ||
|
|
4aeffc76b0 | ||
|
|
cde86a7f99 | ||
|
|
f9c5ab86ef | ||
|
|
fc2687947a | ||
|
|
637304781c | ||
|
|
c973632fb8 | ||
| a79c4f8ca7 | |||
|
|
bbf604e1a8 | ||
|
|
e37aa58398 | ||
|
|
5bff567863 | ||
|
|
80fda62344 | ||
|
|
4a1e944ea2 | ||
|
|
a1a66ebf8e | ||
|
|
b19ed89158 | ||
|
|
25251785fa | ||
| 0e842294be | |||
| 57957740d9 | |||
|
|
25aa2d6cb6 | ||
|
|
eaa643bf3c | ||
|
|
abe0cb0839 | ||
|
|
fc2316b0f2 | ||
| fa1b288f4d | |||
|
|
1110648978 | ||
|
|
581eca124e | ||
|
|
1d1eb6fbfa | ||
|
|
ad90702ab6 | ||
|
|
448e1bad15 | ||
|
|
91f4c5c750 | ||
|
|
5459148538 | ||
|
|
74a97a7dd6 | ||
|
|
31c6cd9606 | ||
|
|
bb0832ad4f | ||
|
|
bea42c9a36 |
72
.vscode/settings.json
vendored
72
.vscode/settings.json
vendored
@@ -1,5 +1,75 @@
|
||||
{
|
||||
"files.associations": {
|
||||
"esp32-hal.h": "c"
|
||||
"*.h": "cpp",
|
||||
"esp32-hal.h": "c",
|
||||
"array": "cpp",
|
||||
"atomic": "cpp",
|
||||
"bit": "cpp",
|
||||
"bitset": "cpp",
|
||||
"cctype": "cpp",
|
||||
"charconv": "cpp",
|
||||
"chrono": "cpp",
|
||||
"clocale": "cpp",
|
||||
"cmath": "cpp",
|
||||
"codecvt": "cpp",
|
||||
"compare": "cpp",
|
||||
"concepts": "cpp",
|
||||
"condition_variable": "cpp",
|
||||
"cstdarg": "cpp",
|
||||
"cstddef": "cpp",
|
||||
"cstdint": "cpp",
|
||||
"cstdio": "cpp",
|
||||
"cstdlib": "cpp",
|
||||
"cstring": "cpp",
|
||||
"ctime": "cpp",
|
||||
"cwchar": "cpp",
|
||||
"cwctype": "cpp",
|
||||
"deque": "cpp",
|
||||
"list": "cpp",
|
||||
"map": "cpp",
|
||||
"set": "cpp",
|
||||
"string": "cpp",
|
||||
"unordered_map": "cpp",
|
||||
"unordered_set": "cpp",
|
||||
"vector": "cpp",
|
||||
"exception": "cpp",
|
||||
"algorithm": "cpp",
|
||||
"functional": "cpp",
|
||||
"iterator": "cpp",
|
||||
"memory": "cpp",
|
||||
"memory_resource": "cpp",
|
||||
"netfwd": "cpp",
|
||||
"numeric": "cpp",
|
||||
"optional": "cpp",
|
||||
"random": "cpp",
|
||||
"ratio": "cpp",
|
||||
"source_location": "cpp",
|
||||
"string_view": "cpp",
|
||||
"system_error": "cpp",
|
||||
"tuple": "cpp",
|
||||
"type_traits": "cpp",
|
||||
"utility": "cpp",
|
||||
"format": "cpp",
|
||||
"initializer_list": "cpp",
|
||||
"iomanip": "cpp",
|
||||
"iosfwd": "cpp",
|
||||
"iostream": "cpp",
|
||||
"istream": "cpp",
|
||||
"limits": "cpp",
|
||||
"mutex": "cpp",
|
||||
"new": "cpp",
|
||||
"numbers": "cpp",
|
||||
"ostream": "cpp",
|
||||
"semaphore": "cpp",
|
||||
"span": "cpp",
|
||||
"sstream": "cpp",
|
||||
"stdexcept": "cpp",
|
||||
"stop_token": "cpp",
|
||||
"streambuf": "cpp",
|
||||
"text_encoding": "cpp",
|
||||
"thread": "cpp",
|
||||
"cinttypes": "cpp",
|
||||
"typeinfo": "cpp",
|
||||
"variant": "cpp"
|
||||
}
|
||||
}
|
||||
63
README.md
63
README.md
@@ -1,3 +1,64 @@
|
||||
# ETcontroller_PRO
|
||||
|
||||
Nuova versione di ETcontroller hardware (lo scatolo) basata su scheda ESP 32 Waveshare [https://www.waveshare.com/wiki/ESP32-S3-ETH-8DI-8RO#Resources]
|
||||
### Nuova versione di ETcontroller hardware (lo scatolo) basata su scheda ESP32-S3 Waveshare
|
||||
[https://www.waveshare.com/wiki/ESP32-S3-ETH-8DI-8RO#Resources]
|
||||
|
||||
## Tool necessari:
|
||||
|
||||
### Plugin VScode
|
||||
* VScode
|
||||
* PlatformIO Plugin per VScode
|
||||
* GitGraph
|
||||
* C/C++ Extension Pack
|
||||
|
||||
### Toolchain e Librerie
|
||||
Dipendenze e toolchain vengono installate direttamente da PlatformIO.
|
||||
Il firmware e' basato sul framework _Arduino_ e piattaforma _esp-idf_ di Espressif.
|
||||
La versione della piattaforma inclusa in PlatformIO e' deprecata, quindi e' necessario scaicarne una indipendente da GitHub. La versione corrente e' listata nel file `platformio.ini` nella root directory, se fosse necessario aggiornarla si trova a: [https://github.com/pioarduino/platform-espressif32/releases]
|
||||
Vale lo stesso per le librerie dipendenti, se non fossero disponibili tramite PlatformIO si possono cercare su GitHub e scaricare manualmente.
|
||||
|
||||
### Documentazione aggiuntiva
|
||||
Nella cartella `docs` sono presenti i datasheet di tutti i device collegati.
|
||||
I driver sono spesso scritti a manina usando quei documenti come reference.
|
||||
|
||||
## Configurazione Hardware e Build
|
||||
|
||||
### Definizione della board
|
||||
Prima di poter compilare e' necessario copiare il file di descrizione della board `esp32-s3-waveshare8.json` che si trova in questa root directory nella cartella delle board di PlatformIO.
|
||||
* Per Windows `%USERPROFILE%\.platformio\platforms\espressif32\boards`
|
||||
* Per Linux `$HOME/.platformio/platforms/espressif32/boards`
|
||||
* Per MAC `dovrebbe essere come linux`
|
||||
|
||||
### Cofigurazioni di build
|
||||
Le configurazioni disponibili sono:
|
||||
* **Release**: `esp32-s3-waveshare8`
|
||||
Build adatta per il deploy, log su seriale ma non e' possibile il debug con PlatformIO
|
||||
* **Debug**: `esp32-s3-waveshare8-debug`
|
||||
Build per il debug del codice in circuit, attenzione che quando il debugger e' attivo tutti i procesi temporizzati dallo scheduler vanno in pausa per cui le funzioni di rete e comunicazione con le perriferche potrebbero non funzionare correttamente.
|
||||
|
||||
Il cambio di configurazione tra Release e Debug causa un rebuild completo del codice.
|
||||
|
||||
### Partizioni della flash
|
||||
La flash dell'ESP32 e' partizionata secondo lo schema definito in `fatfs_partitions.csv`, che deve rimanere nella root del progetto.
|
||||
Le partizioni sono come segue"
|
||||
* **NVS + OTADATA**: Non toccare assoutamente, contengono il bootloader, se si toccano queste addio programmazione via USB, ci vuole il tool apposta.
|
||||
* **APP_0 + APP_1**: contengono entrambe il firmware, quando avviene un aggiornamento via OTA una partizione e' in stby e riceve il firmware aggiornato. Se l'aggiornamento va a buon fine il boot successivo avviene dalla partizione aggiornata e cosi' via per i successivi.
|
||||
* **FFAT** e' una partizione accessibile dal firmware per essere usata come memoria permanente. Montata dalla classe FSMount. E' di circa 9MB e si comporta come un filesystem FAT32.
|
||||
**Attenzione che e' la flash integrata nel micro, evitare letture e scritture troppo frequenti per non bruciarla**
|
||||
|
||||
### Metodi di upload
|
||||
La porta di upload e' configurata con `upload_protocol` nel file `platformio.ini`.
|
||||
I valori possibili sono:
|
||||
* **_esptool_** per upload USB
|
||||
* **_espota_** per upload via Rete.
|
||||
In questo caso il valore di _upload_port_ deve essere l'indirizzo IP della scheda, che sia settato statico o da DHCP.
|
||||
E' possibile ce si debba permettere a VScode di aggiungere una regola al firewall del PC per permettere il collegamento "unsafe" via UDP
|
||||
|
||||
Il metodo di defaut e' tramite la porta USB, che ha un nome diverso a seconda del sistema operativo host e della porta a cui viene collegata.
|
||||
Se si vuole utilizzare il metoto OTA via rete, questo va abilitato dalla scheda (per motivi di sicurezza).
|
||||
Per abilitare OTA resettare la scheda e nel momento del boot tenere premuto il pulsante blu fino a che il buzzer smette di bippare e il led inizia a lampeggiare verde e giallo alternati: da quel momento e' possibile aggiornare via rete.
|
||||
_Ogni aggiornamento causa il reboot della scheda._
|
||||
|
||||
### Logica del Firmware, come funziona?
|
||||
|
||||
[TODO]
|
||||
BIN
docs/ESP32_clock_adjust.xlsx
Normal file
BIN
docs/ESP32_clock_adjust.xlsx
Normal file
Binary file not shown.
@@ -53,7 +53,7 @@
|
||||
"params": null
|
||||
},
|
||||
{
|
||||
"cmd": "getTankLevel",
|
||||
"cmd": "getTankInfo",
|
||||
"params": null
|
||||
},
|
||||
{
|
||||
@@ -64,11 +64,11 @@
|
||||
"cmd": "setIrrigation",
|
||||
"params": {
|
||||
"zone": [
|
||||
"Ricircolo",
|
||||
"ricircolo",
|
||||
"1",
|
||||
"2",
|
||||
"3",
|
||||
"Rubinetti"
|
||||
"rubinetti"
|
||||
],
|
||||
"timeOn": 120,
|
||||
"timePause": 2
|
||||
@@ -82,7 +82,7 @@
|
||||
"cmd": "setCronJob",
|
||||
"params": {
|
||||
"name": "nomedeljob",
|
||||
"timeStr": "* * * 10,45 5 *",
|
||||
"cronExpr": "* * * 10,45 5 *",
|
||||
"action": "qua ci va un dizionario come se arrivasse da mqtt, cosi li interpreto alla stessa maniera"
|
||||
}
|
||||
},
|
||||
|
||||
54
esp32-s3-waveshare8.json
Normal file
54
esp32-s3-waveshare8.json
Normal file
@@ -0,0 +1,54 @@
|
||||
{
|
||||
"build": {
|
||||
"arduino": {
|
||||
"ldscript": "esp32s3_out.ld",
|
||||
"partitions": "app3M_fat9M_16MB.csv"
|
||||
},
|
||||
"core": "esp32",
|
||||
"extra_flags": [
|
||||
"-DARDUINO_ESP32S3_DEV",
|
||||
"-DARDUINO_USB_MODE=1",
|
||||
"-DARDUINO_RUNNING_CORE=1",
|
||||
"-DARDUINO_EVENT_RUNNING_CORE=1",
|
||||
"-DARDUINO_USB_CDC_ON_BOOT=1"
|
||||
],
|
||||
"partitions": "app3M_fat9M_16MB.csv",
|
||||
"f_cpu": "240000000L",
|
||||
"f_flash": "80000000L",
|
||||
"flash_mode": "qio",
|
||||
"hwids": [
|
||||
[
|
||||
"0x303A",
|
||||
"0x1001"
|
||||
]
|
||||
],
|
||||
"mcu": "esp32s3",
|
||||
"variant": "esp32s3"
|
||||
},
|
||||
"connectivity": [
|
||||
"bluetooth",
|
||||
"wifi",
|
||||
"ethernet"
|
||||
],
|
||||
"debug": {
|
||||
"default_tool": "esp-builtin",
|
||||
"onboard_tools": [
|
||||
"esp-builtin"
|
||||
],
|
||||
"openocd_target": "esp32s3.cfg"
|
||||
},
|
||||
"frameworks": [
|
||||
"arduino",
|
||||
"espidf"
|
||||
],
|
||||
"name": "Espressif ESP32-S3-Waveshare_8RO-8DI",
|
||||
"upload": {
|
||||
"flash_size": "16MB",
|
||||
"maximum_ram_size": 327680,
|
||||
"maximum_size": 16777216,
|
||||
"require_upload_port": true,
|
||||
"speed": 921600
|
||||
},
|
||||
"url": "https://docs.espressif.com/projects/esp-idf/en/latest/esp32s3/hw-reference/esp32s3/user-guide-devkitm-1.html",
|
||||
"vendor": "Espressif"
|
||||
}
|
||||
@@ -5,39 +5,7 @@
|
||||
#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");
|
||||
}
|
||||
};
|
||||
#include <fsmount.h>
|
||||
|
||||
class Config
|
||||
{
|
||||
@@ -88,7 +56,14 @@ public:
|
||||
file.close(); // close config file before unmounting filesystem
|
||||
};
|
||||
|
||||
void updateConfig(ArduinoJson::JsonDocument &json)
|
||||
ArduinoJson::JsonDocument &getConfig()
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(m_mutex);
|
||||
serialize();
|
||||
return m_configJson;
|
||||
}
|
||||
|
||||
void setConfig(const ArduinoJson::JsonDocument &json)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(m_mutex);
|
||||
{
|
||||
@@ -97,8 +72,6 @@ public:
|
||||
deserialize();
|
||||
saveConfig();
|
||||
}; // filesystem is unmounted here
|
||||
delay(500);
|
||||
esp_restart(); // configuration updates trigger a cpu restart
|
||||
}
|
||||
|
||||
void resetConfig()
|
||||
@@ -150,8 +123,8 @@ private:
|
||||
auto ethernet = m_configJson["ethernet"].to<ArduinoJson::JsonObject>();
|
||||
ethernet["hostname"] = m_ethHostname;
|
||||
ethernet["ipAddr"] = m_ethIpAddr;
|
||||
ethernet["netmask "] = m_ethNetmask;
|
||||
ethernet["gateway "] = m_ethGateway;
|
||||
ethernet["netmask"] = m_ethNetmask;
|
||||
ethernet["gateway"] = m_ethGateway;
|
||||
};
|
||||
|
||||
{
|
||||
@@ -179,6 +152,7 @@ private:
|
||||
ntp["timezone"] = m_ntpTimezone;
|
||||
ntp["updateInterval"] = m_ntpUpdateInterval;
|
||||
ntp["retries"] = m_ntpRetries;
|
||||
ntp["ntpRtcOffsetRegister"] = m_ntpRtcOffsetRegister;
|
||||
};
|
||||
|
||||
{
|
||||
@@ -188,13 +162,14 @@ private:
|
||||
mqtt["loopTime"] = m_mqttLoopTime;
|
||||
mqtt["clientName"] = m_mqttClientName;
|
||||
mqtt["retries"] = m_mqttRetries;
|
||||
mqtt["keepalive"] = m_mqttKeepalive;
|
||||
auto publish = mqtt["publish"].to<ArduinoJson::JsonObject>();
|
||||
for (auto v : m_mqttSubscribe)
|
||||
for (auto v : m_mqttPublish)
|
||||
{
|
||||
publish[v.first] = v.second;
|
||||
}
|
||||
auto subscribe = mqtt["subscribe"].to<ArduinoJson::JsonObject>();
|
||||
for (auto v : m_mqttPublish)
|
||||
for (auto v : m_mqttSubscribe)
|
||||
{
|
||||
subscribe[v.first] = v.second;
|
||||
}
|
||||
@@ -235,19 +210,21 @@ private:
|
||||
auto temperature = m_configJson["temperature"];
|
||||
m_tempExpectedSensors = temperature["expectedSensors"].as<uint8_t>();
|
||||
auto values = temperature["correctionValues"].as<JsonArray>();
|
||||
m_tempCorrectionValues.clear();
|
||||
m_tempCorrectionValues.reserve(values.size());
|
||||
for (auto v : values)
|
||||
{
|
||||
m_tempCorrectionValues.push_back(v.as<float>());
|
||||
m_tempCorrectionValues.emplace_back(v.as<float>());
|
||||
}
|
||||
};
|
||||
|
||||
{
|
||||
auto ntp = m_configJson["ntp"];
|
||||
m_ntpPool = ntp["pool"].as<std::string>();
|
||||
m_ntpTimezone = ntp["timezone"].as<uint16_t>();
|
||||
m_ntpTimezone = ntp["timezone"].as<int8_t>();
|
||||
m_ntpUpdateInterval = ntp["updateInterval"].as<uint16_t>();
|
||||
m_ntpRetries = ntp["retries"].as<uint8_t>();
|
||||
m_ntpRtcOffsetRegister = ntp["ntpRtcOffsetRegister"].as<uint8_t>();
|
||||
};
|
||||
|
||||
{
|
||||
@@ -255,8 +232,9 @@ private:
|
||||
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>();
|
||||
m_mqttKeepalive = mqtt["keepalive"].as<uint8_t>();
|
||||
m_mqttRetries = mqtt["retries"].as<uint8_t>();
|
||||
auto subscribe = mqtt["subscribe"].as<ArduinoJson::JsonObject>();
|
||||
for (auto v : subscribe)
|
||||
{
|
||||
m_mqttSubscribe[v.key().c_str()] = v.value().as<std::string>();
|
||||
@@ -275,7 +253,7 @@ private:
|
||||
|
||||
public:
|
||||
// Globals
|
||||
std::uint16_t m_globalLoopDelay = 1000; // in milliseconds
|
||||
std::uint16_t m_globalLoopDelay = 5000; // in milliseconds
|
||||
|
||||
// Ethernet
|
||||
std::string m_ethHostname = "ETcontroller_PRO";
|
||||
@@ -296,21 +274,25 @@ public:
|
||||
|
||||
// NTP
|
||||
std::string m_ntpPool = "pool.ntp.org";
|
||||
uint16_t m_ntpTimezone = 3600; // GTM +1
|
||||
int8_t m_ntpTimezone = +1; // GMT +1
|
||||
uint16_t m_ntpUpdateInterval = 3600; // every hour
|
||||
uint8_t m_ntpRetries = 5;
|
||||
uint8_t m_ntpRtcOffsetRegister = 0xE7; // -25 pulses in fast mode
|
||||
|
||||
// MQTT
|
||||
std::string m_mqttHost = "10.0.2.249";
|
||||
uint16_t m_mqttPort = 1883;
|
||||
uint16_t m_mqttLoopTime = 100; // in milliseconds
|
||||
uint8_t m_mqttKeepalive = 15;
|
||||
uint8_t m_mqttRetries = 5;
|
||||
std::string m_mqttClientName = "etcontrollerPRO";
|
||||
|
||||
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 = {
|
||||
{"heatpump", "test/etcontroller/heatpump"},
|
||||
{"temperature", "test/etcontroller/temperatures"},
|
||||
{"irrigation", "test/etcontroller/irrigation"}};
|
||||
{"cronjobs", "etcontroller/hw/cronjobs"},
|
||||
{"answers", "etcontroller/hw/answers"},
|
||||
{"heatpump", "etcontroller/hw/heatpump"},
|
||||
{"temperatures", "etcontroller/hw/temperatures"},
|
||||
{"irrigation", "etcontroller/hw/irrigation"}};
|
||||
};
|
||||
917
include/croncpp.h
Normal file
917
include/croncpp.h
Normal file
@@ -0,0 +1,917 @@
|
||||
#pragma once
|
||||
|
||||
#include <vector>
|
||||
#include <string>
|
||||
#include <sstream>
|
||||
#include <bitset>
|
||||
#include <cctype>
|
||||
#include <ctime>
|
||||
#include <iomanip>
|
||||
#include <algorithm>
|
||||
#include <chrono>
|
||||
|
||||
#if __cplusplus > 201402L
|
||||
#include <string_view>
|
||||
#define CRONCPP_IS_CPP17
|
||||
#endif
|
||||
|
||||
namespace cron
|
||||
{
|
||||
#ifdef CRONCPP_IS_CPP17
|
||||
#define CRONCPP_STRING_VIEW std::string_view
|
||||
#define CRONCPP_STRING_VIEW_NPOS std::string_view::npos
|
||||
#define CRONCPP_CONSTEXPTR constexpr
|
||||
#else
|
||||
#define CRONCPP_STRING_VIEW std::string const &
|
||||
#define CRONCPP_STRING_VIEW_NPOS std::string::npos
|
||||
#define CRONCPP_CONSTEXPTR
|
||||
#endif
|
||||
|
||||
using cron_int = uint8_t;
|
||||
|
||||
constexpr std::time_t INVALID_TIME = static_cast<std::time_t>(-1);
|
||||
|
||||
constexpr size_t INVALID_INDEX = static_cast<size_t>(-1);
|
||||
|
||||
class cronexpr;
|
||||
|
||||
namespace detail
|
||||
{
|
||||
enum class cron_field
|
||||
{
|
||||
second,
|
||||
minute,
|
||||
hour_of_day,
|
||||
day_of_week,
|
||||
day_of_month,
|
||||
month,
|
||||
year
|
||||
};
|
||||
|
||||
template <typename Traits>
|
||||
static bool find_next(cronexpr const & cex,
|
||||
std::tm& date,
|
||||
size_t const dot);
|
||||
}
|
||||
|
||||
struct bad_cronexpr : public std::runtime_error
|
||||
{
|
||||
public:
|
||||
explicit bad_cronexpr(CRONCPP_STRING_VIEW message) :
|
||||
std::runtime_error(message.data())
|
||||
{}
|
||||
};
|
||||
|
||||
|
||||
struct cron_standard_traits
|
||||
{
|
||||
static const cron_int CRON_MIN_SECONDS = 0;
|
||||
static const cron_int CRON_MAX_SECONDS = 59;
|
||||
|
||||
static const cron_int CRON_MIN_MINUTES = 0;
|
||||
static const cron_int CRON_MAX_MINUTES = 59;
|
||||
|
||||
static const cron_int CRON_MIN_HOURS = 0;
|
||||
static const cron_int CRON_MAX_HOURS = 23;
|
||||
|
||||
static const cron_int CRON_MIN_DAYS_OF_WEEK = 0;
|
||||
static const cron_int CRON_MAX_DAYS_OF_WEEK = 6;
|
||||
|
||||
static const cron_int CRON_MIN_DAYS_OF_MONTH = 1;
|
||||
static const cron_int CRON_MAX_DAYS_OF_MONTH = 31;
|
||||
|
||||
static const cron_int CRON_MIN_MONTHS = 1;
|
||||
static const cron_int CRON_MAX_MONTHS = 12;
|
||||
|
||||
static const cron_int CRON_MAX_YEARS_DIFF = 4;
|
||||
|
||||
#ifdef CRONCPP_IS_CPP17
|
||||
static const inline std::vector<std::string> DAYS = { "SUN", "MON", "TUE", "WED", "THU", "FRI", "SAT" };
|
||||
static const inline std::vector<std::string> MONTHS = { "NIL", "JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC" };
|
||||
#else
|
||||
static std::vector<std::string>& DAYS()
|
||||
{
|
||||
static std::vector<std::string> days = { "SUN", "MON", "TUE", "WED", "THU", "FRI", "SAT" };
|
||||
return days;
|
||||
}
|
||||
|
||||
static std::vector<std::string>& MONTHS()
|
||||
{
|
||||
static std::vector<std::string> months = { "NIL", "JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC" };
|
||||
return months;
|
||||
}
|
||||
#endif
|
||||
};
|
||||
|
||||
struct cron_oracle_traits
|
||||
{
|
||||
static const cron_int CRON_MIN_SECONDS = 0;
|
||||
static const cron_int CRON_MAX_SECONDS = 59;
|
||||
|
||||
static const cron_int CRON_MIN_MINUTES = 0;
|
||||
static const cron_int CRON_MAX_MINUTES = 59;
|
||||
|
||||
static const cron_int CRON_MIN_HOURS = 0;
|
||||
static const cron_int CRON_MAX_HOURS = 23;
|
||||
|
||||
static const cron_int CRON_MIN_DAYS_OF_WEEK = 1;
|
||||
static const cron_int CRON_MAX_DAYS_OF_WEEK = 7;
|
||||
|
||||
static const cron_int CRON_MIN_DAYS_OF_MONTH = 1;
|
||||
static const cron_int CRON_MAX_DAYS_OF_MONTH = 31;
|
||||
|
||||
static const cron_int CRON_MIN_MONTHS = 0;
|
||||
static const cron_int CRON_MAX_MONTHS = 11;
|
||||
|
||||
static const cron_int CRON_MAX_YEARS_DIFF = 4;
|
||||
|
||||
#ifdef CRONCPP_IS_CPP17
|
||||
static const inline std::vector<std::string> DAYS = { "NIL", "SUN", "MON", "TUE", "WED", "THU", "FRI", "SAT" };
|
||||
static const inline std::vector<std::string> MONTHS = { "JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC" };
|
||||
#else
|
||||
|
||||
static std::vector<std::string>& DAYS()
|
||||
{
|
||||
static std::vector<std::string> days = { "NIL", "SUN", "MON", "TUE", "WED", "THU", "FRI", "SAT" };
|
||||
return days;
|
||||
}
|
||||
|
||||
static std::vector<std::string>& MONTHS()
|
||||
{
|
||||
static std::vector<std::string> months = { "JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC" };
|
||||
return months;
|
||||
}
|
||||
#endif
|
||||
};
|
||||
|
||||
struct cron_quartz_traits
|
||||
{
|
||||
static const cron_int CRON_MIN_SECONDS = 0;
|
||||
static const cron_int CRON_MAX_SECONDS = 59;
|
||||
|
||||
static const cron_int CRON_MIN_MINUTES = 0;
|
||||
static const cron_int CRON_MAX_MINUTES = 59;
|
||||
|
||||
static const cron_int CRON_MIN_HOURS = 0;
|
||||
static const cron_int CRON_MAX_HOURS = 23;
|
||||
|
||||
static const cron_int CRON_MIN_DAYS_OF_WEEK = 1;
|
||||
static const cron_int CRON_MAX_DAYS_OF_WEEK = 7;
|
||||
|
||||
static const cron_int CRON_MIN_DAYS_OF_MONTH = 1;
|
||||
static const cron_int CRON_MAX_DAYS_OF_MONTH = 31;
|
||||
|
||||
static const cron_int CRON_MIN_MONTHS = 1;
|
||||
static const cron_int CRON_MAX_MONTHS = 12;
|
||||
|
||||
static const cron_int CRON_MAX_YEARS_DIFF = 4;
|
||||
|
||||
#ifdef CRONCPP_IS_CPP17
|
||||
static const inline std::vector<std::string> DAYS = { "NIL", "SUN", "MON", "TUE", "WED", "THU", "FRI", "SAT" };
|
||||
static const inline std::vector<std::string> MONTHS = { "NIL", "JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC" };
|
||||
#else
|
||||
static std::vector<std::string>& DAYS()
|
||||
{
|
||||
static std::vector<std::string> days = { "NIL", "SUN", "MON", "TUE", "WED", "THU", "FRI", "SAT" };
|
||||
return days;
|
||||
}
|
||||
|
||||
static std::vector<std::string>& MONTHS()
|
||||
{
|
||||
static std::vector<std::string> months = { "NIL", "JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC" };
|
||||
return months;
|
||||
}
|
||||
#endif
|
||||
};
|
||||
|
||||
class cronexpr;
|
||||
|
||||
template <typename Traits = cron_standard_traits>
|
||||
static cronexpr make_cron(CRONCPP_STRING_VIEW expr);
|
||||
|
||||
class cronexpr
|
||||
{
|
||||
std::bitset<60> seconds;
|
||||
std::bitset<60> minutes;
|
||||
std::bitset<24> hours;
|
||||
std::bitset<7> days_of_week;
|
||||
std::bitset<31> days_of_month;
|
||||
std::bitset<12> months;
|
||||
std::string expr;
|
||||
|
||||
friend bool operator==(cronexpr const & e1, cronexpr const & e2);
|
||||
friend bool operator!=(cronexpr const & e1, cronexpr const & e2);
|
||||
|
||||
template <typename Traits>
|
||||
friend bool detail::find_next(cronexpr const & cex,
|
||||
std::tm& date,
|
||||
size_t const dot);
|
||||
|
||||
friend std::string to_cronstr(cronexpr const& cex);
|
||||
friend std::string to_string(cronexpr const & cex);
|
||||
|
||||
template <typename Traits>
|
||||
friend cronexpr make_cron(CRONCPP_STRING_VIEW expr);
|
||||
};
|
||||
|
||||
inline bool operator==(cronexpr const & e1, cronexpr const & e2)
|
||||
{
|
||||
return
|
||||
e1.seconds == e2.seconds &&
|
||||
e1.minutes == e2.minutes &&
|
||||
e1.hours == e2.hours &&
|
||||
e1.days_of_week == e2.days_of_week &&
|
||||
e1.days_of_month == e2.days_of_month &&
|
||||
e1.months == e2.months;
|
||||
}
|
||||
|
||||
inline bool operator!=(cronexpr const & e1, cronexpr const & e2)
|
||||
{
|
||||
return !(e1 == e2);
|
||||
}
|
||||
|
||||
inline std::string to_string(cronexpr const & cex)
|
||||
{
|
||||
return
|
||||
cex.seconds.to_string() + " " +
|
||||
cex.minutes.to_string() + " " +
|
||||
cex.hours.to_string() + " " +
|
||||
cex.days_of_month.to_string() + " " +
|
||||
cex.months.to_string() + " " +
|
||||
cex.days_of_week.to_string();
|
||||
}
|
||||
|
||||
inline std::string to_cronstr(cronexpr const& cex)
|
||||
{
|
||||
return cex.expr;
|
||||
}
|
||||
|
||||
namespace utils
|
||||
{
|
||||
inline std::time_t tm_to_time(std::tm& date)
|
||||
{
|
||||
return std::mktime(&date);
|
||||
}
|
||||
|
||||
inline std::tm* time_to_tm(std::time_t const * date, std::tm* const out)
|
||||
{
|
||||
#ifdef _WIN32
|
||||
errno_t err = localtime_s(out, date);
|
||||
return 0 == err ? out : nullptr;
|
||||
#else
|
||||
return localtime_r(date, out);
|
||||
#endif
|
||||
}
|
||||
|
||||
inline std::tm to_tm(CRONCPP_STRING_VIEW time)
|
||||
{
|
||||
std::tm result;
|
||||
#if __cplusplus > 201103L
|
||||
std::istringstream str(time.data());
|
||||
str.imbue(std::locale(setlocale(LC_ALL, nullptr)));
|
||||
|
||||
str >> std::get_time(&result, "%Y-%m-%d %H:%M:%S");
|
||||
if (str.fail()) throw std::runtime_error("Parsing date failed!");
|
||||
#else
|
||||
int year = 1900;
|
||||
int month = 1;
|
||||
int day = 1;
|
||||
int hour = 0;
|
||||
int minute = 0;
|
||||
int second = 0;
|
||||
sscanf(time.data(), "%d-%d-%d %d:%d:%d", &year, &month, &day, &hour, &minute, &second);
|
||||
result.tm_year = year - 1900;
|
||||
result.tm_mon = month - 1;
|
||||
result.tm_mday = day;
|
||||
result.tm_hour = hour;
|
||||
result.tm_min = minute;
|
||||
result.tm_sec = second;
|
||||
#endif
|
||||
result.tm_isdst = -1; // DST info not available
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
inline std::string to_string(std::tm const & tm)
|
||||
{
|
||||
#if __cplusplus > 201103L
|
||||
std::ostringstream str;
|
||||
str.imbue(std::locale(setlocale(LC_ALL, nullptr)));
|
||||
str << std::put_time(&tm, "%Y-%m-%d %H:%M:%S");
|
||||
if (str.fail()) throw std::runtime_error("Writing date failed!");
|
||||
|
||||
return str.str();
|
||||
#else
|
||||
char buff[70] = {0};
|
||||
strftime(buff, sizeof(buff), "%Y-%m-%d %H:%M:%S", &tm);
|
||||
return std::string(buff);
|
||||
#endif
|
||||
}
|
||||
|
||||
inline std::string to_upper(std::string text)
|
||||
{
|
||||
std::transform(std::begin(text), std::end(text),
|
||||
std::begin(text), [](char const c) { return static_cast<char>(std::toupper(c)); });
|
||||
|
||||
return text;
|
||||
}
|
||||
|
||||
static std::vector<std::string> split(CRONCPP_STRING_VIEW text, char const delimiter)
|
||||
{
|
||||
std::vector<std::string> tokens;
|
||||
std::string token;
|
||||
std::istringstream tokenStream(text.data());
|
||||
while (std::getline(tokenStream, token, delimiter))
|
||||
{
|
||||
tokens.push_back(token);
|
||||
}
|
||||
return tokens;
|
||||
}
|
||||
|
||||
CRONCPP_CONSTEXPTR inline bool contains(CRONCPP_STRING_VIEW text, char const ch) noexcept
|
||||
{
|
||||
return CRONCPP_STRING_VIEW_NPOS != text.find_first_of(ch);
|
||||
}
|
||||
}
|
||||
|
||||
namespace detail
|
||||
{
|
||||
|
||||
inline cron_int to_cron_int(CRONCPP_STRING_VIEW text)
|
||||
{
|
||||
try
|
||||
{
|
||||
return static_cast<cron_int>(std::stoul(text.data()));
|
||||
}
|
||||
catch (std::exception const & ex)
|
||||
{
|
||||
throw bad_cronexpr(ex.what());
|
||||
}
|
||||
}
|
||||
|
||||
static std::string replace_ordinals(
|
||||
std::string text,
|
||||
std::vector<std::string> const & replacement)
|
||||
{
|
||||
for (size_t i = 0; i < replacement.size(); ++i)
|
||||
{
|
||||
auto pos = text.find(replacement[i]);
|
||||
if (std::string::npos != pos)
|
||||
text.replace(pos, 3 ,std::to_string(i));
|
||||
}
|
||||
|
||||
return text;
|
||||
}
|
||||
|
||||
static std::pair<cron_int, cron_int> make_range(
|
||||
CRONCPP_STRING_VIEW field,
|
||||
cron_int const minval,
|
||||
cron_int const maxval)
|
||||
{
|
||||
cron_int first = 0;
|
||||
cron_int last = 0;
|
||||
if (field.size() == 1 && field[0] == '*')
|
||||
{
|
||||
first = minval;
|
||||
last = maxval;
|
||||
}
|
||||
else if (!utils::contains(field, '-'))
|
||||
{
|
||||
first = to_cron_int(field);
|
||||
last = first;
|
||||
}
|
||||
else
|
||||
{
|
||||
auto parts = utils::split(field, '-');
|
||||
if (parts.size() != 2)
|
||||
throw bad_cronexpr("Specified range requires two fields");
|
||||
|
||||
first = to_cron_int(parts[0]);
|
||||
last = to_cron_int(parts[1]);
|
||||
}
|
||||
|
||||
if (first > maxval || last > maxval)
|
||||
{
|
||||
throw bad_cronexpr("Specified range exceeds maximum");
|
||||
}
|
||||
if (first < minval || last < minval)
|
||||
{
|
||||
throw bad_cronexpr("Specified range is less than minimum");
|
||||
}
|
||||
if (first > last)
|
||||
{
|
||||
throw bad_cronexpr("Specified range start exceeds range end");
|
||||
}
|
||||
|
||||
return { first, last };
|
||||
}
|
||||
|
||||
template <size_t N>
|
||||
static void set_cron_field(
|
||||
CRONCPP_STRING_VIEW value,
|
||||
std::bitset<N>& target,
|
||||
cron_int const minval,
|
||||
cron_int const maxval)
|
||||
{
|
||||
if(value.length() > 0 && value[value.length()-1] == ',')
|
||||
throw bad_cronexpr("Value cannot end with comma");
|
||||
|
||||
auto fields = utils::split(value, ',');
|
||||
if (fields.empty())
|
||||
throw bad_cronexpr("Expression parsing error");
|
||||
|
||||
for (auto const & field : fields)
|
||||
{
|
||||
if (!utils::contains(field, '/'))
|
||||
{
|
||||
#ifdef CRONCPP_IS_CPP17
|
||||
auto[first, last] = detail::make_range(field, minval, maxval);
|
||||
#else
|
||||
auto range = detail::make_range(field, minval, maxval);
|
||||
auto first = range.first;
|
||||
auto last = range.second;
|
||||
#endif
|
||||
for (cron_int i = first - minval; i <= last - minval; ++i)
|
||||
{
|
||||
target.set(i);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
auto parts = utils::split(field, '/');
|
||||
if (parts.size() != 2)
|
||||
throw bad_cronexpr("Incrementer must have two fields");
|
||||
|
||||
#ifdef CRONCPP_IS_CPP17
|
||||
auto[first, last] = detail::make_range(parts[0], minval, maxval);
|
||||
#else
|
||||
auto range = detail::make_range(parts[0], minval, maxval);
|
||||
auto first = range.first;
|
||||
auto last = range.second;
|
||||
#endif
|
||||
|
||||
if (!utils::contains(parts[0], '-'))
|
||||
{
|
||||
last = maxval;
|
||||
}
|
||||
|
||||
auto delta = detail::to_cron_int(parts[1]);
|
||||
if(delta <= 0)
|
||||
throw bad_cronexpr("Incrementer must be a positive value");
|
||||
|
||||
for (cron_int i = first - minval; i <= last - minval; i += delta)
|
||||
{
|
||||
target.set(i);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
template <typename Traits>
|
||||
static void set_cron_days_of_week(
|
||||
std::string value,
|
||||
std::bitset<7>& target)
|
||||
{
|
||||
auto days = utils::to_upper(value);
|
||||
auto days_replaced = detail::replace_ordinals(
|
||||
days,
|
||||
#ifdef CRONCPP_IS_CPP17
|
||||
Traits::DAYS
|
||||
#else
|
||||
Traits::DAYS()
|
||||
#endif
|
||||
);
|
||||
|
||||
if (days_replaced.size() == 1 && days_replaced[0] == '?')
|
||||
days_replaced[0] = '*';
|
||||
|
||||
set_cron_field(
|
||||
days_replaced,
|
||||
target,
|
||||
Traits::CRON_MIN_DAYS_OF_WEEK,
|
||||
Traits::CRON_MAX_DAYS_OF_WEEK);
|
||||
}
|
||||
|
||||
template <typename Traits>
|
||||
static void set_cron_days_of_month(
|
||||
std::string value,
|
||||
std::bitset<31>& target)
|
||||
{
|
||||
if (value.size() == 1 && value[0] == '?')
|
||||
value[0] = '*';
|
||||
|
||||
set_cron_field(
|
||||
value,
|
||||
target,
|
||||
Traits::CRON_MIN_DAYS_OF_MONTH,
|
||||
Traits::CRON_MAX_DAYS_OF_MONTH);
|
||||
}
|
||||
|
||||
template <typename Traits>
|
||||
static void set_cron_month(
|
||||
std::string value,
|
||||
std::bitset<12>& target)
|
||||
{
|
||||
auto month = utils::to_upper(value);
|
||||
auto month_replaced = replace_ordinals(
|
||||
month,
|
||||
#ifdef CRONCPP_IS_CPP17
|
||||
Traits::MONTHS
|
||||
#else
|
||||
Traits::MONTHS()
|
||||
#endif
|
||||
);
|
||||
|
||||
set_cron_field(
|
||||
month_replaced,
|
||||
target,
|
||||
Traits::CRON_MIN_MONTHS,
|
||||
Traits::CRON_MAX_MONTHS);
|
||||
}
|
||||
|
||||
template <size_t N>
|
||||
inline size_t next_set_bit(
|
||||
std::bitset<N> const & target,
|
||||
size_t /*minimum*/,
|
||||
size_t /*maximum*/,
|
||||
size_t offset)
|
||||
{
|
||||
for (auto i = offset; i < N; ++i)
|
||||
{
|
||||
if (target.test(i)) return i;
|
||||
}
|
||||
|
||||
return INVALID_INDEX;
|
||||
}
|
||||
|
||||
inline void add_to_field(
|
||||
std::tm& date,
|
||||
cron_field const field,
|
||||
int const val)
|
||||
{
|
||||
switch (field)
|
||||
{
|
||||
case cron_field::second:
|
||||
date.tm_sec += val;
|
||||
break;
|
||||
case cron_field::minute:
|
||||
date.tm_min += val;
|
||||
break;
|
||||
case cron_field::hour_of_day:
|
||||
date.tm_hour += val;
|
||||
break;
|
||||
case cron_field::day_of_week:
|
||||
case cron_field::day_of_month:
|
||||
date.tm_mday += val;
|
||||
date.tm_isdst = -1;
|
||||
break;
|
||||
case cron_field::month:
|
||||
date.tm_mon += val;
|
||||
date.tm_isdst = -1;
|
||||
break;
|
||||
case cron_field::year:
|
||||
date.tm_year += val;
|
||||
break;
|
||||
}
|
||||
|
||||
if (INVALID_TIME == utils::tm_to_time(date))
|
||||
throw bad_cronexpr("Invalid time expression");
|
||||
}
|
||||
|
||||
inline void set_field(
|
||||
std::tm& date,
|
||||
cron_field const field,
|
||||
int const val)
|
||||
{
|
||||
switch (field)
|
||||
{
|
||||
case cron_field::second:
|
||||
date.tm_sec = val;
|
||||
break;
|
||||
case cron_field::minute:
|
||||
date.tm_min = val;
|
||||
break;
|
||||
case cron_field::hour_of_day:
|
||||
date.tm_hour = val;
|
||||
break;
|
||||
case cron_field::day_of_week:
|
||||
date.tm_wday = val;
|
||||
break;
|
||||
case cron_field::day_of_month:
|
||||
date.tm_mday = val;
|
||||
date.tm_isdst = -1;
|
||||
break;
|
||||
case cron_field::month:
|
||||
date.tm_mon = val;
|
||||
date.tm_isdst = -1;
|
||||
break;
|
||||
case cron_field::year:
|
||||
date.tm_year = val;
|
||||
break;
|
||||
}
|
||||
|
||||
if (INVALID_TIME == utils::tm_to_time(date))
|
||||
throw bad_cronexpr("Invalid time expression");
|
||||
}
|
||||
|
||||
inline void reset_field(
|
||||
std::tm& date,
|
||||
cron_field const field)
|
||||
{
|
||||
switch (field)
|
||||
{
|
||||
case cron_field::second:
|
||||
date.tm_sec = 0;
|
||||
break;
|
||||
case cron_field::minute:
|
||||
date.tm_min = 0;
|
||||
break;
|
||||
case cron_field::hour_of_day:
|
||||
date.tm_hour = 0;
|
||||
break;
|
||||
case cron_field::day_of_week:
|
||||
date.tm_wday = 0;
|
||||
break;
|
||||
case cron_field::day_of_month:
|
||||
date.tm_mday = 1;
|
||||
date.tm_isdst = -1;
|
||||
break;
|
||||
case cron_field::month:
|
||||
date.tm_mon = 0;
|
||||
date.tm_isdst = -1;
|
||||
break;
|
||||
case cron_field::year:
|
||||
date.tm_year = 0;
|
||||
break;
|
||||
}
|
||||
|
||||
if (INVALID_TIME == utils::tm_to_time(date))
|
||||
throw bad_cronexpr("Invalid time expression");
|
||||
}
|
||||
|
||||
inline void reset_all_fields(
|
||||
std::tm& date,
|
||||
std::bitset<7> const & marked_fields)
|
||||
{
|
||||
for (size_t i = 0; i < marked_fields.size(); ++i)
|
||||
{
|
||||
if (marked_fields.test(i))
|
||||
reset_field(date, static_cast<cron_field>(i));
|
||||
}
|
||||
}
|
||||
|
||||
inline void mark_field(
|
||||
std::bitset<7> & orders,
|
||||
cron_field const field)
|
||||
{
|
||||
if (!orders.test(static_cast<size_t>(field)))
|
||||
orders.set(static_cast<size_t>(field));
|
||||
}
|
||||
|
||||
template <size_t N>
|
||||
static size_t find_next(
|
||||
std::bitset<N> const & target,
|
||||
std::tm& date,
|
||||
unsigned int const minimum,
|
||||
unsigned int const maximum,
|
||||
unsigned int const value,
|
||||
cron_field const field,
|
||||
cron_field const next_field,
|
||||
std::bitset<7> const & marked_fields)
|
||||
{
|
||||
auto next_value = next_set_bit(target, minimum, maximum, value);
|
||||
if (INVALID_INDEX == next_value)
|
||||
{
|
||||
add_to_field(date, next_field, 1);
|
||||
reset_field(date, field);
|
||||
next_value = next_set_bit(target, minimum, maximum, 0);
|
||||
}
|
||||
|
||||
if (INVALID_INDEX == next_value || next_value != value)
|
||||
{
|
||||
set_field(date, field, static_cast<int>(next_value));
|
||||
reset_all_fields(date, marked_fields);
|
||||
}
|
||||
|
||||
return next_value;
|
||||
}
|
||||
|
||||
template <typename Traits>
|
||||
static size_t find_next_day(
|
||||
std::tm& date,
|
||||
std::bitset<31> const & days_of_month,
|
||||
size_t day_of_month,
|
||||
std::bitset<7> const & days_of_week,
|
||||
size_t day_of_week,
|
||||
std::bitset<7> const & marked_fields)
|
||||
{
|
||||
unsigned int count = 0;
|
||||
unsigned int maximum = 366;
|
||||
while (
|
||||
(!days_of_month.test(day_of_month - Traits::CRON_MIN_DAYS_OF_MONTH) ||
|
||||
!days_of_week.test(day_of_week - Traits::CRON_MIN_DAYS_OF_WEEK))
|
||||
&& count++ < maximum)
|
||||
{
|
||||
add_to_field(date, cron_field::day_of_month, 1);
|
||||
|
||||
day_of_month = date.tm_mday;
|
||||
day_of_week = date.tm_wday;
|
||||
|
||||
reset_all_fields(date, marked_fields);
|
||||
}
|
||||
|
||||
return day_of_month;
|
||||
}
|
||||
|
||||
template <typename Traits>
|
||||
static bool find_next(cronexpr const & cex,
|
||||
std::tm& date,
|
||||
size_t const dot)
|
||||
{
|
||||
bool res = true;
|
||||
|
||||
std::bitset<7> marked_fields{ 0 };
|
||||
std::bitset<7> empty_list{ 0 };
|
||||
|
||||
unsigned int second = date.tm_sec;
|
||||
auto updated_second = find_next(
|
||||
cex.seconds,
|
||||
date,
|
||||
Traits::CRON_MIN_SECONDS,
|
||||
Traits::CRON_MAX_SECONDS,
|
||||
second,
|
||||
cron_field::second,
|
||||
cron_field::minute,
|
||||
empty_list);
|
||||
|
||||
if (second == updated_second)
|
||||
{
|
||||
mark_field(marked_fields, cron_field::second);
|
||||
}
|
||||
|
||||
unsigned int minute = date.tm_min;
|
||||
auto update_minute = find_next(
|
||||
cex.minutes,
|
||||
date,
|
||||
Traits::CRON_MIN_MINUTES,
|
||||
Traits::CRON_MAX_MINUTES,
|
||||
minute,
|
||||
cron_field::minute,
|
||||
cron_field::hour_of_day,
|
||||
marked_fields);
|
||||
if (minute == update_minute)
|
||||
{
|
||||
mark_field(marked_fields, cron_field::minute);
|
||||
}
|
||||
else
|
||||
{
|
||||
res = find_next<Traits>(cex, date, dot);
|
||||
if (!res) return res;
|
||||
}
|
||||
|
||||
unsigned int hour = date.tm_hour;
|
||||
auto updated_hour = find_next(
|
||||
cex.hours,
|
||||
date,
|
||||
Traits::CRON_MIN_HOURS,
|
||||
Traits::CRON_MAX_HOURS,
|
||||
hour,
|
||||
cron_field::hour_of_day,
|
||||
cron_field::day_of_week,
|
||||
marked_fields);
|
||||
if (hour == updated_hour)
|
||||
{
|
||||
mark_field(marked_fields, cron_field::hour_of_day);
|
||||
}
|
||||
else
|
||||
{
|
||||
res = find_next<Traits>(cex, date, dot);
|
||||
if (!res) return res;
|
||||
}
|
||||
|
||||
unsigned int day_of_week = date.tm_wday;
|
||||
unsigned int day_of_month = date.tm_mday;
|
||||
auto updated_day_of_month = find_next_day<Traits>(
|
||||
date,
|
||||
cex.days_of_month,
|
||||
day_of_month,
|
||||
cex.days_of_week,
|
||||
day_of_week,
|
||||
marked_fields);
|
||||
if (day_of_month == updated_day_of_month)
|
||||
{
|
||||
mark_field(marked_fields, cron_field::day_of_month);
|
||||
}
|
||||
else
|
||||
{
|
||||
res = find_next<Traits>(cex, date, dot);
|
||||
if (!res) return res;
|
||||
}
|
||||
|
||||
unsigned int month = date.tm_mon;
|
||||
auto updated_month = find_next(
|
||||
cex.months,
|
||||
date,
|
||||
Traits::CRON_MIN_MONTHS,
|
||||
Traits::CRON_MAX_MONTHS,
|
||||
month,
|
||||
cron_field::month,
|
||||
cron_field::year,
|
||||
marked_fields);
|
||||
if (month != updated_month)
|
||||
{
|
||||
if (date.tm_year - dot > Traits::CRON_MAX_YEARS_DIFF)
|
||||
return false;
|
||||
|
||||
res = find_next<Traits>(cex, date, dot);
|
||||
if (!res) return res;
|
||||
}
|
||||
|
||||
return res;
|
||||
}
|
||||
}
|
||||
|
||||
template <typename Traits>
|
||||
static cronexpr make_cron(CRONCPP_STRING_VIEW expr)
|
||||
{
|
||||
cronexpr cex;
|
||||
|
||||
if (expr.empty())
|
||||
throw bad_cronexpr("Invalid empty cron expression");
|
||||
|
||||
auto fields = utils::split(expr, ' ');
|
||||
fields.erase(
|
||||
std::remove_if(std::begin(fields), std::end(fields),
|
||||
[](CRONCPP_STRING_VIEW s) {return s.empty(); }),
|
||||
std::end(fields));
|
||||
if (fields.size() != 6)
|
||||
throw bad_cronexpr("cron expression must have six fields");
|
||||
|
||||
detail::set_cron_field(fields[0], cex.seconds, Traits::CRON_MIN_SECONDS, Traits::CRON_MAX_SECONDS);
|
||||
detail::set_cron_field(fields[1], cex.minutes, Traits::CRON_MIN_MINUTES, Traits::CRON_MAX_MINUTES);
|
||||
detail::set_cron_field(fields[2], cex.hours, Traits::CRON_MIN_HOURS, Traits::CRON_MAX_HOURS);
|
||||
|
||||
detail::set_cron_days_of_week<Traits>(fields[5], cex.days_of_week);
|
||||
|
||||
detail::set_cron_days_of_month<Traits>(fields[3], cex.days_of_month);
|
||||
|
||||
detail::set_cron_month<Traits>(fields[4], cex.months);
|
||||
|
||||
cex.expr = expr;
|
||||
|
||||
return cex;
|
||||
}
|
||||
|
||||
template <typename Traits = cron_standard_traits>
|
||||
static std::tm cron_next(cronexpr const & cex, std::tm date)
|
||||
{
|
||||
time_t original = utils::tm_to_time(date);
|
||||
if (INVALID_TIME == original) return {};
|
||||
|
||||
if (!detail::find_next<Traits>(cex, date, date.tm_year))
|
||||
return {};
|
||||
|
||||
time_t calculated = utils::tm_to_time(date);
|
||||
if (INVALID_TIME == calculated) return {};
|
||||
|
||||
if (calculated == original)
|
||||
{
|
||||
add_to_field(date, detail::cron_field::second, 1);
|
||||
if (!detail::find_next<Traits>(cex, date, date.tm_year))
|
||||
return {};
|
||||
}
|
||||
|
||||
return date;
|
||||
}
|
||||
|
||||
template <typename Traits = cron_standard_traits>
|
||||
static std::time_t cron_next(cronexpr const & cex, std::time_t const & date)
|
||||
{
|
||||
std::tm val;
|
||||
std::tm* dt = utils::time_to_tm(&date, &val);
|
||||
if (dt == nullptr) return INVALID_TIME;
|
||||
|
||||
time_t original = utils::tm_to_time(*dt);
|
||||
if (INVALID_TIME == original) return INVALID_TIME;
|
||||
|
||||
if(!detail::find_next<Traits>(cex, *dt, dt->tm_year))
|
||||
return INVALID_TIME;
|
||||
|
||||
time_t calculated = utils::tm_to_time(*dt);
|
||||
if (INVALID_TIME == calculated) return calculated;
|
||||
|
||||
if (calculated == original)
|
||||
{
|
||||
add_to_field(*dt, detail::cron_field::second, 1);
|
||||
if(!detail::find_next<Traits>(cex, *dt, dt->tm_year))
|
||||
return INVALID_TIME;
|
||||
}
|
||||
|
||||
return utils::tm_to_time(*dt);
|
||||
}
|
||||
|
||||
template <typename Traits = cron_standard_traits>
|
||||
static std::chrono::system_clock::time_point cron_next(cronexpr const & cex, std::chrono::system_clock::time_point const & time_point) {
|
||||
return std::chrono::system_clock::from_time_t(cron_next<Traits>(cex, std::chrono::system_clock::to_time_t(time_point)));
|
||||
}
|
||||
}
|
||||
38
include/fsmount.h
Normal file
38
include/fsmount.h
Normal file
@@ -0,0 +1,38 @@
|
||||
#pragma once
|
||||
|
||||
#define DEBUGLOG_DEFAULT_LOG_LEVEL_DEBUG
|
||||
|
||||
#include <DebugLog.h>
|
||||
#include <Arduino.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");
|
||||
}
|
||||
};
|
||||
82
include/pinlist.h
Normal file
82
include/pinlist.h
Normal file
@@ -0,0 +1,82 @@
|
||||
#pragma once
|
||||
|
||||
enum RO // relay output channels
|
||||
{
|
||||
P4 = 0,
|
||||
P3 = 1,
|
||||
P2 = 2,
|
||||
P1 = 3,
|
||||
RO_4 = 4,
|
||||
FST_FLOOR = 5,
|
||||
GND_FLOOR = 6,
|
||||
PUMP_HT = 7,
|
||||
PUMP_IRR = 8,
|
||||
RETURN = 9,
|
||||
ZONE1 = 10,
|
||||
ZONE2 = 11,
|
||||
ZONE3 = 12,
|
||||
DRIP = 13,
|
||||
RO_14 = 14,
|
||||
RO_15 = 15,
|
||||
RO_MAX = 16 // unused to detect invalid values
|
||||
};
|
||||
|
||||
static const std::map<const int, const char *> RO_2str = {
|
||||
{RO::P1, "HPLimit1"},
|
||||
{RO::P2, "HPLimit2"},
|
||||
{RO::P3, "HPLimit3"},
|
||||
{RO::P4, "HPLimit4"},
|
||||
{RO::RO_4, "Out4"},
|
||||
{RO::FST_FLOOR, "PianoPrimo"},
|
||||
{RO::GND_FLOOR, "PianoTerra"},
|
||||
{RO::PUMP_HT, "PompaRisc"},
|
||||
{RO::PUMP_IRR, "PompaIrr"},
|
||||
{RO::RETURN, "Ricircolo"},
|
||||
{RO::ZONE1, "IrrZona1"},
|
||||
{RO::ZONE2, "IrrZona2"},
|
||||
{RO::ZONE3, "IrrZona3"},
|
||||
{RO::DRIP, "IrrDrip"},
|
||||
{RO::RO_14, "Out14"},
|
||||
{RO::RO_15, "Out15"},
|
||||
{RO::RO_MAX, "Invalid"}};
|
||||
|
||||
enum DI // digital input channels
|
||||
{
|
||||
CONFRESET = 0,
|
||||
RESTART = 1,
|
||||
DI_2 = 2,
|
||||
DI_3 = 3,
|
||||
DI_4 = 4,
|
||||
DI_5 = 5,
|
||||
DI_6 = 6,
|
||||
OTAENABLE = 7,
|
||||
PUMP_PRESSURE = 8,
|
||||
RAIN = 9,
|
||||
IRR_OVERRIDE = 10,
|
||||
DI_11 = 11,
|
||||
DI_12 = 12,
|
||||
DI_13 = 13,
|
||||
DI_14 = 14,
|
||||
DI_15 = 15,
|
||||
DI_MAX = 16 // unused to detect invalid values
|
||||
};
|
||||
|
||||
static const std::map<const int, const char *> DI_2str =
|
||||
{
|
||||
{DI::CONFRESET, "ConfigReset"},
|
||||
{DI::RESTART, "Restart"},
|
||||
{DI::DI_2, "In2"},
|
||||
{DI::DI_3, "In3"},
|
||||
{DI::DI_4, "In4"},
|
||||
{DI::DI_5, "In5"},
|
||||
{DI::DI_6, "In6"},
|
||||
{DI::OTAENABLE, "OtaEnable"},
|
||||
{DI::PUMP_PRESSURE, "IrrPumpPressure"},
|
||||
{DI::RAIN, "IrrRainSensor"},
|
||||
{DI::IRR_OVERRIDE, "IrrRainOverride"},
|
||||
{DI::DI_11, "In11"},
|
||||
{DI::DI_12, "In12"},
|
||||
{DI::DI_13, "In13"},
|
||||
{DI::DI_14, "In14"},
|
||||
{DI::DI_15, "In15"},
|
||||
{DI::DI_MAX, "Invalid"}};
|
||||
@@ -3,12 +3,12 @@
|
||||
namespace drivers
|
||||
{
|
||||
|
||||
Ethernet::Ethernet(const std::string hostname) : m_hostname(hostname), m_connected(false), m_localIP(IPAddress()), m_udp(NetworkUDP()), m_timeClient(m_udp)
|
||||
Ethernet::Ethernet(const std::string &hostname, const std::string &ntpPool, const int8_t tz, const uint16_t updateInterval) : m_hostname(hostname), m_ntpPool(ntpPool), m_connected(false), m_localIP(IPAddress()), m_udp(NetworkUDP()), m_timeClient(m_udp)
|
||||
{
|
||||
SPI.begin(ETH_SPI_SCK, ETH_SPI_MISO, ETH_SPI_MOSI);
|
||||
ETH.begin(ETH_PHY_TYPE, ETH_PHY_ADDR, ETH_PHY_CS, ETH_PHY_IRQ, ETH_PHY_RST, SPI);
|
||||
|
||||
m_timeClient = std::move(NTPClient(m_udp, "pool.ntp.org", 0, 3600)); // NTP server, time offset in seconds, update interval
|
||||
m_timeClient = std::move(NTPClient(m_udp, m_ntpPool.c_str(), tz * 3600, updateInterval)); // NTP server, time offset in seconds, update interval
|
||||
m_timeClient.begin();
|
||||
}
|
||||
|
||||
@@ -30,6 +30,17 @@ namespace drivers
|
||||
return false;
|
||||
}
|
||||
|
||||
const bool Ethernet::setNtpTimeOffset(const int8_t tz)
|
||||
{
|
||||
if (m_connected)
|
||||
{
|
||||
m_timeClient.setTimeOffset(tz * 3600);
|
||||
LOG_DEBUG("Time zone UTC ", tz);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
const bool Ethernet::isConnected()
|
||||
{
|
||||
return m_connected;
|
||||
|
||||
@@ -30,15 +30,17 @@ namespace drivers
|
||||
{
|
||||
|
||||
public:
|
||||
Ethernet(const std::string hostname);
|
||||
Ethernet(const std::string &hostname, const std::string &ntpPool, const int8_t tz, const uint16_t updateInterval);
|
||||
~Ethernet();
|
||||
|
||||
void onEvent(arduino_event_id_t event, arduino_event_info_t info);
|
||||
const bool isConnected();
|
||||
const bool getNtpTime(time_t &time);
|
||||
const bool setNtpTimeOffset(const int8_t tz);
|
||||
|
||||
private:
|
||||
const std::string m_hostname;
|
||||
const std::string m_ntpPool;
|
||||
bool m_connected;
|
||||
NetworkUDP m_udp;
|
||||
IPAddress m_localIP;
|
||||
|
||||
@@ -14,7 +14,7 @@ namespace drivers
|
||||
ledcAttach(c_buzzerPin, 1000, 8);
|
||||
m_bp.pin = c_buzzerPin;
|
||||
m_bp.beeperTask = NULL;
|
||||
beep(50, NOTE_G);
|
||||
beep(50, NOTE_C);
|
||||
}
|
||||
|
||||
Buzzer::~Buzzer()
|
||||
|
||||
@@ -10,8 +10,9 @@ namespace drivers
|
||||
{
|
||||
LOG_INFO("Inizializing RGB Led");
|
||||
pinMode(c_ledPin, OUTPUT);
|
||||
m_lp.pin = c_ledPin;
|
||||
m_lp.blinkTask = NULL;
|
||||
m_blinkTask = NULL;
|
||||
m_flashTimer = NULL;
|
||||
m_enforce = false;
|
||||
}
|
||||
|
||||
Led::~Led()
|
||||
@@ -20,56 +21,102 @@ namespace drivers
|
||||
pinMode(c_ledPin, INPUT);
|
||||
}
|
||||
|
||||
void Led::setEnforce(const bool enf)
|
||||
{
|
||||
m_enforce = enf;
|
||||
}
|
||||
|
||||
void Led::setColor(const color_t color)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(m_ledMutex);
|
||||
if (m_enforce)
|
||||
return;
|
||||
blinkStop();
|
||||
rgbLedWrite(c_ledPin, color.r, color.g, color.b);
|
||||
m_colorDefault = color;
|
||||
rgbLedWrite(c_ledPin, color.g, color.r, color.b);
|
||||
}
|
||||
|
||||
void Led::flashHandle(TimerHandle_t th)
|
||||
{
|
||||
Led *led = (Led *)pvTimerGetTimerID(th);
|
||||
rgbLedWrite(led->c_ledPin, led->m_colorDefault.g, led->m_colorDefault.r, led->m_colorDefault.b); // reset color to saved color
|
||||
return;
|
||||
}
|
||||
|
||||
void Led::flashColor(const uint16_t tOn, const color_t color)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(m_ledMutex);
|
||||
rgbLedWrite(c_ledPin, color.g, color.r, color.b); // set color to flash
|
||||
if (m_flashTimer == NULL)
|
||||
{
|
||||
m_flashTimer = xTimerCreate("flasher", pdMS_TO_TICKS(tOn), pdFALSE, NULL, flashHandle);
|
||||
xTimerStart(m_flashTimer, 0);
|
||||
LOG_INFO("Led Flash timer created");
|
||||
return;
|
||||
}
|
||||
xTimerStop(m_flashTimer, 0);
|
||||
if (!xTimerChangePeriod(m_flashTimer, pdMS_TO_TICKS(tOn), pdMS_TO_TICKS(1)) || !xTimerReset(m_flashTimer, pdMS_TO_TICKS(1)))
|
||||
{
|
||||
LOG_ERROR("Led Flash timer failed reset");
|
||||
xTimerDelete(m_flashTimer, 0);
|
||||
m_flashTimer = NULL;
|
||||
}
|
||||
}
|
||||
|
||||
void Led::blinkColor(const uint16_t tOn, const uint16_t tOff, const color_t color)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(m_ledMutex);
|
||||
if (m_enforce)
|
||||
return;
|
||||
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);
|
||||
m_color1 = color;
|
||||
m_color2 = {0, 0, 0};
|
||||
m_tOn = tOn;
|
||||
m_tOff = tOff;
|
||||
xTaskCreate(blinkTask, "blinker", TASK_STACK, this, TASK_PRIORITY, &m_blinkTask);
|
||||
}
|
||||
|
||||
void Led::blinkAlternate(const uint16_t tOn, const uint16_t tOff, const color_t color1, const color_t color2)
|
||||
{
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(m_ledMutex);
|
||||
if (m_enforce)
|
||||
return;
|
||||
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);
|
||||
}
|
||||
m_color1 = color1;
|
||||
m_color2 = color2;
|
||||
m_tOn = tOn;
|
||||
m_tOff = tOff;
|
||||
xTaskCreate(blinkTask, "blinker", TASK_STACK, this, TASK_PRIORITY, &m_blinkTask);
|
||||
}
|
||||
|
||||
void Led::blinkStop()
|
||||
{
|
||||
if (m_lp.blinkTask != NULL)
|
||||
vTaskDelete(m_lp.blinkTask);
|
||||
m_lp.blinkTask = NULL;
|
||||
if (m_blinkTask != NULL)
|
||||
vTaskDelete(m_blinkTask);
|
||||
m_blinkTask = NULL;
|
||||
}
|
||||
|
||||
void Led::blinkTask(void *params)
|
||||
{
|
||||
Led *led = static_cast<Led *>(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);
|
||||
delay(lPar->tOn);
|
||||
rgbLedWrite(lPar->pin, lPar->color2.g, lPar->color2.r, lPar->color2.b); // off
|
||||
if (lPar->tOff == 0)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(led->m_ledMutex);
|
||||
rgbLedWrite(led->c_ledPin, led->m_color1.g, led->m_color1.r, led->m_color1.b);
|
||||
}
|
||||
delay(led->m_tOn);
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(led->m_ledMutex);
|
||||
rgbLedWrite(led->c_ledPin, led->m_color2.g, led->m_color2.r, led->m_color2.b); // off
|
||||
}
|
||||
if (led->m_tOff == 0)
|
||||
break;
|
||||
delay(lPar->tOff);
|
||||
delay(led->m_tOff);
|
||||
}
|
||||
LOG_DEBUG("Blinker Task Ended");
|
||||
lPar->blinkTask = NULL;
|
||||
led->m_blinkTask = NULL;
|
||||
vTaskDelete(NULL);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,12 +5,13 @@
|
||||
#define DEBUGLOG_DEFAULT_LOG_LEVEL_INFO
|
||||
#include <DebugLog.h>
|
||||
|
||||
#include <mutex>
|
||||
|
||||
namespace drivers
|
||||
{
|
||||
|
||||
class Led
|
||||
{
|
||||
const uint8_t c_ledPin = 38;
|
||||
|
||||
public:
|
||||
typedef struct
|
||||
@@ -20,31 +21,50 @@ namespace drivers
|
||||
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;
|
||||
const color_t COLOR_OFF = {0, 0, 0};
|
||||
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};
|
||||
|
||||
public:
|
||||
Led();
|
||||
~Led();
|
||||
|
||||
void setEnforce(const bool enf);
|
||||
void setColor(const color_t color);
|
||||
void flashColor(const uint16_t tOn, 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 flashHandle(TimerHandle_t th);
|
||||
static void blinkTask(void *params);
|
||||
|
||||
private:
|
||||
led_params_t m_lp;
|
||||
const uint8_t c_ledPin = 38;
|
||||
|
||||
color_t m_color1;
|
||||
color_t m_color2;
|
||||
color_t m_colorDefault;
|
||||
|
||||
uint16_t m_tOn;
|
||||
uint16_t m_tOff;
|
||||
|
||||
TaskHandle_t m_blinkTask;
|
||||
TimerHandle_t m_flashTimer;
|
||||
|
||||
bool m_flashing;
|
||||
bool m_enforce;
|
||||
|
||||
std::mutex m_ledMutex;
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
@@ -3,8 +3,11 @@
|
||||
#include <cstring>
|
||||
#include <endian.h>
|
||||
|
||||
#include <busdelay.h>
|
||||
#include "utils.h"
|
||||
|
||||
#define BUS_DELAY drivers::BusDelay(m_lastAccess, c_minDelay, "MODBUS")
|
||||
|
||||
namespace drivers
|
||||
{
|
||||
|
||||
@@ -80,26 +83,11 @@ namespace drivers
|
||||
return m_mutex;
|
||||
}
|
||||
|
||||
void MODBUS::delayAccess(const uint8_t device)
|
||||
{
|
||||
if (device == m_lastDevice)
|
||||
return;
|
||||
auto now = millis();
|
||||
if ((now - m_lastAccess) < c_minDelay) // fixed milliseconds delay between commands to different devices
|
||||
{
|
||||
LOG_WARN("MODBUS access delay", (now - m_lastAccess), "device", device);
|
||||
delay(now - m_lastAccess);
|
||||
}
|
||||
m_lastDevice = device;
|
||||
m_lastAccess = millis();
|
||||
}
|
||||
|
||||
// Func 0x01
|
||||
const bool MODBUS::readCoils(const uint8_t device, const uint16_t reg, const uint16_t num, std::vector<bool> &coils)
|
||||
{
|
||||
constexpr uint8_t func = 0x01;
|
||||
delayAccess(device);
|
||||
LOG_DEBUG("Read coils: dev[", device, "], reg[", reg, "], num[", num, "]");
|
||||
LOG_DEBUG("Read coils: dev[", printHex(device).c_str(), "], reg[", printHex(reg).c_str(), "], num[", num, "]");
|
||||
return readBinary(device, func, reg, num, coils);
|
||||
}
|
||||
|
||||
@@ -107,8 +95,7 @@ namespace drivers
|
||||
const bool MODBUS::readInputs(const uint8_t device, const uint16_t reg, const uint8_t num, std::vector<bool> &inputs)
|
||||
{
|
||||
constexpr uint8_t func = 0x02;
|
||||
delayAccess(device);
|
||||
LOG_DEBUG("Read multi inputs: dev[", device, "], reg[", reg, "], num[", num, "]");
|
||||
LOG_DEBUG("Read multi inputs: dev[", printHex(device).c_str(), "], reg[", printHex(reg).c_str(), "], num[", num, "]");
|
||||
return readBinary(device, func, reg, num, inputs);
|
||||
}
|
||||
|
||||
@@ -116,8 +103,7 @@ namespace drivers
|
||||
const bool MODBUS::readHoldingRegisters(const uint8_t device, const uint16_t reg, const uint8_t num, std::vector<uint16_t> &values)
|
||||
{
|
||||
constexpr uint8_t func = 0x03;
|
||||
delayAccess(device);
|
||||
LOG_DEBUG("Read multi holding registers: dev[", device, "], reg[", reg, "], num[", num, "]");
|
||||
LOG_DEBUG("Read multi holding registers: dev[", printHex(device).c_str(), "], reg[", printHex(reg).c_str(), "], num[", num, "]");
|
||||
return readInteger(device, func, reg, num, values);
|
||||
}
|
||||
|
||||
@@ -125,8 +111,7 @@ namespace drivers
|
||||
const bool MODBUS::readInputRegisters(const uint8_t device, const uint16_t reg, const uint8_t num, std::vector<uint16_t> &values)
|
||||
{
|
||||
constexpr uint8_t func = 0x04;
|
||||
delayAccess(device);
|
||||
LOG_DEBUG("Read multi input registers: dev[", device, "], reg[", reg, "], num[", num, "]");
|
||||
LOG_DEBUG("Read multi input registers: dev[", printHex(device).c_str(), "], reg[", printHex(reg).c_str(), "], num[", num, "]");
|
||||
return readInteger(device, func, reg, num, values);
|
||||
}
|
||||
|
||||
@@ -134,8 +119,7 @@ namespace drivers
|
||||
const bool MODBUS::writeCoil(const uint8_t device, const uint16_t coil, const bool value)
|
||||
{
|
||||
constexpr uint8_t func = 0x05;
|
||||
delayAccess(device);
|
||||
LOG_DEBUG("Write single coil: dev[", device, "], coil[", coil, "], value[", value ? "true" : "false", "]");
|
||||
LOG_DEBUG("Write single coil: dev[", printHex(device).c_str(), "], coil[", printHex(coil).c_str(), "], value[", value ? "true" : "false", "]");
|
||||
return writeBinary(device, func, coil, {value});
|
||||
}
|
||||
|
||||
@@ -143,8 +127,7 @@ namespace drivers
|
||||
const bool MODBUS::writeRegister(const uint8_t device, const uint16_t reg, const uint16_t value)
|
||||
{
|
||||
constexpr uint8_t func = 0x06;
|
||||
delayAccess(device);
|
||||
LOG_DEBUG("Write single register: dev[", device, "], reg[", reg, "], value[", value, "]");
|
||||
LOG_DEBUG("Write single register: dev[", printHex(device).c_str(), "], reg[", printHex(reg).c_str(), "], value[", value, "]");
|
||||
return writeInteger(device, func, reg, {value}, false);
|
||||
}
|
||||
|
||||
@@ -152,8 +135,7 @@ namespace drivers
|
||||
const bool MODBUS::writeCoils(const uint8_t device, const uint16_t coils, const std::vector<bool> &values)
|
||||
{
|
||||
constexpr uint8_t func = 0x0F;
|
||||
delayAccess(device);
|
||||
LOG_DEBUG("Write multi coils: dev[", device, "], start[", coils, "], num[", values.size(), "]");
|
||||
LOG_DEBUG("Write multi coils: dev[", printHex(device).c_str(), "], start[", printHex(coils).c_str(), "], num[", values.size(), "]");
|
||||
return writeBinary(device, func, coils, values);
|
||||
}
|
||||
|
||||
@@ -161,8 +143,7 @@ namespace drivers
|
||||
const bool MODBUS::writeRegisters(const uint8_t device, const uint16_t reg, const std::vector<uint16_t> &values)
|
||||
{
|
||||
constexpr uint8_t func = 0x10;
|
||||
delayAccess(device);
|
||||
LOG_DEBUG("Write multi registers: dev[", device, "], start[", reg, "], num[", values.size(), "]");
|
||||
LOG_DEBUG("Write multi registers: dev[", printHex(device).c_str(), "], start[", printHex(reg).c_str(), "], num[", values.size(), "]");
|
||||
return writeInteger(device, func, reg, values, true);
|
||||
}
|
||||
|
||||
@@ -172,6 +153,13 @@ namespace drivers
|
||||
|
||||
const bool MODBUS::readBinary(const uint8_t device, const uint8_t func, const uint16_t reg, const uint16_t bits, std::vector<bool> &out)
|
||||
{
|
||||
// Delay Bus Access between different devices
|
||||
if (device != m_lastDevice)
|
||||
{
|
||||
LOG_DEBUG("MODBUS device change from ", printHex(m_lastDevice).c_str(), "to", printHex(device).c_str());
|
||||
BUS_DELAY;
|
||||
m_lastDevice = device;
|
||||
}
|
||||
if (!write(singleRequest(device, func, reg, bits)))
|
||||
{
|
||||
LOG_ERROR("Failed send readBinary command");
|
||||
@@ -222,6 +210,13 @@ namespace drivers
|
||||
|
||||
const bool MODBUS::readInteger(const uint8_t device, const uint8_t func, const uint16_t reg, const uint16_t num, std::vector<uint16_t> &out)
|
||||
{
|
||||
// Delay Bus Access between different devices
|
||||
if (device != m_lastDevice)
|
||||
{
|
||||
LOG_DEBUG("MODBUS device change from ", printHex(m_lastDevice).c_str(), "to", printHex(device).c_str());
|
||||
BUS_DELAY;
|
||||
m_lastDevice = device;
|
||||
}
|
||||
if (!write(singleRequest(device, func, reg, num)))
|
||||
{
|
||||
LOG_ERROR("Failed send readInteger command");
|
||||
@@ -268,6 +263,13 @@ namespace drivers
|
||||
|
||||
const bool MODBUS::writeBinary(const uint8_t device, const uint8_t func, const uint16_t reg, const std::vector<bool> &in)
|
||||
{
|
||||
// Delay Bus Access between different devices
|
||||
if (device != m_lastDevice)
|
||||
{
|
||||
LOG_DEBUG("MODBUS device change from ", printHex(m_lastDevice).c_str(), "to", printHex(device).c_str());
|
||||
BUS_DELAY;
|
||||
m_lastDevice = device;
|
||||
}
|
||||
const uint16_t bits(in.size());
|
||||
std::vector<uint8_t> bitsOut;
|
||||
if (bits == 1) // if single coil value must be 0x00FF[00] for on[off]
|
||||
@@ -320,6 +322,13 @@ namespace drivers
|
||||
|
||||
const bool MODBUS::writeInteger(const uint8_t device, const uint8_t func, const uint16_t reg, const std::vector<uint16_t> &in, const bool multi)
|
||||
{
|
||||
// Delay Bus Access between different devices
|
||||
if (device != m_lastDevice)
|
||||
{
|
||||
LOG_DEBUG("MODBUS device change from ", printHex(m_lastDevice).c_str(), "to", printHex(device).c_str());
|
||||
BUS_DELAY;
|
||||
m_lastDevice = device;
|
||||
}
|
||||
const uint16_t num(in.size());
|
||||
if (!multi)
|
||||
{
|
||||
@@ -439,10 +448,12 @@ namespace drivers
|
||||
// verify crc code
|
||||
if (highByte(computedCrc) != crcHi || lowByte(computedCrc) != crcLo)
|
||||
{
|
||||
LOG_ERROR("Failed verify CRC code: comp[", computedCrc, "], rec[", receivedCrc, "]");
|
||||
LOG_ERROR("Failed verify CRC code: comp[", printHex(computedCrc).c_str(), "], rec[", printHex(receivedCrc).c_str(), "]");
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
#undef BUS_DELAY
|
||||
|
||||
@@ -34,7 +34,7 @@ namespace drivers
|
||||
|
||||
const uint8_t c_respHeaderSize = 3;
|
||||
const uint8_t c_respCrcSize = 2;
|
||||
const uint32_t c_minDelay = 500;
|
||||
const uint32_t c_minDelay = 250;
|
||||
|
||||
typedef struct
|
||||
{
|
||||
|
||||
37
lib/RS485/busdelay.h
Normal file
37
lib/RS485/busdelay.h
Normal file
@@ -0,0 +1,37 @@
|
||||
#pragma once
|
||||
|
||||
#define DEBUGLOG_DEFAULT_LOG_LEVEL_INFO
|
||||
|
||||
#include <DebugLog.h>
|
||||
#include <Arduino.h>
|
||||
|
||||
namespace drivers
|
||||
{
|
||||
|
||||
class BusDelay
|
||||
{
|
||||
public:
|
||||
BusDelay(uint32_t &lastAccess, const uint32_t minDelay, const char *title) : m_lastAccess(lastAccess)
|
||||
{
|
||||
const uint32_t now = millis();
|
||||
const uint32_t wait = now - lastAccess;
|
||||
if (wait < minDelay)
|
||||
{
|
||||
LOG_DEBUG(title, "delay", wait);
|
||||
delay(wait);
|
||||
}
|
||||
}
|
||||
|
||||
BusDelay(BusDelay &) = delete;
|
||||
BusDelay operator=(BusDelay &) = delete;
|
||||
|
||||
~BusDelay()
|
||||
{
|
||||
m_lastAccess = millis();
|
||||
}
|
||||
|
||||
private:
|
||||
uint32_t &m_lastAccess;
|
||||
};
|
||||
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
#include "PCF85063_Driver.h"
|
||||
#include <ctime>
|
||||
#include <utils.h>
|
||||
|
||||
namespace drivers
|
||||
{
|
||||
@@ -157,6 +158,23 @@ namespace drivers
|
||||
return false;
|
||||
}
|
||||
|
||||
const bool PCF85063::setOffset(const uint8_t ofst)
|
||||
{
|
||||
LOG_DEBUG("RTC set offset [", printHex(ofst).c_str(), "]");
|
||||
return m_i2c.write(m_address, RTC_OFFSET_ADDR, {ofst});
|
||||
}
|
||||
|
||||
const uint8_t PCF85063::getOffset()
|
||||
{
|
||||
std::vector<uint8_t> buf;
|
||||
if (m_i2c.read(m_address, RTC_OFFSET_ADDR, 1, buf))
|
||||
{
|
||||
LOG_DEBUG("RTC get offset [", printHex(buf.front()).c_str(), "]");
|
||||
return buf.front();
|
||||
}
|
||||
return UINT8_MAX;
|
||||
}
|
||||
|
||||
const std::string PCF85063::getTimeStr()
|
||||
{
|
||||
datetime_t dt;
|
||||
@@ -179,6 +197,19 @@ namespace drivers
|
||||
}
|
||||
|
||||
const std::string PCF85063::datetime2str(const datetime_t &datetime)
|
||||
{
|
||||
tm dtime = datetime2tm(datetime);
|
||||
const std::string buf(std::asctime(&dtime));
|
||||
return buf.substr(0, std::min(buf.find('\n'), buf.find('\r')));
|
||||
}
|
||||
|
||||
const std::string PCF85063::tm2str(const std::tm &datetime)
|
||||
{
|
||||
const std::string buf(std::asctime(&datetime));
|
||||
return buf.substr(0, std::min(buf.find('\n'), buf.find('\r')));
|
||||
}
|
||||
|
||||
const std::tm PCF85063::datetime2tm(const datetime_t &datetime)
|
||||
{
|
||||
tm dtime;
|
||||
dtime.tm_sec = datetime.second;
|
||||
@@ -188,8 +219,7 @@ namespace drivers
|
||||
dtime.tm_mday = datetime.day;
|
||||
dtime.tm_mon = datetime.month - 1;
|
||||
dtime.tm_year = datetime.year - 1900; // time offset in structure according cpp reference
|
||||
const std::string buf(std::asctime(&dtime));
|
||||
return buf.substr(0, std::min(buf.find('\n'),buf.find('\r')));
|
||||
return dtime;
|
||||
}
|
||||
|
||||
const uint8_t PCF85063::decToBcd(const int val)
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
#include <DebugLog.h>
|
||||
#include "I2C_Driver.h"
|
||||
#include <string>
|
||||
#include <time.h>
|
||||
|
||||
// PCF85063_ADDRESS
|
||||
#define PCF85063_ADDRESS (0x51)
|
||||
@@ -68,8 +69,6 @@ namespace drivers
|
||||
|
||||
class PCF85063
|
||||
{
|
||||
I2C &m_i2c;
|
||||
uint8_t m_address;
|
||||
|
||||
public:
|
||||
typedef struct
|
||||
@@ -84,7 +83,7 @@ namespace drivers
|
||||
} datetime_t;
|
||||
|
||||
public:
|
||||
PCF85063(I2C &i2c, const uint8_t address, const uint8_t ctrl1 = RTC_CTRL_1_DEFAULT, const uint8_t ctrl2 = RTC_CTRL_2_DEFAULT);
|
||||
PCF85063(I2C &i2c, const uint8_t address = PCF85063_ADDRESS, const uint8_t ctrl1 = RTC_CTRL_1_DEFAULT, const uint8_t ctrl2 = RTC_CTRL_2_DEFAULT);
|
||||
|
||||
const bool reset(void);
|
||||
|
||||
@@ -101,14 +100,23 @@ namespace drivers
|
||||
const bool readAlarm(datetime_t &time);
|
||||
const bool getAlarmFlag(uint8_t &flags);
|
||||
|
||||
const bool setOffset(const uint8_t ofst);
|
||||
const uint8_t getOffset();
|
||||
|
||||
const std::string getTimeStr();
|
||||
|
||||
static const std::string datetime2str(const datetime_t &datetime);
|
||||
static const std::string tm2str(const std::tm &datetime);
|
||||
static const std::tm datetime2tm(const datetime_t& datetime);
|
||||
static const PCF85063::datetime_t fromEpoch(const time_t currentTime);
|
||||
|
||||
private:
|
||||
const uint8_t decToBcd(const int val);
|
||||
const int bcdToDec(const uint8_t val);
|
||||
|
||||
private:
|
||||
I2C &m_i2c;
|
||||
uint8_t m_address;
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
#include <S50140_Driver.h>
|
||||
#include <busdelay.h>
|
||||
|
||||
#define BUS_DELAY drivers::BusDelay(m_lastRequest, c_minDelay, "S50140")
|
||||
|
||||
namespace drivers
|
||||
{
|
||||
@@ -63,22 +66,11 @@ namespace drivers
|
||||
return readFloatReg(REG_WhPart);
|
||||
}
|
||||
|
||||
void S50140::delayRequest()
|
||||
{
|
||||
auto now = millis();
|
||||
if ((now - m_lastRequest) < c_minDelay)
|
||||
{ // minimum m_lastRequest between requests
|
||||
LOG_DEBUG("S50140 delay request", (now-m_lastRequest));
|
||||
delay(now - m_lastRequest);
|
||||
}
|
||||
m_lastRequest = millis();
|
||||
}
|
||||
|
||||
const uint8_t S50140::getRegset()
|
||||
{
|
||||
std::vector<uint16_t> value;
|
||||
std::lock_guard<std::mutex> lock(m_bus.getMutex());
|
||||
delayRequest();
|
||||
BUS_DELAY;
|
||||
m_bus.readHoldingRegisters(m_address, REG_Regset, 2, value);
|
||||
if (value.empty())
|
||||
return UINT8_MAX;
|
||||
@@ -89,7 +81,7 @@ namespace drivers
|
||||
{
|
||||
std::vector<uint16_t> value;
|
||||
std::lock_guard<std::mutex> lock(m_bus.getMutex());
|
||||
delayRequest();
|
||||
BUS_DELAY;
|
||||
m_bus.readHoldingRegisters(m_address, REG_PartCount, 2, value);
|
||||
if (value.empty())
|
||||
return UINT16_MAX;
|
||||
@@ -107,18 +99,24 @@ namespace drivers
|
||||
while (retries++ < c_maxRetries)
|
||||
{
|
||||
bool ok(true);
|
||||
delayRequest();
|
||||
{
|
||||
LOG_WARN("Powermeter Counter STOP");
|
||||
BUS_DELAY;
|
||||
ok &= m_bus.writeRegisters(m_address, REG_PartCount, {nullVal, stopAll});
|
||||
delayRequest();
|
||||
};
|
||||
{
|
||||
LOG_WARN("Powermeter Counter RESET");
|
||||
BUS_DELAY;
|
||||
ok &= m_bus.writeRegisters(m_address, REG_PartCount, {nullVal, resetAll});
|
||||
delayRequest();
|
||||
};
|
||||
{
|
||||
LOG_WARN("Powermeter Counter START");
|
||||
BUS_DELAY;
|
||||
ok &= m_bus.writeRegisters(m_address, REG_PartCount, {nullVal, startAll});
|
||||
};
|
||||
if (ok)
|
||||
return;
|
||||
LOG_ERROR("Unable to Reset Powermeter Partial Counters, device", m_address);
|
||||
LOG_ERROR("Unable to Reset Powermeter Partial Counters, device", printHex(m_address).c_str());
|
||||
}
|
||||
return;
|
||||
}
|
||||
@@ -127,10 +125,9 @@ namespace drivers
|
||||
{
|
||||
uint8_t retries(0);
|
||||
std::vector<uint16_t> values;
|
||||
|
||||
while (retries++ < c_maxRetries)
|
||||
{
|
||||
delayRequest();
|
||||
BUS_DELAY;
|
||||
if (m_bus.readHoldingRegisters(m_address, reg, c_dataWords, values) && values.size() == c_dataWords)
|
||||
{
|
||||
floatval_t fv; // potrebbe essere il contrario, vedremo
|
||||
@@ -138,9 +135,11 @@ namespace drivers
|
||||
fv.words.hi = values[1];
|
||||
return fv.f;
|
||||
}
|
||||
LOG_ERROR("Unable to Read Powermeter values, device", m_address);
|
||||
LOG_ERROR("Unable to Read Powermeter values, device", printHex(m_address).c_str());
|
||||
}
|
||||
return MAXFLOAT;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
#undef BUS_DELAY
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
|
||||
#include <DebugLog.h>
|
||||
#include <RS485_Driver.h>
|
||||
#include <utils.h>
|
||||
|
||||
namespace drivers
|
||||
{
|
||||
@@ -13,7 +14,7 @@ namespace drivers
|
||||
private:
|
||||
const uint8_t c_maxRetries = 5;
|
||||
const uint8_t c_dataWords = 2;
|
||||
const uint32_t c_minDelay = 500;
|
||||
const uint32_t c_minDelay = 100;
|
||||
|
||||
const uint16_t REG_V = 0x100C;
|
||||
const uint16_t REG_A = 0x1016;
|
||||
@@ -74,7 +75,6 @@ namespace drivers
|
||||
void resetPartialCounters();
|
||||
|
||||
private:
|
||||
void delayRequest();
|
||||
float_t readFloatReg(const uint16_t reg);
|
||||
|
||||
private:
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
#include <R4DCB08_Driver.h>
|
||||
#include <busdelay.h>
|
||||
|
||||
#define BUS_DELAY drivers::BusDelay(m_lastRequest, c_minDelay, "R4DCB08")
|
||||
|
||||
namespace drivers
|
||||
{
|
||||
@@ -12,17 +15,6 @@ namespace drivers
|
||||
{
|
||||
}
|
||||
|
||||
void R4DCB08::delayRequest()
|
||||
{
|
||||
auto now = millis();
|
||||
if ((now - m_lastRequest) < c_minDelay)
|
||||
{ // minimum m_lastRequest between requests
|
||||
LOG_DEBUG("R4DCB08 delay request", (now-m_lastRequest));
|
||||
delay(now - m_lastRequest);
|
||||
}
|
||||
m_lastRequest = millis();
|
||||
}
|
||||
|
||||
const float R4DCB08::getTemp(const uint8_t ch)
|
||||
{
|
||||
uint8_t retries(0);
|
||||
@@ -35,12 +27,12 @@ namespace drivers
|
||||
std::lock_guard<std::mutex> lock(m_bus.getMutex());
|
||||
while (retries++ < c_maxRetries)
|
||||
{
|
||||
delayRequest();
|
||||
BUS_DELAY;
|
||||
if (m_bus.readHoldingRegisters(m_address, REG_TEMP + ch, 1, rawT) && !rawT.empty())
|
||||
{
|
||||
return rawT.front() / 10.0f;
|
||||
}
|
||||
LOG_ERROR("Failed to Read Temperature, device", m_address, "channel", ch);
|
||||
LOG_ERROR("Failed to Read Temperature, device", printHex(m_address).c_str(), "channel", ch);
|
||||
rawT.clear();
|
||||
}
|
||||
return MAXFLOAT;
|
||||
@@ -54,7 +46,7 @@ namespace drivers
|
||||
std::lock_guard<std::mutex> lock(m_bus.getMutex());
|
||||
while (retries++ < c_maxRetries)
|
||||
{
|
||||
delayRequest();
|
||||
BUS_DELAY;
|
||||
if (m_bus.readHoldingRegisters(m_address, REG_TEMP, getNum(), rawT) && !rawT.empty())
|
||||
{
|
||||
out.reserve(rawT.size());
|
||||
@@ -64,7 +56,7 @@ namespace drivers
|
||||
}
|
||||
return out;
|
||||
}
|
||||
LOG_ERROR("Failed to Read All Temperature, device", m_address);
|
||||
LOG_ERROR("Failed to Read All Temperature, device", printHex(m_address).c_str());
|
||||
rawT.clear();
|
||||
}
|
||||
out.clear();
|
||||
@@ -81,13 +73,13 @@ namespace drivers
|
||||
{
|
||||
while (retries++ < c_maxRetries)
|
||||
{
|
||||
delayRequest();
|
||||
BUS_DELAY;
|
||||
if (m_bus.writeRegister(m_address, REG_TEMPCORR + channel, v * 10)) // convert to decimal degreees to register value
|
||||
{
|
||||
channel++;
|
||||
break;
|
||||
}
|
||||
LOG_ERROR("Failed to Set Temperature Correction, device", m_address);
|
||||
LOG_ERROR("Failed to Set Temperature Correction, device", printHex(m_address).c_str());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -102,7 +94,7 @@ namespace drivers
|
||||
std::lock_guard<std::mutex> lock(m_bus.getMutex());
|
||||
while (retries++ < c_maxRetries)
|
||||
{
|
||||
delayRequest();
|
||||
BUS_DELAY;
|
||||
if (m_bus.readHoldingRegisters(m_address, REG_TEMPCORR, getNum(), rawV))
|
||||
{
|
||||
out.reserve(rawV.size());
|
||||
@@ -112,7 +104,7 @@ namespace drivers
|
||||
}
|
||||
return out;
|
||||
}
|
||||
LOG_ERROR("Failed to Get Temperature Correction, device", m_address);
|
||||
LOG_ERROR("Failed to Get Temperature Correction, device", printHex(m_address).c_str());
|
||||
rawV.clear();
|
||||
}
|
||||
out.clear();
|
||||
@@ -129,7 +121,7 @@ namespace drivers
|
||||
std::lock_guard<std::mutex> lock(m_bus.getMutex());
|
||||
while (retries++ < c_maxRetries)
|
||||
{
|
||||
delayRequest();
|
||||
BUS_DELAY;
|
||||
if (m_bus.readHoldingRegisters(m_address, REG_TEMP, T_MAX, rawT))
|
||||
{
|
||||
for (auto v : rawT)
|
||||
@@ -140,9 +132,11 @@ namespace drivers
|
||||
m_sensors = sensors;
|
||||
return m_sensors;
|
||||
}
|
||||
LOG_ERROR("Failed to Get Sensor Number, device", m_address);
|
||||
LOG_ERROR("Failed to Get Sensor Number, device", printHex(m_address).c_str());
|
||||
}
|
||||
LOG_ERROR("No Temperature Sensors Detected, device", m_address);
|
||||
LOG_ERROR("No Temperature Sensors Detected, device", printHex(m_address).c_str());
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
#undef BUS_DELAY
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
|
||||
#include <DebugLog.h>
|
||||
#include <RS485_Driver.h>
|
||||
#include <utils.h>
|
||||
|
||||
namespace drivers
|
||||
{
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
#include "utils.h"
|
||||
|
||||
|
||||
void printBytes(const char title[], const std::vector<uint8_t> &b)
|
||||
{
|
||||
Serial0.flush();
|
||||
@@ -40,7 +39,7 @@ void printBool(const char title[], const std::vector<bool> &vals)
|
||||
const std::string printBoolVec(const std::vector<bool> &vals)
|
||||
{
|
||||
std::string buf;
|
||||
buf.reserve(vals.size()+1);
|
||||
buf.reserve(vals.size() + 1);
|
||||
buf.append("b");
|
||||
for (const auto v : vals)
|
||||
{
|
||||
@@ -48,3 +47,17 @@ const std::string printBoolVec(const std::vector<bool> &vals)
|
||||
}
|
||||
return buf;
|
||||
}
|
||||
|
||||
const std::string printHex(const uint8_t val)
|
||||
{
|
||||
std::string buf(5, '\0');
|
||||
sprintf(buf.data(), "0x%02x", val);
|
||||
return buf;
|
||||
}
|
||||
|
||||
const std::string printHex(const uint16_t val)
|
||||
{
|
||||
std::string buf(7, '\0');
|
||||
sprintf(buf.data(), "0x%04x", val);
|
||||
return buf;
|
||||
}
|
||||
@@ -16,3 +16,7 @@ void printBytes(const char title[], const std::vector<uint16_t> &b);
|
||||
void printBool(const char title[], const std::vector<bool> &vals);
|
||||
|
||||
const std::string printBoolVec(const std::vector<bool> &vals);
|
||||
|
||||
const std::string printHex(const uint8_t val);
|
||||
|
||||
const std::string printHex(const uint16_t val);
|
||||
|
||||
@@ -23,17 +23,19 @@ build_type = release
|
||||
board_build.filesystem = ffat
|
||||
board_build.partitions = fatfs_partition.csv ; se stai usando uno custom
|
||||
|
||||
upload_protocol = espota
|
||||
upload_port = 10.0.2.139
|
||||
|
||||
|
||||
[env:esp32-s3-waveshare8-debug]
|
||||
platform = ${env:esp32-s3-waveshare8.platform}
|
||||
board = ${env:esp32-s3-waveshare8.board}
|
||||
framework = ${env:esp32-s3-waveshare8.framework}
|
||||
lib_deps =
|
||||
bblanchon/ArduinoJson@^7.4.2
|
||||
arduino-libraries/NTPClient@^3.2.1
|
||||
knolleary/PubSubClient@^2.8
|
||||
robtillaart/CRC@^1.0.3
|
||||
hideakitai/DebugLog@^0.8.4
|
||||
lib_deps = ${env:esp32-s3-waveshare8.lib_deps}
|
||||
|
||||
board_build.filesystem = ffat
|
||||
board_build.partitions = fatfs_partition.csv ; se stai usando uno custom
|
||||
|
||||
build_type = debug
|
||||
build_flags =
|
||||
-O0
|
||||
@@ -44,5 +46,3 @@ build_flags =
|
||||
-fno-tree-sra
|
||||
-fno-builtin
|
||||
|
||||
board_build.filesystem = ffat
|
||||
board_build.partitions = fatfs_partition.csv ; se stai usando uno custom
|
||||
|
||||
577
src/commands.cpp
Normal file
577
src/commands.cpp
Normal file
@@ -0,0 +1,577 @@
|
||||
#include <commands.h>
|
||||
#include <cronjobs.h>
|
||||
|
||||
namespace commands
|
||||
{
|
||||
|
||||
void restart(TimerHandle_t t)
|
||||
{
|
||||
esp_restart();
|
||||
}
|
||||
const ArduinoJson::JsonDocument Commands::setBuzz(const devices_t &dev, const ArduinoJson::JsonDocument ¶ms)
|
||||
{
|
||||
ArduinoJson::JsonDocument response;
|
||||
dev.buzzer.beep(500, NOTE_Bb);
|
||||
return response;
|
||||
}
|
||||
|
||||
// CONFIG //
|
||||
// CONFIG //
|
||||
const ArduinoJson::JsonDocument Commands::setConfig(const devices_t &dev, const ArduinoJson::JsonDocument ¶ms)
|
||||
{
|
||||
ArduinoJson::JsonDocument response;
|
||||
auto &conf = Config::getInstance();
|
||||
std::string buf;
|
||||
response["cmd"] = "setConfig";
|
||||
auto values = response["values"].to<JsonObject>();
|
||||
if (params.isNull())
|
||||
{
|
||||
values["status"] = "Invalid";
|
||||
return response;
|
||||
}
|
||||
conf.setConfig(params);
|
||||
values["status"] = "Valid";
|
||||
serializeJson(params, buf);
|
||||
LOG_INFO("setConfig ->", buf.c_str());
|
||||
TimerHandle_t resetTimer(xTimerCreate("restartTimer", pdMS_TO_TICKS(5000), false, NULL, restart));
|
||||
LOG_WARN("setConfig will cause restart!");
|
||||
if (resetTimer)
|
||||
{
|
||||
xTimerStart(resetTimer, 0);
|
||||
}
|
||||
return response;
|
||||
}
|
||||
const ArduinoJson::JsonDocument Commands::getConfig(const devices_t &dev, const ArduinoJson::JsonDocument ¶ms)
|
||||
{
|
||||
ArduinoJson::JsonDocument response;
|
||||
auto &conf = Config::getInstance();
|
||||
std::string buf;
|
||||
response["cmd"] = "getConfig";
|
||||
response["values"] = conf.getConfig();
|
||||
serializeJson(response["values"], buf);
|
||||
LOG_INFO("getConfig ->", buf.c_str());
|
||||
return response;
|
||||
}
|
||||
// CONFIG //
|
||||
// CONFIG //
|
||||
|
||||
// CRONJOBS //
|
||||
// CRONJOBS //
|
||||
const ArduinoJson::JsonDocument Commands::loadCronJob(const devices_t &dev, const ArduinoJson::JsonDocument ¶ms)
|
||||
{
|
||||
ArduinoJson::JsonDocument response;
|
||||
response["cmd"] = "loadCronJob";
|
||||
auto &cron = Cron::getInstance(dev);
|
||||
if (!cron.loadEvents())
|
||||
{
|
||||
LOG_ERROR("loadCronJob failed to load events from flash");
|
||||
response["values"]["status"] = "invalid";
|
||||
return response;
|
||||
}
|
||||
response["values"]["status"] = "valid";
|
||||
return response;
|
||||
}
|
||||
const ArduinoJson::JsonDocument Commands::addCronJob(const devices_t &dev, const ArduinoJson::JsonDocument ¶ms)
|
||||
{
|
||||
ArduinoJson::JsonDocument response;
|
||||
response["cmd"] = "addCronJob";
|
||||
|
||||
const auto &eventName = params["name"].as<std::string>();
|
||||
const auto &timeStr = params["cronExpr"].as<std::string>();
|
||||
const auto &actionStr = params["action"].as<std::string>();
|
||||
response["values"]["name"] = eventName;
|
||||
|
||||
ArduinoJson::JsonDocument action;
|
||||
if (ArduinoJson::deserializeJson(action, actionStr) != ArduinoJson::DeserializationError::Ok)
|
||||
{
|
||||
LOG_ERROR("addCronJob unable to deserialize cron job [", actionStr.c_str(), "]");
|
||||
response["values"]["status"] = "invalid";
|
||||
return response;
|
||||
}
|
||||
|
||||
auto &cron = Cron::getInstance(dev);
|
||||
if (!cron.addEvent(eventName, timeStr, action))
|
||||
{
|
||||
LOG_ERROR("addCronJob unable to add job [", actionStr.c_str(), "]");
|
||||
response["values"]["status"] = "invalid";
|
||||
return response;
|
||||
}
|
||||
LOG_INFO("addCronJob added job [", actionStr.c_str(), "]");
|
||||
response["values"]["status"] = "valid";
|
||||
return response;
|
||||
}
|
||||
const ArduinoJson::JsonDocument Commands::setCronJob(const devices_t &dev, const ArduinoJson::JsonDocument ¶ms)
|
||||
{
|
||||
ArduinoJson::JsonDocument response;
|
||||
response["cmd"] = "setCronJob";
|
||||
const auto &eventName = params["name"].as<std::string>();
|
||||
const auto &statusStr = params["status"].as<std::string>();
|
||||
response["values"]["name"] = eventName;
|
||||
|
||||
auto &cron = Cron::getInstance(dev);
|
||||
if (Cron::str2Enum(statusStr) == Cron::str2Enum("INVALID"))
|
||||
{
|
||||
LOG_ERROR("setCronJob invalid status [", statusStr.c_str(), "]");
|
||||
response["values"]["status"] = "invalid";
|
||||
return response;
|
||||
}
|
||||
cron.setEvent(eventName, Cron::str2Enum(statusStr));
|
||||
LOG_INFO("setCronJob set job [", eventName.c_str(), "] to [", statusStr.c_str(), "]");
|
||||
response["values"]["status"] = "valid";
|
||||
return response;
|
||||
}
|
||||
const ArduinoJson::JsonDocument Commands::getCronJob(const devices_t &dev, const ArduinoJson::JsonDocument ¶ms)
|
||||
{
|
||||
ArduinoJson::JsonDocument response;
|
||||
response["cmd"] = "getCronJob";
|
||||
auto &cron = Cron::getInstance(dev);
|
||||
auto eventName = params["name"].as<std::string>();
|
||||
|
||||
if (eventName.empty())
|
||||
{
|
||||
LOG_ERROR("getCronJob empty job name");
|
||||
response["values"]["status"] = "invalid";
|
||||
return response;
|
||||
}
|
||||
|
||||
if (eventName == "all")
|
||||
{
|
||||
const auto &eventMap = cron.getAllEvents();
|
||||
uint8_t eventNum(0);
|
||||
for (const auto &[name, event] : eventMap)
|
||||
{
|
||||
ArduinoJson::JsonDocument action;
|
||||
action["cmd"] = event.cmd;
|
||||
action["params"] = event.cmdParams;
|
||||
action["status"] = Cron::enum2Str(event.status);
|
||||
action["next"] = drivers::PCF85063::tm2str(event.next);
|
||||
response["values"][name] = action;
|
||||
eventNum++;
|
||||
}
|
||||
LOG_INFO("getCronJob got [", eventNum, "] events");
|
||||
return response;
|
||||
}
|
||||
|
||||
Cron::CronEvent event;
|
||||
response["values"]["name"] = eventName;
|
||||
if (!cron.getEvent(eventName, event))
|
||||
{
|
||||
LOG_ERROR("getCronJob failed to get job [", eventName.c_str(), "]");
|
||||
response["values"]["status"] = "invalid";
|
||||
return response;
|
||||
}
|
||||
|
||||
ArduinoJson::JsonDocument action;
|
||||
action["cmd"] = event.cmd;
|
||||
action["params"] = event.cmdParams;
|
||||
action["status"] = Cron::enum2Str(event.status);
|
||||
action["next"] = drivers::PCF85063::tm2str(event.next);
|
||||
action["cronExpr"] = cron::to_cronstr(event.cronExpr);
|
||||
response["values"]["action"] = action;
|
||||
LOG_INFO("getCronJob get job [", eventName.c_str(), "]");
|
||||
return response;
|
||||
}
|
||||
const ArduinoJson::JsonDocument Commands::delCronJob(const devices_t &dev, const ArduinoJson::JsonDocument ¶ms)
|
||||
{
|
||||
ArduinoJson::JsonDocument response;
|
||||
response["cmd"] = "delCronJob";
|
||||
auto &cron = Cron::getInstance(dev);
|
||||
auto eventName = params["name"].as<std::string>();
|
||||
response["values"]["name"] = eventName;
|
||||
if (eventName.empty() || !cron.delEvent(eventName))
|
||||
{
|
||||
LOG_ERROR("delCronJob failed to delete job [", eventName.c_str(), "]");
|
||||
response["values"]["status"] = "invalid";
|
||||
return response;
|
||||
}
|
||||
response["values"]["status"] = "valid";
|
||||
return response;
|
||||
}
|
||||
const ArduinoJson::JsonDocument Commands::storeCronJob(const devices_t &dev, const ArduinoJson::JsonDocument ¶ms)
|
||||
{
|
||||
ArduinoJson::JsonDocument response;
|
||||
response["cmd"] = "storeCronJob";
|
||||
auto &cron = Cron::getInstance(dev);
|
||||
if (!cron.storeEvents())
|
||||
{
|
||||
LOG_ERROR("storeCronJob failed to store events in flash");
|
||||
response["values"]["status"] = "invalid";
|
||||
return response;
|
||||
}
|
||||
response["values"]["status"] = "valid";
|
||||
return response;
|
||||
}
|
||||
// CRONJOBS //
|
||||
// CRONJOBS //
|
||||
|
||||
// SETTERS //
|
||||
// SETTERS //
|
||||
const ArduinoJson::JsonDocument Commands::resetHPcounters(const devices_t &dev, const ArduinoJson::JsonDocument ¶ms)
|
||||
{
|
||||
ArduinoJson::JsonDocument response;
|
||||
response["cmd"] = "resetHPcounters";
|
||||
response["values"]["status"] = "valid";
|
||||
dev.seneca.resetPartialCounters();
|
||||
return response;
|
||||
}
|
||||
|
||||
const ArduinoJson::JsonDocument Commands::setHPlimit(const devices_t &dev, const ArduinoJson::JsonDocument ¶ms)
|
||||
{
|
||||
ArduinoJson::JsonDocument response;
|
||||
response["cmd"] = "setHPlimit";
|
||||
if (!params["level"].is<std::string>())
|
||||
{
|
||||
LOG_ERROR("setHPlimit incorrect parameters");
|
||||
return response;
|
||||
}
|
||||
const auto level = params["level"].as<std::string>();
|
||||
response["values"]["level"] = level;
|
||||
if (!c_hpLimitsMap.contains(level))
|
||||
{
|
||||
LOG_ERROR("setHPlimit invalid level", level.c_str());
|
||||
response["values"]["status"] = "invalid";
|
||||
return response;
|
||||
}
|
||||
for (const auto [lvl, ro] : c_hpLimitsMap)
|
||||
{
|
||||
if (ro == RO::RO_MAX)
|
||||
continue; // avoid overshooting relay range
|
||||
if (level == lvl && level != "UNLIMITED")
|
||||
dev.io.digitalOutWrite(ro, true);
|
||||
else
|
||||
dev.io.digitalOutWrite(ro, false);
|
||||
}
|
||||
LOG_INFO("setHPlimit -> level", level.c_str());
|
||||
response["values"]["status"] = "valid";
|
||||
return response;
|
||||
}
|
||||
const ArduinoJson::JsonDocument Commands::setHeating(const devices_t &dev, const ArduinoJson::JsonDocument ¶ms)
|
||||
{
|
||||
ArduinoJson::JsonDocument response;
|
||||
response["cmd"] = "setHeating";
|
||||
if (params.isNull())
|
||||
{
|
||||
LOG_ERROR("setHeating incorrect paramaters");
|
||||
return response;
|
||||
}
|
||||
for (const auto [lvl, ro] : c_heatingValveMap)
|
||||
{
|
||||
if (params[lvl].isNull())
|
||||
continue;
|
||||
if (params[lvl] == "ON")
|
||||
{
|
||||
dev.io.digitalOutWrite(ro, true);
|
||||
response["values"][lvl] = "ON";
|
||||
LOG_INFO("setHeating -> ", lvl.c_str(), "ON");
|
||||
}
|
||||
else if (params[lvl] == "OFF")
|
||||
{
|
||||
dev.io.digitalOutWrite(ro, false);
|
||||
response["values"][lvl] = "OFF";
|
||||
LOG_INFO("setHeating -> ", lvl.c_str(), "OFF");
|
||||
}
|
||||
else
|
||||
{
|
||||
response["values"][lvl] = "invalid";
|
||||
LOG_ERROR("setHeating invalid valve state");
|
||||
}
|
||||
}
|
||||
return response;
|
||||
}
|
||||
void resetZone(TimerHandle_t th)
|
||||
{
|
||||
devices_t *dev = (devices_t *)pvTimerGetTimerID(th);
|
||||
const char *timerName = pcTimerGetName(th);
|
||||
LOG_INFO("setIrrigation shutdown zone [", timerName, "]");
|
||||
if (!c_irrigationValveMap.contains(timerName))
|
||||
{
|
||||
LOG_ERROR("Irrigation timer name invalid");
|
||||
return;
|
||||
}
|
||||
dev->io.digitalOutWrite(c_irrigationValveMap.at(timerName), false);
|
||||
c_irrigationTimerMap.at(timerName).second = NULL; // reset timer handle for this timer
|
||||
xTimerDelete(th, 0); // delete the timer on expiry
|
||||
}
|
||||
void resetWaterPump(TimerHandle_t th)
|
||||
{
|
||||
devices_t *dev = (devices_t *)pvTimerGetTimerID(th);
|
||||
LOG_INFO("setIrrigation shutdown pump");
|
||||
dev->io.digitalOutWrite(RO::PUMP_IRR, false);
|
||||
s_irrigationPumpTimer = NULL;
|
||||
xTimerDelete(th, 0); // delete the timer on expiry
|
||||
}
|
||||
const ArduinoJson::JsonDocument Commands::setIrrigation(const devices_t &dev, const ArduinoJson::JsonDocument ¶ms)
|
||||
{
|
||||
ArduinoJson::JsonDocument response;
|
||||
auto &conf = Config::getInstance();
|
||||
response["cmd"] = "setIrrigation";
|
||||
if (params.isNull())
|
||||
{
|
||||
LOG_ERROR("setIrrigation incorrect paramaters");
|
||||
return response;
|
||||
}
|
||||
const std::string zone(params["zone"].as<std::string>());
|
||||
const uint16_t tOn(params["timeOn"].as<uint16_t>());
|
||||
const uint16_t tPause(params["timePause"].as<uint16_t>());
|
||||
response["values"]["zone"] = zone;
|
||||
|
||||
if (zone == "stop")
|
||||
{ // stop all zones and reset timers
|
||||
LOG_INFO("setIrrigation stop all zones");
|
||||
for (auto &h : c_irrigationTimerMap)
|
||||
{
|
||||
const auto zoneName = h.first;
|
||||
auto &timerHandle = h.second.second; // get the timer handle
|
||||
if (timerHandle) // if handle is not null (not from a deleted timer)
|
||||
{
|
||||
if (xTimerIsTimerActive(timerHandle)) // stop the timer if active
|
||||
{
|
||||
LOG_INFO("setIrrigation stopping timer", zoneName.c_str());
|
||||
xTimerStop(timerHandle, 0);
|
||||
xTimerDelete(timerHandle, pdMS_TO_TICKS(10)); // delete it
|
||||
timerHandle = NULL;
|
||||
}
|
||||
}
|
||||
LOG_INFO("setIrrigation closing", zoneName.c_str());
|
||||
dev.io.digitalOutWrite(c_irrigationValveMap.at(zoneName), false); // shutdown the valve
|
||||
}
|
||||
if (s_irrigationPumpTimer)
|
||||
{
|
||||
xTimerChangePeriod(s_irrigationPumpTimer, pdMS_TO_TICKS(30 * 1000), 0); // shutdown the pump in 30s after the stop
|
||||
xTimerReset(s_irrigationPumpTimer, 0);
|
||||
}
|
||||
response["values"]["status"] = "stop";
|
||||
return response;
|
||||
}
|
||||
|
||||
if (!s_rainOverride && !dev.io.digitalInRead(DI::RAIN)) // verify rain sensor and override value (rain sensor input is inverted)
|
||||
{
|
||||
LOG_WARN("setIrrigation skipping zone [", zone.c_str(), "] because its raining");
|
||||
response["values"]["status"] = "rain";
|
||||
return response;
|
||||
}
|
||||
|
||||
response["values"]["timeOn"] = tOn;
|
||||
response["values"]["timePause"] = tPause;
|
||||
if (!c_irrigationValveMap.contains(zone) || tOn <= 0 || tPause <= 0) // verify if zone is a valid map key
|
||||
{
|
||||
LOG_ERROR("setIrrigation incorrect zone[", zone.c_str(), "] or time values tOn[", tOn, "] tPause[", tPause, "]");
|
||||
response["values"]["status"] = "invalid";
|
||||
return response;
|
||||
}
|
||||
|
||||
// verify if timer was already started, zone is already on
|
||||
const auto timerName = c_irrigationTimerMap.at(zone).first;
|
||||
const auto zoneIoNumber = c_irrigationValveMap.at(zone);
|
||||
auto &timerHandle = c_irrigationTimerMap.at(zone).second;
|
||||
|
||||
if (timerHandle)
|
||||
{ // this timer was alteady started, ignore command
|
||||
LOG_WARN("setIrrigation zone [", timerName, "] already started");
|
||||
response["values"]["status"] = "conflict";
|
||||
return response;
|
||||
}
|
||||
|
||||
const uint32_t pumpTime((tOn + 30) * 1000);
|
||||
const uint32_t zoneTime(tOn * 1000);
|
||||
|
||||
if (!s_irrigationPumpTimer) // Pump has not yet started
|
||||
{
|
||||
s_irrigationPumpTimer = xTimerCreate("pumpTimer", pdMS_TO_TICKS(pumpTime), false, (void *)&dev, resetWaterPump);
|
||||
dev.io.digitalOutWrite(RO::PUMP_IRR, true);
|
||||
xTimerStart(s_irrigationPumpTimer, 0); // immediate start pump timer
|
||||
LOG_INFO("setIrrigation pump time", pumpTime);
|
||||
}
|
||||
else
|
||||
{
|
||||
const auto currentRemaining(xTimerGetExpiryTime(s_irrigationPumpTimer) - xTaskGetTickCount());
|
||||
const auto newRemaining(pumpTime);
|
||||
const auto newPeriod(std::max(newRemaining, currentRemaining));
|
||||
xTimerChangePeriod(s_irrigationPumpTimer, newPeriod, 0); // set new period based on timing of new zone
|
||||
xTimerReset(s_irrigationPumpTimer, 0); // if timer was already started, restart
|
||||
LOG_INFO("setIrrigation pump time reset", newRemaining);
|
||||
}
|
||||
|
||||
TimerHandle_t shTimer(xTimerCreate(timerName, pdMS_TO_TICKS(zoneTime), false, (void *)&dev, resetZone));
|
||||
if (shTimer)
|
||||
{
|
||||
dev.io.digitalOutWrite(zoneIoNumber, true);
|
||||
// controllare riempimento serbatoio con controllo del pressostato, magari in un timer
|
||||
xTimerStart(shTimer, 0);
|
||||
timerHandle = shTimer;
|
||||
response["values"]["status"] = "valid";
|
||||
LOG_INFO("setIrrigation zone [", timerName, "] tOn[", tOn, "] tPause[", tPause, "]");
|
||||
}
|
||||
return response;
|
||||
}
|
||||
const ArduinoJson::JsonDocument Commands::setRainOverride(const devices_t &dev, const ArduinoJson::JsonDocument ¶ms)
|
||||
{
|
||||
ArduinoJson::JsonDocument response;
|
||||
response["cmd"] = "setRainOverride";
|
||||
if (params.isNull())
|
||||
{
|
||||
LOG_ERROR("setRainOverride incorrect paramaters");
|
||||
return response;
|
||||
}
|
||||
s_rainOverride = params["status"].as<std::string>() == "True" ? true : false;
|
||||
response["values"]["status"] = "valid";
|
||||
LOG_INFO("setRainOverride [", s_rainOverride ? "True]" : "False]");
|
||||
return response;
|
||||
}
|
||||
const ArduinoJson::JsonDocument Commands::setTimeNTP(const devices_t &dev, const ArduinoJson::JsonDocument ¶ms)
|
||||
{
|
||||
ArduinoJson::JsonDocument response;
|
||||
response["cmd"] = "setTimeNTP";
|
||||
auto ð = dev.eth;
|
||||
auto &rtc = dev.rtc;
|
||||
|
||||
time_t ntpTime;
|
||||
auto ntpOk = eth.getNtpTime(ntpTime);
|
||||
|
||||
drivers::PCF85063::datetime_t rtcTime(drivers::PCF85063::fromEpoch(ntpTime));
|
||||
auto rtcOk = rtc.setDatetime(rtcTime);
|
||||
|
||||
if (!rtcOk || !ntpOk)
|
||||
{
|
||||
response["values"]["status"] = "invalid";
|
||||
return response;
|
||||
}
|
||||
|
||||
response["values"]["status"] = "valid";
|
||||
response["values"]["time"] = rtc.getTimeStr();
|
||||
LOG_INFO("setTimeNTP -> RTC is [", response["values"]["time"].as<std::string>().c_str(), "]");
|
||||
return response;
|
||||
}
|
||||
// SETTERS //
|
||||
// SETTERS //
|
||||
|
||||
// GETTERS //
|
||||
// GETTERS //
|
||||
const ArduinoJson::JsonDocument Commands::getHPpower(const devices_t &dev, const ArduinoJson::JsonDocument ¶ms)
|
||||
{
|
||||
ArduinoJson::JsonDocument response;
|
||||
response["cmd"] = "getHPpower";
|
||||
const auto pinfo = dev.seneca.getAll();
|
||||
auto values = response["values"].to<JsonObject>();
|
||||
values["power"] = pinfo.pAct;
|
||||
values["current"] = pinfo.a;
|
||||
values["voltage"] = pinfo.v;
|
||||
values["energy"] = pinfo.whPar;
|
||||
LOG_INFO("getHPpower -> power", pinfo.pAct, "current", pinfo.a, "voltage", pinfo.v, "energy", pinfo.whPar);
|
||||
return response;
|
||||
}
|
||||
const ArduinoJson::JsonDocument Commands::getInputStatus(const devices_t &dev, const ArduinoJson::JsonDocument ¶ms)
|
||||
{
|
||||
ArduinoJson::JsonDocument response;
|
||||
response["cmd"] = "getInputStatus";
|
||||
const std::vector<bool> inStatus(dev.io.digitalInReadPort());
|
||||
if (inStatus.empty() || inStatus.size() != dev.io.getInNum())
|
||||
{
|
||||
response["values"] = "invalid";
|
||||
return response;
|
||||
}
|
||||
uint8_t i(0);
|
||||
for (auto s : inStatus)
|
||||
{
|
||||
response["values"][DI_2str.at(i++)] = s;
|
||||
}
|
||||
LOG_INFO("getInputStatus ->", printBoolVec(inStatus).c_str());
|
||||
return response;
|
||||
}
|
||||
const ArduinoJson::JsonDocument Commands::getOutputStatus(const devices_t &dev, const ArduinoJson::JsonDocument ¶ms)
|
||||
{
|
||||
ArduinoJson::JsonDocument response;
|
||||
response["cmd"] = "getOutputStatus";
|
||||
const std::vector<bool> inStatus(dev.io.digitalOutReadPort());
|
||||
if (inStatus.empty() || inStatus.size() != dev.io.getOutNum())
|
||||
{
|
||||
response["values"] = "invalid";
|
||||
return response;
|
||||
}
|
||||
uint8_t i(0);
|
||||
for (auto s : inStatus)
|
||||
{
|
||||
response["values"][RO_2str.at(i++)] = s;
|
||||
}
|
||||
LOG_INFO("getOutputStatus ->", printBoolVec(inStatus).c_str());
|
||||
return response;
|
||||
}
|
||||
const ArduinoJson::JsonDocument Commands::getTemperatures(const devices_t &dev, const ArduinoJson::JsonDocument ¶ms)
|
||||
{
|
||||
ArduinoJson::JsonDocument response;
|
||||
LOG_WARN("Comand not yet implemented");
|
||||
return response;
|
||||
}
|
||||
const ArduinoJson::JsonDocument Commands::getWaterInfo(const devices_t &dev, const ArduinoJson::JsonDocument ¶ms)
|
||||
{
|
||||
ArduinoJson::JsonDocument response;
|
||||
LOG_WARN("Comand not yet implemented");
|
||||
return response;
|
||||
}
|
||||
const ArduinoJson::JsonDocument Commands::getTankInfo(const devices_t &dev, const ArduinoJson::JsonDocument ¶ms)
|
||||
{
|
||||
ArduinoJson::JsonDocument response;
|
||||
LOG_WARN("Comand not yet implemented");
|
||||
return response;
|
||||
}
|
||||
const ArduinoJson::JsonDocument Commands::getRainInfo(const devices_t &dev, const ArduinoJson::JsonDocument ¶ms)
|
||||
{
|
||||
ArduinoJson::JsonDocument response;
|
||||
const auto rain = !dev.io.digitalInRead(DI::RAIN) ? "True" : "False";
|
||||
response["cmd"] = "getRainInfo";
|
||||
response["values"]["status"] = rain;
|
||||
LOG_INFO("getRainInfo -> ", rain);
|
||||
return response;
|
||||
}
|
||||
const ArduinoJson::JsonDocument Commands::getIrrigation(const devices_t &dev, const ArduinoJson::JsonDocument ¶ms)
|
||||
{
|
||||
ArduinoJson::JsonDocument response;
|
||||
LOG_WARN("Comand not yet implemented");
|
||||
return response;
|
||||
}
|
||||
const ArduinoJson::JsonDocument Commands::getRainOverride(const devices_t &dev, const ArduinoJson::JsonDocument ¶ms)
|
||||
{
|
||||
ArduinoJson::JsonDocument response;
|
||||
const auto ovr = s_rainOverride ? "True" : "False";
|
||||
response["cmd"] = "getRainOverride";
|
||||
response["values"]["rainOverride"] = ovr;
|
||||
LOG_INFO("getRainOverride -> ", ovr);
|
||||
return response;
|
||||
}
|
||||
const ArduinoJson::JsonDocument Commands::getTimeDrift(const devices_t &dev, const ArduinoJson::JsonDocument ¶ms)
|
||||
{
|
||||
ArduinoJson::JsonDocument response;
|
||||
response["cmd"] = "getTimeDrift";
|
||||
auto ð = dev.eth;
|
||||
auto &rtc = dev.rtc;
|
||||
|
||||
time_t ntpTime;
|
||||
auto ntpOk = eth.getNtpTime(ntpTime);
|
||||
|
||||
drivers::PCF85063::datetime_t rtcTime;
|
||||
auto rtcOk = rtc.readDatetime(rtcTime);
|
||||
auto rtcTimeTm = drivers::PCF85063::datetime2tm(rtcTime);
|
||||
|
||||
if (!rtcOk || !ntpOk)
|
||||
{
|
||||
response["values"]["status"] = "invalid";
|
||||
return response;
|
||||
}
|
||||
|
||||
auto ntpTimePoint = std::chrono::system_clock::from_time_t(ntpTime);
|
||||
auto rtcTimePoint = std::chrono::system_clock::from_time_t(std::mktime(&rtcTimeTm));
|
||||
|
||||
auto timeDiff = std::chrono::duration_cast<std::chrono::seconds>(ntpTimePoint - rtcTimePoint);
|
||||
auto direction = timeDiff.count() >= 0 ? "BEYOND" : "AHEAD";
|
||||
const int32_t drift = timeDiff.count();
|
||||
|
||||
response["values"]["status"] = "valid";
|
||||
response["values"]["drift"] = drift;
|
||||
response["values"]["direction"] = "RTC is [" + std::string(direction) + "] NTP time";
|
||||
LOG_INFO("getTimeDrift -> RTC is [", drift, "] sec, [", direction, "] NTP time");
|
||||
return response;
|
||||
}
|
||||
// GETTERS //
|
||||
// GETTERS //
|
||||
|
||||
}
|
||||
114
src/commands.h
Normal file
114
src/commands.h
Normal file
@@ -0,0 +1,114 @@
|
||||
#pragma once
|
||||
|
||||
#define DEBUGLOG_DEFAULT_LOG_LEVEL_INFO
|
||||
|
||||
#include <DebugLog.h>
|
||||
#include <Arduino.h>
|
||||
#include <ArduinoJson.h>
|
||||
|
||||
#include <config.h>
|
||||
#include <devices.h>
|
||||
#include <pinlist.h>
|
||||
|
||||
namespace commands
|
||||
{
|
||||
static const std::map<const std::string, uint8_t> c_hpLimitsMap = {{"P1", RO::P1},
|
||||
{"P2", RO::P2},
|
||||
{"P3", RO::P3},
|
||||
{"P4", RO::P4},
|
||||
{"UNLIMITED", RO::RO_MAX}};
|
||||
|
||||
static const std::map<const std::string, uint8_t> c_heatingValveMap = {{"pump", RO::PUMP_HT},
|
||||
{"first", RO::FST_FLOOR},
|
||||
{"ground", RO::GND_FLOOR}};
|
||||
|
||||
static const std::map<const std::string, uint8_t> c_irrigationValveMap = {{"ricircolo", RO::RETURN},
|
||||
{"zone1", RO::ZONE1},
|
||||
{"zone2", RO::ZONE2},
|
||||
{"zone3", RO::ZONE3},
|
||||
{"rubinetti", RO::DRIP}};
|
||||
|
||||
static std::map<const std::string, std::pair<const char *, TimerHandle_t>> c_irrigationTimerMap = {{"ricircolo", {"ricircolo", NULL}},
|
||||
{"zone1", {"zone1", NULL}},
|
||||
{"zone2", {"zone2", NULL}},
|
||||
{"zone3", {"zone3", NULL}},
|
||||
{"rubinetti", {"rubinetti", NULL}}};
|
||||
|
||||
static TimerHandle_t s_irrigationPumpTimer = NULL;
|
||||
static bool s_rainOverride = false;
|
||||
|
||||
// define command callback type
|
||||
using Command = std::function<const ArduinoJson::JsonDocument(const devices_t &, const ArduinoJson::JsonDocument &)>;
|
||||
|
||||
class Commands
|
||||
{
|
||||
Commands() = delete;
|
||||
|
||||
public:
|
||||
// TEST //
|
||||
static const ArduinoJson::JsonDocument setBuzz(const devices_t &dev, const ArduinoJson::JsonDocument ¶ms);
|
||||
|
||||
// CONFIG //
|
||||
static const ArduinoJson::JsonDocument setConfig(const devices_t &dev, const ArduinoJson::JsonDocument ¶ms);
|
||||
static const ArduinoJson::JsonDocument getConfig(const devices_t &dev, const ArduinoJson::JsonDocument ¶ms);
|
||||
|
||||
// CRONJOBS //
|
||||
static const ArduinoJson::JsonDocument loadCronJob(const devices_t &dev, const ArduinoJson::JsonDocument ¶ms);
|
||||
static const ArduinoJson::JsonDocument addCronJob(const devices_t &dev, const ArduinoJson::JsonDocument ¶ms);
|
||||
static const ArduinoJson::JsonDocument setCronJob(const devices_t &dev, const ArduinoJson::JsonDocument ¶ms);
|
||||
static const ArduinoJson::JsonDocument getCronJob(const devices_t &dev, const ArduinoJson::JsonDocument ¶ms);
|
||||
static const ArduinoJson::JsonDocument delCronJob(const devices_t &dev, const ArduinoJson::JsonDocument ¶ms);
|
||||
static const ArduinoJson::JsonDocument storeCronJob(const devices_t &dev, const ArduinoJson::JsonDocument ¶ms);
|
||||
|
||||
// SETTERS //
|
||||
static const ArduinoJson::JsonDocument resetHPcounters(const devices_t &dev, const ArduinoJson::JsonDocument ¶ms);
|
||||
static const ArduinoJson::JsonDocument setHPlimit(const devices_t &dev, const ArduinoJson::JsonDocument ¶ms);
|
||||
static const ArduinoJson::JsonDocument setHeating(const devices_t &dev, const ArduinoJson::JsonDocument ¶ms);
|
||||
static const ArduinoJson::JsonDocument setIrrigation(const devices_t &dev, const ArduinoJson::JsonDocument ¶ms);
|
||||
static const ArduinoJson::JsonDocument setRainOverride(const devices_t &dev, const ArduinoJson::JsonDocument ¶ms);
|
||||
static const ArduinoJson::JsonDocument setTimeNTP(const devices_t &dev, const ArduinoJson::JsonDocument ¶ms);
|
||||
|
||||
// GETTERS //
|
||||
static const ArduinoJson::JsonDocument getHPpower(const devices_t &dev, const ArduinoJson::JsonDocument ¶ms);
|
||||
static const ArduinoJson::JsonDocument getInputStatus(const devices_t &dev, const ArduinoJson::JsonDocument ¶ms);
|
||||
static const ArduinoJson::JsonDocument getOutputStatus(const devices_t &dev, const ArduinoJson::JsonDocument ¶ms);
|
||||
static const ArduinoJson::JsonDocument getTemperatures(const devices_t &dev, const ArduinoJson::JsonDocument ¶ms);
|
||||
static const ArduinoJson::JsonDocument getWaterInfo(const devices_t &dev, const ArduinoJson::JsonDocument ¶ms);
|
||||
static const ArduinoJson::JsonDocument getTankInfo(const devices_t &dev, const ArduinoJson::JsonDocument ¶ms);
|
||||
static const ArduinoJson::JsonDocument getRainInfo(const devices_t &dev, const ArduinoJson::JsonDocument ¶ms);
|
||||
static const ArduinoJson::JsonDocument getIrrigation(const devices_t &dev, const ArduinoJson::JsonDocument ¶ms);
|
||||
static const ArduinoJson::JsonDocument getRainOverride(const devices_t &dev, const ArduinoJson::JsonDocument ¶ms);
|
||||
static const ArduinoJson::JsonDocument getTimeDrift(const devices_t &dev, const ArduinoJson::JsonDocument ¶ms);
|
||||
};
|
||||
|
||||
static const std::map<const std::string, Command> s_commandMap = {
|
||||
// TEST
|
||||
{"setBuzz", Commands::setBuzz},
|
||||
// CONFIG
|
||||
{"setConfig", Commands::setConfig},
|
||||
{"getConfig", Commands::getConfig},
|
||||
// CRONJOBS
|
||||
{"loadCronJob", Commands::loadCronJob},
|
||||
{"addCronJob", Commands::addCronJob},
|
||||
{"setCronJob", Commands::setCronJob},
|
||||
{"getCronJob", Commands::getCronJob},
|
||||
{"delCronJob", Commands::delCronJob},
|
||||
{"storeCronJob", Commands::storeCronJob},
|
||||
// SETTERS
|
||||
{"resetHPcounters", Commands::resetHPcounters},
|
||||
{"setHPlimit", Commands::setHPlimit},
|
||||
{"setHeating", Commands::setHeating},
|
||||
{"setIrrigation", Commands::setIrrigation},
|
||||
{"setRainOverride", Commands::setRainOverride},
|
||||
// GETTERS
|
||||
{"getHPpower", Commands::getHPpower},
|
||||
{"getRainInfo", Commands::getRainInfo},
|
||||
{"getInputStatus", Commands::getInputStatus},
|
||||
{"getOutputStatus", Commands::getOutputStatus},
|
||||
{"getRainOverride", Commands::getRainOverride},
|
||||
// NTP and Time
|
||||
{"getTimeDrift", Commands::getTimeDrift},
|
||||
{"setTimeNTP", Commands::setTimeNTP},
|
||||
};
|
||||
|
||||
}
|
||||
258
src/cronjobs.cpp
Normal file
258
src/cronjobs.cpp
Normal file
@@ -0,0 +1,258 @@
|
||||
#include <cronjobs.h>
|
||||
#include <chrono>
|
||||
#include <fsmount.h>
|
||||
|
||||
#define STACK_DEPTH 4096
|
||||
#define PRIORITY 3
|
||||
#define PROCESS_INTERVAL 1000
|
||||
#define PROCESS_CORE 0
|
||||
|
||||
const bool Cron::loadEvents()
|
||||
{
|
||||
FSmount fs;
|
||||
File cronFile = FFat.open("/cronjobs.json", FILE_READ, false);
|
||||
if (!cronFile)
|
||||
{
|
||||
LOG_ERROR("Cron failed to open cronjobs.json");
|
||||
return false;
|
||||
}
|
||||
ArduinoJson::JsonDocument cronFileContent;
|
||||
if (ArduinoJson::deserializeJson(cronFileContent, cronFile) != ArduinoJson::DeserializationError::Ok)
|
||||
{
|
||||
LOG_ERROR("Cron unable to deserialize cronjobs.json");
|
||||
return false;
|
||||
}
|
||||
|
||||
std::string buf;
|
||||
ArduinoJson::serializeJson(cronFileContent, buf);
|
||||
LOG_INFO("Cron loadEvents loaded cronjobs.json");
|
||||
LOG_INFO(buf.c_str());
|
||||
|
||||
ArduinoJson::JsonArray cronjobList = cronFileContent.as<JsonArray>();
|
||||
LOG_INFO("Cron loadEvents loaded [", cronjobList.size(), "] events");
|
||||
for (const auto &job : cronjobList)
|
||||
{
|
||||
const auto &eventName = job["name"].as<std::string>();
|
||||
const auto &cronExpr = job["cronExpr"].as<std::string>();
|
||||
const auto status = str2Enum(job["status"].as<std::string>());
|
||||
ArduinoJson::JsonDocument action(job["action"]);
|
||||
if (!addEvent(eventName, cronExpr, action, status))
|
||||
LOG_ERROR("Cron failed to load event [", eventName.c_str(), "]");
|
||||
else
|
||||
LOG_INFO("Cron loaded event [", eventName.c_str(), "]");
|
||||
}
|
||||
cronFile.close();
|
||||
return true;
|
||||
}
|
||||
|
||||
const bool Cron::storeEvents()
|
||||
{
|
||||
FSmount fs;
|
||||
std::lock_guard<std::mutex> lock(m_mutex);
|
||||
File cronFile = FFat.open("/cronjobs.json", FILE_WRITE, true);
|
||||
if (!cronFile)
|
||||
{
|
||||
LOG_ERROR("Cron failed to open cronjobs.json");
|
||||
return false;
|
||||
}
|
||||
|
||||
ArduinoJson::JsonDocument cronFileContent;
|
||||
ArduinoJson::JsonArray cronFileArray = cronFileContent.to<JsonArray>();
|
||||
|
||||
for (const auto &[eventName, eventParams] : m_cronMap) // convert cron events map to json file
|
||||
{
|
||||
ArduinoJson::JsonDocument thisJob;
|
||||
thisJob["name"] = eventName;
|
||||
thisJob["cronExpr"] = cron::to_cronstr(eventParams.cronExpr);
|
||||
thisJob["status"] = enum2Str(eventParams.status);
|
||||
thisJob["action"]["cmd"] = eventParams.cmd;
|
||||
thisJob["action"]["params"] = eventParams.cmdParams;
|
||||
cronFileArray.add(thisJob);
|
||||
}
|
||||
|
||||
std::string buf;
|
||||
ArduinoJson::serializeJson(cronFileContent, buf);
|
||||
LOG_INFO("Cron storeEvents generated cronjobs.json");
|
||||
LOG_INFO(buf.c_str());
|
||||
|
||||
ArduinoJson::serializeJson(cronFileContent, cronFile);
|
||||
cronFile.close();
|
||||
return true;
|
||||
}
|
||||
|
||||
const bool Cron::addEvent(const std::string &name, const std::string &expr, const ArduinoJson::JsonDocument action, const CronStatus status)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(m_mutex);
|
||||
if (m_cronMap.contains(name))
|
||||
{
|
||||
LOG_ERROR("Cron event [", name.c_str(), "] already scheduled");
|
||||
return false;
|
||||
}
|
||||
if (name.empty() || expr.empty() || action.isNull())
|
||||
{
|
||||
LOG_ERROR("Cron event invalid parameters");
|
||||
return false;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
const auto cmd = action["cmd"].as<std::string>();
|
||||
const auto params = action["params"];
|
||||
const auto cronExpr(cron::make_cron(expr));
|
||||
if (!commands::s_commandMap.contains(cmd))
|
||||
{
|
||||
LOG_ERROR("Cron unknown command [", cmd.c_str(), "]");
|
||||
return false;
|
||||
}
|
||||
drivers::PCF85063::datetime_t now;
|
||||
if (!m_dev.rtc.readDatetime(now))
|
||||
{
|
||||
LOG_ERROR("Cron unable to update current time");
|
||||
return false;
|
||||
}
|
||||
const std::tm nowTm = drivers::PCF85063::datetime2tm(now);
|
||||
const std::tm next = cron::cron_next(cronExpr, nowTm);
|
||||
JsonDocument cmdParams(params); // create a copy of command parameters
|
||||
LOG_INFO("Cron adding event [", name.c_str(), "] next execution [", drivers::PCF85063::tm2str(next).c_str(), "]");
|
||||
m_cronMap[name] = CronEvent(cmd, cmdParams, cronExpr, next, status);
|
||||
}
|
||||
catch (cron::bad_cronexpr const &ex)
|
||||
{
|
||||
LOG_ERROR("Cron failed to parse expression [", expr.c_str(), "] ->", ex.what());
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
const bool Cron::setEvent(const std::string &name, const CronStatus status)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(m_mutex);
|
||||
if (!m_cronMap.contains(name))
|
||||
{
|
||||
LOG_ERROR("Cron event [", name.c_str(), "] does not exist");
|
||||
return false;
|
||||
}
|
||||
LOG_INFO("Cron set event [", name.c_str(), "] status [", enum2Str(status).c_str(), "]");
|
||||
m_cronMap.at(name).status = status;
|
||||
return true;
|
||||
}
|
||||
|
||||
const bool Cron::getEvent(const std::string &name, CronEvent &event)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(m_mutex);
|
||||
if (!m_cronMap.contains(name))
|
||||
{
|
||||
LOG_ERROR("Cron event [", name.c_str(), "] does not exist");
|
||||
return false;
|
||||
}
|
||||
LOG_INFO("Cron get event [", name.c_str(), "]");
|
||||
event = m_cronMap.at(name);
|
||||
return true;
|
||||
}
|
||||
|
||||
const bool Cron::delEvent(const std::string &name)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(m_mutex);
|
||||
if (!m_cronMap.contains(name))
|
||||
{
|
||||
LOG_WARN("Cron event [", name.c_str(), "] does not exist");
|
||||
return false;
|
||||
}
|
||||
m_cronMap.erase(name);
|
||||
LOG_INFO("Cron removed event [", name.c_str(), "]");
|
||||
return true;
|
||||
}
|
||||
|
||||
const Cron::CronEventMap &Cron::getAllEvents()
|
||||
{
|
||||
return m_cronMap;
|
||||
}
|
||||
|
||||
void cronLoop(void *cronPtr)
|
||||
{
|
||||
auto &cron = *(Cron *)cronPtr;
|
||||
while (true)
|
||||
{
|
||||
cron.processEvents();
|
||||
delay(PROCESS_INTERVAL);
|
||||
}
|
||||
}
|
||||
|
||||
void Cron::startCron()
|
||||
{
|
||||
if (!m_cronTaskHandle)
|
||||
{
|
||||
LOG_INFO("Cron starting loop");
|
||||
if (xTaskCreatePinnedToCore(cronLoop, "cronLoop", STACK_DEPTH, this, PRIORITY, &m_cronTaskHandle, PROCESS_CORE) != pdPASS)
|
||||
{
|
||||
LOG_ERROR("Cron failed to start loop");
|
||||
m_cronTaskHandle = NULL;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void Cron::stopCron()
|
||||
{
|
||||
if (m_cronTaskHandle)
|
||||
{
|
||||
LOG_WARN("Cron stopping loop");
|
||||
vTaskDelete(m_cronTaskHandle);
|
||||
m_cronTaskHandle = NULL;
|
||||
}
|
||||
}
|
||||
|
||||
const bool Cron::processEvents()
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(m_mutex);
|
||||
LOG_DEBUG("Cron processEvents [", m_cronMap.size(), "]");
|
||||
|
||||
drivers::PCF85063::datetime_t now;
|
||||
if (!m_dev.rtc.readDatetime(now))
|
||||
{
|
||||
LOG_ERROR("Cron unable to update current time");
|
||||
return false;
|
||||
}
|
||||
|
||||
std::tm nowTm = drivers::PCF85063::datetime2tm(now);
|
||||
|
||||
for (auto &[eventName, eventParams] : m_cronMap)
|
||||
{
|
||||
const auto nowPoint = std::chrono::system_clock::from_time_t(std::mktime(&nowTm));
|
||||
const auto nextEventPoint = std::chrono::system_clock::from_time_t(std::mktime(&eventParams.next));
|
||||
|
||||
LOG_DEBUG("Cron current time [", std::asctime(&nowTm), "]");
|
||||
LOG_DEBUG("Cron checking event [", eventName.c_str(), "] executionTime [", drivers::PCF85063::tm2str(eventParams.next).c_str(), "]");
|
||||
|
||||
if (nextEventPoint <= nowPoint) // execution time hs passed, run event
|
||||
{
|
||||
ArduinoJson::JsonDocument resp;
|
||||
ArduinoJson::JsonDocument action;
|
||||
eventParams.next = cron::cron_next(eventParams.cronExpr, nowTm); // update next execution time only if event was executed, otherwise time tracking is lost
|
||||
resp["cmd"] = "logCronJob";
|
||||
resp["values"]["name"] = eventName;
|
||||
resp["values"]["now"] = drivers::PCF85063::tm2str(nowTm).c_str();
|
||||
resp["values"]["next"] = drivers::PCF85063::tm2str(eventParams.next).c_str();
|
||||
resp["values"]["status"] = enum2Str(eventParams.status).c_str();
|
||||
switch (eventParams.status)
|
||||
{
|
||||
case CronStatus::ACTIVE:
|
||||
LOG_INFO("Cron running ACTIVE event [", eventName.c_str(), "] next execution time [", drivers::PCF85063::tm2str(eventParams.next).c_str(), "]");
|
||||
action = commands::s_commandMap.at(eventParams.cmd)(m_dev, eventParams.cmdParams); // here the magic happens
|
||||
resp["values"]["action"] = action;
|
||||
break;
|
||||
case CronStatus::INACTIVE:
|
||||
LOG_INFO("Cron skipping INACTIVE event [", eventName.c_str(), "] next execution time [", drivers::PCF85063::tm2str(eventParams.next).c_str(), "]");
|
||||
break;
|
||||
case CronStatus::SKIP:
|
||||
LOG_INFO("Cron skipping one time ACTIVE event [", eventName.c_str(), "] next execution time [", drivers::PCF85063::tm2str(eventParams.next).c_str(), "]");
|
||||
eventParams.status = CronStatus::ACTIVE;
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
if (m_callback)
|
||||
m_callback(resp); // execute cronLog callback action
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
102
src/cronjobs.h
Normal file
102
src/cronjobs.h
Normal file
@@ -0,0 +1,102 @@
|
||||
#pragma once
|
||||
|
||||
#define DEBUGLOG_DEFAULT_LOG_LEVEL_DEBUG
|
||||
|
||||
#include <DebugLog.h>
|
||||
#include <Arduino.h>
|
||||
|
||||
#include <PCF85063_Driver.h>
|
||||
|
||||
#include <commands.h>
|
||||
#include <mqtt.h>
|
||||
|
||||
#include <filesystem>
|
||||
#include <croncpp.h>
|
||||
|
||||
enum class CronStatus
|
||||
{
|
||||
ACTIVE,
|
||||
INACTIVE,
|
||||
SKIP,
|
||||
INVALID
|
||||
};
|
||||
|
||||
static const std::map<const CronStatus, std::string> c_statusEnum2Str = {
|
||||
{CronStatus::ACTIVE, "ACTIVE"},
|
||||
{CronStatus::INACTIVE, "INACTIVE"},
|
||||
{CronStatus::SKIP, "SKIP"},
|
||||
{CronStatus::INVALID, "INVALID"}};
|
||||
|
||||
static const std::map<const std::string, CronStatus> c_statusStr2Enum = {
|
||||
{"ACTIVE", CronStatus::ACTIVE},
|
||||
{"INACTIVE", CronStatus::INACTIVE},
|
||||
{"SKIP", CronStatus::SKIP},
|
||||
{"INVALID", CronStatus::INVALID}};
|
||||
|
||||
class Cron
|
||||
{
|
||||
public:
|
||||
|
||||
struct CronEvent
|
||||
{
|
||||
std::string cmd;
|
||||
ArduinoJson::JsonDocument cmdParams;
|
||||
cron::cronexpr cronExpr;
|
||||
std::tm next;
|
||||
CronStatus status;
|
||||
};
|
||||
|
||||
using CronEventMap = std::map<std::string, CronEvent>;
|
||||
using CronCallback = std::function<void(const ArduinoJson::JsonDocument &)>;
|
||||
|
||||
public:
|
||||
static Cron &getInstance(const devices_t &dev)
|
||||
{
|
||||
static Cron instance(dev);
|
||||
return instance;
|
||||
}
|
||||
|
||||
private:
|
||||
Cron(const devices_t &dev) : m_dev(dev) {};
|
||||
Cron(const Cron &) = delete;
|
||||
Cron &operator=(const Cron &) = delete;
|
||||
|
||||
public:
|
||||
void setResponseCallback(CronCallback &cb)
|
||||
{
|
||||
m_callback = cb;
|
||||
}
|
||||
|
||||
const bool loadEvents();
|
||||
const bool storeEvents();
|
||||
const bool addEvent(const std::string &name, const std::string &expr, const ArduinoJson::JsonDocument action, const CronStatus status = CronStatus::ACTIVE);
|
||||
const bool setEvent(const std::string &name, const CronStatus status);
|
||||
const bool getEvent(const std::string &name, CronEvent &event);
|
||||
const bool delEvent(const std::string &name);
|
||||
const CronEventMap &getAllEvents();
|
||||
|
||||
void startCron();
|
||||
void stopCron();
|
||||
const bool processEvents();
|
||||
|
||||
static const std::string enum2Str(const CronStatus status)
|
||||
{
|
||||
if (!c_statusEnum2Str.contains(status))
|
||||
return "INVALID";
|
||||
return c_statusEnum2Str.at(status);
|
||||
}
|
||||
|
||||
static const CronStatus str2Enum(const std::string &status)
|
||||
{
|
||||
if (!c_statusStr2Enum.contains(status))
|
||||
return CronStatus::INVALID;
|
||||
return c_statusStr2Enum.at(status);
|
||||
}
|
||||
|
||||
private:
|
||||
const devices_t &m_dev;
|
||||
CronCallback m_callback;
|
||||
CronEventMap m_cronMap;
|
||||
TaskHandle_t m_cronTaskHandle;
|
||||
std::mutex m_mutex;
|
||||
};
|
||||
20
src/devices.h
Normal file
20
src/devices.h
Normal file
@@ -0,0 +1,20 @@
|
||||
#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::Ethernet ð
|
||||
drivers::PCF85063 &rtc;
|
||||
drivers::R4DCB08 &tmp;
|
||||
drivers::S50140 &seneca;
|
||||
drivers::Buzzer &buzzer;
|
||||
drivers::Led &led;
|
||||
digitalIO &io;
|
||||
} devices_t;
|
||||
@@ -76,7 +76,7 @@ const std::vector<bool> digitalIO::digitalOutReadPort()
|
||||
rv.reserve(getOutNum());
|
||||
rv.insert(rv.begin(), locals.begin(), locals.end());
|
||||
rv.insert(rv.end(), remotes.begin(), remotes.end());
|
||||
return std::move(rv);
|
||||
return rv;
|
||||
}
|
||||
|
||||
const bool digitalIO::digitalInRead(const uint8_t ch)
|
||||
@@ -104,7 +104,7 @@ const std::vector<bool> digitalIO::digitalInReadPort()
|
||||
rv.reserve(getInNum());
|
||||
rv.insert(rv.begin(), locals.begin(), locals.end());
|
||||
rv.insert(rv.end(), remotes.begin(), remotes.end());
|
||||
return std::move(rv);
|
||||
return rv;
|
||||
}
|
||||
|
||||
void digitalIO::reset()
|
||||
|
||||
258
src/main.cpp
258
src/main.cpp
@@ -1,37 +1,34 @@
|
||||
#define DEBUGLOG_DEFAULT_LOG_LEVEL_DEBUG
|
||||
#define DEBUGLOG_DEFAULT_LOG_LEVEL_INFO
|
||||
|
||||
#include <Arduino.h>
|
||||
#include <DebugLog.h>
|
||||
#include <DebugLogEnable.h>
|
||||
|
||||
#include <config.h>
|
||||
#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>
|
||||
#include <commands.h>
|
||||
#include <cronjobs.h>
|
||||
#include <mqtt.h>
|
||||
#include "utils.h"
|
||||
#include <ota.h>
|
||||
|
||||
#include <devices.h>
|
||||
#include <utils.h>
|
||||
#include <pinlist.h>
|
||||
|
||||
/////////////// GLOBALS ///////////////
|
||||
Config &conf = Config::getInstance();
|
||||
/////////////// 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()
|
||||
{
|
||||
Serial.begin(9600);
|
||||
LOG_ATTACH_SERIAL(Serial);
|
||||
LOG_SET_LEVEL(DebugLogLevel::LVL_INFO);
|
||||
conf.init(); // read the configuration from internal flash
|
||||
LOG_INFO("ESP32 Chip:", ESP.getChipModel());
|
||||
LOG_INFO("ESP32 PSram:", ESP.getPsramSize());
|
||||
LOG_INFO("ESP32 Flash:", ESP.getFlashChipSize());
|
||||
LOG_INFO("ESP32 Heap:", ESP.getHeapSize());
|
||||
LOG_INFO("ESP32 Sketch:", ESP.getFreeSketchSpace());
|
||||
}
|
||||
|
||||
void loop()
|
||||
@@ -39,84 +36,145 @@ void loop()
|
||||
uint16_t k(0);
|
||||
uint8_t sensors(0);
|
||||
bool buzzing(false);
|
||||
NetworkClient logStream;
|
||||
LOG_ATTACH_STREAM(logStream);
|
||||
|
||||
//////////////// DEVICES ////////////////
|
||||
// Declared here to keep devices local to the main loop otherwise the kernel crashes //
|
||||
auto i2c = drivers::I2C();
|
||||
auto bus = drivers::MODBUS(9600, SERIAL_8N1);
|
||||
auto rtc = drivers::PCF85063(i2c, PCF85063_ADDRESS);
|
||||
auto eth = drivers::Ethernet(conf.m_ethHostname);
|
||||
auto rtc = drivers::PCF85063(i2c);
|
||||
auto eth = drivers::Ethernet(conf.m_ethHostname, conf.m_ntpPool, conf.m_ntpTimezone, conf.m_ntpUpdateInterval);
|
||||
auto tmp = drivers::R4DCB08(bus, conf.m_modbusTemperatureAddr);
|
||||
auto seneca = drivers::S50140(bus, conf.m_modbusSenecaAddr);
|
||||
auto buzzer = drivers::Buzzer();
|
||||
auto led = drivers::Led();
|
||||
delay(500);
|
||||
auto io = digitalIO(i2c, bus, {conf.m_modbusRelayAddr});
|
||||
// Create device structure to pass all devices in the callbacks as needed
|
||||
devices_t devices(eth, rtc, tmp, seneca, buzzer, led, io);
|
||||
//
|
||||
// get RTC time drift offset value
|
||||
rtc.setOffset(conf.m_ntpRtcOffsetRegister);
|
||||
LOG_INFO("RTC offset register -> ", printHex(rtc.getOffset()).c_str());
|
||||
// Initialize temperature sensors
|
||||
sensors = tmp.getNum();
|
||||
tmp.setCorrection(conf.m_tempCorrectionValues);
|
||||
LOG_INFO("Temperature sensors connected ->", sensors);
|
||||
// Initialize OTA updater if needed
|
||||
auto ota = OTA(devices);
|
||||
//////////////// DEVICES ////////////////
|
||||
|
||||
//////////////// NETWORK ////////////////
|
||||
//////////////// MQTT ////////////////
|
||||
auto mqtt = MQTTwrapper();
|
||||
//////////////// NETWORK ////////////////
|
||||
//////////////// MQTT ////////////////
|
||||
|
||||
std::function<void(const ArduinoJson::JsonDocument &)> mycallback =
|
||||
[&io](const ArduinoJson::JsonDocument &doc)
|
||||
//////////////// MQTT //////////////
|
||||
/////////////// CALLBACK //////////////
|
||||
MQTTwrapper::ActionCallback 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};
|
||||
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_INFO("SET Digital Outputs V1: ", printBoolVec(v1).c_str());
|
||||
io.digitalOutWritePort(v1);
|
||||
delay(100);
|
||||
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);
|
||||
delay(100);
|
||||
LOG_INFO("GET Digital Outputs V2: ", printBoolVec(io.digitalOutReadPort()).c_str());
|
||||
delay(2000);
|
||||
|
||||
LOG_INFO("GET Digital Inputs: ", printBoolVec(io.digitalInReadPort()).c_str());
|
||||
io.digitalOutWritePort(v0);
|
||||
if (!doc["cmd"].is<std::string>())
|
||||
{
|
||||
LOG_ERROR("Invalid Json Command");
|
||||
return;
|
||||
}
|
||||
const std::string cmd = doc["cmd"].as<std::string>();
|
||||
const ArduinoJson::JsonDocument params = doc["params"];
|
||||
if (commands::s_commandMap.contains(cmd))
|
||||
{ // call command from command map in this same thread (the MQTT thread)
|
||||
LOG_INFO("Executing command", cmd.c_str());
|
||||
const auto answer = std::move(commands::s_commandMap.at(cmd)(devices, params)); // here the magic happens
|
||||
if (answer.isNull())
|
||||
return;
|
||||
mqtt.publish(conf.m_mqttPublish["answers"], answer);
|
||||
}
|
||||
else
|
||||
{
|
||||
LOG_ERROR("Unknown command", cmd.c_str());
|
||||
}
|
||||
};
|
||||
|
||||
MQTTwrapper::MessageCallback onMessage = [&devices](const MQTTwrapper::Topic &topic, const MQTTwrapper::Message &message)
|
||||
{
|
||||
LOG_DEBUG("onMessage callback [", topic.c_str(), "]\n", message.c_str());
|
||||
devices.led.setColor(devices.led.COLOR_MAGENTA);
|
||||
};
|
||||
|
||||
MQTTwrapper::MessageCallback onPublish = [&devices](const MQTTwrapper::Topic &topic, const MQTTwrapper::Message &message)
|
||||
{
|
||||
LOG_DEBUG("onPublish callback [", topic.c_str(), "]\n", message.c_str());
|
||||
devices.led.setColor(devices.led.COLOR_SKYBLUE);
|
||||
};
|
||||
|
||||
///////////// CRONJOB //////////////
|
||||
/////////////// CALLBACK //////////////
|
||||
Cron::CronCallback cronCallback = [&mqtt](const ArduinoJson::JsonDocument &resp)
|
||||
{
|
||||
if (resp.isNull())
|
||||
return;
|
||||
mqtt.publish(conf.m_mqttPublish["cronjobs"], resp);
|
||||
};
|
||||
|
||||
//////////////// CRONJOB ////////////////
|
||||
auto &cron = Cron::getInstance(devices);
|
||||
cron.setResponseCallback(cronCallback);
|
||||
cron.loadEvents();
|
||||
cron.startCron();
|
||||
//////////////// CRONJOB ////////////////
|
||||
|
||||
//////////////// NETWORK ////////////////
|
||||
/////////////// CALLBACK ////////////////
|
||||
Network.onEvent(
|
||||
[ð, &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
|
||||
if (!eth.isConnected())
|
||||
{
|
||||
led.setColor(led.COLOR_RED);
|
||||
logStream.stop();
|
||||
return;
|
||||
}
|
||||
if (io.digitalInRead(DI::OTAENABLE)) // Initialize OTA, BLUE
|
||||
{
|
||||
buzzer.beepRepeat(25, 25, NOTE_A);
|
||||
delay(1000);
|
||||
if (io.digitalInRead(DI::OTAENABLE))
|
||||
{ // maintain keyPress for 1s
|
||||
ota.begin();
|
||||
}
|
||||
buzzer.beep(100, NOTE_G);
|
||||
delay(100);
|
||||
}
|
||||
// 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});
|
||||
eth.setNtpTimeOffset(conf.m_ntpTimezone);
|
||||
LOG_INFO("NTP Timezone UTC", conf.m_ntpTimezone >= 0 ? "+" : "", conf.m_ntpTimezone);
|
||||
if (eth.getNtpTime(ntpTime))
|
||||
{ // skip NTP update for drift testing
|
||||
buzzer.beep(250, NOTE_A);
|
||||
led.setColor(led.COLOR_ORANGE);
|
||||
const drivers::PCF85063::datetime_t dt(drivers::PCF85063::fromEpoch(ntpTime));
|
||||
LOG_INFO("NTP Time: ", drivers::PCF85063::datetime2str(dt).c_str());
|
||||
delay(100);
|
||||
}
|
||||
break;
|
||||
}
|
||||
delay(250);
|
||||
}
|
||||
while (mqttRetries++ < conf.m_mqttRetries)
|
||||
{
|
||||
if (mqtt.connect())
|
||||
{
|
||||
mqtt.subscribe("test/esp32-in", testAction);
|
||||
mqtt.subscribe("test/esp32-functional", mycallback);
|
||||
buzzer.beep(250, NOTE_B);
|
||||
led.setColor(led.COLOR_GREEN);
|
||||
mqtt.subscribe(conf.m_mqttSubscribe["commands"], commandsCallback);
|
||||
mqtt.setOnMessageCb(onMessage);
|
||||
mqtt.setOnPublishCb(onPublish);
|
||||
break;
|
||||
}
|
||||
delay(100);
|
||||
delay(250);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -126,79 +184,57 @@ void loop()
|
||||
|
||||
while (true)
|
||||
{
|
||||
LOG_INFO("[", k++, "] Loop");
|
||||
const uint32_t start(millis());
|
||||
drivers::PCF85063::datetime_t datetime;
|
||||
|
||||
const std::string timeStr(rtc.getTimeStr());
|
||||
LOG_INFO("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())
|
||||
if (!logStream.connected())
|
||||
{
|
||||
LOG_INFO("Temperature channel", i++, "->", v);
|
||||
logStream.stop();
|
||||
logStream.clearWriteError();
|
||||
logStream.setConnectionTimeout(100);
|
||||
logStream.connect(conf.m_mqttHost.c_str(), 9876);
|
||||
LOG_WARN("TCP LogStream Connected");
|
||||
}
|
||||
|
||||
LOG_INFO("Read Red");
|
||||
if (io.digitalInRead(0)) // rosso
|
||||
rtc.readDatetime(datetime);
|
||||
const std::string timeStr(drivers::PCF85063::datetime2str(datetime));
|
||||
LOG_INFO("[", k++, "] Loop - Current Datetime UTC", timeStr.c_str());
|
||||
|
||||
{
|
||||
std::vector<bool> v1 = {1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0};
|
||||
std::vector<bool> v2 = {0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1};
|
||||
std::vector<bool> v0(16, 0);
|
||||
ArduinoJson::JsonDocument poll;
|
||||
poll["cmd"] = "POLL";
|
||||
auto params = poll["values"].to<ArduinoJson::JsonObject>();
|
||||
params["time"] = timeStr;
|
||||
params["number"] = k;
|
||||
mqtt.publish(conf.m_mqttPublish["answers"], poll);
|
||||
};
|
||||
|
||||
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");
|
||||
}
|
||||
ArduinoJson::JsonDocument ti;
|
||||
auto tempinfo = tmp.getTempAll();
|
||||
ti["solar"] = tempinfo.at(0);
|
||||
ti["acs"] = tempinfo.at(1);
|
||||
ti["heating"] = tempinfo.at(2);
|
||||
mqtt.publish(conf.m_mqttPublish["temperatures"], ti);
|
||||
};
|
||||
|
||||
LOG_INFO("Read Green");
|
||||
if (io.digitalInRead(9))
|
||||
{ // verde
|
||||
if (io.digitalInRead(DI::CONFRESET)) // ROSSO - Config Reset
|
||||
{
|
||||
LOG_WARN("Config RESET!");
|
||||
buzzer.beep(450, NOTE_E);
|
||||
delay(500);
|
||||
conf.resetConfig();
|
||||
}
|
||||
|
||||
LOG_INFO("Read Yellow");
|
||||
if (io.digitalInRead(10))
|
||||
{ // giallo
|
||||
if (io.digitalInRead(DI::RESTART)) // GIALLO - Restart
|
||||
{
|
||||
LOG_WARN("RESTART!");
|
||||
buzzer.beep(450, NOTE_D);
|
||||
delay(450);
|
||||
esp_restart();
|
||||
}
|
||||
|
||||
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);
|
||||
|
||||
delay(conf.m_globalLoopDelay);
|
||||
delay(conf.m_globalLoopDelay - (start - millis())); // to avoid too fast loop, keep precise timing computing loop time
|
||||
}
|
||||
|
||||
////////////////////////////////////////
|
||||
|
||||
45
src/mqtt.cpp
45
src/mqtt.cpp
@@ -1,12 +1,15 @@
|
||||
#include <mqtt.h>
|
||||
|
||||
#define STACK_DEPTH 4096
|
||||
#define PRIOTITY 2
|
||||
#define STACK_DEPTH 8192
|
||||
#define BUFFER_SIZE 2048
|
||||
#define PRIORITY 2
|
||||
#define PROCESS_CORE 1
|
||||
|
||||
MQTTwrapper::MQTTwrapper() : m_config(Config::getInstance()), m_tcp(NetworkClient()), m_client(PubSubClient(m_tcp)), m_loopHandle(NULL)
|
||||
{
|
||||
m_client.setServer(m_config.m_mqttHost.c_str(), m_config.m_mqttPort);
|
||||
m_client.setKeepAlive(15);
|
||||
m_client.setKeepAlive(m_config.m_mqttKeepalive);
|
||||
m_client.setBufferSize(BUFFER_SIZE);
|
||||
getInstance(this);
|
||||
}
|
||||
|
||||
@@ -25,7 +28,11 @@ const bool MQTTwrapper::connect()
|
||||
LOG_INFO("MQTT client connected to", m_config.m_mqttHost.c_str());
|
||||
if (m_loopHandle == NULL)
|
||||
{
|
||||
xTaskCreate(clientLoop, "mqttLoop", STACK_DEPTH, this, PRIOTITY, &m_loopHandle);
|
||||
if (xTaskCreatePinnedToCore(clientLoop, "mqttLoop", STACK_DEPTH, this, PRIORITY, &m_loopHandle, PROCESS_CORE) != pdPASS)
|
||||
{
|
||||
m_loopHandle = NULL;
|
||||
return false;
|
||||
}
|
||||
m_client.setCallback(MQTTwrapper::callback);
|
||||
}
|
||||
return true;
|
||||
@@ -42,7 +49,7 @@ const bool MQTTwrapper::disconnect()
|
||||
return true;
|
||||
}
|
||||
|
||||
const bool MQTTwrapper::subscribe(topic_t topic, action_t action)
|
||||
const bool MQTTwrapper::subscribe(const Topic &topic, const ActionCallback action)
|
||||
{
|
||||
if (m_actionMap.contains(topic))
|
||||
{
|
||||
@@ -59,7 +66,7 @@ const bool MQTTwrapper::subscribe(topic_t topic, action_t action)
|
||||
return false;
|
||||
}
|
||||
|
||||
const bool MQTTwrapper::unsubscribe(topic_t topic)
|
||||
const bool MQTTwrapper::unsubscribe(const Topic &topic)
|
||||
{
|
||||
if (!m_actionMap.contains(topic))
|
||||
{
|
||||
@@ -81,7 +88,7 @@ const bool MQTTwrapper::connected()
|
||||
return m_loopHandle != NULL;
|
||||
}
|
||||
|
||||
const bool MQTTwrapper::publish(topic_t topic, const ArduinoJson::JsonDocument obj)
|
||||
const bool MQTTwrapper::publish(const Topic &topic, const ArduinoJson::JsonDocument obj)
|
||||
{
|
||||
std::string message;
|
||||
if (!m_client.connected())
|
||||
@@ -97,12 +104,32 @@ const bool MQTTwrapper::publish(topic_t topic, const ArduinoJson::JsonDocument o
|
||||
if (m_client.publish(topic.c_str(), message.c_str()))
|
||||
{
|
||||
LOG_DEBUG("MQTT published topic [", topic.c_str(), "] - message [", message.c_str(), "]");
|
||||
if (m_onPublish)
|
||||
{
|
||||
m_onPublish(topic, message);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
LOG_ERROR("MQTT failed to publish topic [", topic.c_str(), "] - message [", message.c_str(), "]");
|
||||
return false;
|
||||
}
|
||||
|
||||
void MQTTwrapper::setOnMessageCb(MessageCallback cb)
|
||||
{
|
||||
if (cb)
|
||||
m_onReceive = cb;
|
||||
else
|
||||
LOG_ERROR("MQTT invalid onReceive Callback");
|
||||
}
|
||||
|
||||
void MQTTwrapper::setOnPublishCb(MessageCallback cb)
|
||||
{
|
||||
if (cb)
|
||||
m_onPublish = cb;
|
||||
else
|
||||
LOG_ERROR("MQTT invalid onPublish Callback");
|
||||
}
|
||||
|
||||
void MQTTwrapper::callback(char *topic, uint8_t *payload, unsigned int length)
|
||||
{
|
||||
std::string pl;
|
||||
@@ -118,13 +145,15 @@ void MQTTwrapper::callback(char *topic, uint8_t *payload, unsigned int length)
|
||||
return;
|
||||
}
|
||||
|
||||
void MQTTwrapper::onMessage(const std::string topic, const std::string message)
|
||||
void MQTTwrapper::onMessage(const Topic topic, const Message message)
|
||||
{
|
||||
ArduinoJson::JsonDocument obj;
|
||||
LOG_DEBUG("MQTT received topic [", topic.c_str(), "] - message [", message.c_str(), "]");
|
||||
if (ArduinoJson::deserializeJson(obj, message) == ArduinoJson::DeserializationError::Ok)
|
||||
{
|
||||
m_actionMap[topic](obj);
|
||||
if (m_onReceive)
|
||||
m_onReceive(topic, message);
|
||||
return;
|
||||
}
|
||||
LOG_ERROR("MQTT failed to deserialize message\n", message.c_str());
|
||||
|
||||
29
src/mqtt.h
29
src/mqtt.h
@@ -13,12 +13,16 @@
|
||||
#include <mutex>
|
||||
#include <functional>
|
||||
|
||||
typedef std::string topic_t;
|
||||
typedef std::function<void(const ArduinoJson::JsonDocument &)> action_t; // the actions receive a JsonObject containing the received message
|
||||
typedef std::map<topic_t, action_t> action_map_t;
|
||||
|
||||
class MQTTwrapper
|
||||
{
|
||||
public:
|
||||
using Topic = std::string;
|
||||
using Message = std::string;
|
||||
using MessageCallback = std::function<void(const Topic &topic, const Message &message)>;
|
||||
using ActionCallback = std::function<void(const ArduinoJson::JsonDocument &)>; // the actions receive a JsonObject containing the received message
|
||||
using StateChangeCallback = std::function<void(void)>;
|
||||
|
||||
using ActionMap = std::map<Topic, ActionCallback>;
|
||||
|
||||
private:
|
||||
const std::map<int, std::string> stateMap = {
|
||||
@@ -31,8 +35,7 @@ private:
|
||||
{2, "MQTT_CONNECT_BAD_CLIENT_ID"},
|
||||
{3, "MQTT_CONNECT_UNAVAILABLE"},
|
||||
{4, "MQTT_CONNECT_BAD_CREDENTIALS"},
|
||||
{5, "MQTT_CONNECT_UNAUTHORIZED"}
|
||||
};
|
||||
{5, "MQTT_CONNECT_UNAUTHORIZED"}};
|
||||
|
||||
private:
|
||||
static MQTTwrapper *
|
||||
@@ -54,10 +57,13 @@ public:
|
||||
const bool disconnect();
|
||||
const bool connected();
|
||||
|
||||
const bool subscribe(topic_t topic, action_t action);
|
||||
const bool unsubscribe(topic_t topic);
|
||||
const bool subscribe(const Topic &topic, const ActionCallback action);
|
||||
const bool unsubscribe(const Topic &topic);
|
||||
|
||||
const bool publish(topic_t topic, const ArduinoJson::JsonDocument obj);
|
||||
const bool publish(const Topic &topic, const ArduinoJson::JsonDocument obj);
|
||||
|
||||
void setOnMessageCb(MessageCallback cb);
|
||||
void setOnPublishCb(MessageCallback cb);
|
||||
|
||||
private:
|
||||
static void callback(char *topic, uint8_t *payload, unsigned int length); // C-style callback only to invoke onMessage
|
||||
@@ -68,8 +74,11 @@ private:
|
||||
|
||||
private:
|
||||
const Config &m_config;
|
||||
action_map_t m_actionMap;
|
||||
ActionMap m_actionMap;
|
||||
NetworkClient m_tcp;
|
||||
PubSubClient m_client;
|
||||
TaskHandle_t m_loopHandle;
|
||||
|
||||
MessageCallback m_onPublish;
|
||||
MessageCallback m_onReceive;
|
||||
};
|
||||
|
||||
134
src/ota.cpp
Normal file
134
src/ota.cpp
Normal file
@@ -0,0 +1,134 @@
|
||||
#include <ota.h>
|
||||
|
||||
#define STACK_DEPTH 4096
|
||||
#define TASK_PRIORITY 2
|
||||
#define PROCESS_CORE 1
|
||||
|
||||
OTA::OTA(const devices_t &dev) : m_dev(dev), m_taskHandle(NULL), m_updating(false), m_prevPercent(0)
|
||||
{
|
||||
LOG_WARN("OTA begin, waiting for connection on [", dev.eth.localIP().toString().c_str(), "]");
|
||||
}
|
||||
|
||||
OTA::~OTA()
|
||||
{
|
||||
end();
|
||||
LOG_WARN("OTA end");
|
||||
}
|
||||
|
||||
void OTA::begin()
|
||||
{
|
||||
if (m_taskHandle)
|
||||
{
|
||||
LOG_ERROR("OTA already started");
|
||||
return;
|
||||
}
|
||||
ArduinoOTA.setRebootOnSuccess(true);
|
||||
ArduinoOTA.onStart(s_onStart);
|
||||
ArduinoOTA.onEnd(s_onEnd);
|
||||
ArduinoOTA.onProgress(s_onProgress);
|
||||
ArduinoOTA.onError(s_onError);
|
||||
if (xTaskCreatePinnedToCore(handle, "otaUpdate", STACK_DEPTH, this, TASK_PRIORITY, &m_taskHandle, PROCESS_CORE) != pdPASS)
|
||||
{
|
||||
m_taskHandle = NULL;
|
||||
LOG_ERROR("OTA failed to create handle task");
|
||||
return;
|
||||
}
|
||||
ArduinoOTA.begin(); // start the OTA server
|
||||
m_dev.led.blinkAlternate(100, 100, m_dev.led.COLOR_ORANGE, m_dev.led.COLOR_SKYBLUE);
|
||||
m_dev.led.setEnforce(true); // take unique control of the LED
|
||||
m_active = true;
|
||||
LOG_WARN("OTA started");
|
||||
return;
|
||||
}
|
||||
|
||||
void OTA::end()
|
||||
{
|
||||
if (m_updating)
|
||||
{
|
||||
LOG_WARN("OTA cannot cancel update while running");
|
||||
return;
|
||||
}
|
||||
if (m_taskHandle)
|
||||
{
|
||||
vTaskDelete(m_taskHandle);
|
||||
m_taskHandle = NULL;
|
||||
m_updating = false;
|
||||
ArduinoOTA.end();
|
||||
m_active = false;
|
||||
m_dev.led.setColor(m_dev.led.COLOR_GREEN);
|
||||
m_dev.led.setEnforce(false);
|
||||
}
|
||||
}
|
||||
|
||||
bool OTA::isActive()
|
||||
{
|
||||
return m_active;
|
||||
}
|
||||
|
||||
void OTA::onProgress(const uint32_t progress, const uint32_t total)
|
||||
{
|
||||
float percent = (progress * 100.0f) / total;
|
||||
if (percent > m_prevPercent + 5.0f)
|
||||
{
|
||||
LOG_INFO("OTA progress [", percent, "]%");
|
||||
m_prevPercent = percent;
|
||||
}
|
||||
}
|
||||
|
||||
void OTA::onStart()
|
||||
{
|
||||
LOG_WARN("OTA update started");
|
||||
m_updating = true;
|
||||
m_dev.led.setEnforce(false);
|
||||
m_dev.led.blinkAlternate(25, 50, m_dev.led.COLOR_BLUE, m_dev.led.COLOR_OFF);
|
||||
m_dev.led.setEnforce(true);
|
||||
m_prevPercent = 0;
|
||||
}
|
||||
|
||||
void OTA::onEnd()
|
||||
{
|
||||
LOG_WARN("OTA update end");
|
||||
m_updating = false;
|
||||
m_dev.led.setEnforce(false);
|
||||
m_dev.led.blinkAlternate(50, 50, m_dev.led.COLOR_GREEN, m_dev.led.COLOR_YELLOW);
|
||||
m_dev.led.setEnforce(true);
|
||||
}
|
||||
|
||||
void OTA::onError(const ota_error_t err)
|
||||
{
|
||||
LOG_ERROR("OTA Error [", err, "]");
|
||||
switch (err)
|
||||
{
|
||||
case OTA_AUTH_ERROR:
|
||||
LOG_ERROR("OTA authentication error");
|
||||
break;
|
||||
case OTA_BEGIN_ERROR:
|
||||
LOG_ERROR("OTA begin errror");
|
||||
break;
|
||||
case OTA_CONNECT_ERROR:
|
||||
LOG_ERROR("OTA connection error");
|
||||
break;
|
||||
case OTA_RECEIVE_ERROR:
|
||||
LOG_ERROR("OTA receive error");
|
||||
break;
|
||||
case OTA_END_ERROR:
|
||||
LOG_ERROR("OTA end error");
|
||||
break;
|
||||
default:
|
||||
LOG_ERROR("OTA unknown error");
|
||||
};
|
||||
m_updating = false;
|
||||
end(); // end ota on error
|
||||
}
|
||||
|
||||
void OTA::handle(void *params)
|
||||
{
|
||||
OTA *ota = (OTA *)params;
|
||||
while (true)
|
||||
{ // task never returns
|
||||
ArduinoOTA.handle();
|
||||
delay(50);
|
||||
}
|
||||
vTaskDelete(ota->m_taskHandle);
|
||||
ota->m_taskHandle = NULL;
|
||||
}
|
||||
52
src/ota.h
Normal file
52
src/ota.h
Normal file
@@ -0,0 +1,52 @@
|
||||
#pragma once
|
||||
|
||||
#define DEBUGLOG_DEFAULT_LOG_LEVEL_INFO
|
||||
|
||||
#include <DebugLog.h>
|
||||
#include <Arduino.h>
|
||||
#include <ArduinoOTA.h>
|
||||
#include <devices.h>
|
||||
|
||||
class OTA
|
||||
{
|
||||
|
||||
public:
|
||||
OTA(const devices_t &dev);
|
||||
~OTA();
|
||||
|
||||
void begin();
|
||||
void end();
|
||||
bool isActive();
|
||||
|
||||
private:
|
||||
void onProgress(const uint32_t progress, const uint32_t total);
|
||||
void onStart();
|
||||
void onEnd();
|
||||
void onError(const ota_error_t err);
|
||||
static void handle(void *params);
|
||||
|
||||
private:
|
||||
const devices_t &m_dev;
|
||||
TaskHandle_t m_taskHandle;
|
||||
bool m_updating;
|
||||
bool m_active;
|
||||
float m_prevPercent;
|
||||
|
||||
private: // callbacks, do not init in code
|
||||
ArduinoOTAClass::THandlerFunction s_onStart = [this]()
|
||||
{
|
||||
this->onStart();
|
||||
};
|
||||
ArduinoOTAClass::THandlerFunction s_onEnd = [this]()
|
||||
{
|
||||
this->onEnd();
|
||||
};
|
||||
ArduinoOTAClass::THandlerFunction_Progress s_onProgress = [this](const uint32_t progress, const uint32_t total)
|
||||
{
|
||||
this->onProgress(progress, total);
|
||||
};
|
||||
ArduinoOTAClass::THandlerFunction_Error s_onError = [this](const ota_error_t err)
|
||||
{
|
||||
this->onError(err);
|
||||
};
|
||||
};
|
||||
@@ -1,4 +1,7 @@
|
||||
#include <remoteIO.h>
|
||||
#include <busdelay.h>
|
||||
|
||||
#define BUS_DELAY drivers::BusDelay(m_lastRequest, c_minDelay, "remoteIO")
|
||||
|
||||
remoteIO::remoteIO(const uint8_t address, drivers::MODBUS &bus) : m_address(address), m_initialized(false), m_bus(bus)
|
||||
{
|
||||
@@ -21,23 +24,12 @@ remoteIO::~remoteIO()
|
||||
resetAll(false);
|
||||
}
|
||||
|
||||
void remoteIO::delayRequest()
|
||||
{
|
||||
auto now = millis();
|
||||
if ((now - m_lastRequest) < c_minDelay)
|
||||
{ // minimum m_lastRequest between requests
|
||||
LOG_DEBUG("remoteIO delay request", (now - m_lastRequest));
|
||||
delay(now - m_lastRequest);
|
||||
}
|
||||
m_lastRequest = millis();
|
||||
}
|
||||
|
||||
const bool remoteIO::setOut(const channel_t ch, const bool value)
|
||||
{
|
||||
if (!m_initialized)
|
||||
return false;
|
||||
std::lock_guard<std::mutex> lock(m_bus.getMutex());
|
||||
delayRequest();
|
||||
BUS_DELAY;
|
||||
LOG_DEBUG("Write Channel", ch, "->", value ? "True" : "False");
|
||||
return m_bus.writeCoil(m_address, REG_COILS + ch, value);
|
||||
}
|
||||
@@ -47,7 +39,7 @@ const bool remoteIO::toggleOut(const channel_t ch)
|
||||
if (!m_initialized)
|
||||
return false;
|
||||
std::lock_guard<std::mutex> lock(m_bus.getMutex());
|
||||
delayRequest();
|
||||
BUS_DELAY;
|
||||
std::vector<bool> value;
|
||||
if (!m_bus.readCoils(m_address, REG_COILS + ch, 1, value))
|
||||
return false;
|
||||
@@ -60,7 +52,7 @@ const bool remoteIO::setOutPort(const std::vector<bool> values)
|
||||
if (!m_initialized)
|
||||
return false;
|
||||
std::lock_guard<std::mutex> lock(m_bus.getMutex());
|
||||
delayRequest();
|
||||
BUS_DELAY;
|
||||
LOG_DEBUG("Write Port", CH_MAX);
|
||||
return m_bus.writeCoils(m_address, REG_COILS, values);
|
||||
}
|
||||
@@ -70,7 +62,7 @@ const bool remoteIO::getOut(const channel_t ch, bool &value)
|
||||
if (!m_initialized)
|
||||
return false;
|
||||
std::lock_guard<std::mutex> lock(m_bus.getMutex());
|
||||
delayRequest();
|
||||
BUS_DELAY;
|
||||
std::vector<bool> values;
|
||||
if (!m_bus.readCoils(m_address, REG_COILS + ch, 1, values))
|
||||
return false;
|
||||
@@ -84,7 +76,7 @@ const bool remoteIO::getOutPort(std::vector<bool> &values)
|
||||
if (!m_initialized)
|
||||
return false;
|
||||
std::lock_guard<std::mutex> lock(m_bus.getMutex());
|
||||
delayRequest();
|
||||
BUS_DELAY;
|
||||
LOG_DEBUG("Read Port", CH_MAX);
|
||||
return m_bus.readCoils(m_address, REG_COILS, CH_MAX, values);
|
||||
}
|
||||
@@ -94,7 +86,7 @@ const bool remoteIO::getIn(const channel_t input, bool &value)
|
||||
if (!m_initialized)
|
||||
return false;
|
||||
std::lock_guard<std::mutex> lock(m_bus.getMutex());
|
||||
delayRequest();
|
||||
BUS_DELAY;
|
||||
std::vector<bool> values;
|
||||
if (!m_bus.readInputs(m_address, REG_INPUT + input, 1, values))
|
||||
return false;
|
||||
@@ -108,7 +100,7 @@ const bool remoteIO::getInPort(std::vector<bool> &values)
|
||||
if (!m_initialized)
|
||||
return false;
|
||||
std::lock_guard<std::mutex> lock(m_bus.getMutex());
|
||||
delayRequest();
|
||||
BUS_DELAY;
|
||||
LOG_DEBUG("Read Inputs", CH_MAX);
|
||||
return m_bus.readInputs(m_address, REG_INPUT, CH_MAX, values);
|
||||
}
|
||||
@@ -118,3 +110,5 @@ void remoteIO::resetAll(const bool value)
|
||||
LOG_DEBUG("Reset All ->", value ? "True" : "False");
|
||||
m_bus.writeCoil(m_address, REG_ALLCOILS, value);
|
||||
}
|
||||
|
||||
#undef BUS_DELAY
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
|
||||
#include <DebugLog.h>
|
||||
#include <RS485_Driver.h>
|
||||
#include <utils.h>
|
||||
|
||||
class remoteIO
|
||||
{
|
||||
@@ -44,9 +45,6 @@ public:
|
||||
|
||||
void resetAll(const bool value);
|
||||
|
||||
private:
|
||||
void delayRequest();
|
||||
|
||||
private:
|
||||
bool m_initialized;
|
||||
drivers::MODBUS &m_bus;
|
||||
|
||||
Reference in New Issue
Block a user