84 Commits

Author SHA1 Message Date
Emanuele Trabattoni
1457c6f1d2 minor fixes 2025-09-24 10:48:15 +02:00
Emanuele Trabattoni
d07ee18a22 updated getCronJobs response with next execution 2025-09-22 12:38:59 +02:00
Emanuele Trabattoni
9a0bc4c03f updated clock correction data 2025-09-22 12:05:42 +02:00
Emanuele Trabattoni
df66a9d076 fix timeDrift values and return for getCronJobs all 2025-08-31 10:16:10 +02:00
Emanuele Trabattoni
145698d3b9 fix pinlist naming 2025-08-30 11:34:57 +02:00
Emanuele Trabattoni
0952be3141 fix HPlimits pin ordering and introduce pin naming map 2025-08-30 10:55:40 +02:00
Emanuele Trabattoni
6a6931bde0 added getRainInfo command 2025-08-29 22:19:06 +02:00
Emanuele Trabattoni
4aeffc76b0 fixed log on TCP reconnection 2025-08-29 22:18:49 +02:00
Emanuele Trabattoni
cde86a7f99 reenabled ota and logs to TCP ocnnection port 9876 2025-08-29 21:30:38 +02:00
Emanuele Trabattoni
f9c5ab86ef refactor cronjobs 2025-08-29 19:30:41 +02:00
Emanuele Trabattoni
fc2687947a Fixed pinlist and temperature sensor map 2025-08-29 10:21:44 +02:00
Emanuele Trabattoni
637304781c Merge branch 'pro-develop' of https://git.etss.it/Obbart/ETcontroller_PRO into pro-develop 2025-08-17 18:41:28 +02:00
Emanuele Trabattoni
c973632fb8 PSram check 2025-08-17 18:41:24 +02:00
a79c4f8ca7 fix P1 limit pin in enum 2025-08-08 18:42:56 +02:00
Emanuele Trabattoni
bbf604e1a8 Readme first version 2025-08-06 11:24:22 +02:00
Emanuele Trabattoni
e37aa58398 OTA fixes + enable when network connected and switch pressed 2025-08-06 09:49:46 +02:00
Emanuele Trabattoni
5bff567863 ota update first version, with led management 2025-08-05 11:56:13 +02:00
Emanuele Trabattoni
80fda62344 read input and output commands 2025-08-04 11:37:53 +02:00
Emanuele Trabattoni
4a1e944ea2 set ntp parameters via config file 2025-08-03 12:11:00 +02:00
Emanuele Trabattoni
a1a66ebf8e RTC fix time lag correction 2025-08-03 11:27:07 +02:00
Emanuele Trabattoni
b19ed89158 clock correction 2025-08-02 18:04:40 +02:00
Emanuele Trabattoni
25251785fa led flash not working ma vabbeh 2025-08-02 17:39:02 +02:00
0e842294be Values vs Value 2025-08-01 11:31:05 +02:00
57957740d9 Merge remote-tracking branch 'origin/pro-develop' into pro-develop 2025-08-01 10:55:47 +02:00
Emanuele Trabattoni
25aa2d6cb6 led class refactor 2025-08-01 10:38:41 +02:00
Emanuele Trabattoni
eaa643bf3c fixed typo "values" 2025-08-01 10:38:29 +02:00
Emanuele Trabattoni
abe0cb0839 improved responses content for commands and cronjobs 2025-07-31 16:16:06 +02:00
Emanuele Trabattoni
fc2316b0f2 refactor tyoes + added callbacks 2025-07-31 16:15:36 +02:00
fa1b288f4d added setBuzz demo test command 2025-07-30 16:26:18 +02:00
Emanuele Trabattoni
1110648978 added set time via ntp as command and retrieve all cron jobs 2025-07-30 15:24:11 +02:00
Emanuele Trabattoni
581eca124e added time drift check command 2025-07-30 10:15:13 +02:00
Emanuele Trabattoni
1d1eb6fbfa cron job load and store events 2025-07-27 15:49:40 +02:00
Emanuele Trabattoni
ad90702ab6 string conversion utility in rtc driver 2025-07-27 13:59:50 +02:00
Emanuele Trabattoni
448e1bad15 first version of cron, does not read configuation from file 2025-07-26 16:05:03 +02:00
Emanuele Trabattoni
91f4c5c750 improved logging 2025-07-26 11:21:32 +02:00
Emanuele Trabattoni
5459148538 implemented config and irrigation commands 2025-07-25 21:53:49 +02:00
Emanuele Trabattoni
74a97a7dd6 get and set config via mqtt messages 2025-07-25 14:37:38 +02:00
Emanuele Trabattoni
31c6cd9606 improved bus wait with raii class that updates last access 2025-07-25 10:57:17 +02:00
Emanuele Trabattoni
bb0832ad4f Application develop start 2025-07-24 22:46:31 +02:00
Emanuele Trabattoni
bea42c9a36 Merge branch 'mqtt-wrapper' into pro-develop 2025-07-24 16:19:29 +02:00
Emanuele Trabattoni
cdbc904bec Adjusted mutex lock and delay for modbus 2025-07-24 16:18:42 +02:00
Emanuele Trabattoni
07dd200de8 expand and fix digitalIO class 2025-07-24 13:51:21 +02:00
Emanuele Trabattoni
71c7ff8756 formatting 2025-07-23 22:52:53 +02:00
Emanuele Trabattoni
59d8c2c2d4 variables name refactoring 2025-07-23 22:39:40 +02:00
Emanuele Trabattoni
8f5615a034 Lock position fix 2025-07-22 11:30:07 +02:00
Emanuele Trabattoni
16bb029e93 Fix lock on MODBUS 2025-07-22 11:15:57 +02:00
Emanuele Trabattoni
146a2b558b Improved reconnection 2025-07-22 11:15:36 +02:00
Emanuele Trabattoni
7c776e4787 fixed auto reconnect and resubscribe inside mqtt wrapper loop 2025-07-18 19:29:19 +02:00
Emanuele Trabattoni
e8f395f8ef mqtt wrapper first version working 2025-07-18 02:00:58 +02:00
Emanuele Trabattoni
52a89e58f7 Merge branch 'drivers-refactoring' into pro-develop 2025-07-17 20:59:31 +02:00
Emanuele Trabattoni
b7881355a2 Config class as singleton with initializer in setup 2025-07-17 20:57:50 +02:00
Emanuele Trabattoni
92de57a760 Implemented config file and save to memory using ffat 2025-07-17 18:01:03 +02:00
Emanuele Trabattoni
0b5d725d3a Added Buzzer and RGB led drivers 2025-07-16 20:42:11 +02:00
Emanuele Trabattoni
30ed0d283a Fixed time format conversion to be static 2025-07-16 20:41:57 +02:00
Emanuele Trabattoni
3923aa3c05 Added power factor register 2025-07-16 20:41:38 +02:00
Emanuele Trabattoni
53b82c32c3 DebugLog level in every header 2025-07-14 11:35:19 +02:00
Emanuele Trabattoni
bdf3b9b41a Added mutex to MODBUS and I@c for mutithreading 2025-07-14 11:29:16 +02:00
Emanuele Trabattoni
7e02f3cef2 Fixed MODBUS and seneca drivers, added partial counter reset 2025-07-13 13:16:24 +02:00
Emanuele Trabattoni
d2eba9085e Added seneca powermeter driver 2025-07-12 23:00:21 +02:00
Emanuele Trabattoni
1ad98799b4 Added Temperature board driver 2025-07-12 16:11:05 +02:00
Emanuele Trabattoni
e4d28b55cb commands and responses template 2025-07-12 13:45:19 +02:00
Emanuele Trabattoni
ef7b9506b6 DigitalIO driver with dynamic channel count 2025-07-12 13:45:00 +02:00
Emanuele Trabattoni
1955b8cb39 MQTT Tesk OK 2025-07-10 23:06:37 +02:00
Emanuele Trabattoni
208f5f7534 Fixed RTC and Ethernet drivers, with NTP 2025-07-10 21:48:30 +02:00
Emanuele Trabattoni
7fd4a284af RTC Driver OK 2025-07-10 17:11:21 +02:00
Emanuele Trabattoni
8f701ce81a Modbus Driver fixing multiRequest 2025-07-10 16:01:10 +02:00
Emanuele Trabattoni
4b97e6535d Added debug config 2025-07-06 19:52:48 +02:00
Emanuele Trabattoni
f274970d63 Major fixes to MODBUS Driver 2025-07-02 18:45:57 +02:00
Emanuele Trabattoni
3d2d44c0bb Added STM32 platform for debugging and development 2025-06-27 18:55:20 +02:00
Emanuele Trabattoni
01db0e543f Added R4DCB08 Temperature module docs 2025-06-27 18:54:59 +02:00
Emanuele Trabattoni
4acce987de Removed example files (can be recovered later)
Now it compiles with test main code
2025-06-26 12:44:20 +02:00
Emanuele Trabattoni
b54c0e5018 First version of RS485 + MODBUS Driver 2025-06-26 11:52:09 +02:00
Emanuele Trabattoni
17f5a1dfe5 Halfway RS485 driver refactoring 2025-06-24 15:30:59 +02:00
Emanuele Trabattoni
7a7d677bfe File renaming 2025-06-23 14:54:00 +02:00
Emanuele Trabattoni
9530aab1c1 Completed RTC driver refactoring 2025-06-23 14:29:42 +02:00
Emanuele Trabattoni
19197aa022 Added reference manuals 2025-06-23 10:12:50 +02:00
Emanuele Trabattoni
79e5760d19 Halfway RTC driver refactoring 2025-06-22 15:27:10 +02:00
Emanuele Trabattoni
dcbe637ccc Fixed typos 2025-06-22 15:26:41 +02:00
Emanuele Trabattoni
b5de72a6d1 Fixed formatting 2025-06-22 12:35:19 +02:00
Emanuele Trabattoni
adb15962c6 I2C Digitalout driver 2025-06-22 12:23:38 +02:00
Emanuele Trabattoni
83a63c1241 I2C driver 2025-06-21 16:34:11 +02:00
Emanuele Trabattoni
2a33316ba8 Removed launch.json 2025-06-21 11:13:30 +02:00
Emanuele Trabattoni
12ab46f826 Updated .gitignore
launch configuration is dependent on compile machine, do not track in git
2025-06-21 11:11:21 +02:00
7ea491905f File reorg, step1 2025-06-20 17:13:16 +02:00
88 changed files with 76649 additions and 2881 deletions

2
.gitignore vendored
View File

@@ -91,7 +91,7 @@ dkms.conf
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
#!.vscode/launch.json
!.vscode/extensions.json
!.vscode/*.code-snippets

44
.vscode/launch.json vendored
View File

@@ -1,44 +0,0 @@
// AUTOMATICALLY GENERATED FILE. PLEASE DO NOT MODIFY IT MANUALLY
//
// PlatformIO Debugging Solution
//
// Documentation: https://docs.platformio.org/en/latest/plus/debugging.html
// Configuration: https://docs.platformio.org/en/latest/projectconf/sections/env/options/debug/index.html
{
"version": "0.2.0",
"configurations": [
{
"type": "platformio-debug",
"request": "launch",
"name": "PIO Debug",
"executable": "C:/Users/ematr/Documents/VScode/ETcontroller_PRO/.pio/build/esp32-s3-waveshare8/firmware.elf",
"projectEnvName": "esp32-s3-waveshare8",
"toolchainBinDir": "C:/Users/ematr/.platformio/packages/toolchain-xtensa-esp-elf/bin",
"internalConsoleOptions": "openOnSessionStart",
"preLaunchTask": {
"type": "PlatformIO",
"task": "Pre-Debug"
}
},
{
"type": "platformio-debug",
"request": "launch",
"name": "PIO Debug (skip Pre-Debug)",
"executable": "C:/Users/ematr/Documents/VScode/ETcontroller_PRO/.pio/build/esp32-s3-waveshare8/firmware.elf",
"projectEnvName": "esp32-s3-waveshare8",
"toolchainBinDir": "C:/Users/ematr/.platformio/packages/toolchain-xtensa-esp-elf/bin",
"internalConsoleOptions": "openOnSessionStart"
},
{
"type": "platformio-debug",
"request": "launch",
"name": "PIO Debug (without uploading)",
"executable": "C:/Users/ematr/Documents/VScode/ETcontroller_PRO/.pio/build/esp32-s3-waveshare8/firmware.elf",
"projectEnvName": "esp32-s3-waveshare8",
"toolchainBinDir": "C:/Users/ematr/.platformio/packages/toolchain-xtensa-esp-elf/bin",
"internalConsoleOptions": "openOnSessionStart",
"loadMode": "manual"
}
]
}

72
.vscode/settings.json vendored
View File

@@ -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"
}
}

View File

@@ -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]

3
data/example.json Normal file
View File

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

Binary file not shown.

Binary file not shown.

Binary file not shown.

File diff suppressed because one or more lines are too long

BIN
docs/PCF85063A.pdf Normal file

Binary file not shown.

Binary file not shown.

101
docs/commands.json Normal file
View File

@@ -0,0 +1,101 @@
[
{
"cmd": "setHPlimit",
"params": {
"level": [
"UNLIMITED",
"P1",
"P2",
"P3",
"P4"
]
}
},
{
"cmd": "setHeating",
"params": {
"pump": [
"ON",
"OFF"
],
"ground": [
"ON",
"OFF"
],
"first": [
"ON",
"OFF"
]
}
},
{
"cmd": "getHPpower",
"params": null
},
{
"cmd": "getHPlimit",
"params": null
},
{
"cmd": "getInputStatus",
"params": null
},
{
"cmd": "getOutputStatus",
"params": null
},
{
"cmd": "getTemperatures",
"params": null
},
{
"cmd": "getWaterInfo",
"params": null
},
{
"cmd": "getTankInfo",
"params": null
},
{
"cmd": "getRainInfo",
"params": null
},
{
"cmd": "setIrrigation",
"params": {
"zone": [
"ricircolo",
"1",
"2",
"3",
"rubinetti"
],
"timeOn": 120,
"timePause": 2
}
},
{
"cmd": "getIrrigation",
"params": null
},
{
"cmd": "setCronJob",
"params": {
"name": "nomedeljob",
"cronExpr": "* * * 10,45 5 *",
"action": "qua ci va un dizionario come se arrivasse da mqtt, cosi li interpreto alla stessa maniera"
}
},
{
"cmd": "getCronJob",
"params": {
"name": "nomedeljob"
}
},
{
"cmd": "delCronJob",
"params": {
"name": "nomedeljob"
}
}
]

BIN
docs/mi00383-11-en.pdf Normal file

Binary file not shown.

BIN
docs/mi004700-i-e.pdf Normal file

Binary file not shown.

123
docs/response.json Normal file
View File

@@ -0,0 +1,123 @@
[
{
"cmd": "POLL",
"values": {
"number": 1234,
"date": "20250810-123512"
}
},
{
"cmd": "getHPpower",
"values": {
"power": 3200,
"current": 16,
"energy": 12341234
}
},
{
"cmd": "getHPlimit",
"values": {
"level": [
"UNLIMITED",
"P1",
"P2",
"P3",
"P4"
]
}
},
{
"cmd": "getInputStatus",
"values": {
"rain": [
"ON",
"OFF"
],
"waterPressure": [
"ON",
"OFF"
]
}
},
{
"cmd": "getOutputStatus",
"values": {
"pump": [
"ON",
"OFF"
],
"ground": [
"ON",
"OFF"
],
"first": [
"ON",
"OFF"
]
}
},
{
"cmd": "getTemperatures",
"values": {
"solar": 1234,
"acs": 1234,
"heating": 1234
}
},
{
"cmd": "getWaterInfo",
"values": {
"flow": 1234,
"consumption": 1234,
"temperature": 1234
}
},
{
"cmd": "getTankLevel",
"values": {
"level": 10
}
},
{
"cmd": "getRainInfo",
"values": {
"rain": [
"ON",
"OFF"
]
}
},
{
"cmd": "getIrrigation",
"values": {
"Ricircolo": [
"ON",
"OFF"
],
"1": [
"ON",
"OFF"
],
"2": [
"ON",
"OFF"
],
"3": [
"ON",
"OFF"
],
"Rubinetti": [
"ON",
"OFF"
]
}
},
{
"cmd": "getCronJob",
"values": {
"name": "nomedeljob",
"timeStr": "* * * 10,45 5 *",
"action": "dizionario che dice cosa deve fare come e' salvato nel micro"
}
}
]

BIN
docs/tca9554.pdf Normal file

Binary file not shown.

54
esp32-s3-waveshare8.json Normal file
View 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"
}

6
fatfs_partition.csv Normal file
View File

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

298
include/config.h Normal file
View File

@@ -0,0 +1,298 @@
#pragma once
#define DEBUGLOG_DEFAULT_LOG_LEVEL_DEBUG
#include <DebugLog.h>
#include <Arduino.h>
#include <ArduinoJson.h>
#include <fsmount.h>
class Config
{
public:
static Config &getInstance()
{
static Config instance;
return instance;
}
private:
Config() = default;
Config(const Config &) = delete;
Config &operator=(const Config &) = delete;
public:
void init()
{
FSmount mount; // scoped mount of the filesystem
// Initialize and mount filesystem
LOG_INFO("Initializing Config");
if (!FFat.exists("/config.json"))
{
LOG_WARN("Initializing default config");
saveConfig();
}
File file = FFat.open("/config.json", FILE_READ, false);
if (!file)
{
LOG_ERROR("Unable to open config.json");
return;
}
if (ArduinoJson::deserializeJson(m_configJson, file) != ArduinoJson::DeserializationError::Ok)
{
LOG_ERROR("Unable to load config.json");
}
std::string loadedConf;
ArduinoJson::serializeJsonPretty(m_configJson, loadedConf);
LOG_INFO("Loaded Configuration\n", loadedConf.c_str());
deserialize(); // convert from json format to class members
file.close(); // close config file before unmounting filesystem
};
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);
{
FSmount mount;
m_configJson = json;
deserialize();
saveConfig();
}; // filesystem is unmounted here
}
void resetConfig()
{
std::lock_guard<std::mutex> lock(m_mutex);
{
FSmount mount;
LOG_WARN("Removing config.json");
if (!FFat.remove("/config.json"))
{
LOG_ERROR("Unable to remove config.json");
}
LOG_WARN("Configuration reset, Restarting");
}; // filesystem is unmounted here
delay(500);
esp_restart();
}
private:
void saveConfig() // write configuration to flash memory
{
File file = FFat.open("/config.json", FILE_WRITE, true);
if (!file)
{
LOG_ERROR("Unable to open config.json for writing");
return;
}
serialize(); // serialize default configuration
if (ArduinoJson::serializeJson(m_configJson, file) == 0)
{
LOG_ERROR("Serialization Failed");
}
file.close();
}
//////////////////////////////////////////////////////////////
////////////// SERIALIZATION + DESERIALIZATION ///////////////
//////////////////////////////////////////////////////////////
void serialize()
{
// form class members to json document
{
auto globals = m_configJson["globals"].to<ArduinoJson::JsonObject>();
globals["loopDelay"] = m_globalLoopDelay;
};
{
auto ethernet = m_configJson["ethernet"].to<ArduinoJson::JsonObject>();
ethernet["hostname"] = m_ethHostname;
ethernet["ipAddr"] = m_ethIpAddr;
ethernet["netmask"] = m_ethNetmask;
ethernet["gateway"] = m_ethGateway;
};
{
auto modbus = m_configJson["modbus"].to<ArduinoJson::JsonObject>();
modbus["relayAddr"] = m_modbusRelayAddr;
modbus["temperatureAddr"] = m_modbusTemperatureAddr;
modbus["senecaAddr"] = m_modbusSenecaAddr;
modbus["flowmeterAddr"] = m_modbusFlowmeterAddr;
modbus["tankLevelAddr"] = m_modbusTankLevelAddr;
};
{
auto temperature = m_configJson["temperature"].to<ArduinoJson::JsonObject>();
temperature["expectedSensors"] = m_tempExpectedSensors;
auto values = temperature["correctionValues"].to<ArduinoJson::JsonArray>();
for (auto v : m_tempCorrectionValues)
{
values.add(v);
}
};
{
auto ntp = m_configJson["ntp"].to<ArduinoJson::JsonObject>();
ntp["pool"] = m_ntpPool;
ntp["timezone"] = m_ntpTimezone;
ntp["updateInterval"] = m_ntpUpdateInterval;
ntp["retries"] = m_ntpRetries;
ntp["ntpRtcOffsetRegister"] = m_ntpRtcOffsetRegister;
};
{
auto mqtt = m_configJson["mqtt"].to<ArduinoJson::JsonObject>();
mqtt["host"] = m_mqttHost;
mqtt["port"] = m_mqttPort;
mqtt["loopTime"] = m_mqttLoopTime;
mqtt["clientName"] = m_mqttClientName;
mqtt["retries"] = m_mqttRetries;
mqtt["keepalive"] = m_mqttKeepalive;
auto publish = mqtt["publish"].to<ArduinoJson::JsonObject>();
for (auto v : m_mqttPublish)
{
publish[v.first] = v.second;
}
auto subscribe = mqtt["subscribe"].to<ArduinoJson::JsonObject>();
for (auto v : m_mqttSubscribe)
{
subscribe[v.first] = v.second;
}
};
};
void deserialize()
{ // from json document to class members
if (m_configJson.isNull())
{
LOG_ERROR("NUll config document");
return;
}
{
auto globals = m_configJson["globals"];
m_globalLoopDelay = globals["loopDelay"].as<uint16_t>();
};
{
auto ethernet = m_configJson["ethernet"];
m_ethHostname = ethernet["hostname"].as<std::string>();
m_ethIpAddr = ethernet["ipAddr"].as<std::string>();
m_ethNetmask = ethernet["netmask"].as<std::string>();
m_ethGateway = ethernet["gateway"].as<std::string>();
};
{
auto modbus = m_configJson["modbus"];
m_modbusRelayAddr = modbus["relayAddr"].as<uint8_t>();
m_modbusTemperatureAddr = modbus["temperatureAddr"].as<uint8_t>();
m_modbusSenecaAddr = modbus["senecaAddr"].as<uint8_t>();
m_modbusFlowmeterAddr = modbus["flowmeterAddr"].as<uint8_t>();
m_modbusTankLevelAddr = modbus["tankLevelAddr"].as<uint8_t>();
};
{
auto temperature = m_configJson["temperature"];
m_tempExpectedSensors = temperature["expectedSensors"].as<uint8_t>();
auto values = temperature["correctionValues"].as<JsonArray>();
m_tempCorrectionValues.clear();
m_tempCorrectionValues.reserve(values.size());
for (auto v : values)
{
m_tempCorrectionValues.emplace_back(v.as<float>());
}
};
{
auto ntp = m_configJson["ntp"];
m_ntpPool = ntp["pool"].as<std::string>();
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>();
};
{
auto mqtt = m_configJson["mqtt"];
m_mqttHost = mqtt["host"].as<std::string>();
m_mqttPort = mqtt["port"].as<uint16_t>();
m_mqttLoopTime = mqtt["loopTime"].as<uint16_t>();
m_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>();
}
auto publish = mqtt["publish"].as<ArduinoJson::JsonObject>();
for (auto v : publish)
{
m_mqttPublish[v.key().c_str()] = v.value().as<std::string>();
}
};
};
private:
ArduinoJson::JsonDocument m_configJson;
std::mutex m_mutex;
public:
// Globals
std::uint16_t m_globalLoopDelay = 5000; // in milliseconds
// Ethernet
std::string m_ethHostname = "ETcontroller_PRO";
std::string m_ethIpAddr = "10.0.2.251";
std::string m_ethNetmask = "255.255.255.0";
std::string m_ethGateway = "10.0.2.1";
// MODBUS
uint8_t m_modbusRelayAddr = 0x01;
uint8_t m_modbusTemperatureAddr = 0xAA;
uint8_t m_modbusSenecaAddr = 0xBB;
uint8_t m_modbusFlowmeterAddr = 0xCC;
uint8_t m_modbusTankLevelAddr = 0xDD;
// Temperature Board
uint8_t m_tempExpectedSensors = 1;
std::vector<float> m_tempCorrectionValues = std::vector<float>(8, 0.0f);
// NTP
std::string m_ntpPool = "pool.ntp.org";
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", "etcontroller/hw/commands"}};
std::map<const std::string, std::string> m_mqttPublish = {
{"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
View 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
View 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
View 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"}};

83
lib/ETH/ETH_Driver.cpp Normal file
View File

@@ -0,0 +1,83 @@
#include "ETH_Driver.h"
namespace drivers
{
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, m_ntpPool.c_str(), tz * 3600, updateInterval)); // NTP server, time offset in seconds, update interval
m_timeClient.begin();
}
Ethernet::~Ethernet()
{
m_timeClient.end();
ETH.end();
SPI.end();
}
const bool Ethernet::getNtpTime(time_t &time)
{
if (m_connected && m_timeClient.update())
{
time = m_timeClient.getEpochTime();
LOG_DEBUG("Epoch Time:", (long)time);
return true;
}
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;
}
void Ethernet::onEvent(arduino_event_id_t event, arduino_event_info_t info)
{
switch (event)
{
case ARDUINO_EVENT_ETH_START:
ETH.setHostname("waveshare-esp32s3");
break;
case ARDUINO_EVENT_ETH_CONNECTED:
LOG_INFO("ETH Connected");
break;
case ARDUINO_EVENT_ETH_GOT_IP:
m_localIP = ETH.localIP();
LOG_INFO("ETH ", esp_netif_get_desc(info.got_ip.esp_netif), " Got IP:", m_localIP.toString().c_str());
LOG_INFO("ETH ", esp_netif_get_desc(info.got_ip.esp_netif), " Gateway:", ETH.gatewayIP().toString().c_str());
LOG_INFO("ETH ", esp_netif_get_desc(info.got_ip.esp_netif), " Netmask:", ETH.subnetMask().toString().c_str());
m_connected = true;
break;
case ARDUINO_EVENT_ETH_LOST_IP:
LOG_INFO("ETH Lost IP");
m_connected = false;
break;
case ARDUINO_EVENT_ETH_DISCONNECTED:
LOG_INFO("ETH Disconnected");
m_connected = false;
break;
case ARDUINO_EVENT_ETH_STOP:
LOG_INFO("ETH Stopped");
m_connected = false;
break;
default:
break;
}
}
}

50
lib/ETH/ETH_Driver.h Normal file
View File

@@ -0,0 +1,50 @@
#pragma once
#define DEBUGLOG_DEFAULT_LOG_LEVEL_INFO
#include <DebugLog.h>
#include <Arduino.h>
#include <Network.h>
#include <NTPClient.h>
#include <ETH.h>
#include <SPI.h>
// PHY defines hardware related
#ifndef ETH_PHY_TYPE
#define ETH_PHY_TYPE ETH_PHY_W5500
#define ETH_PHY_ADDR 1
#define ETH_PHY_CS 16
#define ETH_PHY_IRQ 12
#define ETH_PHY_RST 39
#endif
// SPI pins
#define ETH_SPI_SCK 15
#define ETH_SPI_MISO 14
#define ETH_SPI_MOSI 13
namespace drivers
{
class Ethernet : public ETHClass
{
public:
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;
NTPClient m_timeClient;
};
}

View File

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

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

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

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

@@ -0,0 +1,122 @@
#include <LED_Driver.h>
#define TASK_PRIORITY 20
#define TASK_STACK 2048
namespace drivers
{
Led::Led()
{
LOG_INFO("Inizializing RGB Led");
pinMode(c_ledPin, OUTPUT);
m_blinkTask = NULL;
m_flashTimer = NULL;
m_enforce = false;
}
Led::~Led()
{
setColor({0, 0, 0});
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();
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_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_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_blinkTask != NULL)
vTaskDelete(m_blinkTask);
m_blinkTask = NULL;
}
void Led::blinkTask(void *params)
{
Led *led = static_cast<Led *>(params);
LOG_DEBUG("Blinker Task Created");
while (true)
{
{
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(led->m_tOff);
}
LOG_DEBUG("Blinker Task Ended");
led->m_blinkTask = NULL;
vTaskDelete(NULL);
}
}

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

@@ -0,0 +1,70 @@
#pragma once
#include <Arduino.h>
#define DEBUGLOG_DEFAULT_LOG_LEVEL_INFO
#include <DebugLog.h>
#include <mutex>
namespace drivers
{
class Led
{
public:
typedef struct
{
uint8_t r;
uint8_t g;
uint8_t b;
} color_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:
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;
};
}

View File

@@ -0,0 +1,92 @@
#include "TCA9554PWR_Driver.h"
namespace drivers
{
TCA9554PWR::TCA9554PWR(I2C &i2c, const uint8_t address) : m_i2c(i2c), m_address(address)
{
writeRegister(TCA9554_OUTPUT_REG, Low); // set all pins to Low state
writeRegister(TCA9554_CONFIG_REG, TCA9554_OUT_MODE); // set all pins as output (relay mode for this board)
}
TCA9554PWR::~TCA9554PWR() {
writeRegister(TCA9554_OUTPUT_REG, Low); // set all pins to Low state
writeRegister(TCA9554_CONFIG_REG, TCA9554_OUT_MODE); // set all pins as output (relay mode for this board)
}
const bool TCA9554PWR::writeRegister(const uint8_t reg, const uint8_t val)
{
if (m_i2c.write(m_address, reg, {val}))
return true;
LOG_ERROR("Unable to write register: reg[%d], val[%d] ", reg, val);
return false;
}
const bool TCA9554PWR::readRegister(const uint8_t reg, uint8_t &val)
{
std::vector<uint8_t> data;
if (m_i2c.read(m_address, reg, 1, data))
{
val = data.back();
return true;
}
LOG_ERROR("Unable to read register: reg[%d]");
return false;
}
const bool TCA9554PWR::setOut(const uint8_t ch, const bool state)
{
uint8_t currState(0);
uint8_t newState(0);
if (ch < DO1 || ch > DO8)
{
LOG_ERROR("Invalid write to output channel: [%d]", ch);
return false;
}
if (!readPort(currState))
return false;
if (state)
newState = (High << ch) | currState;
else
newState = (~(High << ch)) & currState;
return setPort(newState);
}
const bool TCA9554PWR::toggleOut(const uint8_t channel)
{
bool value;
return readOut(channel, value) && setOut(channel, value);
}
const bool TCA9554PWR::setPort(const uint8_t state)
{
if (writeRegister(TCA9554_OUTPUT_REG, state))
return true;
LOG_ERROR("Unable to write IO port: state[%02x]", state);
return false;
}
const bool TCA9554PWR::readOut(const uint8_t ch, bool &state)
{
uint8_t currState(0);
if (ch < DO1 || ch > DO8)
{
LOG_ERROR("Invalid read to output channel: [%d]", ch);
return false;
}
if (!readPort(currState))
return false;
state = (currState && (High << ch));
return true;
}
const bool TCA9554PWR::readPort(uint8_t &state)
{
if (readRegister(TCA9554_OUTPUT_REG, state))
return true;
LOG_ERROR("Unable to read IO port: state[%02x]", state);
return false;
}
}

View File

@@ -0,0 +1,57 @@
#pragma once
#define DEBUGLOG_DEFAULT_LOG_LEVEL_INFO
#include <DebugLog.h>
#include "I2C_Driver.h"
/****************************************************** The macro defines the TCA9554PWR information ******************************************************/
#define TCA9554_ADDRESS 0x20 // TCA9554PWR I2C address
#define TCA9554_INPUT_REG 0x00 // Input register, input level
#define TCA9554_OUTPUT_REG 0x01 // Output register, high and low level output
#define TCA9554_POLARITY_REG 0x02 // The Polarity Inversion register (register 2) allows polarity inversion of pins defined as inputs by the Configuration register.
#define TCA9554_CONFIG_REG 0x03 // Configuration register, mode configuration
#define TCA9554_OUT_MODE 0x00 // Configuration register value, output mode
#define TCA9554_IN_MODE 0xff // Configuration register value, input mode
#define Low 0x00
#define High 0x01
namespace drivers
{
class TCA9554PWR
{
public:
typedef enum
{
DO1,
DO2,
DO3,
DO4,
DO5,
DO6,
DO7,
DO8,
DO_MAX
} channel_t;
TCA9554PWR(I2C &i2c, const uint8_t address);
~TCA9554PWR();
const bool setOut(const uint8_t channel, const bool state);
const bool toggleOut(const uint8_t channel);
const bool setPort(const uint8_t state);
const bool readOut(const uint8_t channel, bool &state);
const bool readPort(uint8_t &state);
private:
I2C &m_i2c;
uint8_t m_address;
const bool writeRegister(const uint8_t reg, const uint8_t val);
const bool readRegister(const uint8_t reg, uint8_t &val);
};
}

77
lib/I2C/I2C_Driver.cpp Normal file
View File

@@ -0,0 +1,77 @@
#include "I2C_Driver.h"
namespace drivers
{
I2C::I2C(): m_initialized(true)
{
Wire.begin(I2C_SDA_PIN, I2C_SCL_PIN);
}
I2C::~I2C()
{
Wire.end();
m_initialized = false;
}
const bool I2C::read(const uint8_t deviceAddr, const uint8_t deviceReg, const uint8_t len, std::vector<uint8_t> &data)
{
std::lock_guard<std::mutex> lock(m_mutex);
Wire.beginTransmission(deviceAddr);
Wire.write(deviceReg);
switch (Wire.endTransmission(true))
{
case 0:
break; // no error, break switch
case 1:
LOG_ERROR("Data to long to fit in buffer: [%d]", len);
case 2:
LOG_ERROR("Received NAK on address transmit");
case 3:
LOG_ERROR("Received NAK on data transmit");
case 4:
LOG_ERROR("Unknown Error");
return false;
}
const uint8_t nBytes = Wire.requestFrom(deviceAddr, len);
if (nBytes < len)
{
LOG_ERROR("Received data is less than expected: len[%d], nBytes[%d]", len, nBytes);
}
data.clear();
data.resize(nBytes); // resize out buffer to received data len, no check if data len is correct
for (auto i = 0; i < nBytes; i++)
{
data[i] = static_cast<uint8_t>(Wire.read());
}
return true;
}
const bool I2C::write(const uint8_t deviceAddr, const uint8_t deviceReg, const std::vector<uint8_t> &data)
{
std::lock_guard<std::mutex> lock(m_mutex);
Wire.beginTransmission(deviceAddr);
Wire.write(deviceReg);
for (auto d : data)
{
Wire.write(d);
}
switch (Wire.endTransmission(true))
{
case 0:
break; // no error, break switch
case 1:
LOG_ERROR("Data to long to fit in buffer: [%d]", data.size());
case 2:
LOG_ERROR("Received NAK on address transmit");
case 3:
LOG_ERROR("Received NAK on data transmit");
case 4:
LOG_ERROR("Unknown Error");
return false;
}
return true;
}
} // namespace drivers

31
lib/I2C/I2C_Driver.h Normal file
View File

@@ -0,0 +1,31 @@
#pragma once
#define DEBUGLOG_DEFAULT_LOG_LEVEL_INFO
#include <DebugLog.h>
#include <Arduino.h>
#include <Wire.h>
#include <vector>
#include <mutex>
#define I2C_SCL_PIN 41
#define I2C_SDA_PIN 42
namespace drivers
{
class I2C
{
public:
I2C(void);
~I2C(void);
const bool read(const uint8_t deviceAddr, const uint8_t deviceReg, const uint8_t len, std::vector<uint8_t> &data);
const bool write(const uint8_t deviceAddr, const uint8_t deviceReg, const std::vector<uint8_t> &data);
private:
bool m_initialized;
std::mutex m_mutex;
};
}

459
lib/RS485/RS485_Driver.cpp Normal file
View File

@@ -0,0 +1,459 @@
#include "RS485_driver.h"
#include <algorithm>
#include <cstring>
#include <endian.h>
#include <busdelay.h>
#include "utils.h"
#define BUS_DELAY drivers::BusDelay(m_lastAccess, c_minDelay, "MODBUS")
namespace drivers
{
////////////////////////////////
//////////// RS485 ////////////
////////////////////////////////
RS485::RS485(const uint32_t baud, const SerialConfig conf) : m_serial(Serial1)
{
LOG_INFO("Init serial port 1");
// RS485 is hardwired to serial port 1
m_serial.begin(baud, conf, 18, 17);
m_serial.setTimeout(1000);
m_serial.flush();
}
const bool RS485::write(const std::vector<uint8_t> data)
{
return data.size() == m_serial.write(data.data(), data.size());
}
const bool RS485::readAll(std::vector<uint8_t> &data)
{
const uint32_t avail(m_serial.available());
if (avail == 0)
return true;
data.resize(avail);
return data.size() == m_serial.readBytes(data.data(), avail);
}
const bool RS485::readN(const uint16_t nBytes, std::vector<uint8_t> &data)
{
std::vector<uint8_t> buf;
buf.resize(nBytes);
if (m_serial.readBytes(buf.data(), nBytes) == nBytes)
{
data = std::move(buf);
return true;
}
return false;
}
const bool RS485::readUntil(const uint8_t ch, std::vector<uint8_t> &data)
{
const uint32_t avail(m_serial.available());
data.resize(avail);
m_serial.readBytesUntil(ch, data.data(), avail);
data.shrink_to_fit();
return true;
}
////////////////////////////////
//////////// MODBUS ////////////
////////////////////////////////
MODBUS::MODBUS(const uint32_t baud, const SerialConfig conf) : RS485::RS485(baud, conf)
{
std::vector<uint8_t> garbage;
readAll(garbage);
LOG_INFO("Init MODBUS Master Mode");
m_crc.reset(CRC16_MODBUS_POLYNOME, CRC16_MODBUS_INITIAL, CRC16_MODBUS_XOR_OUT, CRC16_MODBUS_REV_IN, CRC16_MAXIM_REV_OUT);
m_lastAccess = millis();
m_lastDevice = 0;
}
// Get transaction lock
std::unique_lock<std::mutex> MODBUS::getLock()
{
return std::unique_lock<std::mutex>(m_mutex);
}
std::mutex &MODBUS::getMutex()
{
return m_mutex;
}
// 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;
LOG_DEBUG("Read coils: dev[", printHex(device).c_str(), "], reg[", printHex(reg).c_str(), "], num[", num, "]");
return readBinary(device, func, reg, num, coils);
}
// Func 0x02
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;
LOG_DEBUG("Read multi inputs: dev[", printHex(device).c_str(), "], reg[", printHex(reg).c_str(), "], num[", num, "]");
return readBinary(device, func, reg, num, inputs);
}
// Func 0x03
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;
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);
}
// Func 0x04
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;
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);
}
// Func 0x05
const bool MODBUS::writeCoil(const uint8_t device, const uint16_t coil, const bool value)
{
constexpr uint8_t func = 0x05;
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});
}
// Func 0x06
const bool MODBUS::writeRegister(const uint8_t device, const uint16_t reg, const uint16_t value)
{
constexpr uint8_t func = 0x06;
LOG_DEBUG("Write single register: dev[", printHex(device).c_str(), "], reg[", printHex(reg).c_str(), "], value[", value, "]");
return writeInteger(device, func, reg, {value}, false);
}
// Func 0x0F
const bool MODBUS::writeCoils(const uint8_t device, const uint16_t coils, const std::vector<bool> &values)
{
constexpr uint8_t func = 0x0F;
LOG_DEBUG("Write multi coils: dev[", printHex(device).c_str(), "], start[", printHex(coils).c_str(), "], num[", values.size(), "]");
return writeBinary(device, func, coils, values);
}
// Func 0x10
const bool MODBUS::writeRegisters(const uint8_t device, const uint16_t reg, const std::vector<uint16_t> &values)
{
constexpr uint8_t func = 0x10;
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);
}
/////////////////////////////////////////////////////////////////
/////////////////////// Utility Functions ///////////////////////
/////////////////////////////////////////////////////////////////
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");
return false;
}
const uint16_t nRespDataBytes = (uint16_t)ceil(bits / 8.0f); // 1 bit for every coil, if not 8 mutiple padded with zeroes
const uint16_t expectedRespLen = (c_respHeaderSize + c_respCrcSize) + nRespDataBytes; // device + function + nbytes + data[] + crc(16b)
std::vector<uint8_t> response;
if (!readN(expectedRespLen, response))
{
LOG_ERROR("Failed receive readBinary response, expected[", expectedRespLen, "], received[", response.size(), "]");
return false;
}
#ifdef DEBUGLOG_DEFAULT_LOG_LEVEL_TRACE
printBytes("readBinary Response", response);
#endif
// element 2 of response has the response data bytes expected
const uint8_t actualRespLen(response.at(2));
if (actualRespLen != nRespDataBytes)
{
LOG_ERROR("Failed receive, data to short: actual[", actualRespLen, "], expected[", nRespDataBytes, "]");
return false;
}
// compute crc of current message
if (!verifyCrc(response))
return false;
// extract coils data from data portion of response
out.clear();
out.reserve(bits);
uint16_t bitNum(0);
// get response data bytes excluding header and crc
const std::vector<uint8_t> respData(response.begin() + c_respHeaderSize, response.end() - sizeof(crc_t));
for (auto it = respData.begin(); it < respData.end(); it++)
{
for (uint8_t j(0); j < 8 && bitNum < bits; j++)
{
const bool cv((0x01 << j) & *it);
out.push_back(cv);
bitNum++;
}
}
return true;
}
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");
return false;
}
const uint16_t nRespDataBytes = num * sizeof(uint16_t);
const uint16_t expectedRespLen = (c_respHeaderSize + sizeof(crc_t)) + nRespDataBytes; // device + function + nbytes + data[] + crc(16b)
std::vector<uint8_t> response;
if (!readN(expectedRespLen, response))
{
LOG_ERROR("Failed receive readInteger response, expected[", expectedRespLen, "], received[", response.size(), "]");
return false;
}
#ifdef DEBUGLOG_DEFAULT_LOG_LEVEL_TRACE
printBytes("readInteger Response", response);
#endif
// element 2 of response has the response data bytes expected
const uint8_t actualRespLen(response.at(2));
if (actualRespLen != nRespDataBytes)
{
LOG_ERROR("Failed receive, data to short: actual[", actualRespLen, "], expected[", nRespDataBytes, "]");
return false;
}
// compute crc of current message
if (!verifyCrc(response))
return false;
// extract coils data from data portion of response
out.clear();
out.reserve(nRespDataBytes / sizeof(uint16_t));
// get response data bytes excluding header and crc
const std::vector<uint8_t> respData(response.begin() + c_respHeaderSize, response.end() - c_respCrcSize);
for (auto it = respData.begin(); it < respData.end(); it++)
{
const uint8_t lo(*it++);
const uint8_t hi(*it);
const uint16_t val(0xFFFF & ((hi << 8) | lo));
out.push_back(be16toh(val));
}
return true;
}
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]
{
if (!write(singleRequest(device, func, reg, in.front() ? 0xFF00 : 0x0000)))
{
LOG_ERROR("Failed send writeSingleBinary command");
return false;
}
}
else // if multiple coils value is 0x01 shifted for the number of coil intended
{
const uint16_t numBytes((uint16_t)ceil(bits / 8.0f));
bitsOut.resize(numBytes, 0x00);
for (uint16_t i(0); i < in.size(); i++)
{
if (!in[i]) // if value is false skip
continue;
bitsOut[i / 8] |= 0x01 << i % 8;
}
#ifdef DEBUGLOG_DEFAULT_LOG_LEVEL_TRACE
LOG_DEBUG("\nnumBytes", numBytes);
printBool("bitsOut", in);
printBytes("bitsOut", bitsOut);
#endif
if (!write(multiRequest(device, func, reg, bits, bitsOut)))
{
LOG_ERROR("Failed send writeMultiBinary command");
return false;
}
}
const uint16_t expectedRespLen(sizeof(resp_t) + sizeof(crc_t));
std::vector<uint8_t> response;
if (!readN(expectedRespLen, response))
{
LOG_ERROR("Failed receive writeBinary response, expected[", expectedRespLen, "], received[", response.size(), "]");
return false;
}
#ifdef DEBUGLOG_DEFAULT_LOG_LEVEL_TRACE
printBytes("writeBinary Response", response);
#endif
// compute crc of current message
if (!verifyCrc(response))
return false;
return true;
}
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)
{
if (!write(singleRequest(device, func, reg, in[0])))
{
LOG_ERROR("Failed send writeSingleInteger command");
return false;
}
}
else
{
// build data vector for request, inverting bytes if necessary
std::vector<uint8_t> requestData;
requestData.resize(in.size() * sizeof(uint16_t), 0xff);
auto it = requestData.begin();
for (auto inV : in)
{
const uint16_t beV(htobe16(inV));
*(it++) = lowByte(beV);
*(it++) = highByte(beV);
}
if (!write(multiRequest(device, func, reg, num, requestData)))
{
LOG_ERROR("Failed send writeMultiInteger command");
return false;
}
}
const uint16_t expectedRespLen(sizeof(resp_t) + sizeof(crc_t));
std::vector<uint8_t> response;
if (!readN(expectedRespLen, response))
{
LOG_ERROR("Failed receive writeInteger response, expected[", expectedRespLen, "], received[", response.size(), "]");
return false;
}
#ifdef DEBUGLOG_DEFAULT_LOG_LEVEL_TRACE
printBytes("writeInteger Response", response);
#endif
// compute crc of current message
if (!verifyCrc(response))
return false;
return true;
}
const std::vector<uint8_t> MODBUS::singleRequest(const uint8_t device, const uint8_t func, const uint16_t reg, const uint16_t data)
{
req_t header;
header.device = device;
header.func = func;
header.reg = htobe16(reg);
header.data = htobe16(data);
const uint8_t headerBytes(sizeof(req_t));
const uint8_t crcBytes(sizeof(crc_t));
// compute crc for header + data
m_crc.restart();
m_crc.add((uint8_t *)&header, headerBytes); // exclude last two bytes of crc
const uint16_t crc(htole16(m_crc.calc()));
std::vector<uint8_t> dataOut(headerBytes + crcBytes, 0);
std::memcpy(dataOut.data(), &header, headerBytes);
std::memcpy(dataOut.data() + headerBytes, &crc, crcBytes);
#ifdef DEBUGLOG_DEFAULT_LOG_LEVEL_TRACE
printBytes("singleRequest", dataOut);
#endif
return dataOut;
}
const std::vector<uint8_t> MODBUS::multiRequest(const uint8_t device, const uint8_t func, const uint16_t reg, const uint16_t qty, const std::vector<uint8_t> &data)
{
req_multi_t header;
header.device = device;
header.func = func;
header.reg = htobe16(reg);
header.qty = htobe16(qty);
header.bytes = data.size(); // 8 bit value
// const uint8_t headerBytes(sizeof(req_multi_t)); // sizeof not working because of memory padding
const uint8_t headerBytes(7);
const uint8_t dataBytes(data.size());
const uint8_t crcBytes(sizeof(crc_t));
// compute crc for header + data
m_crc.restart();
m_crc.add((uint8_t *)&header, headerBytes); // add the request excluding the CRC code
m_crc.add((uint8_t *)data.data(), dataBytes);
const uint16_t crc(htole16(m_crc.calc()));
std::vector<uint8_t> dataOut;
dataOut.resize(headerBytes + dataBytes + crcBytes); // header message + data values + crc code
std::memcpy(dataOut.data(), &header, headerBytes); // copy message
std::memcpy(dataOut.data() + headerBytes, data.data(), dataBytes); // copy data
std::memcpy(dataOut.data() + headerBytes + dataBytes, &crc, crcBytes); // copy crc
#ifdef DEBUGLOG_DEFAULT_LOG_LEVEL_TRACE
printBytes("multiRequest", dataOut);
#endif
return dataOut;
}
const bool MODBUS::verifyCrc(const std::vector<uint8_t> &data)
{
// compute crc of current message
m_crc.restart();
m_crc.add(data.data(), data.size() - sizeof(crc_t));
const uint16_t computedCrc(m_crc.calc());
// extract crc from response
const uint16_t size(data.size());
const uint8_t crcLo(data.at(size - 2));
const uint8_t crcHi(data.at(size - 1));
const uint16_t receivedCrc(0xFFFF & ((crcHi << 8) | crcLo));
// verify crc code
if (highByte(computedCrc) != crcHi || lowByte(computedCrc) != crcLo)
{
LOG_ERROR("Failed verify CRC code: comp[", printHex(computedCrc).c_str(), "], rec[", printHex(receivedCrc).c_str(), "]");
return false;
}
return true;
}
}
#undef BUS_DELAY

106
lib/RS485/RS485_Driver.h Normal file
View File

@@ -0,0 +1,106 @@
#pragma once
#define DEBUGLOG_DEFAULT_LOG_LEVEL_INFO
#include <DebugLog.h>
#include <Arduino.h>
#include <HardwareSerial.h> // Reference the ESP32 built-in serial port library
#include <CRC16.h>
#include <memory>
#include <mutex>
namespace drivers
{
class RS485
{
const uint8_t c_port = 1;
public:
RS485(const uint32_t baud, const SerialConfig conf);
RS485(const RS485 &) = delete; // remove copy constructors
RS485 &operator=(const RS485 &) = delete;
const bool write(const std::vector<uint8_t> data);
const bool readAll(std::vector<uint8_t> &data);
const bool readN(const uint16_t nBytes, std::vector<uint8_t> &data);
const bool readUntil(const uint8_t ch, std::vector<uint8_t> &data);
private:
HardwareSerial &m_serial;
};
class MODBUS : private RS485
{
const uint8_t c_respHeaderSize = 3;
const uint8_t c_respCrcSize = 2;
const uint32_t c_minDelay = 250;
typedef struct
{
uint8_t device;
uint8_t func;
uint16_t reg;
uint16_t data;
} req_t;
typedef struct
{
uint8_t device;
uint8_t func;
uint16_t reg;
uint16_t qty;
uint8_t bytes;
} req_multi_t;
typedef req_t resp_t;
typedef uint16_t crc_t;
public:
MODBUS(const uint32_t baud, const SerialConfig conf);
MODBUS(const MODBUS &) = delete; // remove copy constructors
MODBUS &operator=(const MODBUS &) = delete;
// Get transaction lock
std::unique_lock<std::mutex> getLock();
std::mutex &getMutex();
// Func 0x01
const bool readCoils(const uint8_t device, const uint16_t reg, const uint16_t num, std::vector<bool> &coils);
// Func 0x02
const bool readInputs(const uint8_t device, const uint16_t reg, const uint8_t num, std::vector<bool> &inputs);
// Func 0x03
const bool readHoldingRegisters(const uint8_t device, const uint16_t reg, const uint8_t num, std::vector<uint16_t> &values);
// Func 0x04
const bool readInputRegisters(const uint8_t device, const uint16_t reg, const uint8_t num, std::vector<uint16_t> &values);
// Func 0x05
const bool writeCoil(const uint8_t device, const uint16_t coil, const bool value);
// Func 0x06
const bool writeRegister(const uint8_t device, const uint16_t reg, const uint16_t value);
// Func 0x0F
const bool writeCoils(const uint8_t device, const uint16_t coils, const std::vector<bool> &values);
// Func 0x10
const bool writeRegisters(const uint8_t device, const uint16_t reg, const std::vector<uint16_t> &values);
private:
CRC16 m_crc;
std::mutex m_mutex;
uint8_t m_lastDevice;
uint32_t m_lastAccess;
void delayAccess(const uint8_t device);
const std::vector<uint8_t> singleRequest(const uint8_t device, const uint8_t func, const uint16_t reg, const uint16_t data);
const std::vector<uint8_t> multiRequest(const uint8_t device, const uint8_t func, const uint16_t reg, const uint16_t qty, const std::vector<uint8_t> &data);
const bool readBinary(const uint8_t device, const uint8_t func, const uint16_t reg, const uint16_t bits, std::vector<bool> &out);
const bool readInteger(const uint8_t device, const uint8_t func, const uint16_t reg, const uint16_t num, std::vector<uint16_t> &out);
const bool writeBinary(const uint8_t device, const uint8_t func, const uint16_t reg, const std::vector<bool> &in);
const bool writeInteger(const uint8_t device, const uint8_t func, const uint16_t reg, const std::vector<uint16_t> &in, const bool multi);
const bool verifyCrc(const std::vector<uint8_t> &data);
};
}

37
lib/RS485/busdelay.h Normal file
View 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;
};
}

234
lib/RTC/PCF85063_Driver.cpp Normal file
View File

@@ -0,0 +1,234 @@
#include "PCF85063_Driver.h"
#include <ctime>
#include <utils.h>
namespace drivers
{
PCF85063::PCF85063(I2C &i2c, const uint8_t address, const uint8_t ctrl1, const uint8_t ctrl2) : m_i2c(i2c), m_address(address)
{
bool success(true);
if (ctrl1 == RTC_CTRL_1_DEFAULT)
{
const uint8_t def_conf1 = RTC_CTRL_1_DEFAULT | RTC_CTRL_1_CAP_SEL; // 12.5pF cap and 24h format
success &= m_i2c.write(m_address, RTC_CTRL_1_ADDR, {def_conf1});
}
if (ctrl2 == RTC_CTRL_2_DEFAULT)
{
const uint8_t def_conf2 = RTC_CTRL_2_DEFAULT | RTC_CTRL_2_MI; // enable 1 minute interrupt
success &= m_i2c.write(m_address, RTC_CTRL_2_ADDR, {def_conf2});
}
if (!success)
LOG_ERROR("RTC Init Failure");
}
const bool PCF85063::reset(void)
{
LOG_INFO("RTC Reset Initiated");
const uint8_t cfg = RTC_CTRL_1_DEFAULT | RTC_CTRL_1_CAP_SEL | RTC_CTRL_1_SR;
if (m_i2c.write(m_address, RTC_CTRL_1_ADDR, {cfg}))
return true;
LOG_ERROR("RTC Reset Failure");
return false;
}
const bool PCF85063::setTime(const datetime_t time)
{
const std::vector<uint8_t> buf = {
decToBcd(time.second),
decToBcd(time.minute),
decToBcd(time.hour)};
if (m_i2c.write(m_address, RTC_SECOND_ADDR, buf))
return true;
LOG_ERROR("RTC setTime failure");
return false;
}
const bool PCF85063::setDate(const datetime_t date)
{
const std::vector<uint8_t> buf = {
decToBcd(date.day),
decToBcd(date.dotw),
decToBcd(date.month),
decToBcd(date.year - YEAR_OFFSET)};
if (m_i2c.write(m_address, RTC_DAY_ADDR, buf))
return true;
LOG_ERROR("RTC setDate failure");
return false;
}
const bool PCF85063::setDatetime(const datetime_t datetime)
{
return setDate(datetime) && setTime(datetime);
}
const bool PCF85063::readDate(datetime_t &datetime)
{
std::vector<uint8_t> buf;
if (m_i2c.read(m_address, RTC_DAY_ADDR, 4, buf))
{
datetime.day = bcdToDec(buf[0] & 0x3F);
datetime.dotw = bcdToDec(buf[1] & 0x07);
datetime.month = bcdToDec(buf[2] & 0x1F);
datetime.year = bcdToDec(buf[3]) + YEAR_OFFSET;
return true;
}
LOG_ERROR("RTC readDate Failure");
return false;
}
const bool PCF85063::readTime(datetime_t &datetime)
{
std::vector<uint8_t> buf;
if (m_i2c.read(m_address, RTC_SECOND_ADDR, 3, buf))
{
datetime.second = bcdToDec(buf[0] & 0x7F);
datetime.minute = bcdToDec(buf[1] & 0x7F);
datetime.hour = bcdToDec(buf[2] & 0x3F);
return true;
}
LOG_ERROR("RTC readTime Failure");
return false;
}
const bool PCF85063::readDatetime(datetime_t &datetime)
{
return readTime(datetime) && readDate(datetime);
}
const bool PCF85063::enableAlarm(const bool enable)
{
bool success(true);
std::vector<uint8_t> currStatus(1, RTC_CTRL_2_DEFAULT);
success &= m_i2c.read(m_address, RTC_CTRL_2_ADDR, 1, currStatus);
currStatus.at(0) &= ~RTC_CTRL_2_AF; // clear alarm flag
if (enable)
currStatus.at(0) |= RTC_CTRL_2_AIE; // enable alarm
else
currStatus.at(0) &= ~RTC_CTRL_2_AIE; // disable alarm
if (m_i2c.write(m_address, RTC_CTRL_2_ADDR, currStatus))
return true;
LOG_ERROR("RTC enableAlarm failure");
return false;
}
const bool PCF85063::setAlarm(datetime_t time)
{
const std::vector<uint8_t> buf = {
(uint8_t)(decToBcd(time.second) & (~RTC_ALARM)),
(uint8_t)(decToBcd(time.minute) & (~RTC_ALARM)),
(uint8_t)(decToBcd(time.hour) & (~RTC_ALARM)),
(uint8_t)(RTC_ALARM), // disalbe day
(uint8_t)(RTC_ALARM) // disalbe weekday
};
if (m_i2c.write(m_address, RTC_SECOND_ALARM, buf))
return true;
LOG_ERROR("RTC setAlarm failure");
return false;
}
const bool PCF85063::readAlarm(datetime_t &time)
{
std::vector<uint8_t> buf;
if (m_i2c.read(m_address, RTC_SECOND_ALARM, 5, buf))
{
time.second = (uint8_t)bcdToDec(buf[0] & 0x7F);
time.minute = (uint8_t)bcdToDec(buf[1] & 0x7F);
time.hour = (uint8_t)bcdToDec(buf[2] & 0x3F);
time.day = (uint8_t)bcdToDec(buf[3] & 0x3F);
time.dotw = (uint8_t)bcdToDec(buf[4] & 0x07);
return true;
}
LOG_ERROR("RTC readAlarm failure");
return false;
}
const bool PCF85063::getAlarmFlag(uint8_t &flags)
{
std::vector<uint8_t> buf;
if (m_i2c.read(m_address, RTC_CTRL_2_ADDR, 1, buf))
{
flags = buf.at(0);
return true;
}
LOG_ERROR("RTC readAlarmFlags failure");
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;
readDatetime(dt);
return datetime2str(dt);
}
const PCF85063::datetime_t PCF85063::fromEpoch(const time_t currentTime)
{
PCF85063::datetime_t tm;
struct tm *localTime = std::localtime(&currentTime);
tm.year = localTime->tm_year + 1900;
tm.month = localTime->tm_mon + 1;
tm.day = localTime->tm_mday;
tm.dotw = localTime->tm_wday;
tm.hour = localTime->tm_hour;
tm.minute = localTime->tm_min;
tm.second = localTime->tm_sec;
return tm;
}
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;
dtime.tm_min = datetime.minute;
dtime.tm_hour = datetime.hour;
dtime.tm_wday = datetime.dotw;
dtime.tm_mday = datetime.day;
dtime.tm_mon = datetime.month - 1;
dtime.tm_year = datetime.year - 1900; // time offset in structure according cpp reference
return dtime;
}
const uint8_t PCF85063::decToBcd(const int val)
{
return (uint8_t)((val / 10 * 16) + (val % 10));
}
const int PCF85063::bcdToDec(uint8_t val)
{
return (const int)((val / 16 * 10) + (val % 16));
}
}

122
lib/RTC/PCF85063_Driver.h Normal file
View File

@@ -0,0 +1,122 @@
#pragma once
#define DEBUGLOG_DEFAULT_LOG_LEVEL_INFO
#include <DebugLog.h>
#include "I2C_Driver.h"
#include <string>
#include <time.h>
// PCF85063_ADDRESS
#define PCF85063_ADDRESS (0x51)
#define YEAR_OFFSET (1970)
// registar overview - crtl & status reg
#define RTC_CTRL_1_ADDR (0x00)
#define RTC_CTRL_2_ADDR (0x01)
#define RTC_OFFSET_ADDR (0x02)
#define RTC_RAM_by_ADDR (0x03)
// registar overview - time & data reg
#define RTC_SECOND_ADDR (0x04)
#define RTC_MINUTE_ADDR (0x05)
#define RTC_HOUR_ADDR (0x06)
#define RTC_DAY_ADDR (0x07)
#define RTC_WDAY_ADDR (0x08)
#define RTC_MONTH_ADDR (0x09)
#define RTC_YEAR_ADDR (0x0A) // years 0-99; calculate real year = 1970 + RCC reg year
// registar overview - alarm reg
#define RTC_SECOND_ALARM (0x0B)
#define RTC_MINUTE_ALARM (0x0C)
#define RTC_HOUR_ALARM (0x0D)
#define RTC_DAY_ALARM (0x0E)
#define RTC_WDAY_ALARM (0x0F)
// registar overview - timer reg
#define RTC_TIMER_VAL (0x10)
#define RTC_TIMER_MODE (0x11)
// RTC_CTRL_1 registar
#define RTC_CTRL_1_EXT_TEST (0x80)
#define RTC_CTRL_1_STOP (0x20) // 0-RTC clock runs 1- RTC clock is stopped
#define RTC_CTRL_1_SR (0X10) // 0-no software reset 1-initiate software rese
#define RTC_CTRL_1_CIE (0X04) // 0-no correction interrupt generated 1-interrupt pulses are generated at every correction cycle
#define RTC_CTRL_1_12_24 (0X02) // 0-24H 1-12H
#define RTC_CTRL_1_CAP_SEL (0X01) // 0-7PF 1-12.5PF
// RTC_CTRL_2 registar
#define RTC_CTRL_2_AIE (0X80) // alarm interrupt 0-disalbe 1-enable
#define RTC_CTRL_2_AF (0X40) // alarm flag 0-inactive/cleared 1-active/unchanged
#define RTC_CTRL_2_MI (0X20) // minute interrupt 0-disalbe 1-enable
#define RTC_CTRL_2_HMI (0X10) // half minute interrupt
#define RTC_CTRL_2_TF (0X08)
//
#define RTC_OFFSET_MODE (0X80)
//
#define RTC_TIMER_MODE_TE (0X04) // timer enable 0-disalbe 1-enable
#define RTC_TIMER_MODE_TIE (0X02) // timer interrupt enable 0-disalbe 1-enable
#define RTC_TIMER_MODE_TI_TP (0X01) // timer interrupt mode 0-interrupt follows timer flag 1-interrupt generates a pulse
// format
#define RTC_ALARM (0x80) // set AEN_x registers
#define RTC_CTRL_1_DEFAULT (0x00)
#define RTC_CTRL_2_DEFAULT (0x00)
#define RTC_TIMER_FLAG (0x08)
namespace drivers
{
class PCF85063
{
public:
typedef struct
{
uint16_t year;
uint8_t month;
uint8_t day;
uint8_t dotw;
uint8_t hour;
uint8_t minute;
uint8_t second;
} datetime_t;
public:
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);
const bool setTime(const datetime_t time);
const bool setDate(const datetime_t date);
const bool setDatetime(const datetime_t datetime);
const bool readDate(datetime_t &datetime);
const bool readTime(datetime_t &datetime);
const bool readDatetime(datetime_t &datetime);
const bool enableAlarm(const bool enable);
const bool setAlarm(const datetime_t time);
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;
};
}

View File

@@ -0,0 +1,145 @@
#include <S50140_Driver.h>
#include <busdelay.h>
#define BUS_DELAY drivers::BusDelay(m_lastRequest, c_minDelay, "S50140")
namespace drivers
{
S50140::S50140(drivers::MODBUS &bus, const uint8_t address) : m_bus(bus), m_address(address), m_lastRequest(millis())
{
}
S50140::~S50140()
{
}
const S50140::powerinfo_t S50140::getAll()
{
powerinfo_t info{MAXFLOAT};
std::lock_guard<std::mutex> lock(m_bus.getMutex());
info.v = getV();
info.a = getA();
info.pAct = getPact();
info.pApp = getPapp();
info.pRea = getPrea();
info.pf = getPf();
info.f = getF();
info.whTot = getWhTot();
info.whPar = getWhPar();
return info;
}
const float_t S50140::getV()
{
return readFloatReg(REG_V);
}
const float_t S50140::getA()
{
return readFloatReg(REG_A);
}
const float_t S50140::getPact()
{
return readFloatReg(REG_Pact);
}
const float_t S50140::getPapp()
{
return readFloatReg(REG_Papp);
}
const float_t S50140::getPrea()
{
return readFloatReg(REG_Prea);
}
const float_t S50140::getPf()
{
return readFloatReg(REG_Pf);
}
const float_t S50140::getF()
{
return readFloatReg(REG_Freq);
}
const float_t S50140::getWhTot()
{
return readFloatReg(REG_WhTot);
}
const float_t S50140::getWhPar()
{
return readFloatReg(REG_WhPart);
}
const uint8_t S50140::getRegset()
{
std::vector<uint16_t> value;
std::lock_guard<std::mutex> lock(m_bus.getMutex());
BUS_DELAY;
m_bus.readHoldingRegisters(m_address, REG_Regset, 2, value);
if (value.empty())
return UINT8_MAX;
return value.front() + value.back();
}
const uint16_t S50140::getCounterStatus()
{
std::vector<uint16_t> value;
std::lock_guard<std::mutex> lock(m_bus.getMutex());
BUS_DELAY;
m_bus.readHoldingRegisters(m_address, REG_PartCount, 2, value);
if (value.empty())
return UINT16_MAX;
return value.front() + value.back();
}
void S50140::resetPartialCounters()
{
uint8_t retries(0);
constexpr uint16_t nullVal = 0x0000;
constexpr uint16_t resetAll = 0x0A03;
constexpr uint16_t stopAll = 0x0A02;
constexpr uint16_t startAll = 0x0A01;
std::lock_guard<std::mutex> lock(m_bus.getMutex());
while (retries++ < c_maxRetries)
{
bool ok(true);
{
LOG_WARN("Powermeter Counter STOP");
BUS_DELAY;
ok &= m_bus.writeRegisters(m_address, REG_PartCount, {nullVal, stopAll});
};
{
LOG_WARN("Powermeter Counter RESET");
BUS_DELAY;
ok &= m_bus.writeRegisters(m_address, REG_PartCount, {nullVal, resetAll});
};
{
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", printHex(m_address).c_str());
}
return;
}
float_t S50140::readFloatReg(const uint16_t reg)
{
uint8_t retries(0);
std::vector<uint16_t> values;
while (retries++ < c_maxRetries)
{
BUS_DELAY;
if (m_bus.readHoldingRegisters(m_address, reg, c_dataWords, values) && values.size() == c_dataWords)
{
floatval_t fv; // potrebbe essere il contrario, vedremo
fv.words.lo = values[0]; // magari va invertita ancora l'endianness
fv.words.hi = values[1];
return fv.f;
}
LOG_ERROR("Unable to Read Powermeter values, device", printHex(m_address).c_str());
}
return MAXFLOAT;
}
}
#undef BUS_DELAY

View File

@@ -0,0 +1,85 @@
#pragma once
#define DEBUGLOG_DEFAULT_LOG_LEVEL_INFO
#include <DebugLog.h>
#include <RS485_Driver.h>
#include <utils.h>
namespace drivers
{
class S50140
{
private:
const uint8_t c_maxRetries = 5;
const uint8_t c_dataWords = 2;
const uint32_t c_minDelay = 100;
const uint16_t REG_V = 0x100C;
const uint16_t REG_A = 0x1016;
const uint16_t REG_Pact = 0x1026;
const uint16_t REG_Papp = 0x102E;
const uint16_t REG_Prea = 0x1036;
const uint16_t REG_Freq = 0x1038;
const uint16_t REG_Pf = 0x101E;
const uint16_t REG_WhTot = 0x1106;
const uint16_t REG_WhPart = 0x1400;
const uint16_t REG_Serial = 0x0500;
const uint16_t REG_Regset = 0x0538;
const uint16_t REG_PartCount = 0x0526;
typedef union
{
float_t f;
struct
{
uint16_t hi;
uint16_t lo;
} words;
} floatval_t;
public:
typedef struct
{
float_t v;
float_t a;
float_t pAct;
float_t pApp;
float_t pRea;
float_t pf;
float_t f;
float_t whTot;
float_t whPar;
} powerinfo_t;
public:
S50140(drivers::MODBUS &bus, const uint8_t address);
~S50140();
const powerinfo_t getAll();
const float_t getV();
const float_t getA();
const float_t getPact();
const float_t getPapp();
const float_t getPrea();
const float_t getPf();
const float_t getF();
const float_t getWhTot();
const float_t getWhPar();
const uint8_t getRegset();
const uint16_t getCounterStatus();
void resetPartialCounters();
private:
float_t readFloatReg(const uint16_t reg);
private:
const uint8_t m_address;
drivers::MODBUS &m_bus;
uint32_t m_lastRequest;
};
}

142
lib/TEMP/R4DCB08_Driver.cpp Normal file
View File

@@ -0,0 +1,142 @@
#include <R4DCB08_Driver.h>
#include <busdelay.h>
#define BUS_DELAY drivers::BusDelay(m_lastRequest, c_minDelay, "R4DCB08")
namespace drivers
{
R4DCB08::R4DCB08(drivers::MODBUS &bus, const uint8_t address) : m_address(address), m_bus(bus), m_sensors(0)
{
m_sensors = getNum();
m_lastRequest = millis();
}
R4DCB08::~R4DCB08()
{
}
const float R4DCB08::getTemp(const uint8_t ch)
{
uint8_t retries(0);
std::vector<uint16_t> rawT;
if (ch < 0 || ch > getNum())
{
LOG_ERROR("Invalid Temperature Channel number", ch);
return MAXFLOAT;
}
std::lock_guard<std::mutex> lock(m_bus.getMutex());
while (retries++ < c_maxRetries)
{
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", printHex(m_address).c_str(), "channel", ch);
rawT.clear();
}
return MAXFLOAT;
}
const std::vector<float> R4DCB08::getTempAll()
{
uint8_t retries(0);
std::vector<uint16_t> rawT;
std::vector<float> out;
std::lock_guard<std::mutex> lock(m_bus.getMutex());
while (retries++ < c_maxRetries)
{
BUS_DELAY;
if (m_bus.readHoldingRegisters(m_address, REG_TEMP, getNum(), rawT) && !rawT.empty())
{
out.reserve(rawT.size());
for (auto v : rawT)
{
out.push_back(v / 10.0f);
}
return out;
}
LOG_ERROR("Failed to Read All Temperature, device", printHex(m_address).c_str());
rawT.clear();
}
out.clear();
return out;
}
void R4DCB08::setCorrection(std::vector<float> corr)
{
uint8_t retries(0);
uint8_t channel(0);
corr.resize(getNum()); // max number of temperature correction values is equal to number of sensors
std::lock_guard<std::mutex> lock(m_bus.getMutex());
for (auto v : corr)
{
while (retries++ < c_maxRetries)
{
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", printHex(m_address).c_str());
}
}
}
std::vector<float> R4DCB08::getCorrection()
{
uint8_t retries(0);
std::vector<uint16_t> rawV;
std::vector<float> out;
rawV.reserve(getNum());
std::lock_guard<std::mutex> lock(m_bus.getMutex());
while (retries++ < c_maxRetries)
{
BUS_DELAY;
if (m_bus.readHoldingRegisters(m_address, REG_TEMPCORR, getNum(), rawV))
{
out.reserve(rawV.size());
for (auto v : rawV)
{
out.push_back(v / 10.0f);
}
return out;
}
LOG_ERROR("Failed to Get Temperature Correction, device", printHex(m_address).c_str());
rawV.clear();
}
out.clear();
return out;
}
const uint8_t R4DCB08::getNum()
{
if (m_sensors)
return m_sensors;
uint8_t retries(0);
uint8_t sensors(0);
std::vector<uint16_t> rawT;
std::lock_guard<std::mutex> lock(m_bus.getMutex());
while (retries++ < c_maxRetries)
{
BUS_DELAY;
if (m_bus.readHoldingRegisters(m_address, REG_TEMP, T_MAX, rawT))
{
for (auto v : rawT)
{
if (v <= INT16_MAX)
sensors++; // 32768 is returned if sensor is disconnected
}
m_sensors = sensors;
return m_sensors;
}
LOG_ERROR("Failed to Get Sensor Number, device", printHex(m_address).c_str());
}
LOG_ERROR("No Temperature Sensors Detected, device", printHex(m_address).c_str());
return 0;
}
}
#undef BUS_DELAY

56
lib/TEMP/R4DCB08_Driver.h Normal file
View File

@@ -0,0 +1,56 @@
#pragma once
#define DEBUGLOG_DEFAULT_LOG_LEVEL_INFO
#include <DebugLog.h>
#include <RS485_Driver.h>
#include <utils.h>
namespace drivers
{
class R4DCB08
{
public:
enum tempCh
{
T1,
T2,
T3,
T4,
T5,
T6,
T7,
T8,
T_MAX
};
private:
const uint8_t c_maxRetries = 5;
const uint32_t c_minDelay = 500;
const uint16_t REG_TEMP = 0x0000;
const uint16_t REG_TEMPCORR = 0x0008;
public:
R4DCB08(drivers::MODBUS &bus, const uint8_t address);
~R4DCB08();
const float getTemp(const uint8_t ch);
const std::vector<float> getTempAll();
void setCorrection(std::vector<float> corr);
std::vector<float> getCorrection();
const uint8_t getNum();
private:
void delayRequest();
private:
const uint8_t m_address;
uint8_t m_sensors;
MODBUS &m_bus;
uint32_t m_lastRequest;
};
}

63
lib/utils/utils.cpp Normal file
View File

@@ -0,0 +1,63 @@
#include "utils.h"
void printBytes(const char title[], const std::vector<uint8_t> &b)
{
Serial0.flush();
printf("%s: ", title);
for (auto v : b)
{
printf("0x%02x ", v);
}
printf("\n");
Serial0.flush();
}
void printBytes(const char title[], const std::vector<uint16_t> &b)
{
Serial0.flush();
printf("%s: ", title);
for (auto v : b)
{
printf("0x%04x ", v);
}
printf("\n");
Serial0.flush();
}
void printBool(const char title[], const std::vector<bool> &vals)
{
Serial0.flush();
printf("%s: ", title);
for (auto j(0); j < vals.size(); j++)
{
printf("%s ", vals.at(j) ? "True" : "False");
}
printf("\n");
Serial0.flush();
}
const std::string printBoolVec(const std::vector<bool> &vals)
{
std::string buf;
buf.reserve(vals.size() + 1);
buf.append("b");
for (const auto v : vals)
{
buf.append(v ? "1" : "0");
}
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;
}

22
lib/utils/utils.h Normal file
View File

@@ -0,0 +1,22 @@
#pragma once
#define DEBUGLOG_DEFAULT_LOG_LEVEL_INFO
#include <Arduino.h>
#include <DebugLog.h>
#include <string>
#include <vector>
///////////// UTIL Functions /////////////////
void printBytes(const char title[], const std::vector<uint8_t> &b);
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);

View File

@@ -16,3 +16,33 @@ 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
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 = ${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
-g3
-ggdb
-fno-inline
-fno-ipa-sra
-fno-tree-sra
-fno-builtin

View File

@@ -1,36 +0,0 @@
#include "I2C_Driver.h"
void I2C_Init(void) {
Wire.begin( I2C_SDA_PIN, I2C_SCL_PIN);
}
bool I2C_Read(uint8_t Driver_addr, uint8_t Reg_addr, uint8_t *Reg_data, uint32_t Length)
{
Wire.beginTransmission(Driver_addr);
Wire.write(Reg_addr);
if ( Wire.endTransmission(true)){
printf("The I2C transmission fails. - I2C Read\r\n");
return -1;
}
Wire.requestFrom(Driver_addr, Length);
for (int i = 0; i < Length; i++) {
*Reg_data++ = Wire.read();
}
return 0;
}
bool I2C_Write(uint8_t Driver_addr, uint8_t Reg_addr, const uint8_t *Reg_data, uint32_t Length)
{
Wire.beginTransmission(Driver_addr);
Wire.write(Reg_addr);
for (int i = 0; i < Length; i++) {
Wire.write(*Reg_data++);
}
if ( Wire.endTransmission(true))
{
printf("The I2C transmission fails. - I2C Write\r\n");
return -1;
}
return 0;
}

View File

@@ -1,10 +0,0 @@
#pragma once
#include <Wire.h>
#define I2C_SCL_PIN 41
#define I2C_SDA_PIN 42
void I2C_Init(void);
bool I2C_Read(uint8_t Driver_addr, uint8_t Reg_addr, uint8_t *Reg_data, uint32_t Length);
bool I2C_Write(uint8_t Driver_addr, uint8_t Reg_addr, const uint8_t *Reg_data, uint32_t Length);

View File

@@ -1,37 +0,0 @@
#include <Arduino.h>
#include <HardwareSerial.h> // Reference the ESP32 built-in serial port library
#include "WS_MQTT.h"
#include "WS_Bluetooth.h"
#include "WS_GPIO.h"
#include "WS_Serial.h"
#include "WS_RTC.h"
#include "WS_GPIO.h"
#include "WS_DIN.h"
#include "WS_SD.h"
#include "WS_ETH.h"
uint32_t Simulated_time=0; // Analog time counting
/******************************************************** Initializing ********************************************************/
void setup() {
Flash_test();
GPIO_Init(); // RGB . Buzzer GPIO
I2C_Init();
RTC_Init();// RTC
SD_Init();
Serial_Init(); // UART(RS485/CAN)
MQTT_Init();// MQTT
Bluetooth_Init();// Bluetooth
ETH_Init();
DIN_Init(); // If you don't want to control the relay through DIN, change Relay_Immediate_Default to 0 in WS_DIN.h and re-burn the program
Relay_Init();
printf("Connect to the WIFI network named \"ESP32-S3-POE-ETH-8DI-8RO\" and access the Internet using the connected IP address!!!\r\n");
}
/********************************************************** While **********************************************************/
void loop() {
}

View File

@@ -1,152 +0,0 @@
#include "WS_Bluetooth.h"
BLEServer* pServer; // Used to represent a BLE server
BLECharacteristic* pTxCharacteristic;
BLECharacteristic* pRxCharacteristic;
/********************************************************** Bluetooth *********************************************************/
class MyServerCallbacks : public BLEServerCallbacks { //By overriding the onConnect() and onDisconnect() functions
void onConnect(BLEServer* pServer) { // When the Device is connected, "Device connected" is printed.
Serial.println("Device connected");
}
void onDisconnect(BLEServer* pServer) { // "Device disconnected" will be printed when the device is disconnected
Serial.println("Device disconnected");
BLEAdvertising *pAdvertising = BLEDevice::getAdvertising(); // Re-broadcast so that the device can query
pAdvertising->addServiceUUID(SERVICE_UUID); // Re-broadcast so that the device can query
pAdvertising->setScanResponse(true); // Re-broadcast so that the device can query
pAdvertising->setMinPreferred(0x06); // Re-broadcast so that the device can query
pAdvertising->setMinPreferred(0x12); // Re-broadcast so that the device can query
BLEDevice::startAdvertising(); // Re-broadcast so that the device can query
pRxCharacteristic->notify(); // Re-broadcast so that the device can query
pAdvertising->start(); // Re-broadcast so that the device can query
}
};
class MyRXCallback : public BLECharacteristicCallbacks {
void onWrite(BLECharacteristic* pCharacteristic) { // The onWrite function is called when the remote device sends data to your feature
String rxValue = String(pCharacteristic->getValue().c_str());
if (!rxValue.isEmpty()) {
// The received data rxValue is processed here
if(rxValue.length() == 1)
{
printf("%s\n", rxValue.c_str()); // Print output through the serial port
uint8_t* valueBytes = reinterpret_cast<uint8_t*>(const_cast<char*>(rxValue.c_str())); // Convert value to uint8 t*
Relay_Analysis(valueBytes,Bluetooth_Mode); // pilot relay
}
else if(rxValue.length() == 2)
{
if(Extension_Enable)
{
printf("%s\n", rxValue.c_str()); // Print output through the serial port
uint8_t* valueBytes = reinterpret_cast<uint8_t*>(const_cast<char*>(rxValue.c_str())); // Convert value to uint8 t*
if(valueBytes[0] == 0x06) // Instruction check correct
RS485_Analysis(valueBytes); // Control external relay
else
printf("Note : Non-instruction data was received - Bluetooth !\r\n");
}
else
printf("Note : Non-instruction data was received or external relays are not enabled - Bluetooth !\r\n");
}
else if(rxValue.length() == 14)
{
if(RTC_Event_Enable)
{
// printf("%s\n", rxValue.c_str()); // Print output through the serial port
uint8_t* valueBytes = reinterpret_cast<uint8_t*>(const_cast<char*>(rxValue.c_str()));
BLE_Set_RTC_Event(valueBytes);
}
else
printf("Note : Non-instruction data was received or RTC events were not enabled - Bluetooth !\r\n");
}
else
{
printf("Note : Non-instruction data was received - Bluetooth !\r\n");
}
pRxCharacteristic->setValue(""); // After data is read, set it to blank for next read
}
}
};
void BLE_Set_RTC_Event(uint8_t* valueBytes){
if(valueBytes[0] == 0xA1 && valueBytes[6] == 0xAA && valueBytes[13] == 0xFF ){
datetime_t Event_Time={0};
Event_Time.year = (valueBytes[1]/16*10 + valueBytes[1] % 16) *100 + valueBytes[2]/16*10 + valueBytes[2] % 16;
Event_Time.month = valueBytes[3]/16*10 + valueBytes[3] % 16;
Event_Time.day = valueBytes[4]/16*10 + valueBytes[4] % 16;
Event_Time.dotw = valueBytes[5]/16*10 + valueBytes[5] % 16;
// valueBytes[6] == 0xAA; // check
Event_Time.hour = valueBytes[7]/16*10 + valueBytes[7] % 16;
Event_Time.minute = valueBytes[8]/16*10 + valueBytes[8] % 16;
Event_Time.second = valueBytes[9]/16*10 + valueBytes[9] % 16;
Repetition_event Repetition = (Repetition_event)valueBytes[12]; // cyclical indicators
if(valueBytes[11]){ // Whether to control all relays 1:Control all relays 0Control a relay
uint8_t CHxs = valueBytes[10]; // relay control
TimerEvent_CHxs_Set(Event_Time, CHxs, Repetition);
}
else{
uint8_t CHx = valueBytes[10]/16;
bool State = (valueBytes[10] % 16);
TimerEvent_CHx_Set(Event_Time,CHx, State, Repetition);
}
}
}
void Bluetooth_SendData(char* Data) { // Send data using Bluetooth
if (Data != nullptr && strlen(Data) > 0) {
if (pServer->getConnectedCount() > 0) {
String SendValue = String(Data); // Convert char* to String
pTxCharacteristic->setValue(SendValue.c_str()); // Set SendValue to the eigenvalue (String type)
pTxCharacteristic->notify(); // Sends a notification to all connected devices
}
}
}
void Bluetooth_Init()
{
/*************************************************************************
Bluetooth
*************************************************************************/
BLEDevice::init("ESP32-S3-POE-ETH-8DI-8RO"); // Initialize Bluetooth and start broadcasting
pServer = BLEDevice::createServer();
pServer->setCallbacks(new MyServerCallbacks());
BLEService* pService = pServer->createService(SERVICE_UUID);
pTxCharacteristic = pService->createCharacteristic(
TX_CHARACTERISTIC_UUID,
BLECharacteristic:: PROPERTY_READ); // The eigenvalues are readable and can be read by remote devices
pRxCharacteristic = pService->createCharacteristic(
RX_CHARACTERISTIC_UUID,
BLECharacteristic::PROPERTY_WRITE); // The eigenvalues are writable and can be written to by remote devices
pRxCharacteristic->setCallbacks(new MyRXCallback());
pRxCharacteristic->setValue("Successfully Connect To ESP32-S3-POE-ETH-8DI-8RO");
pService->start();
BLEAdvertising *pAdvertising = BLEDevice::getAdvertising();
pAdvertising->addServiceUUID(SERVICE_UUID);
pAdvertising->setScanResponse(true);
pAdvertising->setMinPreferred(0x06);
pAdvertising->setMinPreferred(0x12);
BLEDevice::startAdvertising();
pRxCharacteristic->notify();
pAdvertising->start();
RGB_Open_Time(0, 0, 60,1000, 0);
printf("Now you can read it in your phone!\r\n");
xTaskCreatePinnedToCore(
BLETask,
"BLETask",
4096,
NULL,
2,
NULL,
0
);
}
void BLETask(void *parameter) {
while(1){
Bluetooth_SendData(ipStr);
vTaskDelay(pdMS_TO_TICKS(100));
}
vTaskDelete(NULL);
}

View File

@@ -1,24 +0,0 @@
#pragma once
#include <HardwareSerial.h> // Reference the ESP32 built-in serial port library
#include <BLEDevice.h>
#include <BLEUtils.h>
#include <BLEServer.h>
#include "WS_GPIO.h"
#include "WS_Serial.h"
#include "WS_Information.h"
#include "WS_Relay.h"
#include "WS_MQTT.h"
#include "WS_RTC.h"
#define SERVICE_UUID "4fafc201-1fb5-459e-8fcc-c5c9c331914b" // UUID of the server
#define RX_CHARACTERISTIC_UUID "beb5483e-36e1-4688-b7f5-ea07361b26a8" // UUID of the characteristic Tx
#define TX_CHARACTERISTIC_UUID "beb5484a-36e1-4688-b7f5-ea07361b26a8" // UUID of the characteristic Rx
#define Bluetooth_Mode 2
void Bluetooth_SendData(char * Data);
void Bluetooth_Init();
void BLETask(void *parameter);
void BLE_Set_RTC_Event(uint8_t* valueBytes);

View File

@@ -1,219 +0,0 @@
#include "WS_CAN.h"
static bool driver_installed = false;
void CAN_Init(void)
{ // Initializing serial port
// Initialize configuration structures using macro initializers
twai_general_config_t g_config = TWAI_GENERAL_CONFIG_DEFAULT((gpio_num_t)TXD1, (gpio_num_t)RXD1, TWAI_MODE_NORMAL);
twai_timing_config_t t_config = TWAI_TIMING_CONFIG_250KBITS(); //Look in the api-reference for other speed sets.
twai_filter_config_t f_config = TWAI_FILTER_CONFIG_ACCEPT_ALL();
// Install TWAI driver
if (twai_driver_install(&g_config, &t_config, &f_config) == ESP_OK) {
printf("Driver installed\r\n");
} else {
printf("Failed to install driver\r\n");
return;
}
// Start TWAI driver
if (twai_start() == ESP_OK) {
printf("Driver started\r\n");
} else {
printf("Failed to start driver\r\n");
return;
}
// Reconfigure alerts to detect TX alerts and Bus-Off errors
uint32_t alerts_to_enable = TWAI_ALERT_RX_DATA | TWAI_ALERT_ERR_PASS | TWAI_ALERT_BUS_ERROR | TWAI_ALERT_RX_QUEUE_FULL | TWAI_ALERT_TX_IDLE | TWAI_ALERT_TX_SUCCESS | TWAI_ALERT_TX_FAILED;
if (twai_reconfigure_alerts(alerts_to_enable, NULL) == ESP_OK) {
printf("CAN Alerts reconfigured\r\n");
} else {
printf("Failed to reconfigure alerts\r\n");
return;
}
// TWAI driver is now successfully installed and started
driver_installed = true;
xTaskCreatePinnedToCore(
CANTask,
"CANTask",
4096,
NULL,
3,
NULL,
0
);
}
static void send_message_Test(void) {
// Send message
// Configure message to transmit
twai_message_t message;
message.identifier = 0x0F6;
message.data_length_code = 4;
for (int i = 0; i < 4; i++) {
message.data[i] = i;
}
// Queue message for transmission
if (twai_transmit(&message, pdMS_TO_TICKS(1000)) == ESP_OK) {
printf("Message queued for transmission\n");
} else {
printf("Failed to queue message for transmission\n");
}
}
// Standard frames ID: 0x000 to 0x7FF
// Extended frames ID: 0x00000000 to 0x1FFFFFFF
// Frame_type : 1Extended frames 0Standard frames
void send_message(uint32_t CAN_ID, uint8_t* Data, uint8_t Data_length, bool Frame_type) {
// Send message
// Configure message to transmit
twai_message_t message;
message.identifier = CAN_ID;
message.rtr = 0; // Disable remote frame
if(CAN_ID > 0x7FF){
if(!Frame_type)
printf("The frame type is set incorrectly and data will eventually be sent as an extended frame!!!!\r\n");
message.extd = 1;
}
else
message.extd = Frame_type;
if(Data_length > 8){
uint16_t Frame_count = (Data_length / 8);
for (int i = 0; i < Frame_count; i++) {
message.data_length_code = 8;
for (int j = 0; j < 8; j++) {
message.data[j] = Data[j + (i * 8)];
}
// Queue message for transmission
if (twai_transmit(&message, pdMS_TO_TICKS(1000)) == ESP_OK) {
printf("Message queued for transmission\n");
} else {
printf("Failed to queue message for transmission\n");
}
}
if(Data_length % 8){
uint8_t Data_length_Now = Data_length % 8;
message.data_length_code = Data_length_Now;
for (int k = 0; k < Data_length_Now; k++) {
message.data[k] = Data[k + (Data_length - Data_length_Now)];
}
// Queue message for transmission
if (twai_transmit(&message, pdMS_TO_TICKS(1000)) == ESP_OK) {
printf("Message queued for transmission\n");
} else {
printf("Failed to queue message for transmission\n");
}
}
}
else{
message.data_length_code = Data_length;
for (int i = 0; i < Data_length; i++) {
message.data[i] = Data[i];
}
// Queue message for transmission
if (twai_transmit(&message, pdMS_TO_TICKS(1000)) == ESP_OK) {
printf("Message queued for transmission\n");
} else {
printf("Failed to queue message for transmission\n");
}
}
}
static void handle_rx_message(twai_message_t &message) {
// Process received message
if (message.extd) {
printf("Message is in Extended Format\r\n");
} else {
printf("Message is in Standard Format\r\n");
}
printf("ID: %lx\nByte:", message.identifier);
if (!(message.rtr)) {
if (message.data_length_code > 0) {
printf(" Data: ");
for (int i = 0; i < message.data_length_code; i++) {
printf("%02x ", message.data[i]);
}
printf("\r\n");
// printf("Send back the received data!\r\n");
// send_message(message.identifier, message.data, message.data_length_code, message.extd);
} else {
printf(" No data available\r\n");
}
} else {
printf("This is a Remote Transmission Request (RTR) frame.\r\n");
}
}
unsigned long previousMillis = 0; // will store last time a message was send
#if Communication_failure_Enable
static unsigned long previous_bus_error_time = 0; // To store the last time a BUS_ERROR was printed
#endif
void CAN_Loop(void)
{
if(driver_installed){
// Check if an alert happened
uint32_t alerts_triggered;
twai_read_alerts(&alerts_triggered, pdMS_TO_TICKS(POLLING_RATE_MS));
twai_status_info_t twaistatus;
twai_get_status_info(&twaistatus);
// Handle alerts
if (alerts_triggered & TWAI_ALERT_ERR_PASS) {
printf("Alert: TWAI controller has become error passive.\r\n");
}
if (alerts_triggered & TWAI_ALERT_BUS_ERROR) {
// printf("Alert: A (Bit, Stuff, CRC, Form, ACK) error has occurred on the bus.\r\n");
// printf("Bus error count: %ld\n", twaistatus.bus_error_count);
#if Communication_failure_Enable
unsigned long currentMillis = millis();
// Only print the message if more than 2 seconds have passed since the last time it was printed
if (currentMillis - previous_bus_error_time >= BUS_ERROR_INTERVAL_MS) {
printf("Note if there are other devices on the CAN bus (other devices must be present) and that the rate of the device is the same as set in this program\r\n");
previous_bus_error_time = currentMillis; // Update the last print time
}
#endif
}
if (alerts_triggered & TWAI_ALERT_RX_QUEUE_FULL) {
printf("Alert: The RX queue is full causing a received frame to be lost.\r\n");
printf("RX buffered: %ld\t", twaistatus.msgs_to_rx);
printf("RX missed: %ld\t", twaistatus.rx_missed_count);
printf("RX overrun %ld\n", twaistatus.rx_overrun_count);
}
if (alerts_triggered & TWAI_ALERT_TX_FAILED) {
printf("Alert: The Transmission failed.\r\n");
printf("TX buffered: %ld\t", twaistatus.msgs_to_tx);
printf("TX error: %ld\t", twaistatus.tx_error_counter);
printf("TX failed: %ld\n", twaistatus.tx_failed_count);
}
if (alerts_triggered & TWAI_ALERT_TX_SUCCESS) {
printf("Alert: The Transmission was successful.\r\n");
printf("TX buffered: %ld\t \r\n", twaistatus.msgs_to_tx);
}
// Receive messages if any are available
if (alerts_triggered & TWAI_ALERT_RX_DATA) {
// One or more messages received. Handle all.
twai_message_t message; // This is the structure used to store the received CAN message.
while (twai_receive(&message, 0) == ESP_OK) {
handle_rx_message(message); // This function will process the received message.
}
}
}
}
void CANTask(void *parameter) {
// send_message_Test();
// uint8_t Data[27]={0x80, 0x2A, 0xC3, 0x58, 0x17, 0x11, 0x4D, 0x3F, 0x3B, 0xCE, 0x0F, 0xFF, 0x79, 0x20, 0xB4, 0x40, 0x5D, 0x29, 0x05, 0x49, 0xE6, 0x12, 0x57, 0x0E, 0x6D, 0xC9, 0xAE};
// send_message(0x079,Data,27);
while(1){
CAN_Loop();
vTaskDelay(pdMS_TO_TICKS(50));
}
vTaskDelete(NULL);
}

View File

@@ -1,22 +0,0 @@
#pragma once
#include "driver/twai.h"
#include "WS_GPIO.h"
// Interval:
#define TRANSMIT_RATE_MS 1000
// Interval:
#define POLLING_RATE_MS 1000
#define Communication_failure_Enable 0 // If the CAN bus is faulty for a long time, determine whether to forcibly exit
#if Communication_failure_Enable
#define BUS_ERROR_INTERVAL_MS 5000 // Send a message every 2 seconds (2000 ms)
#endif
void CAN_Init(void);
void CAN_Loop(void);
void CANTask(void *parameter);
void send_message(uint32_t CAN_ID, uint8_t* Data, uint8_t Data_length);

View File

@@ -1,151 +0,0 @@
#include "WS_DIN.h"
bool DIN_Flag[8] = {0}; // DIN current status flag
uint8_t DIN_Data = 0;
bool Relay_Immediate_Enable = Relay_Immediate_Default;
bool DIN_Read_CH1(void){
DIN_Flag[0] = digitalRead(DIN_PIN_CH1);
if(DIN_Flag[0]){
DIN_Data |= (1 << 0);
return 1;
}
else{
DIN_Data &= (~(1 << 0));
return 0;
}
}
bool DIN_Read_CH2(void){
DIN_Flag[1] = digitalRead(DIN_PIN_CH2);
if(DIN_Flag[1]){
DIN_Data |= (1 << 1);
return 1;
}
else{
DIN_Data &= (~(1 << 1));
return 0;
}
}
bool DIN_Read_CH3(void){
DIN_Flag[2] = digitalRead(DIN_PIN_CH3);
if(DIN_Flag[2]){
DIN_Data |= (1 << 2);
return 1;
}
else{
DIN_Data &= (~(1 << 2));
return 0;
}
}
bool DIN_Read_CH4(void){
DIN_Flag[3] = digitalRead(DIN_PIN_CH4);
if(DIN_Flag[3]){
DIN_Data |= (1 << 3);
return 1;
}
else{
DIN_Data &= (~(1 << 3));
return 0;
}
}
bool DIN_Read_CH5(void){
DIN_Flag[4] = digitalRead(DIN_PIN_CH5);
if(DIN_Flag[4]){
DIN_Data |= (1 << 4);
return 1;
}
else{
DIN_Data &= (~(1 << 4));
return 0;
}
}
bool DIN_Read_CH6(void){
DIN_Flag[5] = digitalRead(DIN_PIN_CH6);
if(DIN_Flag[5]){
DIN_Data |= (1 << 5);
return 1;
}
else{
DIN_Data &= (~(1 << 5));
return 0;
}
}
bool DIN_Read_CH7(void){
DIN_Flag[6] = digitalRead(DIN_PIN_CH7);
if(DIN_Flag[6]){
DIN_Data |= (1 << 6);
return 1;
}
else{
DIN_Data &= (~(1 << 6));
return 0;
}
}
bool DIN_Read_CH8(void){
DIN_Flag[7] = digitalRead(DIN_PIN_CH8);
if(DIN_Flag[7]){
DIN_Data |= (1 << 7);
return 1;
}
else{
DIN_Data &= (~(1 << 7));
return 0;
}
}
uint8_t DIN_Read_CHxs(){
DIN_Read_CH1();
DIN_Read_CH2();
DIN_Read_CH3();
DIN_Read_CH4();
DIN_Read_CH5();
DIN_Read_CH6();
DIN_Read_CH7();
DIN_Read_CH8();
return DIN_Data;
}
static uint8_t DIN_Data_Old = 0;
void DINTask(void *parameter) {
while(1){
if(Relay_Immediate_Enable){
DIN_Read_CHxs();
if(DIN_Data_Old != DIN_Data){
if(DIN_Inverse_Enable)
Relay_Immediate_CHxs(~DIN_Data , DIN_Mode);
else
Relay_Immediate_CHxs(DIN_Data , DIN_Mode);
DIN_Data_Old = DIN_Data;
}
}
vTaskDelay(pdMS_TO_TICKS(20));
}
vTaskDelete(NULL);
}
void DIN_Init(void)
{
pinMode(DIN_PIN_CH1, INPUT_PULLUP);
pinMode(DIN_PIN_CH2, INPUT_PULLUP);
pinMode(DIN_PIN_CH3, INPUT_PULLUP);
pinMode(DIN_PIN_CH4, INPUT_PULLUP);
pinMode(DIN_PIN_CH5, INPUT_PULLUP);
pinMode(DIN_PIN_CH6, INPUT_PULLUP);
pinMode(DIN_PIN_CH7, INPUT_PULLUP);
pinMode(DIN_PIN_CH8, INPUT_PULLUP);
DIN_Read_CHxs();
if(DIN_Inverse_Enable)
DIN_Data_Old = 0xFF;
else
DIN_Data_Old = 0x00;
xTaskCreatePinnedToCore(
DINTask,
"DINTask",
4096,
NULL,
4,
NULL,
0
);
}

View File

@@ -1,18 +0,0 @@
#pragma once
#include "WS_GPIO.h"
#include "WS_Relay.h"
/************************************************************* I/O *************************************************************/
#define DIN_PIN_CH1 4 // DIN CH1 GPIO
#define DIN_PIN_CH2 5 // DIN CH2 GPIO
#define DIN_PIN_CH3 6 // DIN CH3 GPIO
#define DIN_PIN_CH4 7 // DIN CH4 GPIO
#define DIN_PIN_CH5 8 // DIN CH5 GPIO
#define DIN_PIN_CH6 9 // DIN CH6 GPIO
#define DIN_PIN_CH7 10 // DIN CH7 GPIO
#define DIN_PIN_CH8 11 // DIN CH8 GPIO
#define Relay_Immediate_Default 1 // Enable the input control relay
#define DIN_Inverse_Enable 1 // Input is reversed from control
void DIN_Init(void);

View File

@@ -1,120 +0,0 @@
#include "WS_ETH.h"
#include <NTPClient.h>
#include <WiFiUdp.h>
static bool eth_connected = false;
static bool eth_connected_Old = false;
IPAddress ETH_ip;
// NTP setup
WiFiUDP udp;
NTPClient timeClient(udp, "pool.ntp.org", timezone*3600, 60000); // NTP server, time offset in seconds, update interval
void onEvent(arduino_event_id_t event, arduino_event_info_t info) {
switch (event) {
case ARDUINO_EVENT_ETH_START:
printf("ETH Started\r\n");
//set eth hostname here
ETH.setHostname("esp32-eth0");
break;
case ARDUINO_EVENT_ETH_CONNECTED: printf("ETH Connected\r\n"); break;
case ARDUINO_EVENT_ETH_GOT_IP: printf("ETH Got IP: '%s'\n", esp_netif_get_desc(info.got_ip.esp_netif)); //printf("%s\r\n",ETH);
ETH_ip = ETH.localIP();
printf("ETH Got IP: %d.%d.%d.%d\n", ETH_ip[0], ETH_ip[1], ETH_ip[2], ETH_ip[3]);
#if USE_TWO_ETH_PORTS
// printf("%d\r\n",ETH1);
#endif
eth_connected = true;
break;
case ARDUINO_EVENT_ETH_LOST_IP:
printf("ETH Lost IP\r\n");
eth_connected = false;
break;
case ARDUINO_EVENT_ETH_DISCONNECTED:
printf("ETH Disconnected\r\n");
eth_connected = false;
break;
case ARDUINO_EVENT_ETH_STOP:
printf("ETH Stopped\r\n");
eth_connected = false;
break;
default: break;
}
}
void testClient(const char *host, uint16_t port) {
printf("\nconnecting to \r\n");;
printf("%s\r\n",host);
NetworkClient client;
if (!client.connect(host, port)) {
printf("connection failed\r\n");
return;
}
client.printf("GET / HTTP/1.1\r\nHost: %s\r\n\r\n", host);
while (client.connected() && !client.available());
while (client.available()) {
printf("%c",(char)client.read());
}
printf("closing connection\n");
client.stop();
}
void ETH_Init(void) {
printf("Ethernet Start\r\n");
Network.onEvent(onEvent);
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);
#if USE_TWO_ETH_PORTS
ETH1.begin(ETH1_PHY_TYPE, ETH1_PHY_ADDR, ETH1_PHY_CS, ETH1_PHY_IRQ, ETH1_PHY_RST, SPI);
#endif
xTaskCreatePinnedToCore(
EthernetTask,
"EthernetTask",
4096,
NULL,
2,
NULL,
0
);
}
void EthernetTask(void *parameter) {
while(1){
if (eth_connected && !eth_connected_Old) {
eth_connected_Old = eth_connected;
RGB_Open_Time(0, 60, 0,1000, 0);
printf("Network port connected!\r\n");
Acquisition_time();
}
else if(!eth_connected && eth_connected_Old){
eth_connected_Old = eth_connected;
printf("Network port disconnected!\r\n");
}
vTaskDelay(pdMS_TO_TICKS(100));
}
vTaskDelete(NULL);
}
void Acquisition_time(void) { // Get the network time and set to DS3231 to be called after the WIFI connection is successful
timeClient.begin();
timeClient.update();
time_t currentTime = timeClient.getEpochTime();
while(currentTime < 1609459200) // Using the current timestamp to compare with a known larger value,1609459200 is a known larger timestamp value that corresponds to January 1, 2021
{
timeClient.update();
currentTime = timeClient.getEpochTime();
printf("ETH - Online clock error!!!\r\n");
}
struct tm *localTime = localtime(&currentTime);
static datetime_t PCF85063_Time = {0};
PCF85063_Time.year = localTime->tm_year + 1900;
PCF85063_Time.month = localTime->tm_mon + 1;
PCF85063_Time.day = localTime->tm_mday;
PCF85063_Time.dotw = localTime->tm_wday;
PCF85063_Time.hour = localTime->tm_hour;
PCF85063_Time.minute = localTime->tm_min;
PCF85063_Time.second = localTime->tm_sec;
PCF85063_Set_All(PCF85063_Time);
}

View File

@@ -1,44 +0,0 @@
#pragma once
#include <Arduino.h>
#include <ETH.h>
#include <SPI.h>
#include "WS_PCF85063.h"
#include "WS_GPIO.h"
#include "WS_RTC.h"
// Set this to 1 to enable dual Ethernet support
#define USE_TWO_ETH_PORTS 0
#ifndef ETH_PHY_TYPE
#define ETH_PHY_TYPE ETH_PHY_W5500
#define ETH_PHY_ADDR 1
#define ETH_PHY_CS 16
#define ETH_PHY_IRQ 12
#define ETH_PHY_RST 39
#endif
// SPI pins
#define ETH_SPI_SCK 15
#define ETH_SPI_MISO 14
#define ETH_SPI_MOSI 13
#if USE_TWO_ETH_PORTS
// Second port on shared SPI bus
#ifndef ETH1_PHY_TYPE
#define ETH1_PHY_TYPE ETH_PHY_W5500
#define ETH1_PHY_ADDR 1
#define ETH1_PHY_CS 32
#define ETH1_PHY_IRQ 33
#define ETH1_PHY_RST 18
#endif
ETHClass ETH1(1);
#endif
#define timezone 8 // china
void ETH_Init(void);
void ETH_Loop(void);
void EthernetTask(void *parameter);
void Acquisition_time(void);

View File

@@ -1,166 +0,0 @@
#include "WS_GPIO.h"
/************************************************************* I/O Init *************************************************************/
void GPIO_Init() {
pinMode(GPIO_PIN_RGB, OUTPUT); // Initialize the control GPIO of RGB
pinMode(GPIO_PIN_Buzzer, OUTPUT); // Initialize the control GPIO of Buzzer
// TODO: Re enable this
//ledcAttach(GPIO_PIN_Buzzer, Frequency, Resolution);
Set_Dutyfactor(0); //0~100
xTaskCreatePinnedToCore(
RGBTask,
"RelayFailTask",
4096,
NULL,
2,
NULL,
0
);
xTaskCreatePinnedToCore(
BuzzerTask,
"RelayFailTask",
4096,
NULL,
2,
NULL,
0
);
}
/************************************************************* RGB *************************************************************/
void RGB_Light(uint8_t red_val, uint8_t green_val, uint8_t blue_val) {
rgbLedWrite(GPIO_PIN_RGB, green_val, red_val, blue_val); // RGB color adjustment
}
RGB_Indicate RGB_indicate[RGB_Indicate_Number];
static uint8_t RGB_indicate_Num = 0;
void RGB_Open_Time(uint8_t red_val, uint8_t green_val, uint8_t blue_val, uint16_t Time, uint16_t flicker_time) {
if(RGB_indicate_Num + 1 >= RGB_Indicate_Number)
{
printf("Note : The RGB indicates that the cache is full and has been ignored\r\n");
}
else{
RGB_indicate[RGB_indicate_Num].Red = red_val;
RGB_indicate[RGB_indicate_Num].Green = green_val;
RGB_indicate[RGB_indicate_Num].Blue = blue_val;
RGB_indicate[RGB_indicate_Num].RGB_Time = Time;
if(flicker_time<51)
flicker_time = 0; // If the blinking interval is less than 50ms, the blinking is ignored
RGB_indicate[RGB_indicate_Num].RGB_Flicker = flicker_time;
RGB_indicate_Num ++;
}
}
void RGBTask(void *parameter) {
bool RGB_Flag = 0;
while(1){
if(RGB_indicate[0].RGB_Time)
{
RGB_Flag = 1;
RGB_Light(RGB_indicate[0].Red, RGB_indicate[0].Green, RGB_indicate[0].Blue);
if(RGB_indicate[0].RGB_Flicker){
vTaskDelay(pdMS_TO_TICKS(RGB_indicate[0].RGB_Flicker));
RGB_Light(0, 0, 0);
vTaskDelay(pdMS_TO_TICKS(RGB_indicate[0].RGB_Flicker));
}
if(RGB_indicate[0].RGB_Time > (RGB_indicate[0].RGB_Flicker * 2 +50))
RGB_indicate[0].RGB_Time = RGB_indicate[0].RGB_Time -(RGB_indicate[0].RGB_Flicker * 2 +50);
else
RGB_indicate[0].RGB_Time = 0;
}
else if(RGB_Flag && !RGB_indicate[0].RGB_Time){
RGB_Light(0, 0, 0);
RGB_Flag = 0;
RGB_indicate[0].Red = 0;
RGB_indicate[0].Green = 0;
RGB_indicate[0].Blue = 0;
RGB_indicate[0].RGB_Time = 0;
RGB_indicate[0].RGB_Flicker = 0;
if(RGB_indicate_Num > 0){
for (int i = 1; i < RGB_Indicate_Number; i++) {
RGB_indicate[i-1] = RGB_indicate[i];
}
RGB_indicate[RGB_Indicate_Number -1].Red = 0;
RGB_indicate[RGB_Indicate_Number -1].Green = 0;
RGB_indicate[RGB_Indicate_Number -1].Blue = 0;
RGB_indicate[RGB_Indicate_Number -1].RGB_Time = 0;
RGB_indicate[RGB_Indicate_Number -1].RGB_Flicker = 0;
RGB_indicate_Num --;
vTaskDelay(pdMS_TO_TICKS(RGB_Indicating_interval));
}
}
vTaskDelay(pdMS_TO_TICKS(50));
}
vTaskDelete(NULL);
}
/************************************************************* Buzzer *************************************************************/
void Set_Dutyfactor(uint16_t dutyfactor)
{
if(dutyfactor > Dutyfactor_MAX || dutyfactor < 0)
printf("Set Backlight parameters in the range of 0 to %d \r\n",Dutyfactor_MAX);
else{
ledcWrite(GPIO_PIN_Buzzer, dutyfactor);
}
}
void Buzzer_Open(void)
{
Set_Dutyfactor(Dutyfactor);
}
void Buzzer_Closs(void)
{
Set_Dutyfactor(0);
}
Buzzer_Indicate Buzzer_indicate[Buzzer_Indicate_Number];
static uint8_t Buzzer_indicate_Num = 0;
void Buzzer_Open_Time(uint16_t Time, uint16_t flicker_time)
{
if(Buzzer_indicate_Num + 1 >= Buzzer_Indicate_Number)
{
printf("Note : The buzzer indicates that the cache is full and has been ignored\r\n");
}
else{
Buzzer_indicate[Buzzer_indicate_Num].Buzzer_Time = Time;
if(flicker_time<51)
flicker_time = 0; // If the blinking interval is less than 50ms, the blinking is ignored
Buzzer_indicate[Buzzer_indicate_Num].Buzzer_Flicker = flicker_time;
Buzzer_indicate_Num ++;
}
}
void BuzzerTask(void *parameter) {
bool Buzzer_Flag = 0;
while(1){
if(Buzzer_indicate[0].Buzzer_Time)
{
Buzzer_Flag = 1;
Buzzer_Open();
if(Buzzer_indicate[0].Buzzer_Flicker){
vTaskDelay(pdMS_TO_TICKS(Buzzer_indicate[0].Buzzer_Flicker));
Buzzer_Closs();
vTaskDelay(pdMS_TO_TICKS(Buzzer_indicate[0].Buzzer_Flicker));
}
if(Buzzer_indicate[0].Buzzer_Time > (Buzzer_indicate[0].Buzzer_Flicker * 2 +50))
Buzzer_indicate[0].Buzzer_Time = Buzzer_indicate[0].Buzzer_Time -(Buzzer_indicate[0].Buzzer_Flicker * 2 +50);
else
Buzzer_indicate[0].Buzzer_Time = 0;
}
else if(Buzzer_Flag && !Buzzer_indicate[0].Buzzer_Time){
Buzzer_Closs();
Buzzer_Flag = 0;
Buzzer_indicate[0].Buzzer_Time = 0;
Buzzer_indicate[0].Buzzer_Flicker = 0;
if(Buzzer_indicate_Num > 0){
for (int i = 1; i < Buzzer_indicate_Num; i++) {
Buzzer_indicate[i-1] = Buzzer_indicate[i];
}
Buzzer_indicate[Buzzer_indicate_Num - 1].Buzzer_Time = 0;
Buzzer_indicate[Buzzer_indicate_Num - 1].Buzzer_Flicker = 0;
Buzzer_indicate_Num --;
}
}
vTaskDelay(pdMS_TO_TICKS(50));
}
vTaskDelete(NULL);
}

View File

@@ -1,44 +0,0 @@
#pragma once
#include <Arduino.h>
#include <HardwareSerial.h> // Reference the ESP32 built-in serial port library
/************************************************************* I/O *************************************************************/
#define TXD1 17 //The TXD of UART1 corresponds to GPIO RS485/CAN
#define RXD1 18 //The RXD of UART1 corresponds to GPIO RS485/CAN
#define GPIO_PIN_RGB 38 // RGB Control GPIO
/*********************************************************** Buzzer ***********************************************************/
#define GPIO_PIN_Buzzer 46 // Buzzer Control GPIO
#define PWM_Channel 1 // PWM Channel
#define Frequency 1000 // PWM frequencyconst
#define Resolution 8 // PWM resolution ratio
#define Dutyfactor 200 // PWM Dutyfactor
#define Dutyfactor_MAX 255
#define RGB_Indicate_Number 10 // Number of saved RGB indicator signals
#define RGB_Indicating_interval 500 // Time interval of each indication signal(unit: ms)
typedef struct {
uint8_t Red = 0;
uint8_t Green = 0;
uint8_t Blue = 0;
uint16_t RGB_Time = 0; // RGB lighting duration
uint16_t RGB_Flicker = 0; // RGB flicker interval
} RGB_Indicate;
#define Buzzer_Indicate_Number 10 // Number of saved RGB indicator signals
typedef struct {
uint16_t Buzzer_Time = 0; // Buzzer duration
uint16_t Buzzer_Flicker = 0; // Buzzer interval duration
} Buzzer_Indicate;
/************************************************************* I/O *************************************************************/
void GPIO_Init();
void RGB_Light(uint8_t red_val, uint8_t green_val, uint8_t blue_val);
void RGB_Open_Time(uint8_t red_val, uint8_t green_val, uint8_t blue_val, uint16_t Time, uint16_t flicker_time);
void RGBTask(void *parameter);
void Set_Dutyfactor(uint16_t dutyfactor);
void Buzzer_Open(void);
void Buzzer_Closs(void);
void Buzzer_Open_Time(uint16_t Time, uint16_t flicker_time);
void BuzzerTask(void *parameter);

View File

@@ -1,18 +0,0 @@
#pragma once
#define Extension_Enable 1 // Whether to extend the connection to external devices 1:Expansion device Modbus RTU Relay 0:No extend
#define RS485_CAN_Enable 1 // This item is configured according to product selection 1:Select RS485 0:Select CAN
#define RTC_Event_Enable 1 // Whether to enable RTC events (Bluetooth) 1:Enable 0:Disable
// Name and password of the WiFi access point
#define STASSID "JSBPI"
#define STAPSK "waveshare0755"
// Details about devices on the Waveshare cloud
#define MQTT_Server "mqtt.waveshare.cloud"
#define MQTT_Port 1883
#define MQTT_ID "fc2d8db5"
#define MQTT_Pub "Pub/59/54/fc2d8db5"
#define MQTT_Sub "Sub/59/54/fc2d8db5"

View File

@@ -1,248 +0,0 @@
#include "WS_MQTT.h"
// The name and password of the WiFi access point
const char* ssid = STASSID;
const char* password = STAPSK;
// Details about devices on the Waveshare cloud
const char* mqtt_server = MQTT_Server;
int PORT = MQTT_Port;
const char* ID = MQTT_ID; // Defining device ID
char pub[] = MQTT_Pub; // MQTT release topic
char sub[] = MQTT_Sub; // MQTT subscribe to topics
WiFiClient espClient; //MQTT initializes the contents
PubSubClient client(espClient);
JsonDocument sendJson;
JsonDocument readJson;
unsigned long lastUpdateTime = 0;
char msg[MSG_BUFFER_SIZE];
bool WIFI_Connection = 0;
bool WIFI_Connection_Old = 0;
char ipStr[16];
const unsigned long updateInterval = 5000;
void WIFI_Init(void)
{
xTaskCreatePinnedToCore(
WifiStaTask,
"WifiStaTask",
4096,
NULL,
3,
NULL,
0
);
}
void WifiStaTask(void *parameter) {
uint8_t Count = 0;
WiFi.mode(WIFI_STA);
WiFi.setSleep(true);
WiFi.begin(ssid, password); // Connect to the specified Wi-Fi network
while(1){
if(WiFi.status() != WL_CONNECTED)
{
WIFI_Connection = 0;
printf(".\n");
RGB_Open_Time(50, 0, 0, 500, 0);
Count++;
if(Count >= 10){
Count = 0;
printf("\r\n");
WiFi.disconnect();
vTaskDelay(pdMS_TO_TICKS(100));
WiFi.mode(WIFI_OFF);
vTaskDelay(pdMS_TO_TICKS(100));
WiFi.mode(WIFI_STA);
vTaskDelay(pdMS_TO_TICKS(100));
WiFi.begin(ssid, password);
}
}
else{
WIFI_Connection = 1;
IPAddress myIP = WiFi.localIP();
printf("IP Address: ");
sprintf(ipStr, "%d.%d.%d.%d", myIP[0], myIP[1], myIP[2], myIP[3]);
printf("%s\r\n", ipStr);
RGB_Open_Time(0, 50, 0, 1000, 0);
printf("WIFI connection is successful, relay control can be performed via Waveshare cloud.\r\n");
while (WiFi.status() == WL_CONNECTED){
vTaskDelay(pdMS_TO_TICKS(100));
}
}
vTaskDelay(pdMS_TO_TICKS(1000));
}
vTaskDelete(NULL);
}
// MQTT subscribes to callback functions for processing received messages
void callback(char* topic, byte* payload, unsigned int length) {
uint8_t CH_Flag = 0;
String inputString;
for (int i = 0; i < length; i++) {
inputString += (char)payload[i];
}
printf("%s\r\n",inputString.c_str()); // Format of data sent back by the server {"data":{"CH1":1}}
int dataBegin = inputString.indexOf("\"data\""); // Finds if "data" is present in the string (quotes also)
if (dataBegin == -1) {
printf("Missing 'data' field in JSON. - MQTT\r\n");
return;
}
int CH_Begin = -1;
if (inputString.indexOf("\"CH1\"", dataBegin) != -1){
CH_Flag = 1;
CH_Begin = inputString.indexOf("\"CH1\"", dataBegin);
}
else if (inputString.indexOf("\"CH2\"", dataBegin) != -1){
CH_Flag = 2;
CH_Begin = inputString.indexOf("\"CH2\"", dataBegin);
}
else if (inputString.indexOf("\"CH3\"", dataBegin) != -1){
CH_Flag = 3;
CH_Begin = inputString.indexOf("\"CH3\"", dataBegin);
}
else if (inputString.indexOf("\"CH4\"", dataBegin) != -1){
CH_Flag = 4;
CH_Begin = inputString.indexOf("\"CH4\"", dataBegin);
}
else if (inputString.indexOf("\"CH5\"", dataBegin) != -1){
CH_Flag = 5;
CH_Begin = inputString.indexOf("\"CH5\"", dataBegin);
}
else if (inputString.indexOf("\"CH6\"", dataBegin) != -1){
CH_Flag = 6;
CH_Begin = inputString.indexOf("\"CH6\"", dataBegin);
}
else if (inputString.indexOf("\"CH7\"", dataBegin) != -1){
CH_Flag = 7;
CH_Begin = inputString.indexOf("\"CH7\"", dataBegin);
}
else if (inputString.indexOf("\"CH8\"", dataBegin) != -1){
CH_Flag = 8;
CH_Begin = inputString.indexOf("\"CH8\"", dataBegin);
}
else if (inputString.indexOf("\"ALL\"", dataBegin) != -1){
CH_Flag = 9;
CH_Begin = inputString.indexOf("\"ALL\"", dataBegin);
}
else{
printf("Note : Non-instruction data was received - MQTT!\r\n");
CH_Flag = 0;
return;
}
int valueBegin = inputString.indexOf(':', CH_Begin);
int valueEnd = inputString.indexOf('}', valueBegin);
if (valueBegin != -1 && valueEnd != -1) {
if(CH_Flag != 0)
{
String ValueStr = inputString.substring(valueBegin + 1, valueEnd);
int Value = ValueStr.toInt();
if(CH_Flag < 9){
if(Value == 1 && Relay_Flag[CH_Flag - 1] == 0){
uint8_t Data[1]={CH_Flag+48};
Relay_Analysis(Data,MQTT_Mode);
}
else if(Value == 0 && Relay_Flag[CH_Flag - 1] == 1){
uint8_t Data[1]={CH_Flag+48};
Relay_Analysis(Data,MQTT_Mode);
}
}
else if(CH_Flag == 9){
if(Value == 1 && ((Relay_Flag[0] & Relay_Flag[1] & Relay_Flag[2] & Relay_Flag[3] & Relay_Flag[4] & Relay_Flag[5] & Relay_Flag[6] & Relay_Flag[7]) == 0)){
uint8_t Data[1]={9+48};
Relay_Analysis(Data,MQTT_Mode);
}
else if(Value == 0 && ((Relay_Flag[0] | Relay_Flag[1] | Relay_Flag[2] | Relay_Flag[3] | Relay_Flag[4] | Relay_Flag[5] | Relay_Flag[6] | Relay_Flag[7] )== 1)){
uint8_t Data[1]={0+48};
Relay_Analysis(Data,MQTT_Mode);
}
}
}
}
}
// Reconnect to the MQTT server
void reconnect(void) {
uint8_t Count = 0;
while (!client.connected()) {
Count++;
if (client.connect(ID)) {
client.subscribe(sub);
printf("Waveshare Cloud connection is successful and now you can use all features.\r\n");
}
else{
delay(500);
if(Count % 2 == 0 && Count != 0){
printf("%d\r\n", client.state());
RGB_Open_Time(50, 0, 50, 1000, 0);
}
if(Count % 10 == 0){ // 10 attempts failed to connect, cancel the connection, try again
client.disconnect();
delay(100);
client.setServer(mqtt_server, PORT);
delay(100);
client.setCallback(callback);
delay(100);
}
if(Count > 32){ // connection fail
Count = 0;
printf("warning: Waveshare cloud connection fails. Currently, only Bluetooth control is available !!!\r\n");
}
}
}
}
// Send data in JSON format to MQTT server
void sendJsonData(void) {
sendJson["ID"] = ID;
String pubres;
serializeJson(sendJson, pubres);
int str_len = pubres.length() + 1;
char char_array[str_len];
pubres.toCharArray(char_array, str_len);
client.publish(pub, char_array);
}
void MQTTTask(void *parameter) {
bool WIFI_Connection_Old;
while(1){
if(WIFI_Connection == 1)
{
if(!WIFI_Connection_Old){
WIFI_Connection_Old = 1;
client.setServer(mqtt_server, PORT);
client.setCallback(callback);
}
if (!client.connected()) {
reconnect();
}
client.loop();
}
else{
WIFI_Connection_Old = 0;
}
vTaskDelay(pdMS_TO_TICKS(10));
}
vTaskDelete(NULL);
}
void MQTT_Init(void)
{
WIFI_Init();
xTaskCreatePinnedToCore(
MQTTTask,
"MQTTTask",
4096,
NULL,
3,
NULL,
0
);
}

View File

@@ -1,25 +0,0 @@
#ifndef _WS_MQTT_H_
#define _WS_MQTT_H_
#include <ArduinoJson.h>
#include <Arduino.h>
#include <PubSubClient.h>
#include <WiFi.h>
#include <WiFiClientSecure.h>
#include "WS_GPIO.h"
#include "WS_Information.h"
#include "WS_Relay.h"
#define MSG_BUFFER_SIZE (50)
extern char ipStr[16];
void WIFI_Init(void);
void WifiStaTask(void *parameter);
void callback(char* topic, byte* payload, unsigned int length); // MQTT subscribes to callback functions for processing received messages
void reconnect(void); // Reconnect to the MQTT server
void sendJsonData(void); // Send data in JSON format to MQTT server
void MQTT_Init(void);
#endif

View File

@@ -1,189 +0,0 @@
#include "WS_PCF85063.h"
datetime_t datetime= {0};
datetime_t Update_datetime= {0};
static uint8_t decToBcd(int val);
static int bcdToDec(uint8_t val);
void Time_printf(void *parameter) {
while(1){
char datetime_str[50];
datetime_to_str(datetime_str,datetime);
printf("Time:%s\r\n",datetime_str);
vTaskDelay(pdMS_TO_TICKS(500));
}
vTaskDelete(NULL);
}
void PCF85063_Init(void) // PCF85063 initialized
{
uint8_t Value = RTC_CTRL_1_DEFAULT|RTC_CTRL_1_CAP_SEL;
I2C_Write(PCF85063_ADDRESS, RTC_CTRL_1_ADDR, &Value, 1);
I2C_Read(PCF85063_ADDRESS, RTC_CTRL_1_ADDR, &Value, 1);
if(Value & RTC_CTRL_1_STOP)
printf("PCF85063 failed to be initialized.state :%d\r\n",Value);
else
printf("PCF85063 is running,state :%d\r\n",Value);
//
// Update_datetime.year = 2024;
// Update_datetime.month = 9;
// Update_datetime.day = 20;
// Update_datetime.dotw = 5;
// Update_datetime.hour = 9;
// Update_datetime.minute = 50;
// Update_datetime.second = 0;
// PCF85063_Set_All(Update_datetime);
xTaskCreatePinnedToCore(
PCF85063Task,
"PCF85063Task",
4096,
NULL,
3,
NULL,
0
);
// xTaskCreatePinnedToCore(
// Time_printf,
// "Time_printf",
// 4096,
// NULL,
// 3,
// NULL,
// 0
// );
}
void PCF85063Task(void *parameter) {
while(1){
PCF85063_Read_Time(&datetime);
vTaskDelay(pdMS_TO_TICKS(100));
}
vTaskDelete(NULL);
}
void PCF85063_Reset() // Reset PCF85063
{
uint8_t Value = RTC_CTRL_1_DEFAULT|RTC_CTRL_1_CAP_SEL|RTC_CTRL_1_SR;
esp_err_t ret = I2C_Write(PCF85063_ADDRESS, RTC_CTRL_1_ADDR, &Value, 1);
if(ret != ESP_OK)
printf("PCF85063 : Reset failure\r\n");
}
void PCF85063_Set_Time(datetime_t time) // Set Time
{
uint8_t buf[3] = {decToBcd(time.second),
decToBcd(time.minute),
decToBcd(time.hour)};
esp_err_t ret = I2C_Write(PCF85063_ADDRESS, RTC_SECOND_ADDR, buf, sizeof(buf));
if(ret != ESP_OK)
printf("PCF85063 : Time setting failure\r\n");
}
void PCF85063_Set_Date(datetime_t date) // Set Date
{
uint8_t buf[4] = {decToBcd(date.day),
decToBcd(date.dotw),
decToBcd(date.month),
decToBcd(date.year - YEAR_OFFSET)};
esp_err_t ret = I2C_Write(PCF85063_ADDRESS, RTC_DAY_ADDR, buf, sizeof(buf));
if(ret != ESP_OK)
printf("PCF85063 : Date setting failed\r\n");
}
void PCF85063_Set_All(datetime_t time) // Set Time And Date
{
uint8_t buf[7] = {decToBcd(time.second),
decToBcd(time.minute),
decToBcd(time.hour),
decToBcd(time.day),
decToBcd(time.dotw),
decToBcd(time.month),
decToBcd(time.year - YEAR_OFFSET)};
esp_err_t ret = I2C_Write(PCF85063_ADDRESS, RTC_SECOND_ADDR, buf, sizeof(buf));
if(ret != ESP_OK)
printf("PCF85063 : Failed to set the date and time\r\n");
}
void PCF85063_Read_Time(datetime_t *time) // Read Time And Date
{
uint8_t buf[7] = {0};
esp_err_t ret = I2C_Read(PCF85063_ADDRESS, RTC_SECOND_ADDR, buf, sizeof(buf));
if(ret != ESP_OK)
printf("PCF85063 : Time read failure\r\n");
else{
time->second = bcdToDec(buf[0] & 0x7F);
time->minute = bcdToDec(buf[1] & 0x7F);
time->hour = bcdToDec(buf[2] & 0x3F);
time->day = bcdToDec(buf[3] & 0x3F);
time->dotw = bcdToDec(buf[4] & 0x07);
time->month = bcdToDec(buf[5] & 0x1F);
time->year = bcdToDec(buf[6]) + YEAR_OFFSET;
}
}
void PCF85063_Enable_Alarm() // Enable Alarm and Clear Alarm flag
{
uint8_t Value = RTC_CTRL_2_DEFAULT | RTC_CTRL_2_AIE;
Value &= ~RTC_CTRL_2_AF;
esp_err_t ret = I2C_Write(PCF85063_ADDRESS, RTC_CTRL_2_ADDR, &Value, 1);
if(ret != ESP_OK)
printf("PCF85063 : Failed to enable Alarm Flag and Clear Alarm Flag \r\n");
}
uint8_t PCF85063_Get_Alarm_Flag() // Get Alarm flag
{
uint8_t Value = 0;
esp_err_t ret = I2C_Read(PCF85063_ADDRESS, RTC_CTRL_2_ADDR, &Value, 1);
if(ret != ESP_OK)
printf("PCF85063 : Failed to obtain a warning flag.\r\n");
else
Value &= RTC_CTRL_2_AF | RTC_CTRL_2_AIE;
//printf("Value = 0x%x",Value);
return Value;
}
void PCF85063_Set_Alarm(datetime_t time) // Set Alarm
{
uint8_t buf[5] ={
decToBcd(time.second)&(~RTC_ALARM),
decToBcd(time.minute)&(~RTC_ALARM),
decToBcd(time.hour)&(~RTC_ALARM),
//decToBcd(time.day)&(~RTC_ALARM),
//decToBcd(time.dotw)&(~RTC_ALARM)
RTC_ALARM, //disalbe day
RTC_ALARM //disalbe weekday
};
esp_err_t ret = I2C_Write(PCF85063_ADDRESS, RTC_SECOND_ALARM, buf, sizeof(buf));
if(ret != ESP_OK)
printf("PCF85063 : Failed to set alarm flag\r\n");
}
void PCF85063_Read_Alarm(datetime_t *time) // Read Alarm
{
uint8_t buf[5] = {0};
esp_err_t ret = I2C_Read(PCF85063_ADDRESS, RTC_SECOND_ALARM, buf, sizeof(buf));
if(ret != ESP_OK)
printf("PCF85063 : Failed to read the alarm sign\r\n");
else{
time->second = bcdToDec(buf[0] & 0x7F);
time->minute = bcdToDec(buf[1] & 0x7F);
time->hour = bcdToDec(buf[2] & 0x3F);
time->day = bcdToDec(buf[3] & 0x3F);
time->dotw = bcdToDec(buf[4] & 0x07);
}
}
static uint8_t decToBcd(int val) // Convert normal decimal numbers to binary coded decimal
{
return (uint8_t)((val / 10 * 16) + (val % 10));
}
static int bcdToDec(uint8_t val) // Convert binary coded decimal to normal decimal numbers
{
return (int)((val / 16 * 10) + (val % 16));
}
void datetime_to_str(char *datetime_str,datetime_t time)
{
sprintf(datetime_str, " %d.%d.%d %d:%d:%d %s", time.year, time.month,
time.day, time.hour, time.minute, time.second, Week[time.dotw]);
}

View File

@@ -1,103 +0,0 @@
#pragma once
#include "I2C_Driver.h"
//PCF85063_ADDRESS
#define PCF85063_ADDRESS (0x51)
//
#define YEAR_OFFSET (1970)
// registar overview - crtl & status reg
#define RTC_CTRL_1_ADDR (0x00)
#define RTC_CTRL_2_ADDR (0x01)
#define RTC_OFFSET_ADDR (0x02)
#define RTC_RAM_by_ADDR (0x03)
// registar overview - time & data reg
#define RTC_SECOND_ADDR (0x04)
#define RTC_MINUTE_ADDR (0x05)
#define RTC_HOUR_ADDR (0x06)
#define RTC_DAY_ADDR (0x07)
#define RTC_WDAY_ADDR (0x08)
#define RTC_MONTH_ADDR (0x09)
#define RTC_YEAR_ADDR (0x0A) // years 0-99; calculate real year = 1970 + RCC reg year
// registar overview - alarm reg
#define RTC_SECOND_ALARM (0x0B)
#define RTC_MINUTE_ALARM (0x0C)
#define RTC_HOUR_ALARM (0x0D)
#define RTC_DAY_ALARM (0x0E)
#define RTC_WDAY_ALARM (0x0F)
// registar overview - timer reg
#define RTC_TIMER_VAL (0x10)
#define RTC_TIMER_MODE (0x11)
//RTC_CTRL_1 registar
#define RTC_CTRL_1_EXT_TEST (0x80)
#define RTC_CTRL_1_STOP (0x20) //0-RTC clock runs 1- RTC clock is stopped
#define RTC_CTRL_1_SR (0X10) //0-no software reset 1-initiate software rese
#define RTC_CTRL_1_CIE (0X04) //0-no correction interrupt generated 1-interrupt pulses are generated at every correction cycle
#define RTC_CTRL_1_12_24 (0X02) //0-24H 1-12H
#define RTC_CTRL_1_CAP_SEL (0X01) //0-7PF 1-12.5PF
//RTC_CTRL_2 registar
#define RTC_CTRL_2_AIE (0X80) //alarm interrupt 0-disalbe 1-enable
#define RTC_CTRL_2_AF (0X40) //alarm flag 0-inactive/cleared 1-active/unchanged
#define RTC_CTRL_2_MI (0X20) //minute interrupt 0-disalbe 1-enable
#define RTC_CTRL_2_HMI (0X10) //half minute interrupt
#define RTC_CTRL_2_TF (0X08)
//
#define RTC_OFFSET_MODE (0X80)
//
#define RTC_TIMER_MODE_TE (0X04) //timer enable 0-disalbe 1-enable
#define RTC_TIMER_MODE_TIE (0X02) //timer interrupt enable 0-disalbe 1-enable
#define RTC_TIMER_MODE_TI_TP (0X01) //timer interrupt mode 0-interrupt follows timer flag 1-interrupt generates a pulse
// format
#define RTC_ALARM (0x80) // set AEN_x registers
#define RTC_CTRL_1_DEFAULT (0x00)
#define RTC_CTRL_2_DEFAULT (0x00)
#define RTC_TIMER_FLAG (0x08)
typedef struct {
uint16_t year;
uint8_t month;
uint8_t day;
uint8_t dotw;
uint8_t hour;
uint8_t minute;
uint8_t second;
}datetime_t;
const unsigned char MonthStr[12][4] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov","Dec"};
const unsigned char Week[7][5] = {"SUN","Mon","Tues","Wed","Thur","Fri","Sat"};
extern datetime_t datetime;
void PCF85063_Init(void);
void PCF85063_Reset(void);
void PCF85063Task(void *parameter);
void PCF85063_Set_Time(datetime_t time);
void PCF85063_Set_Date(datetime_t date);
void PCF85063_Set_All(datetime_t time);
void PCF85063_Read_Time(datetime_t *time);
void PCF85063_Enable_Alarm(void);
uint8_t PCF85063_Get_Alarm_Flag();
void PCF85063_Set_Alarm(datetime_t time);
void PCF85063_Read_Alarm(datetime_t *time);
void datetime_to_str(char *datetime_str,datetime_t time);
// weekday format
// 0 - sunday
// 1 - monday
// 2 - tuesday
// 3 - wednesday
// 4 - thursday
// 5 - friday
// 6 - saturday

View File

@@ -1,163 +0,0 @@
#include "WS_RS485.h"
#include <algorithm>
HardwareSerial lidarSerial(1); // Using serial port 1
uint8_t data[][8] = { // ESP32-S3-POE-ETH-8DI-8RO Control Command (RS485 receiving data)
{ 0x06, 0x05, 0x00, 0x01, 0x55, 0x00, 0xA2, 0xED }, // ESP32-S3-POE-ETH-8DI-8RO CH1 Toggle
{ 0x06, 0x05, 0x00, 0x02, 0x55, 0x00, 0x52, 0xED }, // ESP32-S3-POE-ETH-8DI-8RO CH2 Toggle
{ 0x06, 0x05, 0x00, 0x03, 0x55, 0x00, 0x03, 0x2D }, // ESP32-S3-POE-ETH-8DI-8RO CH3 Toggle
{ 0x06, 0x05, 0x00, 0x04, 0x55, 0x00, 0xB2, 0xEC }, // ESP32-S3-POE-ETH-8DI-8RO CH4 Toggle
{ 0x06, 0x05, 0x00, 0x05, 0x55, 0x00, 0xE3, 0x2C }, // ESP32-S3-POE-ETH-8DI-8RO CH5 Toggle
{ 0x06, 0x05, 0x00, 0x06, 0x55, 0x00, 0x13, 0x2C }, // ESP32-S3-POE-ETH-8DI-8RO CH6 Toggle
{ 0x06, 0x05, 0x00, 0x07, 0x55, 0x00, 0x42, 0xEC }, // ESP32-S3-POE-ETH-8DI-8RO CH7 Toggle
{ 0x06, 0x05, 0x00, 0x08, 0x55, 0x00, 0x72, 0xEF }, // ESP32-S3-POE-ETH-8DI-8RO CH8 Toggle
{ 0x06, 0x05, 0x00, 0xFF, 0xFF, 0x00, 0xBD, 0xBD }, // ESP32-S3-POE-ETH-8DI-8RO ALL ON
{ 0x06, 0x05, 0x00, 0xFF, 0x00, 0x00, 0xFC, 0x4D }, // ESP32-S3-POE-ETH-8DI-8RO ALL OFF
};
uint8_t Send_Data[][8] = { // Modbus RTU Relay Control Command (RS485 send data)
{ 0x01, 0x05, 0x00, 0x00, 0x55, 0x00, 0xF2, 0x9A }, // Modbus RTU Relay CH1 Toggle
{ 0x01, 0x05, 0x00, 0x01, 0x55, 0x00, 0xA3, 0x5A }, // Modbus RTU Relay CH2 Toggle
{ 0x01, 0x05, 0x00, 0x02, 0x55, 0x00, 0x53, 0x5A }, // Modbus RTU Relay CH3 Toggle
{ 0x01, 0x05, 0x00, 0x03, 0x55, 0x00, 0x02, 0x9A }, // Modbus RTU Relay CH4 Toggle
{ 0x01, 0x05, 0x00, 0x04, 0x55, 0x00, 0xB3, 0x5B }, // Modbus RTU Relay CH5 Toggle
{ 0x01, 0x05, 0x00, 0x05, 0x55, 0x00, 0xE2, 0x9B }, // Modbus RTU Relay CH6 Toggle
{ 0x01, 0x05, 0x00, 0x06, 0x55, 0x00, 0x12, 0x9B }, // Modbus RTU Relay CH7 Toggle
{ 0x01, 0x05, 0x00, 0x07, 0x55, 0x00, 0x43, 0x5B }, // Modbus RTU Relay CH8 Toggle
{ 0x01, 0x05, 0x00, 0xFF, 0xFF, 0xFF, 0xFC, 0x4A }, // Modbus RTU Relay ALL ON
{ 0x01, 0x05, 0x00, 0xFF, 0x00, 0x00, 0xFD, 0xFA }, // Modbus RTU Relay ALL OFF
};
uint8_t buf[20] = {0}; // Data storage area
int numRows = sizeof(data) / sizeof(data[0]);
void SetData(uint8_t* data, size_t length) {
lidarSerial.write(data, length); // Send data from the RS485
}
void ReadData(uint8_t* buf, uint8_t length) {
uint8_t Receive_Flag = 0;
Receive_Flag = lidarSerial.available();
if (Receive_Flag >= length) {
lidarSerial.readBytes(buf, length);
char printBuf[length * 3 + 1];
sprintf(printBuf, "Received data: ");
for (int i = 0; i < length; i++) {
sprintf(printBuf + strlen(printBuf), "%02X ", buf[i]);
}
printf(printBuf);
/*************************
Add a receiving data handler
*************************/
Receive_Flag = 0;
memset(buf, 0, sizeof(buf));
}
}
void RS485_Analysis(uint8_t *buf)
{
switch(buf[1])
{
case Extension_CH1:
SetData(Send_Data[0],sizeof(Send_Data[0]));
printf("|*** Toggle expansion channel 1 ***|\r\n");
break;
case Extension_CH2:
SetData(Send_Data[1],sizeof(Send_Data[1]));
printf("|*** Toggle expansion channel 2 ***|\r\n");
break;
case Extension_CH3:
SetData(Send_Data[2],sizeof(Send_Data[2]));
printf("|*** Toggle expansion channel 3 ***|\r\n");
break;
case Extension_CH4:
SetData(Send_Data[3],sizeof(Send_Data[3]));
printf("|*** Toggle expansion channel 4 ***|\r\n");
break;
case Extension_CH5:
SetData(Send_Data[4],sizeof(Send_Data[4]));
printf("|*** Toggle expansion channel 5 ***|\r\n");
break;
case Extension_CH6:
SetData(Send_Data[5],sizeof(Send_Data[5]));
printf("|*** Toggle expansion channel 6 ***|\r\n");
break;
case Extension_CH7:
SetData(Send_Data[6],sizeof(Send_Data[6]));
printf("|*** Toggle expansion channel 7 ***|\r\n");
break;
case Extension_CH8:
SetData(Send_Data[7],sizeof(Send_Data[7]));
printf("|*** Toggle expansion channel 8 ***|\r\n");
break;
case Extension_ALL_ON:
SetData(Send_Data[8],sizeof(Send_Data[8]));
printf("|*** Enable all extension channels ***|\r\n");
break;
case Extension_ALL_OFF:
SetData(Send_Data[9],sizeof(Send_Data[9]));
printf("|*** Close all expansion channels ***|\r\n");
break;
default:
printf("Note : Non-control external device instructions !\r\n");
}
}
uint32_t Baudrate = 0;
double transmission_time = 0;
double RS485_cmd_Time = 0;
void RS485_Init() // Initializing serial port
{
Baudrate = 9600; // Set the baud rate of the serial port
lidarSerial.begin(Baudrate, SERIAL_8N1, RXD1, TXD1); // Initializing serial port
transmission_time = 10.0 / Baudrate * 1000 ;
RS485_cmd_Time = transmission_time*8; // 8:data length
xTaskCreatePinnedToCore(
RS485Task,
"RS485Task",
4096,
NULL,
3,
NULL,
0
);
}
void RS485Task(void *parameter) {
while(1){
RS485_Loop();
vTaskDelay(pdMS_TO_TICKS(50));
}
vTaskDelete(NULL);
}
void RS485_Loop()
{
uint8_t Receive_Flag = 0; // Receiving mark
Receive_Flag = lidarSerial.available();
if (Receive_Flag > 0) {
if(RS485_cmd_Time > 1) // Time greater than 1 millisecond
delay((uint16_t)RS485_cmd_Time);
else // Time is less than 1 millisecond
delay(1);
Receive_Flag = lidarSerial.available();
lidarSerial.readBytes(buf, Receive_Flag); // The Receive_Flag length is read
if(Receive_Flag == 8){
uint8_t i=0;
for(i=0;i<numRows;i++){
bool result = std::equal(std::begin(buf), std::begin(buf) + 8, std::begin(data[i])); // Compare two arrays
if(result){
if(i < numRows-1)
buf[0] = i+1+48;
else if(i == numRows-1)
buf[0] = 48;
Relay_Analysis(buf,RS485_Mode);
break;
}
}
if(i > numRows-1)
printf("Note : Non-instruction data was received - RS485 !\r\n");
}
else{
printf("Note : Non-instruction data was received .Number of bytes: %d - RS485 !\r\n",Receive_Flag);
}
Receive_Flag=0;
memset(buf,0, sizeof(buf));
}
}

View File

@@ -1,26 +0,0 @@
#pragma once
#include <HardwareSerial.h> // Reference the ESP32 built-in serial port library
#include "WS_GPIO.h"
#include "WS_Relay.h"
#define Extension_CH1 1 // Expansion Channel 1
#define Extension_CH2 2 // Expansion Channel 2
#define Extension_CH3 3 // Expansion Channel 3
#define Extension_CH4 4 // Expansion Channel 4
#define Extension_CH5 5 // Expansion Channel 5
#define Extension_CH6 6 // Expansion Channel 6
#define Extension_CH7 7 // Expansion Channel 7
#define Extension_CH8 8 // Expansion Channel 8
#define Extension_ALL_ON 9 // Expansion ALL ON
#define Extension_ALL_OFF 10 // Expansion ALL OFF
void SetData(uint8_t* data, size_t length); // Send data from the RS485
void ReadData(uint8_t* buf, uint8_t length); // Data is received over RS485
void RS485_Analysis(uint8_t *buf); // External relay control
void RS485_Init(); // Example Initialize the system serial port and RS485
void RS485_Loop(); // Read RS485 data, parse and control relays
void RS485Task(void *parameter);

View File

@@ -1,350 +0,0 @@
#include "WS_RTC.h"
Timing_RTC CHx_State[Timing_events_Number_MAX]; // Set a maximum of Timing_events_Number_MAX timers
char Event_str[Timing_events_Number_MAX][1000];
static Timing_RTC CHx_State_Default; // Event initial state
const unsigned char Event_cycle[4][13] = {"Aperiodicity","everyday","Weekly","monthly"};
void RTC_Init(void){
PCF85063_Init();
xTaskCreatePinnedToCore(
RTCTask,
"RTCTask",
4096,
NULL,
3,
NULL,
0
);
}
uint8_t Timing_events_Num = 0;
void RTCTask(void *parameter)
{
static uint8_t Time_Old = 0;
while(1){
if(Timing_events_Num){
for (int i = 0; i < Timing_events_Number_MAX; i++){
if(CHx_State[i].Enable_Flag){
if(CHx_State[i].Time.hour == datetime.hour && CHx_State[i].Time.minute == datetime.minute && CHx_State[i].Time.second == datetime.second && datetime.second != Time_Old){ // The event time is consistent with the current time
switch(CHx_State[i].repetition_State){
case Repetition_NONE:
if(CHx_State[i].Time.year == datetime.year && CHx_State[i].Time.month == datetime.month && CHx_State[i].Time.day == datetime.day){ // Executes at the defined date and time
TimerEvent_handling(CHx_State[i]);
TimerEvent_Del(CHx_State[i]);
}
break;
case Repetition_everyday:
TimerEvent_handling(CHx_State[i]);
break;
case Repetition_Weekly:
if(CHx_State[i].Time.dotw == datetime.dotw){
TimerEvent_handling(CHx_State[i]);
}
break;
case Repetition_monthly:
if(CHx_State[i].Time.day == datetime.day){
TimerEvent_handling(CHx_State[i]);
}
break;
default:
printf("Event error!!!!\n");
break;
}
}
}
}
}
Time_Old = datetime.second;
vTaskDelay(pdMS_TO_TICKS(100));
}
vTaskDelete(NULL);
}
void TimerEvent_handling(Timing_RTC event){
uint8_t Retain_channels = 0;
printf("Event %d : \r\n", event.Event_Number);
char datetime_str[50];
datetime_to_str(datetime_str,event.Time);
for (int i = 0; i < Relay_Number_MAX; i++) {
if(*(&(event.Relay_CH1)+i) == STATE_Retain) // Find the modified channel
Retain_channels ++; // Number of unmodified channels
}
if(Retain_channels < Relay_Number_MAX - 1){
printf("%s\r\n", datetime_str);
printf("CHx Open : ");
int j = 0;
for (j = 0; j < Relay_Number_MAX; j++) {
if(*(&(event.Relay_CH1)+j) == STATE_Open)
printf("CH%d ", j+1);
}
printf("\r\nCHx Closs : ");
for (j = 0; j < Relay_Number_MAX; j++) {
if(*(&(event.Relay_CH1)+j) == STATE_Closs)
printf("CH%d ", j+1);
}
if(Retain_channels){
printf("\r\nCHx Retain : ");
for (j = 0; j < Relay_Number_MAX; j++) {
if(*(&(event.Relay_CH1)+j) == STATE_Retain)
printf("CH%d ", j+1);
}
}
printf("\r\n");
Relay_Immediate_CHxn(&(event.Relay_CH1), RTC_Mode);
printf("\r\n");
}
else if(Retain_channels == Relay_Number_MAX - 1){ // Modified a channel (use TimerEvent_CHx_Set())
printf("%s\r\n", datetime_str);
for (int x = 0; x < Relay_Number_MAX; x++) {
if(*(&(event.Relay_CH1)+x) != STATE_Retain){ // Find the modified channel
if(*(&(event.Relay_CH1)+x)){
printf("CH%d Open\r\n", x);
Relay_Immediate(x, true, RTC_Mode);
printf("\r\n");
}
else{
printf("CH%d Closs\r\n", x);
Relay_Immediate(x, false, RTC_Mode);
printf("\r\n");
}
break;
}
}
}
else{
printf("Event error or no relay control!!!\r\n");
}
}
void TimerEvent_CHx_Set(datetime_t time,uint8_t CHx, bool State, Repetition_event Repetition)
{
char datetime_str[50];
datetime_to_str(datetime_str,datetime);
printf("Now Time: %s!!!!\r\n", datetime_str);
if(CHx > Relay_Number_MAX){
printf("Timing_CHx_Set(function): Error passing parameter CHx!!!!\r\n");
return;
}
if(Timing_events_Num + 1 >= Timing_events_Number_MAX)
{
printf("Note : The number of scheduled events is full.\r\n");
}
else{
RGB_Open_Time(50, 36, 0, 1000, 0);
CHx_State[Timing_events_Num].Enable_Flag = true;
CHx_State[Timing_events_Num].Event_Number = Timing_events_Num + 1;
*(&(CHx_State[Timing_events_Num].Relay_CH1)+CHx) = (Status_adjustment)State;
CHx_State[Timing_events_Num].Time = time;
CHx_State[Timing_events_Num].repetition_State = Repetition;
Timing_events_Num ++;
datetime_to_str(datetime_str,time);
if(State){
printf("New timing event%d :\r\n %s set CH%d Open ----- %s\r\n\r\n", Timing_events_Num, datetime_str, CHx, Event_cycle[Repetition]);
sprintf(Event_str[Timing_events_Num-1], "Event %d : %s set CH%d Open ----- %s\\n\\n", Timing_events_Num, datetime_str, CHx, Event_cycle[Repetition]);
}
else{
printf("New timing event%d :\r\n %s set CH%d Closs ----- %s\r\n\r\n", Timing_events_Num, datetime_str, CHx, Event_cycle[Repetition]);
sprintf(Event_str[Timing_events_Num-1], "Event %d : %s set CH%d Closs ----- %s\\n\\n", Timing_events_Num, datetime_str, CHx, Event_cycle[Repetition]);
}
Buzzer_Open_Time(700, 0);
}
}
void TimerEvent_CHxs_Set(datetime_t time,uint8_t PinState, Repetition_event Repetition)
{
char datetime_str[50];
datetime_to_str(datetime_str,datetime);
printf("Now Time: %s!!!!\r\n", datetime_str);
if(Timing_events_Num + 1 >= Timing_events_Number_MAX)
{
printf("Note : The number of scheduled events is full.\r\n");
}
else{
RGB_Open_Time(50, 36, 0, 1000, 0);
CHx_State[Timing_events_Num].Enable_Flag = true;
CHx_State[Timing_events_Num].Event_Number = Timing_events_Num + 1;
for (int i = 0; i < Relay_Number_MAX; i++) {
*(&(CHx_State[Timing_events_Num].Relay_CH1)+i) = (Status_adjustment)((PinState >> i) & 0x01);
}
CHx_State[Timing_events_Num].Time = time;
CHx_State[Timing_events_Num].repetition_State = Repetition;
Timing_events_Num ++;
datetime_to_str(datetime_str,time);
printf("New timing event%d :\r\n %s \r\n",Timing_events_Num, datetime_str);
printf(" CHx :");
for (int i = 0; i < Relay_Number_MAX; i++)
printf("CH%d ", i+1);
printf("\r\n State :");
for (int i = 0; i < Relay_Number_MAX; i++) {
if((PinState >> i) & 0x01)
printf("Open ");
else
printf("Closs ");
}
printf("\r\n");
printf(" ----- %s\r\n\r\n", Event_cycle[Repetition]);
printf("\r\n");
Buzzer_Open_Time(700, 0);
int len = 0;
char Event_content[1000];
len += snprintf(Event_content + len, sizeof(Event_content) - len, "&nbsp;&nbsp;&nbsp;&nbsp;CHx&nbsp;&nbsp;:");
for (int i = 0; i < Relay_Number_MAX; i++) {
len += snprintf(Event_content + len, sizeof(Event_content) - len, "CH%d&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;", i + 1);
}
len += snprintf(Event_content + len, sizeof(Event_content) - len, "\\n &nbsp;&nbsp;&nbsp;&nbsp;State :");
for (int i = 0; i < Relay_Number_MAX; i++) {
if ((PinState >> i) & 0x01)
len += snprintf(Event_content + len, sizeof(Event_content) - len, "Open&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;");
else
len += snprintf(Event_content + len, sizeof(Event_content) - len, "Closs&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;");
}
len += snprintf(Event_content + len, sizeof(Event_content) - len, "\\n&nbsp;&nbsp;&nbsp;&nbsp;----- %s\\n\\n", Event_cycle[Repetition]);
// printf("%s\r\n", Event_content);
sprintf(Event_str[Timing_events_Num-1], "Event %d : %s \\n%s", Timing_events_Num, datetime_str,Event_content);
}
}
void TimerEvent_CHxn_Set(datetime_t time,Status_adjustment *Relay_n, Repetition_event Repetition)
{
char datetime_str[50];
datetime_to_str(datetime_str,datetime);
printf("Now Time: %s!!!!\r\n", datetime_str);
if(Timing_events_Num + 1 >= Timing_events_Number_MAX)
{
printf("Note : The number of scheduled events is full.\r\n");
}
else{
RGB_Open_Time(50, 36, 0, 1000, 0);
CHx_State[Timing_events_Num].Enable_Flag = true;
CHx_State[Timing_events_Num].Event_Number = Timing_events_Num + 1;
for (int i = 0; i < Relay_Number_MAX; i++) {
*(&(CHx_State[Timing_events_Num].Relay_CH1)+i) = Relay_n[i];
}
CHx_State[Timing_events_Num].Time = time;
CHx_State[Timing_events_Num].repetition_State = Repetition;
Timing_events_Num ++;
datetime_to_str(datetime_str,time);
printf("New timing event%d :\r\n %s \r\n",Timing_events_Num, datetime_str);
printf(" CHx :");
for (int i = 0; i < Relay_Number_MAX; i++)
printf("CH%d ", i+1);
printf("\r\n State :");
for (int i = 0; i < Relay_Number_MAX; i++) {
if(Relay_n[i] == STATE_Open)
printf("Open ");
else if(Relay_n[i] == STATE_Closs)
printf("Closs ");
else if(Relay_n[i] == STATE_Retain)
printf("Retain ");
}
printf("\r\n");
printf(" ----- %s\r\n\r\n", Event_cycle[Repetition]);
printf("\r\n");
Buzzer_Open_Time(700, 0);
int len = 0;
char Event_content[1000];
len += snprintf(Event_content + len, sizeof(Event_content) - len, "&nbsp;&nbsp;&nbsp;&nbsp;CHx&nbsp;&nbsp;:");
for (int i = 0; i < Relay_Number_MAX; i++) {
len += snprintf(Event_content + len, sizeof(Event_content) - len, "CH%d&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;", i + 1);
}
len += snprintf(Event_content + len, sizeof(Event_content) - len, "\\n&nbsp;&nbsp;&nbsp;&nbsp;State&nbsp;:");
for (int i = 0; i < Relay_Number_MAX; i++) {
if (Relay_n[i] == STATE_Open)
len += snprintf(Event_content + len, sizeof(Event_content) - len, "Open&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;");
else if(Relay_n[i] == STATE_Closs)
len += snprintf(Event_content + len, sizeof(Event_content) - len, "Closs&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;");
else if(Relay_n[i] == STATE_Retain)
len += snprintf(Event_content + len, sizeof(Event_content) - len, "Retain&nbsp;&nbsp;&nbsp;");
}
len += snprintf(Event_content + len, sizeof(Event_content) - len, "\\n&nbsp;&nbsp;&nbsp;&nbsp;----- %s\\n\\n", Event_cycle[Repetition]);
// printf("%s\r\n", Event_content);
sprintf(Event_str[Timing_events_Num-1], "Event %d : %s \\n%s", Timing_events_Num, datetime_str,Event_content);
}
}
void TimerEvent_printf(Timing_RTC event){
uint8_t Retain_channels = 0;
uint8_t open[8]={0};
printf("Event %d : \r\n", event.Event_Number);
char datetime_str[50];
datetime_to_str(datetime_str,event.Time);
for (int i = 0; i < Relay_Number_MAX; i++) {
if(*(&(event.Relay_CH1)+i) == STATE_Retain) // Find the modified channel
Retain_channels ++; // Number of unmodified channels
else
open[i] = *(&(event.Relay_CH1)+i);
}
if(Retain_channels == 0){ // All channels have been modified (use TimerEvent_CHxs_Set())
printf("%s\r\n", datetime_str);
printf(" CHx Open : ");
for (int j = 0; j < Relay_Number_MAX; j++) {
if(open[j])
printf("CH%d ", j);
}
printf("\r\n CHx Closs : ");
for (int k = 0; k < Relay_Number_MAX; k++) {
if(!open[k])
printf("CH%d ", k);
}
printf("\r\n");
}
else if(Retain_channels == Relay_Number_MAX - 1){ // Modified a channel (use TimerEvent_CHx_Set())
printf("%s ,", datetime_str);
for (int x = 0; x < Relay_Number_MAX; x++) {
if(*(&(event.Relay_CH1)+x) != STATE_Retain){ // Find the modified channel
if(*(&(event.Relay_CH1)+x))
printf("CH%d Open\r\n", x);
else
printf("CH%d Closs\r\n", x);
break;
}
}
}
else{
printf("%s\r\n", datetime_str);
printf("CHx Open : ");
int j = 0;
for (j = 0; j < Relay_Number_MAX; j++) {
if(open[j] == STATE_Open)
printf("CH%d ", j+1);
}
printf("\r\nCHx Closs : ");
for (j = 0; j < Relay_Number_MAX; j++) {
if(open[j] == STATE_Closs)
printf("CH%d ", j+1);
}
printf("\r\nCHx Retain : ");
for (j = 0; j < Relay_Number_MAX; j++) {
if(open[j] == STATE_Retain)
printf("CH%d ", j+1);
}
printf("\r\n");
}
}
void TimerEvent_printf_ALL(void)
{
printf("/******************* Current RTC event *******************/ \r\n");
for (int i = 0; i < Timing_events_Number_MAX; i++) {
if(CHx_State[i].Enable_Flag)
TimerEvent_printf(CHx_State[i]);
}
printf("/******************* Current RTC event *******************/\r\n\r\n ");
}
void TimerEvent_Del(Timing_RTC event){
RGB_Open_Time(20, 0, 50, 1000, 0);
printf("Example Delete an RTC event%d\r\n\r\n",event.Event_Number);
for (int i = event.Event_Number; i < Timing_events_Number_MAX; i++) {
CHx_State[i].Event_Number = CHx_State[i].Event_Number -1;
CHx_State[i-1] = CHx_State[i];
}
CHx_State[Timing_events_Number_MAX - 1] = CHx_State_Default;
memset(Event_str[Timing_events_Number_MAX - 1], 0, sizeof(Event_str[Timing_events_Number_MAX - 1]));
Timing_events_Num --;
}
void TimerEvent_Del_Number(uint8_t Event_Number){
TimerEvent_Del(CHx_State[Event_Number - 1]);
Buzzer_Open_Time(700, 300);
}

View File

@@ -1,45 +0,0 @@
#pragma once
#include "WS_PCF85063.h"
#include "WS_Relay.h"
#include "WS_GPIO.h"
#define Timing_events_Number_MAX 10 // Indicates the number of timers that can be set
typedef enum {
Repetition_NONE = 0, // aperiodicity
Repetition_everyday = 1, // The event is repeated at this time every day
Repetition_Weekly = 2, // This event is repeated every week at this time
Repetition_monthly = 3, // This event is repeated every month at this time
} Repetition_event;
typedef struct {
bool Enable_Flag = false; // The timer event enabled flag.
uint8_t Event_Number = 0; // Current event sequence number
Status_adjustment Relay_CH1 = STATE_Retain; // The CH1 status is changed periodically
Status_adjustment Relay_CH2 = STATE_Retain; // The CH2 status is changed periodically
Status_adjustment Relay_CH3 = STATE_Retain; // The CH3 status is changed periodically
Status_adjustment Relay_CH4 = STATE_Retain; // The CH4 status is changed periodically
Status_adjustment Relay_CH5 = STATE_Retain; // The CH5 status is changed periodically
Status_adjustment Relay_CH6 = STATE_Retain; // The CH6 status is changed periodically
Status_adjustment Relay_CH7 = STATE_Retain; // The CH7 status is changed periodically
Status_adjustment Relay_CH8 = STATE_Retain; // The CH8 status is changed periodically
datetime_t Time;
Repetition_event repetition_State = Repetition_NONE; // Periodic execution
}Timing_RTC;
extern uint8_t Timing_events_Num;
extern Timing_RTC CHx_State[Timing_events_Number_MAX];
extern char Event_str[Timing_events_Number_MAX][1000];
void RTCTask(void *parameter);
void TimerEvent_handling(Timing_RTC event);
void TimerEvent_printf(Timing_RTC event);
void TimerEvent_Del(Timing_RTC event);
void RTC_Init(void);
void TimerEvent_CHx_Set(datetime_t time,uint8_t CHx, bool State, Repetition_event Repetition);
void TimerEvent_CHxs_Set(datetime_t time,uint8_t PinState, Repetition_event Repetition);
void TimerEvent_CHxn_Set(datetime_t time,Status_adjustment *Relay_n, Repetition_event Repetition);
void TimerEvent_printf_ALL(void);
void TimerEvent_Del_Number(uint8_t Event_Number);

View File

@@ -1,273 +0,0 @@
#include "WS_Relay.h"
bool Failure_Flag = 0;
/************************************************************* Relay I/O *************************************************************/
bool Relay_Open(uint8_t CHx)
{
if(!Set_EXIO(CHx, true)){
printf("Failed to Open CH%d!!!\r\n", CHx);
Failure_Flag = 1;
return 0;
}
return 1;
}
bool Relay_Closs(uint8_t CHx)
{
if(!Set_EXIO(CHx, false)){
printf("Failed to Closs CH%d!!!\r\n", CHx);
Failure_Flag = 1;
return 0;
}
return 1;
}
bool Relay_CHx_Toggle(uint8_t CHx)
{
if(!Set_Toggle(CHx)){
printf("Failed to Toggle CH%d!!!\r\n", CHx);
Failure_Flag = 1;
return 0;
}
return 1;
}
bool Relay_CHx(uint8_t CHx, bool State)
{
bool result = 0;
if(State)
result = Relay_Open(CHx);
else
result = Relay_Closs(CHx);
if(!result)
Failure_Flag = 1;
return result;
}
bool Relay_CHxs_PinState(uint8_t PinState)
{
if(!Set_EXIOS(PinState)){
printf("Failed to set the relay status!!!\r\n");
Failure_Flag = 1;
return 0;
}
return 1;
}
void RelayFailTask(void *parameter) {
while(1){
if(Failure_Flag)
{
Failure_Flag = 0;
printf("Error: Relay control failed!!!\r\n");
RGB_Open_Time(60,0,0,5000,500);
Buzzer_Open_Time(5000, 500);
}
vTaskDelay(pdMS_TO_TICKS(50));
}
vTaskDelete(NULL);
}
void Relay_Init(void)
{
TCA9554PWR_Init(0x00);
xTaskCreatePinnedToCore(
RelayFailTask,
"RelayFailTask",
4096,
NULL,
3,
NULL,
0
);
}
/******************************************************** Data Analysis ********************************************************/
bool Relay_Flag[8] = {0}; // Relay current status flag
void Relay_Analysis(uint8_t *buf,uint8_t Mode_Flag)
{
uint8_t ret = 0;
if(Mode_Flag == Bluetooth_Mode)
printf("Bluetooth Data :\r\n");
else if(Mode_Flag == WIFI_Mode)
printf("WIFI Data :\r\n");
else if(Mode_Flag == MQTT_Mode)
printf("MQTT Data :\r\n");
else if(Mode_Flag == RS485_Mode)
printf("RS485 Data :\r\n");
switch(buf[0])
{
case CH1:
ret = Relay_CHx_Toggle(GPIO_PIN_CH1); //Toggle the level status of the GPIO_PIN_CH1 pin
if(ret){
Relay_Flag[0] =! Relay_Flag[0];
Buzzer_Open_Time(200, 0);
if(Relay_Flag[0])
printf("|*** Relay CH1 on ***|\r\n");
else
printf("|*** Relay CH1 off ***|\r\n");
}
break;
case CH2:
ret = Relay_CHx_Toggle(GPIO_PIN_CH2); //Toggle the level status of the GPIO_PIN_CH2 pin
if(ret){
Relay_Flag[1] =! Relay_Flag[1];
Buzzer_Open_Time(200, 0);
if(Relay_Flag[1])
printf("|*** Relay CH2 on ***|\r\n");
else
printf("|*** Relay CH2 off ***|\r\n");
}
break;
case CH3:
ret = Relay_CHx_Toggle(GPIO_PIN_CH3); //Toggle the level status of the GPIO_PIN_CH3 pin
if(ret){
Relay_Flag[2] =! Relay_Flag[2];
Buzzer_Open_Time(200, 0);
if(Relay_Flag[2])
printf("|*** Relay CH3 on ***|\r\n");
else
printf("|*** Relay CH3 off ***|\r\n");
}
break;
case CH4:
ret = Relay_CHx_Toggle(GPIO_PIN_CH4); //Toggle the level status of the GPIO_PIN_CH4 pin
if(ret){
Relay_Flag[3] =! Relay_Flag[3];
Buzzer_Open_Time(200, 0);
if(Relay_Flag[3])
printf("|*** Relay CH4 on ***|\r\n");
else
printf("|*** Relay CH4 off ***|\r\n");
}
break;
case CH5:
ret = Relay_CHx_Toggle(GPIO_PIN_CH5); //Toggle the level status of the GPIO_PIN_CH5 pin
if(ret){
Relay_Flag[4] =! Relay_Flag[4];
Buzzer_Open_Time(200, 0);
if(Relay_Flag[4])
printf("|*** Relay CH5 on ***|\r\n");
else
printf("|*** Relay CH5 off ***|\r\n");
}
break;
case CH6:
ret = Relay_CHx_Toggle(GPIO_PIN_CH6); //Toggle the level status of the GPIO_PIN_CH6 pin
if(ret){
Relay_Flag[5] =! Relay_Flag[5];
Buzzer_Open_Time(200, 0);
if(Relay_Flag[5])
printf("|*** Relay CH6 on ***|\r\n");
else
printf("|*** Relay CH6 off ***|\r\n");
}
break;
case CH7:
ret = Relay_CHx_Toggle(GPIO_PIN_CH7); //Toggle the level status of the GPIO_PIN_CH6 pin
if(ret){
Relay_Flag[6] =! Relay_Flag[6];
Buzzer_Open_Time(200, 0);
if(Relay_Flag[6])
printf("|*** Relay CH7 on ***|\r\n");
else
printf("|*** Relay CH7 off ***|\r\n");
}
break;
case CH8:
ret = Relay_CHx_Toggle(GPIO_PIN_CH8); //Toggle the level status of the GPIO_PIN_CH6 pin
if(ret){
Relay_Flag[7] =! Relay_Flag[7];
Buzzer_Open_Time(200, 0);
if(Relay_Flag[7])
printf("|*** Relay CH8 on ***|\r\n");
else
printf("|*** Relay CH8 off ***|\r\n");
}
break;
case ALL_ON:
ret = Relay_CHxs_PinState(0xFF); // Turn on all relay
if(ret){
memset(Relay_Flag,1, sizeof(Relay_Flag));
printf("|*** Relay ALL on ***|\r\n");
Buzzer_Open_Time(500, 0);
}
break;
case ALL_OFF:
ret = Relay_CHxs_PinState(0x00); // Turn off all relay
if(ret){
memset(Relay_Flag,0, sizeof(Relay_Flag));
printf("|*** Relay ALL off ***|\r\n");
Buzzer_Open_Time(500, 150);
}
break;
default:
printf("Note : Non-instruction data was received ! - %c\r\n", buf[0]);
}
}
void Relay_Immediate(uint8_t CHx, bool State, uint8_t Mode_Flag)
{
if(!CHx || CHx > 8){
printf("Relay_Immediate(function): Incoming parameter error!!!!\r\n");
Failure_Flag = 1;
}
else{
uint8_t ret = 0;
if(Mode_Flag == DIN_Mode)
printf("DIN Data :\r\n");
else if(Mode_Flag == RTC_Mode)
printf("RTC Data :\r\n");
ret = Relay_CHx(CHx,State);
if(ret){
Relay_Flag[CHx-1] = State;
Buzzer_Open_Time(200, 0);
if(Relay_Flag[0])
printf("|*** Relay CH%d on ***|\r\n",CHx);
else
printf("|*** Relay CH%d off ***|\r\n",CHx);
}
}
}
void Relay_Immediate_CHxn(Status_adjustment * Relay_n, uint8_t Mode_Flag)
{
uint8_t ret = 0;
if(Mode_Flag == DIN_Mode)
printf("DIN Data :\r\n");
else if(Mode_Flag == RTC_Mode)
printf("RTC Data :\r\n");
for (int i = 0; i < 8; i++) {
if(Relay_n[i] == STATE_Open || Relay_n[i] == STATE_Closs){
Relay_Flag[i] = (bool)Relay_n[i];
ret = Relay_CHx(i+1,Relay_n[i]);
if(Relay_n[i] == STATE_Open)
printf("|*** Relay CH%d on ***|\r\n",i+1);
else if(Relay_n[i] == STATE_Closs)
printf("|*** Relay CH%d off ***|\r\n",i+1);
}
}
Buzzer_Open_Time(200, 0);
}
void Relay_Immediate_CHxs(uint8_t PinState, uint8_t Mode_Flag)
{
uint8_t ret = 0;
if(Mode_Flag == DIN_Mode)
printf("DIN Data :\r\n");
else if(Mode_Flag == RTC_Mode)
printf("RTC Data :\r\n");
for (int i = 0; i < 8; i++) {
Relay_Flag[i] = (PinState >> i) & 0x01; // 提取每一位并赋值
}
ret = Relay_CHxs_PinState(PinState);
if(ret){
for (int j = 0; j < 8; j++) {
if(Relay_Flag[j])
printf("|*** Relay CH%d on ***|\r\n",j+1);
else
printf("|*** Relay CH%d off ***|\r\n",j+1);
}
Buzzer_Open_Time(200, 0);
}
else
{
printf("Relay_Immediate_CHxs(function): Relay control failure!!!!\r\n");
Failure_Flag = 1;
}
}

View File

@@ -1,56 +0,0 @@
#pragma once
#include "WS_TCA9554PWR.h"
#include <HardwareSerial.h> // Reference the ESP32 built-in serial port library
#include "WS_GPIO.h"
/************************************************************* I/O *************************************************************/
#define Relay_Number_MAX 8
#define GPIO_PIN_CH1 EXIO_PIN1 // CH1 Control GPIO
#define GPIO_PIN_CH2 EXIO_PIN2 // CH2 Control GPIO
#define GPIO_PIN_CH3 EXIO_PIN3 // CH3 Control GPIO
#define GPIO_PIN_CH4 EXIO_PIN4 // CH4 Control GPIO
#define GPIO_PIN_CH5 EXIO_PIN5 // CH5 Control GPIO
#define GPIO_PIN_CH6 EXIO_PIN6 // CH6 Control GPIO
#define GPIO_PIN_CH7 EXIO_PIN7 // CH7 Control GPIO
#define GPIO_PIN_CH8 EXIO_PIN8 // CH8 Control GPIO
#define CH1 '1' // CH1 Enabled Instruction Hex : 0x31
#define CH2 '2' // CH2 Enabled Instruction Hex : 0x32
#define CH3 '3' // CH3 Enabled Instruction Hex : 0x33
#define CH4 '4' // CH4 Enabled Instruction Hex : 0x34
#define CH5 '5' // CH5 Enabled Instruction Hex : 0x35
#define CH6 '6' // CH6 Enabled Instruction Hex : 0x36
#define CH7 '7' // CH5 Enabled Instruction Hex : 0x37
#define CH8 '8' // CH6 Enabled Instruction Hex : 0x38
#define ALL_ON '9' // Start all channel instructions Hex : 0x39
#define ALL_OFF '0' // Disable all channel instructions Hex : 0x30
#define DIN_Mode 1
#define RS485_Mode 2 // Used to distinguish data sources
#define Bluetooth_Mode 3
#define WIFI_Mode 4
#define MQTT_Mode 5
#define RTC_Mode 6
typedef enum {
STATE_Closs = 0, // Closs Relay
STATE_Open = 1, // Open Relay
STATE_Retain = 2, // Stay in place
} Status_adjustment;
extern bool Relay_Flag[8]; // Relay current status flag
void Relay_Init(void);
bool Relay_Closs(uint8_t CHx);
bool Relay_Open(uint8_t CHx);
bool Relay_CHx_Toggle(uint8_t CHx);
bool Relay_CHx(uint8_t CHx, bool State);
bool Relay_CHxs_PinState(uint8_t PinState);
void Relay_Analysis(uint8_t *buf,uint8_t Mode_Flag);
void Relay_Immediate(uint8_t CHx, bool State, uint8_t Mode_Flag);
void Relay_Immediate_CHxs(uint8_t PinState, uint8_t Mode_Flag);
void Relay_Immediate_CHxn(Status_adjustment * Relay_n, uint8_t Mode_Flag);

View File

@@ -1,113 +0,0 @@
#include "WS_SD.h"
bool SDCard_Flag = 0;
bool SDCard_Finish = 0;
uint16_t SDCard_Size = 0;
uint16_t Flash_Size = 0;
void SD_Init() {
// SD MMC
if(!SD_MMC.setPins(SD_CLK_PIN, SD_CMD_PIN, SD_D0_PIN,-1,-1,-1)){
printf("SD MMC: Pin change failed!\r\n");
return;
}
if (SD_MMC.begin("/sdcard", true, true)) { // "/sdcard", true, true or "/sdcard", true, false
printf("SD card initialization successful!\r\n");
} else {
printf("SD card initialization failed!\r\n");
}
uint8_t cardType = SD_MMC.cardType();
if(cardType == CARD_NONE){
printf("No SD card attached\r\n");
return;
}
else{
printf("SD Card Type: ");
if(cardType == CARD_MMC){
printf("MMC\r\n");
} else if(cardType == CARD_SD){
printf("SDSC\r\n");
} else if(cardType == CARD_SDHC){
printf("SDHC\r\n");
} else {
printf("UNKNOWN\r\n");
}
uint64_t totalBytes = SD_MMC.totalBytes();
uint64_t usedBytes = SD_MMC.usedBytes();
SDCard_Size = totalBytes/(1024*1024);
printf("Total space: %llu\n", totalBytes);
printf("Used space: %llu\n", usedBytes);
printf("Free space: %llu\n", totalBytes - usedBytes);
}
}
bool File_Search(const char* directory, const char* fileName)
{
File Path = SD_MMC.open(directory);
if (!Path) {
printf("Path: <%s> does not exist\r\n",directory);
return false;
}
File file = Path.openNextFile();
while (file) {
if (strcmp(file.name(), fileName) == 0) {
if (strcmp(directory, "/") == 0)
printf("File '%s%s' found in root directory.\r\n",directory,fileName);
else
printf("File '%s/%s' found in root directory.\r\n",directory,fileName);
Path.close();
return true;
}
file = Path.openNextFile();
}
if (strcmp(directory, "/") == 0)
printf("File '%s%s' not found in root directory.\r\n",directory,fileName);
else
printf("File '%s/%s' not found in root directory.\r\n",directory,fileName);
Path.close();
return false;
}
uint16_t Folder_retrieval(const char* directory, const char* fileExtension, char File_Name[][100],uint16_t maxFiles)
{
File Path = SD_MMC.open(directory);
if (!Path) {
printf("Path: <%s> does not exist\r\n",directory);
return false;
}
uint16_t fileCount = 0;
char filePath[100];
File file = Path.openNextFile();
while (file && fileCount < maxFiles) {
if (!file.isDirectory() && strstr(file.name(), fileExtension)) {
strncpy(File_Name[fileCount], file.name(), sizeof(File_Name[fileCount]));
if (strcmp(directory, "/") == 0) {
snprintf(filePath, 100, "%s%s", directory, file.name());
} else {
snprintf(filePath, 100, "%s/%s", directory, file.name());
}
printf("File found: %s\r\n", filePath);
fileCount++;
}
file = Path.openNextFile();
}
Path.close();
if (fileCount > 0) {
printf("Retrieved %d mp3 files\r\n",fileCount);
return fileCount;
} else {
printf("No files with extension '%s' found in directory: %s\r\n", fileExtension, directory);
return 0;
}
}
void Flash_test()
{
printf("/********** RAM Test**********/\r\n");
// Get Flash size
uint32_t flashSize = ESP.getFlashChipSize();
Flash_Size = flashSize/1024/1024;
printf("Flash size: %d MB \r\n", flashSize/1024/1024);
printf("/******* RAM Test Over********/\r\n\r\n");
}

View File

@@ -1,18 +0,0 @@
#pragma once
#include "Arduino.h"
#include <cstring>
#include "FS.h"
#include "SD_MMC.h"
#define SD_CLK_PIN 48
#define SD_CMD_PIN 47
#define SD_D0_PIN 45
extern uint16_t SDCard_Size;
extern uint16_t Flash_Size;
void SD_Init();
void Flash_test();
bool File_Search(const char* directory, const char* fileName);
uint16_t Folder_retrieval(const char* directory, const char* fileExtension, char File_Name[][100],uint16_t maxFiles);

View File

@@ -1,8 +0,0 @@
#include "WS_Serial.h"
void Serial_Init()
{
if(RS485_CAN_Enable)
RS485_Init();
else
CAN_Init();
}

View File

@@ -1,8 +0,0 @@
#pragma once
#include "WS_Information.h"
#include "WS_RS485.h"
#include "WS_CAN.h"
void Serial_Init(); // Example Initialize the system serial port and RS485
void Serial_Loop(); // Read RS485 data, parse and control relays

View File

@@ -1,107 +0,0 @@
#include "WS_TCA9554PWR.h"
/***************************************************** Operation register REG ****************************************************/
uint8_t Read_REG(uint8_t REG) // Read the value of the TCA9554PWR register REG
{
Wire.beginTransmission(TCA9554_ADDRESS);
Wire.write(REG);
uint8_t result = Wire.endTransmission();
if (result != 0) {
printf("Data Transfer Failure !!!\r\n");
}
Wire.requestFrom(TCA9554_ADDRESS, 1);
uint8_t bitsStatus = Wire.read();
return bitsStatus;
}
uint8_t Write_REG(uint8_t REG,uint8_t Data) // Write Data to the REG register of the TCA9554PWR
{
Wire.beginTransmission(TCA9554_ADDRESS);
Wire.write(REG);
Wire.write(Data);
uint8_t result = Wire.endTransmission();
if (result != 0) {
printf("Data write failure!!!\r\n");
return -1;
}
return 0;
}
/********************************************************** Set EXIO mode **********************************************************/
void Mode_EXIO(uint8_t Pin,uint8_t State) // Set the mode of the TCA9554PWR Pin. The default is Output mode (output mode or input mode). State: 0= Output mode 1= input mode
{
uint8_t bitsStatus = Read_REG(TCA9554_CONFIG_REG);
uint8_t Data = (0x01 << (Pin-1)) | bitsStatus;
uint8_t result = Write_REG(TCA9554_CONFIG_REG,Data);
if (result != 0) {
printf("I/O Configuration Failure !!!\r\n");
}
}
void Mode_EXIOS(uint8_t PinState) // Set the mode of the 7 pins from the TCA9554PWR with PinState
{
uint8_t result = Write_REG(TCA9554_CONFIG_REG,PinState);
if (result != 0) {
printf("I/O Configuration Failure !!!\r\n");
}
}
/********************************************************** Read EXIO status **********************************************************/
uint8_t Read_EXIO(uint8_t Pin) // Read the level of the TCA9554PWR Pin
{
uint8_t inputBits = Read_REG(TCA9554_INPUT_REG);
uint8_t bitStatus = (inputBits >> (Pin-1)) & 0x01;
return bitStatus;
}
uint8_t Read_EXIOS(uint8_t REG = TCA9554_INPUT_REG) // Read the level of all pins of TCA9554PWR, the default read input level state, want to get the current IO output state, pass the parameter TCA9554_OUTPUT_REG, such as Read_EXIOS(TCA9554_OUTPUT_REG);
{
uint8_t inputBits = Read_REG(REG);
return inputBits;
}
/********************************************************** Set the EXIO output status **********************************************************/
bool Set_EXIO(uint8_t Pin,uint8_t State) // Sets the level state of the Pin without affecting the other pins
{
uint8_t Data;
if(State < 2 && Pin < 9 && Pin > 0){
uint8_t bitsStatus = Read_EXIOS(TCA9554_OUTPUT_REG);
if(State == 1)
Data = (0x01 << (Pin-1)) | bitsStatus;
else if(State == 0)
Data = (~(0x01 << (Pin-1))) & bitsStatus;
uint8_t result = Write_REG(TCA9554_OUTPUT_REG,Data);
if (result != 0) {
printf("Failed to set GPIO!!!\r\n");
return 0;
}
return 1;
}
else
{
printf("Parameter error, please enter the correct parameter!\r\n");
return 0;
}
}
bool Set_EXIOS(uint8_t PinState) // Set 7 pins to the PinState state such as :PinState=0x23, 0010 0011 state (the highest bit is not used)
{
uint8_t result = Write_REG(TCA9554_OUTPUT_REG,PinState);
if (result != 0) {
printf("Failed to set GPIO!!!\r\n");
return 0;
}
return 1;
}
/********************************************************** Flip EXIO state **********************************************************/
bool Set_Toggle(uint8_t Pin) // Flip the level of the TCA9554PWR Pin
{
uint8_t bitsStatus = Read_EXIO(Pin);
uint8_t result = Set_EXIO(Pin,(bool)!bitsStatus);
if (!result) {
printf("Failed to Toggle GPIO!!!\r\n");
return 0;
}
return 1;
}
/********************************************************* TCA9554PWR Initializes the device ***********************************************************/
void TCA9554PWR_Init(uint8_t PinMode, uint8_t PinState) // Set the seven pins to PinState state, for example :PinState=0x23, 0010 0011 State (Output mode or input mode) 0= Output mode 1= Input mode. The default value is output mode
{
Set_EXIOS(PinState);
Mode_EXIOS(PinMode);
}

View File

@@ -1,41 +0,0 @@
#pragma once
#include <stdio.h>
#include "I2C_Driver.h"
/****************************************************** The macro defines the TCA9554PWR information ******************************************************/
#define TCA9554_ADDRESS 0x20 // TCA9554PWR I2C address
#define TCA9554_INPUT_REG 0x00 // Input register,input level
#define TCA9554_OUTPUT_REG 0x01 // Output register, high and low level output
#define TCA9554_Polarity_REG 0x02 // The Polarity Inversion register (register 2) allows polarity inversion of pins defined as inputs by the Configuration register.
#define TCA9554_CONFIG_REG 0x03 // Configuration register, mode configuration
#define Low 0
#define High 1
#define EXIO_PIN1 1
#define EXIO_PIN2 2
#define EXIO_PIN3 3
#define EXIO_PIN4 4
#define EXIO_PIN5 5
#define EXIO_PIN6 6
#define EXIO_PIN7 7
#define EXIO_PIN8 8
/***************************************************** Operation register REG ****************************************************/
uint8_t Read_REG(uint8_t REG); // Read the value of the TCA9554PWR register REG
uint8_t Write_REG(uint8_t REG,uint8_t Data); // Write Data to the REG register of the TCA9554PWR
/********************************************************** Set EXIO mode **********************************************************/
void Mode_EXIO(uint8_t Pin,uint8_t State); // Set the mode of the TCA9554PWR Pin. The default is Output mode (output mode or input mode). State: 0= Output mode 1= input mode
void Mode_EXIOS(uint8_t PinState); // Set the mode of the 7 pins from the TCA9554PWR with PinState
/********************************************************** Read EXIO status **********************************************************/
uint8_t Read_EXIO(uint8_t Pin); // Read the level of the TCA9554PWR Pin
uint8_t Read_EXIOS(uint8_t REG); // Read the level of all pins of TCA9554PWR, the default read input level state, want to get the current IO output state, pass the parameter TCA9554_OUTPUT_REG, such as Read_EXIOS(TCA9554_OUTPUT_REG);
/********************************************************** Set the EXIO output status **********************************************************/
bool Set_EXIO(uint8_t Pin,uint8_t State); // Sets the level state of the Pin without affecting the other pins
bool Set_EXIOS(uint8_t PinState); // Set 7 pins to the PinState state such as :PinState=0x23, 0010 0011 state (the highest bit is not used)
/********************************************************** Flip EXIO state **********************************************************/
bool Set_Toggle(uint8_t Pin); // Flip the level of the TCA9554PWR Pin
/********************************************************* TCA9554PWR Initializes the device ***********************************************************/
void TCA9554PWR_Init(uint8_t PinMode = 0x00, uint8_t PinState = 0x00); // Set the seven pins to PinState state, for example :PinState=0x23, 0010 0011 State (the highest bit is not used) (Output mode or input mode) 0= Output mode 1= Input mode. The default value is output mode

577
src/commands.cpp Normal file
View 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 &params)
{
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 &params)
{
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 &params)
{
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 &params)
{
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 &params)
{
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 &params)
{
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 &params)
{
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 &params)
{
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 &params)
{
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 &params)
{
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 &params)
{
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 &params)
{
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 &params)
{
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 &params)
{
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 &params)
{
ArduinoJson::JsonDocument response;
response["cmd"] = "setTimeNTP";
auto &eth = 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 &params)
{
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 &params)
{
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 &params)
{
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 &params)
{
ArduinoJson::JsonDocument response;
LOG_WARN("Comand not yet implemented");
return response;
}
const ArduinoJson::JsonDocument Commands::getWaterInfo(const devices_t &dev, const ArduinoJson::JsonDocument &params)
{
ArduinoJson::JsonDocument response;
LOG_WARN("Comand not yet implemented");
return response;
}
const ArduinoJson::JsonDocument Commands::getTankInfo(const devices_t &dev, const ArduinoJson::JsonDocument &params)
{
ArduinoJson::JsonDocument response;
LOG_WARN("Comand not yet implemented");
return response;
}
const ArduinoJson::JsonDocument Commands::getRainInfo(const devices_t &dev, const ArduinoJson::JsonDocument &params)
{
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 &params)
{
ArduinoJson::JsonDocument response;
LOG_WARN("Comand not yet implemented");
return response;
}
const ArduinoJson::JsonDocument Commands::getRainOverride(const devices_t &dev, const ArduinoJson::JsonDocument &params)
{
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 &params)
{
ArduinoJson::JsonDocument response;
response["cmd"] = "getTimeDrift";
auto &eth = 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
View 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 &params);
// CONFIG //
static const ArduinoJson::JsonDocument setConfig(const devices_t &dev, const ArduinoJson::JsonDocument &params);
static const ArduinoJson::JsonDocument getConfig(const devices_t &dev, const ArduinoJson::JsonDocument &params);
// CRONJOBS //
static const ArduinoJson::JsonDocument loadCronJob(const devices_t &dev, const ArduinoJson::JsonDocument &params);
static const ArduinoJson::JsonDocument addCronJob(const devices_t &dev, const ArduinoJson::JsonDocument &params);
static const ArduinoJson::JsonDocument setCronJob(const devices_t &dev, const ArduinoJson::JsonDocument &params);
static const ArduinoJson::JsonDocument getCronJob(const devices_t &dev, const ArduinoJson::JsonDocument &params);
static const ArduinoJson::JsonDocument delCronJob(const devices_t &dev, const ArduinoJson::JsonDocument &params);
static const ArduinoJson::JsonDocument storeCronJob(const devices_t &dev, const ArduinoJson::JsonDocument &params);
// SETTERS //
static const ArduinoJson::JsonDocument resetHPcounters(const devices_t &dev, const ArduinoJson::JsonDocument &params);
static const ArduinoJson::JsonDocument setHPlimit(const devices_t &dev, const ArduinoJson::JsonDocument &params);
static const ArduinoJson::JsonDocument setHeating(const devices_t &dev, const ArduinoJson::JsonDocument &params);
static const ArduinoJson::JsonDocument setIrrigation(const devices_t &dev, const ArduinoJson::JsonDocument &params);
static const ArduinoJson::JsonDocument setRainOverride(const devices_t &dev, const ArduinoJson::JsonDocument &params);
static const ArduinoJson::JsonDocument setTimeNTP(const devices_t &dev, const ArduinoJson::JsonDocument &params);
// GETTERS //
static const ArduinoJson::JsonDocument getHPpower(const devices_t &dev, const ArduinoJson::JsonDocument &params);
static const ArduinoJson::JsonDocument getInputStatus(const devices_t &dev, const ArduinoJson::JsonDocument &params);
static const ArduinoJson::JsonDocument getOutputStatus(const devices_t &dev, const ArduinoJson::JsonDocument &params);
static const ArduinoJson::JsonDocument getTemperatures(const devices_t &dev, const ArduinoJson::JsonDocument &params);
static const ArduinoJson::JsonDocument getWaterInfo(const devices_t &dev, const ArduinoJson::JsonDocument &params);
static const ArduinoJson::JsonDocument getTankInfo(const devices_t &dev, const ArduinoJson::JsonDocument &params);
static const ArduinoJson::JsonDocument getRainInfo(const devices_t &dev, const ArduinoJson::JsonDocument &params);
static const ArduinoJson::JsonDocument getIrrigation(const devices_t &dev, const ArduinoJson::JsonDocument &params);
static const ArduinoJson::JsonDocument getRainOverride(const devices_t &dev, const ArduinoJson::JsonDocument &params);
static const ArduinoJson::JsonDocument getTimeDrift(const devices_t &dev, const ArduinoJson::JsonDocument &params);
};
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
View 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
View 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
View 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 &eth;
drivers::PCF85063 &rtc;
drivers::R4DCB08 &tmp;
drivers::S50140 &seneca;
drivers::Buzzer &buzzer;
drivers::Led &led;
digitalIO &io;
} devices_t;

368
src/digitalIO.cpp Normal file
View File

@@ -0,0 +1,368 @@
#include <digitalIO.h>
#include <utils.h>
digitalIO::digitalIO(drivers::I2C &i2c, drivers::MODBUS &bus, std::vector<uint8_t> remotes) : m_localOuts(drivers::TCA9554PWR(i2c, TCA9554_ADDRESS)), m_remoteAddrs(remotes)
{
for (uint8_t i(DI1); i < DI_MAX; i++)
{
pinMode(i, INPUT_PULLUP); // set all local pins as digitalInput
}
for (auto a : remotes)
{
m_remotes.emplace_back(a, bus);
}
LOG_INFO("Initialized digitalIO -> inputs", getInNum(), "outputs", getOutNum());
}
digitalIO::~digitalIO()
{
}
void digitalIO::digitalOutWrite(const uint8_t ch, const bool value)
{
if (ch < 0 || ch > getOutNum())
{
LOG_ERROR("Invalid digitalOutWrite channel number", ch);
return;
}
if (ch < drivers::TCA9554PWR::DO_MAX) // write to i2c device for local outputs
{
writeLocal(ch, value);
}
else
{
writeRemote(ch - drivers::TCA9554PWR::DO_MAX, value);
}
}
void digitalIO::digitalOutWritePort(const std::vector<bool> &values)
{
if (values.size() != getOutNum())
{
LOG_ERROR("Invalid digitalOutWrite channel number", values.size());
return;
}
const std::vector<bool> locals(values.begin(), values.begin() + drivers::TCA9554PWR::DO_MAX);
const std::vector<bool> remotes(values.begin() + drivers::TCA9554PWR::DO_MAX, values.end());
writeLocalPort(locals);
writeRemotePort(remotes);
}
const bool digitalIO::digitalOutRead(const uint8_t ch)
{
if (ch < 0 || ch > getOutNum())
{
LOG_ERROR("Invalid digitalOutRead channel number", ch);
return false;
}
if (ch < drivers::TCA9554PWR::DO_MAX) // write to i2c device for local outputs
{
return readLocalIn(ch);
}
else
{
return readRemoteIn(ch - drivers::TCA9554PWR::DO_MAX);
}
}
const std::vector<bool> digitalIO::digitalOutReadPort()
{
const std::vector<bool> locals(readLocalOutPort());
const std::vector<bool> remotes(readRemoteOutPort());
std::vector<bool> rv;
rv.reserve(getOutNum());
rv.insert(rv.begin(), locals.begin(), locals.end());
rv.insert(rv.end(), remotes.begin(), remotes.end());
return rv;
}
const bool digitalIO::digitalInRead(const uint8_t ch)
{
if (ch < 0 || ch > getInNum())
{
LOG_ERROR("Invalid digitalIORead channel number", ch);
}
if (ch < (DI_MAX - DI1)) // read from local inputs not as gpio numbers
{
return readLocalIn(ch);
}
else
{
return readRemoteIn(ch - (DI_MAX - DI1));
}
}
const std::vector<bool> digitalIO::digitalInReadPort()
{
const std::vector<bool> locals(readLocalInPort());
const std::vector<bool> remotes(readRemoteInPort());
std::vector<bool> rv;
rv.reserve(getInNum());
rv.insert(rv.begin(), locals.begin(), locals.end());
rv.insert(rv.end(), remotes.begin(), remotes.end());
return rv;
}
void digitalIO::reset()
{
// set all local and remote outputs to 0
m_localOuts.setPort(0x00);
for (auto r : m_remotes)
r.resetAll(false);
}
const uint8_t digitalIO::getLocalInNum()
{
return (DI_MAX - DI1);
}
const uint8_t digitalIO::getLocalOutNum()
{
return drivers::TCA9554PWR::DO_MAX;
}
const uint8_t digitalIO::getRemoteInNum()
{
return m_remotes.size() * remoteIO::CH_MAX;
}
const uint8_t digitalIO::getRemoteOutNum()
{
return m_remotes.size() * remoteIO::CH_MAX;
}
const uint8_t digitalIO::getOutNum()
{
return getLocalOutNum() + getRemoteOutNum();
}
const uint8_t digitalIO::getInNum()
{
return getLocalInNum() + getRemoteInNum();
}
void digitalIO::writeLocal(const uint8_t ch, const bool value)
{
uint8_t retries(0);
while (retries++ < c_maxRetries)
{
if (m_localOuts.setOut(ch, value))
{
LOG_DEBUG("writeLocal channel", ch, " status", value ? "True" : "False");
return;
}
LOG_ERROR("Failed writeLocal channel ", ch, " status", value ? "True" : "False");
}
}
void digitalIO::writeLocalPort(const std::vector<bool> &values)
{
uint8_t retries(0);
uint8_t decValue(0);
for (uint8_t i(0); i < 8; i++) // convert from bits to byte value
{
if (values[i])
decValue |= High << i;
}
while (retries++ < c_maxRetries)
{
if (m_localOuts.setPort(decValue))
{
LOG_DEBUG("writeLocalPort value", printBoolVec(values).c_str());
return;
}
LOG_ERROR("Failed writeLocalPort value", printBoolVec(values).c_str());
}
}
void digitalIO::writeRemote(const uint8_t ch, const bool value)
{
uint8_t retries(0);
const uint8_t selectedRemote(floor(ch / (float)remoteIO::CH_MAX));
const uint8_t selectedChannel(ch % remoteIO::CH_MAX);
while (retries++ < c_maxRetries)
{
if (m_remotes[selectedRemote].setOut((remoteIO::channel_t)selectedChannel, value))
{
LOG_DEBUG("writeRemote remote", selectedRemote, " channel ", selectedChannel, " status", value ? "True" : "False");
return;
}
LOG_ERROR("Failed writeRemote remote", selectedRemote, " channel ", selectedChannel, " status", value ? "True" : "False");
}
}
void digitalIO::writeRemotePort(const std::vector<bool> &values)
{
uint8_t retries(0);
while (retries++ < c_maxRetries)
{
bool ok(true);
for (uint8_t i(0); i < values.size(); i += remoteIO::CH_MAX)
{
const uint8_t selectedRemote(floor(i / (float)remoteIO::CH_MAX));
const std::vector<bool> currValues(values.begin() + i, values.begin() + i + remoteIO::CH_MAX);
ok &= m_remotes[selectedRemote].setOutPort(currValues);
if (ok)
{
LOG_DEBUG("writeRemotePort remote", selectedRemote, "values", printBoolVec(values).c_str());
continue;
}
LOG_ERROR("Failed writeRemotePort remote", selectedRemote, "values", printBoolVec(values).c_str());
break;
}
if (ok)
break;
}
}
const bool digitalIO::readLocalIn(const uint8_t ch)
{
bool value = !digitalRead(ch + DI1); // base pin number in enum, inverted input
LOG_DEBUG("readLocalIn pin", (ch + DI1), " status", value ? "True" : "False");
return value;
}
const bool digitalIO::readLocalOut(const uint8_t ch)
{
bool value(false);
uint8_t retries(0);
while (retries++ < c_maxRetries)
{
if (m_localOuts.readOut(ch, value))
{
LOG_DEBUG("readLocalOut pin", (ch), " status", value ? "True" : "False");
return value;
}
LOG_ERROR("Failed readLocalOut channel", ch);
}
return false;
}
const std::vector<bool> digitalIO::readLocalInPort()
{
std::vector<bool> values(getLocalInNum());
for (uint8_t i(0); i < values.size(); i++)
{
values[i] = readLocalIn(i);
}
LOG_DEBUG("readLocalInPort values", printBoolVec(values).c_str());
return values;
}
const std::vector<bool> digitalIO::readLocalOutPort()
{
uint8_t retries(0);
uint8_t state(0);
std::vector<bool> values(getLocalOutNum());
while (retries++ < c_maxRetries)
{
if (m_localOuts.readPort(state))
{
for (uint8_t i(0); i < values.size(); i++)
{
values[i] = (state >> i) & High;
}
LOG_DEBUG("readLocalOutPort values", printBoolVec(values).c_str());
return values;
}
LOG_ERROR("Failed readLocalOutPort");
}
values.clear();
return values;
}
const bool digitalIO::readRemoteIn(const uint8_t ch)
{
uint8_t retries(0);
const uint8_t selectedRemote(floor(ch / 8.0f));
const uint8_t selectedChannel(ch % remoteIO::CH_MAX);
bool value;
while (retries++ < c_maxRetries)
{
if (m_remotes[selectedRemote].getIn((remoteIO::channel_t)selectedChannel, value))
{
LOG_DEBUG("readRemoteIn remote", selectedRemote, " channel ", selectedChannel, " status", value ? "True" : "False");
return value;
}
LOG_ERROR("Failed readRemoteIn remote", selectedRemote, " channel ", selectedChannel, " status", value ? "True" : "False");
}
return false;
}
const bool digitalIO::readRemoteOut(const uint8_t ch)
{
uint8_t retries(0);
const uint8_t selectedRemote(floor(ch / (float)remoteIO::CH_MAX));
const uint8_t selectedChannel(ch % remoteIO::CH_MAX);
bool value;
while (retries++ < c_maxRetries)
{
if (m_remotes[selectedRemote].getOut((remoteIO::channel_t)selectedChannel, value))
{
LOG_DEBUG("readRemoteOut remote", selectedRemote, " channel ", selectedChannel, " status", value ? "True" : "False");
return value;
}
LOG_ERROR("Failed readRemoteOut remote", selectedRemote, " channel ", selectedChannel, " status", value ? "True" : "False");
}
return false;
}
const std::vector<bool> digitalIO::readRemoteInPort()
{
uint8_t retries(0);
std::vector<bool> values;
values.reserve(getRemoteInNum());
while (retries++ < c_maxRetries)
{
bool ok(true);
for (uint8_t i(0); i < getRemoteInNum(); i += remoteIO::CH_MAX)
{
const uint8_t selectedRemote(floor(i / (float)remoteIO::CH_MAX));
std::vector<bool> remVals(remoteIO::CH_MAX);
ok &= m_remotes[selectedRemote].getInPort(remVals);
if (ok)
{
values.insert(values.begin() + values.size(), remVals.begin(), remVals.end());
LOG_DEBUG("readRemoteInPort remote", selectedRemote, "values", printBoolVec(remVals).c_str());
continue;
}
LOG_ERROR("Failed readRemoteInPort remote", selectedRemote);
break;
}
if (ok)
return values;
}
values.clear();
return values;
}
const std::vector<bool> digitalIO::readRemoteOutPort()
{
uint8_t retries(0);
std::vector<bool> values;
values.reserve(getRemoteOutNum());
while (retries++ < c_maxRetries)
{
bool ok(true);
for (uint8_t i(0); i < getRemoteOutNum(); i += remoteIO::CH_MAX)
{
const uint8_t selectedRemote(floor(i / (float)remoteIO::CH_MAX));
std::vector<bool> remVals(remoteIO::CH_MAX);
ok &= m_remotes[selectedRemote].getOutPort(remVals);
if (ok)
{
values.insert(values.begin() + values.size(), remVals.begin(), remVals.end());
LOG_DEBUG("readRemoteOutPort remote", selectedRemote, "values", printBoolVec(remVals).c_str());
continue;
}
LOG_ERROR("Failed readRemoteOutPort remote", selectedRemote);
break;
}
if (ok)
return values;
}
values.clear();
return values;
}

74
src/digitalIO.h Normal file
View File

@@ -0,0 +1,74 @@
#pragma once
#define DEBUGLOG_DEFAULT_LOG_LEVEL_INFO
#include <DebugLog.h>
#include <Arduino.h>
#include <remoteIO.h>
#include <TCA9554PWR_Driver.h>
#define ON true
#define OFF false
class digitalIO
{
private:
enum localInputs
{
DI1 = 4, // gpio for local inputs starts at 4 as per manufacturer documentation
DI2,
DI3,
DI4,
DI5,
DI6,
DI7,
DI8,
DI_MAX
};
const uint8_t c_maxRetries = 5;
public:
digitalIO(drivers::I2C &i2c, drivers::MODBUS &bus, std::vector<uint8_t> remotes);
~digitalIO();
void digitalOutWrite(const uint8_t ch, const bool value);
void digitalOutWritePort(const std::vector<bool> &values);
const bool digitalOutRead(const uint8_t ch);
const std::vector<bool> digitalOutReadPort();
const bool digitalInRead(const uint8_t ch);
const std::vector<bool> digitalInReadPort();
void reset();
const uint8_t getOutNum();
const uint8_t getInNum();
private:
const uint8_t getLocalInNum();
const uint8_t getLocalOutNum();
const uint8_t getRemoteInNum();
const uint8_t getRemoteOutNum();
void writeLocal(const uint8_t ch, const bool value);
void writeLocalPort(const std::vector<bool> &values);
void writeRemote(const uint8_t ch, const bool value);
void writeRemotePort(const std::vector<bool> &values);
const bool readLocalIn(const uint8_t ch);
const bool readLocalOut(const uint8_t ch);
const std::vector<bool> readLocalInPort();
const std::vector<bool> readLocalOutPort();
const bool readRemoteIn(const uint8_t ch);
const bool readRemoteOut(const uint8_t ch);
const std::vector<bool> readRemoteInPort();
const std::vector<bool> readRemoteOutPort();
private:
std::vector<uint8_t> m_remoteAddrs;
drivers::TCA9554PWR m_localOuts;
std::vector<remoteIO> m_remotes;
};

243
src/main.cpp Normal file
View File

@@ -0,0 +1,243 @@
#define DEBUGLOG_DEFAULT_LOG_LEVEL_INFO
#include <Arduino.h>
#include <DebugLog.h>
#include <DebugLogEnable.h>
#include <config.h>
#include <commands.h>
#include <cronjobs.h>
#include <mqtt.h>
#include <ota.h>
#include <devices.h>
#include <utils.h>
#include <pinlist.h>
/////////////// GLOBALS ///////////////
Config &conf = Config::getInstance();
/////////////// GLOBALS ///////////////
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()
{
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);
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();
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 ////////////////
//////////////// MQTT ////////////////
auto mqtt = MQTTwrapper();
//////////////// MQTT ////////////////
//////////////// MQTT //////////////
/////////////// CALLBACK //////////////
MQTTwrapper::ActionCallback commandsCallback =
[&mqtt, &devices](const ArduinoJson::JsonDocument &doc)
{
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(
[&](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)
{
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());
break;
}
delay(250);
}
while (mqttRetries++ < conf.m_mqttRetries)
{
if (mqtt.connect())
{
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(250);
}
});
////////////////////////////////////////
///////// MAIN LOOP INSIDE LOOP ////////
////////////////////////////////////////
while (true)
{
const uint32_t start(millis());
drivers::PCF85063::datetime_t datetime;
if (!logStream.connected())
{
logStream.stop();
logStream.clearWriteError();
logStream.setConnectionTimeout(100);
logStream.connect(conf.m_mqttHost.c_str(), 9876);
LOG_WARN("TCP LogStream Connected");
}
rtc.readDatetime(datetime);
const std::string timeStr(drivers::PCF85063::datetime2str(datetime));
LOG_INFO("[", k++, "] Loop - Current Datetime UTC", timeStr.c_str());
{
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);
};
{
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);
};
if (io.digitalInRead(DI::CONFRESET)) // ROSSO - Config Reset
{
LOG_WARN("Config RESET!");
buzzer.beep(450, NOTE_E);
delay(500);
conf.resetConfig();
}
if (io.digitalInRead(DI::RESTART)) // GIALLO - Restart
{
LOG_WARN("RESTART!");
buzzer.beep(450, NOTE_D);
delay(450);
esp_restart();
}
delay(conf.m_globalLoopDelay - (start - millis())); // to avoid too fast loop, keep precise timing computing loop time
}
////////////////////////////////////////
///////// MAIN LOOP INSIDE LOOP ////////
////////////////////////////////////////
}

205
src/mqtt.cpp Normal file
View File

@@ -0,0 +1,205 @@
#include <mqtt.h>
#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(m_config.m_mqttKeepalive);
m_client.setBufferSize(BUFFER_SIZE);
getInstance(this);
}
MQTTwrapper::~MQTTwrapper()
{
disconnect();
}
const bool MQTTwrapper::connect()
{
if (!m_client.connect(m_config.m_mqttClientName.c_str()))
{
LOG_ERROR("MQTT unable to connect to host", m_config.m_mqttHost.c_str());
return false;
}
LOG_INFO("MQTT client connected to", m_config.m_mqttHost.c_str());
if (m_loopHandle == NULL)
{
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;
}
const bool MQTTwrapper::disconnect()
{
m_client.disconnect();
if (m_loopHandle)
{
vTaskDelete(m_loopHandle); // immediate terminate loop
m_loopHandle = NULL;
}
return true;
}
const bool MQTTwrapper::subscribe(const Topic &topic, const ActionCallback action)
{
if (m_actionMap.contains(topic))
{
LOG_WARN("MQTT was already subscribed to", topic.c_str());
return true;
}
if (m_client.subscribe(topic.c_str()))
{
m_actionMap[topic] = action;
LOG_INFO("MQTT subscribed to", topic.c_str());
return true;
}
LOG_ERROR("MQTT unable to subscribe to", topic.c_str());
return false;
}
const bool MQTTwrapper::unsubscribe(const Topic &topic)
{
if (!m_actionMap.contains(topic))
{
LOG_WARN("MQTT was NOT subscribed to", topic.c_str());
return false;
}
if (m_client.unsubscribe(topic.c_str()))
{
LOG_INFO("MQTT unsubscribed to", topic.c_str());
m_actionMap.erase(topic);
return true;
}
LOG_ERROR("MQTT unable to unsubscribe to", topic.c_str());
return false;
}
const bool MQTTwrapper::connected()
{
return m_loopHandle != NULL;
}
const bool MQTTwrapper::publish(const Topic &topic, const ArduinoJson::JsonDocument obj)
{
std::string message;
if (!m_client.connected())
{
LOG_ERROR("MQTT client not connected");
return false;
}
if (!ArduinoJson::serializeJson(obj, message))
{
LOG_ERROR("MQTT failed to serialize object");
return false;
}
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;
pl.resize(length + 1);
std::snprintf(pl.data(), length + 1, "%s", payload);
auto inst = getInstance();
if (inst)
{
inst->onMessage(std::string(topic), pl);
return;
}
LOG_ERROR("MQTT no client instance set");
return;
}
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());
return;
}
void MQTTwrapper::clientLoop(void *params)
{
auto wrapper = (MQTTwrapper *)(params);
auto &client = wrapper->m_client;
auto &config = wrapper->m_config;
auto &stateMap = wrapper->stateMap;
const auto loopTime = config.m_mqttLoopTime;
const auto mqttRetries = config.m_mqttRetries;
const auto clientName = config.m_mqttClientName;
uint8_t connectAttempt(0);
LOG_INFO("MQTT starting client loop");
while (connectAttempt++ < mqttRetries)
{
while (client.connected())
{
client.loop();
delay(loopTime);
}
if (client.state() != MQTT_CONNECTED)
{
LOG_ERROR("MQTT disconnect reason ", stateMap.at(client.state()).c_str());
delay(loopTime * 50);
const bool ok = client.connect(clientName.c_str());
LOG_WARN("MQTT reconnected", ok ? "True" : "False");
if (ok)
{
for (auto &v : wrapper->m_actionMap)
{
const std::string &topic(v.first);
LOG_WARN("MQTT resubscribing to", topic.c_str());
if (!wrapper->m_client.subscribe(topic.c_str()))
{
LOG_ERROR("Unable to resubscribe to", topic.c_str());
}
}
connectAttempt = 0;
}
}
}
LOG_ERROR("MQTT client loop terminated, disconnected");
wrapper->m_loopHandle = NULL;
vTaskDelete(NULL); // delete the current task
}

84
src/mqtt.h Normal file
View File

@@ -0,0 +1,84 @@
#pragma once
#define DEBUGLOG_DEFAULT_LOG_LEVEL_DEBUG
#include <DebugLog.h>
#include <Arduino.h>
#include <ArduinoJson.h>
#include <Network.h>
#include <PubSubClient.h>
#include <config.h>
#include <mutex>
#include <functional>
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 = {
{-4, "MQTT_CONNECTION_TIMEOUT"},
{-3, "MQTT_CONNECTION_LOST"},
{-2, "MQTT_CONNECT_FAILED"},
{-1, "MQTT_DISCONNECTED"},
{0, "MQTT_CONNECTED"},
{1, "MQTT_CONNECT_BAD_PROTOCOL"},
{2, "MQTT_CONNECT_BAD_CLIENT_ID"},
{3, "MQTT_CONNECT_UNAVAILABLE"},
{4, "MQTT_CONNECT_BAD_CREDENTIALS"},
{5, "MQTT_CONNECT_UNAUTHORIZED"}};
private:
static MQTTwrapper *
getInstance(MQTTwrapper *inst = nullptr)
{
static std::unique_ptr<MQTTwrapper> m_instance;
if (inst)
m_instance.reset(inst);
if (m_instance)
return m_instance.get();
return nullptr;
}
public:
MQTTwrapper();
~MQTTwrapper();
const bool connect();
const bool disconnect();
const bool connected();
const bool subscribe(const Topic &topic, const ActionCallback action);
const bool unsubscribe(const Topic &topic);
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
void onMessage(const std::string topic, const std::string message);
// infinite loop to call the client loop method in a taskHandle
static void clientLoop(void *params);
private:
const Config &m_config;
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
View 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
View 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);
};
};

114
src/remoteIO.cpp Normal file
View File

@@ -0,0 +1,114 @@
#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)
{
LOG_INFO("Initializing relay module");
std::vector<uint16_t> response;
std::lock_guard<std::mutex> lock(m_bus.getMutex());
if (!m_bus.readHoldingRegisters(m_address, REG_VERSION, 1, response))
{
LOG_ERROR("Unable to inizialize relay module");
};
LOG_INFO("Software version", std::to_string(response.at(0) / 100.0f).c_str());
m_initialized = true;
m_lastRequest = millis();
resetAll(false);
}
remoteIO::~remoteIO()
{
m_initialized = false;
resetAll(false);
}
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());
BUS_DELAY;
LOG_DEBUG("Write Channel", ch, "->", value ? "True" : "False");
return m_bus.writeCoil(m_address, REG_COILS + ch, value);
}
const bool remoteIO::toggleOut(const channel_t ch)
{
if (!m_initialized)
return false;
std::lock_guard<std::mutex> lock(m_bus.getMutex());
BUS_DELAY;
std::vector<bool> value;
if (!m_bus.readCoils(m_address, REG_COILS + ch, 1, value))
return false;
LOG_DEBUG("Toggle Channel", ch, "->", !value.front() ? "True" : "False");
return m_bus.writeCoil(m_address, REG_COILS + ch, !value.front());
}
const bool remoteIO::setOutPort(const std::vector<bool> values)
{
if (!m_initialized)
return false;
std::lock_guard<std::mutex> lock(m_bus.getMutex());
BUS_DELAY;
LOG_DEBUG("Write Port", CH_MAX);
return m_bus.writeCoils(m_address, REG_COILS, values);
}
const bool remoteIO::getOut(const channel_t ch, bool &value)
{
if (!m_initialized)
return false;
std::lock_guard<std::mutex> lock(m_bus.getMutex());
BUS_DELAY;
std::vector<bool> values;
if (!m_bus.readCoils(m_address, REG_COILS + ch, 1, values))
return false;
value = values.front();
LOG_DEBUG("Read Channel", ch, "->", value ? "True" : "False");
return true;
}
const bool remoteIO::getOutPort(std::vector<bool> &values)
{
if (!m_initialized)
return false;
std::lock_guard<std::mutex> lock(m_bus.getMutex());
BUS_DELAY;
LOG_DEBUG("Read Port", CH_MAX);
return m_bus.readCoils(m_address, REG_COILS, CH_MAX, values);
}
const bool remoteIO::getIn(const channel_t input, bool &value)
{
if (!m_initialized)
return false;
std::lock_guard<std::mutex> lock(m_bus.getMutex());
BUS_DELAY;
std::vector<bool> values;
if (!m_bus.readInputs(m_address, REG_INPUT + input, 1, values))
return false;
value = values.front();
LOG_DEBUG("Read Input", input, "->", values.front() ? "True" : "False");
return true;
}
const bool remoteIO::getInPort(std::vector<bool> &values)
{
if (!m_initialized)
return false;
std::lock_guard<std::mutex> lock(m_bus.getMutex());
BUS_DELAY;
LOG_DEBUG("Read Inputs", CH_MAX);
return m_bus.readInputs(m_address, REG_INPUT, CH_MAX, values);
}
void remoteIO::resetAll(const bool value)
{
LOG_DEBUG("Reset All ->", value ? "True" : "False");
m_bus.writeCoil(m_address, REG_ALLCOILS, value);
}
#undef BUS_DELAY

53
src/remoteIO.h Normal file
View File

@@ -0,0 +1,53 @@
#pragma once
#define DEBUGLOG_DEFAULT_LOG_LEVEL_INFO
#include <DebugLog.h>
#include <RS485_Driver.h>
#include <utils.h>
class remoteIO
{
public:
typedef enum
{
CH1,
CH2,
CH3,
CH4,
CH5,
CH6,
CH7,
CH8,
CH_MAX
} channel_t;
private:
const uint32_t c_minDelay = 100;
const uint16_t REG_VERSION = 0x8000;
const uint16_t REG_COILS = 0x0000;
const uint16_t REG_INPUT = 0x0000;
const uint16_t REG_ALLCOILS = 0x00FF;
public:
remoteIO(const uint8_t address, drivers::MODBUS &bus);
~remoteIO();
const bool setOut(const channel_t ch, const bool value);
const bool toggleOut(const channel_t ch);
const bool setOutPort(const std::vector<bool> values);
const bool getOut(const channel_t ch, bool &value);
const bool getOutPort(std::vector<bool> &values);
const bool getIn(const channel_t input, bool &value);
const bool getInPort(std::vector<bool> &values);
void resetAll(const bool value);
private:
bool m_initialized;
drivers::MODBUS &m_bus;
const uint8_t m_address;
uint32_t m_lastRequest;
};