Compare commits
52 Commits
4acce987de
...
DEPLOYED
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4a1e944ea2 | ||
|
|
a1a66ebf8e | ||
|
|
b19ed89158 | ||
|
|
25251785fa | ||
| 0e842294be | |||
| 57957740d9 | |||
|
|
25aa2d6cb6 | ||
|
|
eaa643bf3c | ||
|
|
abe0cb0839 | ||
|
|
fc2316b0f2 | ||
| fa1b288f4d | |||
|
|
1110648978 | ||
|
|
581eca124e | ||
|
|
1d1eb6fbfa | ||
|
|
ad90702ab6 | ||
|
|
448e1bad15 | ||
|
|
91f4c5c750 | ||
|
|
5459148538 | ||
|
|
74a97a7dd6 | ||
|
|
31c6cd9606 | ||
|
|
bb0832ad4f | ||
|
|
bea42c9a36 | ||
|
|
cdbc904bec | ||
|
|
07dd200de8 | ||
|
|
71c7ff8756 | ||
|
|
59d8c2c2d4 | ||
|
|
8f5615a034 | ||
|
|
16bb029e93 | ||
|
|
146a2b558b | ||
|
|
7c776e4787 | ||
|
|
e8f395f8ef | ||
|
|
52a89e58f7 | ||
|
|
b7881355a2 | ||
|
|
92de57a760 | ||
|
|
0b5d725d3a | ||
|
|
30ed0d283a | ||
|
|
3923aa3c05 | ||
|
|
53b82c32c3 | ||
|
|
bdf3b9b41a | ||
|
|
7e02f3cef2 | ||
|
|
d2eba9085e | ||
|
|
1ad98799b4 | ||
|
|
e4d28b55cb | ||
|
|
ef7b9506b6 | ||
|
|
1955b8cb39 | ||
|
|
208f5f7534 | ||
|
|
7fd4a284af | ||
|
|
8f701ce81a | ||
|
|
4b97e6535d | ||
|
|
f274970d63 | ||
|
|
3d2d44c0bb | ||
|
|
01db0e543f |
3
data/example.json
Normal file
3
data/example.json
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
{
|
||||||
|
"data": "value"
|
||||||
|
}
|
||||||
BIN
docs/ESP32_clock_adjust.xlsx
Normal file
BIN
docs/ESP32_clock_adjust.xlsx
Normal file
Binary file not shown.
BIN
docs/S3d571435154f4fceaa9234cf635d13cdI.pdf
Normal file
BIN
docs/S3d571435154f4fceaa9234cf635d13cdI.pdf
Normal file
Binary file not shown.
101
docs/commands.json
Normal file
101
docs/commands.json
Normal 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
BIN
docs/mi00383-11-en.pdf
Normal file
Binary file not shown.
BIN
docs/mi004700-i-e.pdf
Normal file
BIN
docs/mi004700-i-e.pdf
Normal file
Binary file not shown.
123
docs/response.json
Normal file
123
docs/response.json
Normal 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"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
54
esp32-s3-waveshare8.json
Normal file
54
esp32-s3-waveshare8.json
Normal file
@@ -0,0 +1,54 @@
|
|||||||
|
{
|
||||||
|
"build": {
|
||||||
|
"arduino": {
|
||||||
|
"ldscript": "esp32s3_out.ld",
|
||||||
|
"partitions": "app3M_fat9M_16MB.csv"
|
||||||
|
},
|
||||||
|
"core": "esp32",
|
||||||
|
"extra_flags": [
|
||||||
|
"-DARDUINO_ESP32S3_DEV",
|
||||||
|
"-DARDUINO_USB_MODE=1",
|
||||||
|
"-DARDUINO_RUNNING_CORE=1",
|
||||||
|
"-DARDUINO_EVENT_RUNNING_CORE=1",
|
||||||
|
"-DARDUINO_USB_CDC_ON_BOOT=1"
|
||||||
|
],
|
||||||
|
"partitions": "app3M_fat9M_16MB.csv",
|
||||||
|
"f_cpu": "240000000L",
|
||||||
|
"f_flash": "80000000L",
|
||||||
|
"flash_mode": "qio",
|
||||||
|
"hwids": [
|
||||||
|
[
|
||||||
|
"0x303A",
|
||||||
|
"0x1001"
|
||||||
|
]
|
||||||
|
],
|
||||||
|
"mcu": "esp32s3",
|
||||||
|
"variant": "esp32s3"
|
||||||
|
},
|
||||||
|
"connectivity": [
|
||||||
|
"bluetooth",
|
||||||
|
"wifi",
|
||||||
|
"ethernet"
|
||||||
|
],
|
||||||
|
"debug": {
|
||||||
|
"default_tool": "esp-builtin",
|
||||||
|
"onboard_tools": [
|
||||||
|
"esp-builtin"
|
||||||
|
],
|
||||||
|
"openocd_target": "esp32s3.cfg"
|
||||||
|
},
|
||||||
|
"frameworks": [
|
||||||
|
"arduino",
|
||||||
|
"espidf"
|
||||||
|
],
|
||||||
|
"name": "Espressif ESP32-S3-Waveshare_8RO-8DI",
|
||||||
|
"upload": {
|
||||||
|
"flash_size": "16MB",
|
||||||
|
"maximum_ram_size": 327680,
|
||||||
|
"maximum_size": 16777216,
|
||||||
|
"require_upload_port": true,
|
||||||
|
"speed": 921600
|
||||||
|
},
|
||||||
|
"url": "https://docs.espressif.com/projects/esp-idf/en/latest/esp32s3/hw-reference/esp32s3/user-guide-devkitm-1.html",
|
||||||
|
"vendor": "Espressif"
|
||||||
|
}
|
||||||
6
fatfs_partition.csv
Normal file
6
fatfs_partition.csv
Normal 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,
|
||||||
|
298
include/config.h
Normal file
298
include/config.h
Normal 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
917
include/croncpp.h
Normal file
@@ -0,0 +1,917 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <vector>
|
||||||
|
#include <string>
|
||||||
|
#include <sstream>
|
||||||
|
#include <bitset>
|
||||||
|
#include <cctype>
|
||||||
|
#include <ctime>
|
||||||
|
#include <iomanip>
|
||||||
|
#include <algorithm>
|
||||||
|
#include <chrono>
|
||||||
|
|
||||||
|
#if __cplusplus > 201402L
|
||||||
|
#include <string_view>
|
||||||
|
#define CRONCPP_IS_CPP17
|
||||||
|
#endif
|
||||||
|
|
||||||
|
namespace cron
|
||||||
|
{
|
||||||
|
#ifdef CRONCPP_IS_CPP17
|
||||||
|
#define CRONCPP_STRING_VIEW std::string_view
|
||||||
|
#define CRONCPP_STRING_VIEW_NPOS std::string_view::npos
|
||||||
|
#define CRONCPP_CONSTEXPTR constexpr
|
||||||
|
#else
|
||||||
|
#define CRONCPP_STRING_VIEW std::string const &
|
||||||
|
#define CRONCPP_STRING_VIEW_NPOS std::string::npos
|
||||||
|
#define CRONCPP_CONSTEXPTR
|
||||||
|
#endif
|
||||||
|
|
||||||
|
using cron_int = uint8_t;
|
||||||
|
|
||||||
|
constexpr std::time_t INVALID_TIME = static_cast<std::time_t>(-1);
|
||||||
|
|
||||||
|
constexpr size_t INVALID_INDEX = static_cast<size_t>(-1);
|
||||||
|
|
||||||
|
class cronexpr;
|
||||||
|
|
||||||
|
namespace detail
|
||||||
|
{
|
||||||
|
enum class cron_field
|
||||||
|
{
|
||||||
|
second,
|
||||||
|
minute,
|
||||||
|
hour_of_day,
|
||||||
|
day_of_week,
|
||||||
|
day_of_month,
|
||||||
|
month,
|
||||||
|
year
|
||||||
|
};
|
||||||
|
|
||||||
|
template <typename Traits>
|
||||||
|
static bool find_next(cronexpr const & cex,
|
||||||
|
std::tm& date,
|
||||||
|
size_t const dot);
|
||||||
|
}
|
||||||
|
|
||||||
|
struct bad_cronexpr : public std::runtime_error
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
explicit bad_cronexpr(CRONCPP_STRING_VIEW message) :
|
||||||
|
std::runtime_error(message.data())
|
||||||
|
{}
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
|
struct cron_standard_traits
|
||||||
|
{
|
||||||
|
static const cron_int CRON_MIN_SECONDS = 0;
|
||||||
|
static const cron_int CRON_MAX_SECONDS = 59;
|
||||||
|
|
||||||
|
static const cron_int CRON_MIN_MINUTES = 0;
|
||||||
|
static const cron_int CRON_MAX_MINUTES = 59;
|
||||||
|
|
||||||
|
static const cron_int CRON_MIN_HOURS = 0;
|
||||||
|
static const cron_int CRON_MAX_HOURS = 23;
|
||||||
|
|
||||||
|
static const cron_int CRON_MIN_DAYS_OF_WEEK = 0;
|
||||||
|
static const cron_int CRON_MAX_DAYS_OF_WEEK = 6;
|
||||||
|
|
||||||
|
static const cron_int CRON_MIN_DAYS_OF_MONTH = 1;
|
||||||
|
static const cron_int CRON_MAX_DAYS_OF_MONTH = 31;
|
||||||
|
|
||||||
|
static const cron_int CRON_MIN_MONTHS = 1;
|
||||||
|
static const cron_int CRON_MAX_MONTHS = 12;
|
||||||
|
|
||||||
|
static const cron_int CRON_MAX_YEARS_DIFF = 4;
|
||||||
|
|
||||||
|
#ifdef CRONCPP_IS_CPP17
|
||||||
|
static const inline std::vector<std::string> DAYS = { "SUN", "MON", "TUE", "WED", "THU", "FRI", "SAT" };
|
||||||
|
static const inline std::vector<std::string> MONTHS = { "NIL", "JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC" };
|
||||||
|
#else
|
||||||
|
static std::vector<std::string>& DAYS()
|
||||||
|
{
|
||||||
|
static std::vector<std::string> days = { "SUN", "MON", "TUE", "WED", "THU", "FRI", "SAT" };
|
||||||
|
return days;
|
||||||
|
}
|
||||||
|
|
||||||
|
static std::vector<std::string>& MONTHS()
|
||||||
|
{
|
||||||
|
static std::vector<std::string> months = { "NIL", "JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC" };
|
||||||
|
return months;
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
};
|
||||||
|
|
||||||
|
struct cron_oracle_traits
|
||||||
|
{
|
||||||
|
static const cron_int CRON_MIN_SECONDS = 0;
|
||||||
|
static const cron_int CRON_MAX_SECONDS = 59;
|
||||||
|
|
||||||
|
static const cron_int CRON_MIN_MINUTES = 0;
|
||||||
|
static const cron_int CRON_MAX_MINUTES = 59;
|
||||||
|
|
||||||
|
static const cron_int CRON_MIN_HOURS = 0;
|
||||||
|
static const cron_int CRON_MAX_HOURS = 23;
|
||||||
|
|
||||||
|
static const cron_int CRON_MIN_DAYS_OF_WEEK = 1;
|
||||||
|
static const cron_int CRON_MAX_DAYS_OF_WEEK = 7;
|
||||||
|
|
||||||
|
static const cron_int CRON_MIN_DAYS_OF_MONTH = 1;
|
||||||
|
static const cron_int CRON_MAX_DAYS_OF_MONTH = 31;
|
||||||
|
|
||||||
|
static const cron_int CRON_MIN_MONTHS = 0;
|
||||||
|
static const cron_int CRON_MAX_MONTHS = 11;
|
||||||
|
|
||||||
|
static const cron_int CRON_MAX_YEARS_DIFF = 4;
|
||||||
|
|
||||||
|
#ifdef CRONCPP_IS_CPP17
|
||||||
|
static const inline std::vector<std::string> DAYS = { "NIL", "SUN", "MON", "TUE", "WED", "THU", "FRI", "SAT" };
|
||||||
|
static const inline std::vector<std::string> MONTHS = { "JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC" };
|
||||||
|
#else
|
||||||
|
|
||||||
|
static std::vector<std::string>& DAYS()
|
||||||
|
{
|
||||||
|
static std::vector<std::string> days = { "NIL", "SUN", "MON", "TUE", "WED", "THU", "FRI", "SAT" };
|
||||||
|
return days;
|
||||||
|
}
|
||||||
|
|
||||||
|
static std::vector<std::string>& MONTHS()
|
||||||
|
{
|
||||||
|
static std::vector<std::string> months = { "JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC" };
|
||||||
|
return months;
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
};
|
||||||
|
|
||||||
|
struct cron_quartz_traits
|
||||||
|
{
|
||||||
|
static const cron_int CRON_MIN_SECONDS = 0;
|
||||||
|
static const cron_int CRON_MAX_SECONDS = 59;
|
||||||
|
|
||||||
|
static const cron_int CRON_MIN_MINUTES = 0;
|
||||||
|
static const cron_int CRON_MAX_MINUTES = 59;
|
||||||
|
|
||||||
|
static const cron_int CRON_MIN_HOURS = 0;
|
||||||
|
static const cron_int CRON_MAX_HOURS = 23;
|
||||||
|
|
||||||
|
static const cron_int CRON_MIN_DAYS_OF_WEEK = 1;
|
||||||
|
static const cron_int CRON_MAX_DAYS_OF_WEEK = 7;
|
||||||
|
|
||||||
|
static const cron_int CRON_MIN_DAYS_OF_MONTH = 1;
|
||||||
|
static const cron_int CRON_MAX_DAYS_OF_MONTH = 31;
|
||||||
|
|
||||||
|
static const cron_int CRON_MIN_MONTHS = 1;
|
||||||
|
static const cron_int CRON_MAX_MONTHS = 12;
|
||||||
|
|
||||||
|
static const cron_int CRON_MAX_YEARS_DIFF = 4;
|
||||||
|
|
||||||
|
#ifdef CRONCPP_IS_CPP17
|
||||||
|
static const inline std::vector<std::string> DAYS = { "NIL", "SUN", "MON", "TUE", "WED", "THU", "FRI", "SAT" };
|
||||||
|
static const inline std::vector<std::string> MONTHS = { "NIL", "JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC" };
|
||||||
|
#else
|
||||||
|
static std::vector<std::string>& DAYS()
|
||||||
|
{
|
||||||
|
static std::vector<std::string> days = { "NIL", "SUN", "MON", "TUE", "WED", "THU", "FRI", "SAT" };
|
||||||
|
return days;
|
||||||
|
}
|
||||||
|
|
||||||
|
static std::vector<std::string>& MONTHS()
|
||||||
|
{
|
||||||
|
static std::vector<std::string> months = { "NIL", "JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC" };
|
||||||
|
return months;
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
};
|
||||||
|
|
||||||
|
class cronexpr;
|
||||||
|
|
||||||
|
template <typename Traits = cron_standard_traits>
|
||||||
|
static cronexpr make_cron(CRONCPP_STRING_VIEW expr);
|
||||||
|
|
||||||
|
class cronexpr
|
||||||
|
{
|
||||||
|
std::bitset<60> seconds;
|
||||||
|
std::bitset<60> minutes;
|
||||||
|
std::bitset<24> hours;
|
||||||
|
std::bitset<7> days_of_week;
|
||||||
|
std::bitset<31> days_of_month;
|
||||||
|
std::bitset<12> months;
|
||||||
|
std::string expr;
|
||||||
|
|
||||||
|
friend bool operator==(cronexpr const & e1, cronexpr const & e2);
|
||||||
|
friend bool operator!=(cronexpr const & e1, cronexpr const & e2);
|
||||||
|
|
||||||
|
template <typename Traits>
|
||||||
|
friend bool detail::find_next(cronexpr const & cex,
|
||||||
|
std::tm& date,
|
||||||
|
size_t const dot);
|
||||||
|
|
||||||
|
friend std::string to_cronstr(cronexpr const& cex);
|
||||||
|
friend std::string to_string(cronexpr const & cex);
|
||||||
|
|
||||||
|
template <typename Traits>
|
||||||
|
friend cronexpr make_cron(CRONCPP_STRING_VIEW expr);
|
||||||
|
};
|
||||||
|
|
||||||
|
inline bool operator==(cronexpr const & e1, cronexpr const & e2)
|
||||||
|
{
|
||||||
|
return
|
||||||
|
e1.seconds == e2.seconds &&
|
||||||
|
e1.minutes == e2.minutes &&
|
||||||
|
e1.hours == e2.hours &&
|
||||||
|
e1.days_of_week == e2.days_of_week &&
|
||||||
|
e1.days_of_month == e2.days_of_month &&
|
||||||
|
e1.months == e2.months;
|
||||||
|
}
|
||||||
|
|
||||||
|
inline bool operator!=(cronexpr const & e1, cronexpr const & e2)
|
||||||
|
{
|
||||||
|
return !(e1 == e2);
|
||||||
|
}
|
||||||
|
|
||||||
|
inline std::string to_string(cronexpr const & cex)
|
||||||
|
{
|
||||||
|
return
|
||||||
|
cex.seconds.to_string() + " " +
|
||||||
|
cex.minutes.to_string() + " " +
|
||||||
|
cex.hours.to_string() + " " +
|
||||||
|
cex.days_of_month.to_string() + " " +
|
||||||
|
cex.months.to_string() + " " +
|
||||||
|
cex.days_of_week.to_string();
|
||||||
|
}
|
||||||
|
|
||||||
|
inline std::string to_cronstr(cronexpr const& cex)
|
||||||
|
{
|
||||||
|
return cex.expr;
|
||||||
|
}
|
||||||
|
|
||||||
|
namespace utils
|
||||||
|
{
|
||||||
|
inline std::time_t tm_to_time(std::tm& date)
|
||||||
|
{
|
||||||
|
return std::mktime(&date);
|
||||||
|
}
|
||||||
|
|
||||||
|
inline std::tm* time_to_tm(std::time_t const * date, std::tm* const out)
|
||||||
|
{
|
||||||
|
#ifdef _WIN32
|
||||||
|
errno_t err = localtime_s(out, date);
|
||||||
|
return 0 == err ? out : nullptr;
|
||||||
|
#else
|
||||||
|
return localtime_r(date, out);
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
|
||||||
|
inline std::tm to_tm(CRONCPP_STRING_VIEW time)
|
||||||
|
{
|
||||||
|
std::tm result;
|
||||||
|
#if __cplusplus > 201103L
|
||||||
|
std::istringstream str(time.data());
|
||||||
|
str.imbue(std::locale(setlocale(LC_ALL, nullptr)));
|
||||||
|
|
||||||
|
str >> std::get_time(&result, "%Y-%m-%d %H:%M:%S");
|
||||||
|
if (str.fail()) throw std::runtime_error("Parsing date failed!");
|
||||||
|
#else
|
||||||
|
int year = 1900;
|
||||||
|
int month = 1;
|
||||||
|
int day = 1;
|
||||||
|
int hour = 0;
|
||||||
|
int minute = 0;
|
||||||
|
int second = 0;
|
||||||
|
sscanf(time.data(), "%d-%d-%d %d:%d:%d", &year, &month, &day, &hour, &minute, &second);
|
||||||
|
result.tm_year = year - 1900;
|
||||||
|
result.tm_mon = month - 1;
|
||||||
|
result.tm_mday = day;
|
||||||
|
result.tm_hour = hour;
|
||||||
|
result.tm_min = minute;
|
||||||
|
result.tm_sec = second;
|
||||||
|
#endif
|
||||||
|
result.tm_isdst = -1; // DST info not available
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
inline std::string to_string(std::tm const & tm)
|
||||||
|
{
|
||||||
|
#if __cplusplus > 201103L
|
||||||
|
std::ostringstream str;
|
||||||
|
str.imbue(std::locale(setlocale(LC_ALL, nullptr)));
|
||||||
|
str << std::put_time(&tm, "%Y-%m-%d %H:%M:%S");
|
||||||
|
if (str.fail()) throw std::runtime_error("Writing date failed!");
|
||||||
|
|
||||||
|
return str.str();
|
||||||
|
#else
|
||||||
|
char buff[70] = {0};
|
||||||
|
strftime(buff, sizeof(buff), "%Y-%m-%d %H:%M:%S", &tm);
|
||||||
|
return std::string(buff);
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
|
||||||
|
inline std::string to_upper(std::string text)
|
||||||
|
{
|
||||||
|
std::transform(std::begin(text), std::end(text),
|
||||||
|
std::begin(text), [](char const c) { return static_cast<char>(std::toupper(c)); });
|
||||||
|
|
||||||
|
return text;
|
||||||
|
}
|
||||||
|
|
||||||
|
static std::vector<std::string> split(CRONCPP_STRING_VIEW text, char const delimiter)
|
||||||
|
{
|
||||||
|
std::vector<std::string> tokens;
|
||||||
|
std::string token;
|
||||||
|
std::istringstream tokenStream(text.data());
|
||||||
|
while (std::getline(tokenStream, token, delimiter))
|
||||||
|
{
|
||||||
|
tokens.push_back(token);
|
||||||
|
}
|
||||||
|
return tokens;
|
||||||
|
}
|
||||||
|
|
||||||
|
CRONCPP_CONSTEXPTR inline bool contains(CRONCPP_STRING_VIEW text, char const ch) noexcept
|
||||||
|
{
|
||||||
|
return CRONCPP_STRING_VIEW_NPOS != text.find_first_of(ch);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
namespace detail
|
||||||
|
{
|
||||||
|
|
||||||
|
inline cron_int to_cron_int(CRONCPP_STRING_VIEW text)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
return static_cast<cron_int>(std::stoul(text.data()));
|
||||||
|
}
|
||||||
|
catch (std::exception const & ex)
|
||||||
|
{
|
||||||
|
throw bad_cronexpr(ex.what());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static std::string replace_ordinals(
|
||||||
|
std::string text,
|
||||||
|
std::vector<std::string> const & replacement)
|
||||||
|
{
|
||||||
|
for (size_t i = 0; i < replacement.size(); ++i)
|
||||||
|
{
|
||||||
|
auto pos = text.find(replacement[i]);
|
||||||
|
if (std::string::npos != pos)
|
||||||
|
text.replace(pos, 3 ,std::to_string(i));
|
||||||
|
}
|
||||||
|
|
||||||
|
return text;
|
||||||
|
}
|
||||||
|
|
||||||
|
static std::pair<cron_int, cron_int> make_range(
|
||||||
|
CRONCPP_STRING_VIEW field,
|
||||||
|
cron_int const minval,
|
||||||
|
cron_int const maxval)
|
||||||
|
{
|
||||||
|
cron_int first = 0;
|
||||||
|
cron_int last = 0;
|
||||||
|
if (field.size() == 1 && field[0] == '*')
|
||||||
|
{
|
||||||
|
first = minval;
|
||||||
|
last = maxval;
|
||||||
|
}
|
||||||
|
else if (!utils::contains(field, '-'))
|
||||||
|
{
|
||||||
|
first = to_cron_int(field);
|
||||||
|
last = first;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
auto parts = utils::split(field, '-');
|
||||||
|
if (parts.size() != 2)
|
||||||
|
throw bad_cronexpr("Specified range requires two fields");
|
||||||
|
|
||||||
|
first = to_cron_int(parts[0]);
|
||||||
|
last = to_cron_int(parts[1]);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (first > maxval || last > maxval)
|
||||||
|
{
|
||||||
|
throw bad_cronexpr("Specified range exceeds maximum");
|
||||||
|
}
|
||||||
|
if (first < minval || last < minval)
|
||||||
|
{
|
||||||
|
throw bad_cronexpr("Specified range is less than minimum");
|
||||||
|
}
|
||||||
|
if (first > last)
|
||||||
|
{
|
||||||
|
throw bad_cronexpr("Specified range start exceeds range end");
|
||||||
|
}
|
||||||
|
|
||||||
|
return { first, last };
|
||||||
|
}
|
||||||
|
|
||||||
|
template <size_t N>
|
||||||
|
static void set_cron_field(
|
||||||
|
CRONCPP_STRING_VIEW value,
|
||||||
|
std::bitset<N>& target,
|
||||||
|
cron_int const minval,
|
||||||
|
cron_int const maxval)
|
||||||
|
{
|
||||||
|
if(value.length() > 0 && value[value.length()-1] == ',')
|
||||||
|
throw bad_cronexpr("Value cannot end with comma");
|
||||||
|
|
||||||
|
auto fields = utils::split(value, ',');
|
||||||
|
if (fields.empty())
|
||||||
|
throw bad_cronexpr("Expression parsing error");
|
||||||
|
|
||||||
|
for (auto const & field : fields)
|
||||||
|
{
|
||||||
|
if (!utils::contains(field, '/'))
|
||||||
|
{
|
||||||
|
#ifdef CRONCPP_IS_CPP17
|
||||||
|
auto[first, last] = detail::make_range(field, minval, maxval);
|
||||||
|
#else
|
||||||
|
auto range = detail::make_range(field, minval, maxval);
|
||||||
|
auto first = range.first;
|
||||||
|
auto last = range.second;
|
||||||
|
#endif
|
||||||
|
for (cron_int i = first - minval; i <= last - minval; ++i)
|
||||||
|
{
|
||||||
|
target.set(i);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
auto parts = utils::split(field, '/');
|
||||||
|
if (parts.size() != 2)
|
||||||
|
throw bad_cronexpr("Incrementer must have two fields");
|
||||||
|
|
||||||
|
#ifdef CRONCPP_IS_CPP17
|
||||||
|
auto[first, last] = detail::make_range(parts[0], minval, maxval);
|
||||||
|
#else
|
||||||
|
auto range = detail::make_range(parts[0], minval, maxval);
|
||||||
|
auto first = range.first;
|
||||||
|
auto last = range.second;
|
||||||
|
#endif
|
||||||
|
|
||||||
|
if (!utils::contains(parts[0], '-'))
|
||||||
|
{
|
||||||
|
last = maxval;
|
||||||
|
}
|
||||||
|
|
||||||
|
auto delta = detail::to_cron_int(parts[1]);
|
||||||
|
if(delta <= 0)
|
||||||
|
throw bad_cronexpr("Incrementer must be a positive value");
|
||||||
|
|
||||||
|
for (cron_int i = first - minval; i <= last - minval; i += delta)
|
||||||
|
{
|
||||||
|
target.set(i);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
template <typename Traits>
|
||||||
|
static void set_cron_days_of_week(
|
||||||
|
std::string value,
|
||||||
|
std::bitset<7>& target)
|
||||||
|
{
|
||||||
|
auto days = utils::to_upper(value);
|
||||||
|
auto days_replaced = detail::replace_ordinals(
|
||||||
|
days,
|
||||||
|
#ifdef CRONCPP_IS_CPP17
|
||||||
|
Traits::DAYS
|
||||||
|
#else
|
||||||
|
Traits::DAYS()
|
||||||
|
#endif
|
||||||
|
);
|
||||||
|
|
||||||
|
if (days_replaced.size() == 1 && days_replaced[0] == '?')
|
||||||
|
days_replaced[0] = '*';
|
||||||
|
|
||||||
|
set_cron_field(
|
||||||
|
days_replaced,
|
||||||
|
target,
|
||||||
|
Traits::CRON_MIN_DAYS_OF_WEEK,
|
||||||
|
Traits::CRON_MAX_DAYS_OF_WEEK);
|
||||||
|
}
|
||||||
|
|
||||||
|
template <typename Traits>
|
||||||
|
static void set_cron_days_of_month(
|
||||||
|
std::string value,
|
||||||
|
std::bitset<31>& target)
|
||||||
|
{
|
||||||
|
if (value.size() == 1 && value[0] == '?')
|
||||||
|
value[0] = '*';
|
||||||
|
|
||||||
|
set_cron_field(
|
||||||
|
value,
|
||||||
|
target,
|
||||||
|
Traits::CRON_MIN_DAYS_OF_MONTH,
|
||||||
|
Traits::CRON_MAX_DAYS_OF_MONTH);
|
||||||
|
}
|
||||||
|
|
||||||
|
template <typename Traits>
|
||||||
|
static void set_cron_month(
|
||||||
|
std::string value,
|
||||||
|
std::bitset<12>& target)
|
||||||
|
{
|
||||||
|
auto month = utils::to_upper(value);
|
||||||
|
auto month_replaced = replace_ordinals(
|
||||||
|
month,
|
||||||
|
#ifdef CRONCPP_IS_CPP17
|
||||||
|
Traits::MONTHS
|
||||||
|
#else
|
||||||
|
Traits::MONTHS()
|
||||||
|
#endif
|
||||||
|
);
|
||||||
|
|
||||||
|
set_cron_field(
|
||||||
|
month_replaced,
|
||||||
|
target,
|
||||||
|
Traits::CRON_MIN_MONTHS,
|
||||||
|
Traits::CRON_MAX_MONTHS);
|
||||||
|
}
|
||||||
|
|
||||||
|
template <size_t N>
|
||||||
|
inline size_t next_set_bit(
|
||||||
|
std::bitset<N> const & target,
|
||||||
|
size_t /*minimum*/,
|
||||||
|
size_t /*maximum*/,
|
||||||
|
size_t offset)
|
||||||
|
{
|
||||||
|
for (auto i = offset; i < N; ++i)
|
||||||
|
{
|
||||||
|
if (target.test(i)) return i;
|
||||||
|
}
|
||||||
|
|
||||||
|
return INVALID_INDEX;
|
||||||
|
}
|
||||||
|
|
||||||
|
inline void add_to_field(
|
||||||
|
std::tm& date,
|
||||||
|
cron_field const field,
|
||||||
|
int const val)
|
||||||
|
{
|
||||||
|
switch (field)
|
||||||
|
{
|
||||||
|
case cron_field::second:
|
||||||
|
date.tm_sec += val;
|
||||||
|
break;
|
||||||
|
case cron_field::minute:
|
||||||
|
date.tm_min += val;
|
||||||
|
break;
|
||||||
|
case cron_field::hour_of_day:
|
||||||
|
date.tm_hour += val;
|
||||||
|
break;
|
||||||
|
case cron_field::day_of_week:
|
||||||
|
case cron_field::day_of_month:
|
||||||
|
date.tm_mday += val;
|
||||||
|
date.tm_isdst = -1;
|
||||||
|
break;
|
||||||
|
case cron_field::month:
|
||||||
|
date.tm_mon += val;
|
||||||
|
date.tm_isdst = -1;
|
||||||
|
break;
|
||||||
|
case cron_field::year:
|
||||||
|
date.tm_year += val;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (INVALID_TIME == utils::tm_to_time(date))
|
||||||
|
throw bad_cronexpr("Invalid time expression");
|
||||||
|
}
|
||||||
|
|
||||||
|
inline void set_field(
|
||||||
|
std::tm& date,
|
||||||
|
cron_field const field,
|
||||||
|
int const val)
|
||||||
|
{
|
||||||
|
switch (field)
|
||||||
|
{
|
||||||
|
case cron_field::second:
|
||||||
|
date.tm_sec = val;
|
||||||
|
break;
|
||||||
|
case cron_field::minute:
|
||||||
|
date.tm_min = val;
|
||||||
|
break;
|
||||||
|
case cron_field::hour_of_day:
|
||||||
|
date.tm_hour = val;
|
||||||
|
break;
|
||||||
|
case cron_field::day_of_week:
|
||||||
|
date.tm_wday = val;
|
||||||
|
break;
|
||||||
|
case cron_field::day_of_month:
|
||||||
|
date.tm_mday = val;
|
||||||
|
date.tm_isdst = -1;
|
||||||
|
break;
|
||||||
|
case cron_field::month:
|
||||||
|
date.tm_mon = val;
|
||||||
|
date.tm_isdst = -1;
|
||||||
|
break;
|
||||||
|
case cron_field::year:
|
||||||
|
date.tm_year = val;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (INVALID_TIME == utils::tm_to_time(date))
|
||||||
|
throw bad_cronexpr("Invalid time expression");
|
||||||
|
}
|
||||||
|
|
||||||
|
inline void reset_field(
|
||||||
|
std::tm& date,
|
||||||
|
cron_field const field)
|
||||||
|
{
|
||||||
|
switch (field)
|
||||||
|
{
|
||||||
|
case cron_field::second:
|
||||||
|
date.tm_sec = 0;
|
||||||
|
break;
|
||||||
|
case cron_field::minute:
|
||||||
|
date.tm_min = 0;
|
||||||
|
break;
|
||||||
|
case cron_field::hour_of_day:
|
||||||
|
date.tm_hour = 0;
|
||||||
|
break;
|
||||||
|
case cron_field::day_of_week:
|
||||||
|
date.tm_wday = 0;
|
||||||
|
break;
|
||||||
|
case cron_field::day_of_month:
|
||||||
|
date.tm_mday = 1;
|
||||||
|
date.tm_isdst = -1;
|
||||||
|
break;
|
||||||
|
case cron_field::month:
|
||||||
|
date.tm_mon = 0;
|
||||||
|
date.tm_isdst = -1;
|
||||||
|
break;
|
||||||
|
case cron_field::year:
|
||||||
|
date.tm_year = 0;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (INVALID_TIME == utils::tm_to_time(date))
|
||||||
|
throw bad_cronexpr("Invalid time expression");
|
||||||
|
}
|
||||||
|
|
||||||
|
inline void reset_all_fields(
|
||||||
|
std::tm& date,
|
||||||
|
std::bitset<7> const & marked_fields)
|
||||||
|
{
|
||||||
|
for (size_t i = 0; i < marked_fields.size(); ++i)
|
||||||
|
{
|
||||||
|
if (marked_fields.test(i))
|
||||||
|
reset_field(date, static_cast<cron_field>(i));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
inline void mark_field(
|
||||||
|
std::bitset<7> & orders,
|
||||||
|
cron_field const field)
|
||||||
|
{
|
||||||
|
if (!orders.test(static_cast<size_t>(field)))
|
||||||
|
orders.set(static_cast<size_t>(field));
|
||||||
|
}
|
||||||
|
|
||||||
|
template <size_t N>
|
||||||
|
static size_t find_next(
|
||||||
|
std::bitset<N> const & target,
|
||||||
|
std::tm& date,
|
||||||
|
unsigned int const minimum,
|
||||||
|
unsigned int const maximum,
|
||||||
|
unsigned int const value,
|
||||||
|
cron_field const field,
|
||||||
|
cron_field const next_field,
|
||||||
|
std::bitset<7> const & marked_fields)
|
||||||
|
{
|
||||||
|
auto next_value = next_set_bit(target, minimum, maximum, value);
|
||||||
|
if (INVALID_INDEX == next_value)
|
||||||
|
{
|
||||||
|
add_to_field(date, next_field, 1);
|
||||||
|
reset_field(date, field);
|
||||||
|
next_value = next_set_bit(target, minimum, maximum, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (INVALID_INDEX == next_value || next_value != value)
|
||||||
|
{
|
||||||
|
set_field(date, field, static_cast<int>(next_value));
|
||||||
|
reset_all_fields(date, marked_fields);
|
||||||
|
}
|
||||||
|
|
||||||
|
return next_value;
|
||||||
|
}
|
||||||
|
|
||||||
|
template <typename Traits>
|
||||||
|
static size_t find_next_day(
|
||||||
|
std::tm& date,
|
||||||
|
std::bitset<31> const & days_of_month,
|
||||||
|
size_t day_of_month,
|
||||||
|
std::bitset<7> const & days_of_week,
|
||||||
|
size_t day_of_week,
|
||||||
|
std::bitset<7> const & marked_fields)
|
||||||
|
{
|
||||||
|
unsigned int count = 0;
|
||||||
|
unsigned int maximum = 366;
|
||||||
|
while (
|
||||||
|
(!days_of_month.test(day_of_month - Traits::CRON_MIN_DAYS_OF_MONTH) ||
|
||||||
|
!days_of_week.test(day_of_week - Traits::CRON_MIN_DAYS_OF_WEEK))
|
||||||
|
&& count++ < maximum)
|
||||||
|
{
|
||||||
|
add_to_field(date, cron_field::day_of_month, 1);
|
||||||
|
|
||||||
|
day_of_month = date.tm_mday;
|
||||||
|
day_of_week = date.tm_wday;
|
||||||
|
|
||||||
|
reset_all_fields(date, marked_fields);
|
||||||
|
}
|
||||||
|
|
||||||
|
return day_of_month;
|
||||||
|
}
|
||||||
|
|
||||||
|
template <typename Traits>
|
||||||
|
static bool find_next(cronexpr const & cex,
|
||||||
|
std::tm& date,
|
||||||
|
size_t const dot)
|
||||||
|
{
|
||||||
|
bool res = true;
|
||||||
|
|
||||||
|
std::bitset<7> marked_fields{ 0 };
|
||||||
|
std::bitset<7> empty_list{ 0 };
|
||||||
|
|
||||||
|
unsigned int second = date.tm_sec;
|
||||||
|
auto updated_second = find_next(
|
||||||
|
cex.seconds,
|
||||||
|
date,
|
||||||
|
Traits::CRON_MIN_SECONDS,
|
||||||
|
Traits::CRON_MAX_SECONDS,
|
||||||
|
second,
|
||||||
|
cron_field::second,
|
||||||
|
cron_field::minute,
|
||||||
|
empty_list);
|
||||||
|
|
||||||
|
if (second == updated_second)
|
||||||
|
{
|
||||||
|
mark_field(marked_fields, cron_field::second);
|
||||||
|
}
|
||||||
|
|
||||||
|
unsigned int minute = date.tm_min;
|
||||||
|
auto update_minute = find_next(
|
||||||
|
cex.minutes,
|
||||||
|
date,
|
||||||
|
Traits::CRON_MIN_MINUTES,
|
||||||
|
Traits::CRON_MAX_MINUTES,
|
||||||
|
minute,
|
||||||
|
cron_field::minute,
|
||||||
|
cron_field::hour_of_day,
|
||||||
|
marked_fields);
|
||||||
|
if (minute == update_minute)
|
||||||
|
{
|
||||||
|
mark_field(marked_fields, cron_field::minute);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
res = find_next<Traits>(cex, date, dot);
|
||||||
|
if (!res) return res;
|
||||||
|
}
|
||||||
|
|
||||||
|
unsigned int hour = date.tm_hour;
|
||||||
|
auto updated_hour = find_next(
|
||||||
|
cex.hours,
|
||||||
|
date,
|
||||||
|
Traits::CRON_MIN_HOURS,
|
||||||
|
Traits::CRON_MAX_HOURS,
|
||||||
|
hour,
|
||||||
|
cron_field::hour_of_day,
|
||||||
|
cron_field::day_of_week,
|
||||||
|
marked_fields);
|
||||||
|
if (hour == updated_hour)
|
||||||
|
{
|
||||||
|
mark_field(marked_fields, cron_field::hour_of_day);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
res = find_next<Traits>(cex, date, dot);
|
||||||
|
if (!res) return res;
|
||||||
|
}
|
||||||
|
|
||||||
|
unsigned int day_of_week = date.tm_wday;
|
||||||
|
unsigned int day_of_month = date.tm_mday;
|
||||||
|
auto updated_day_of_month = find_next_day<Traits>(
|
||||||
|
date,
|
||||||
|
cex.days_of_month,
|
||||||
|
day_of_month,
|
||||||
|
cex.days_of_week,
|
||||||
|
day_of_week,
|
||||||
|
marked_fields);
|
||||||
|
if (day_of_month == updated_day_of_month)
|
||||||
|
{
|
||||||
|
mark_field(marked_fields, cron_field::day_of_month);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
res = find_next<Traits>(cex, date, dot);
|
||||||
|
if (!res) return res;
|
||||||
|
}
|
||||||
|
|
||||||
|
unsigned int month = date.tm_mon;
|
||||||
|
auto updated_month = find_next(
|
||||||
|
cex.months,
|
||||||
|
date,
|
||||||
|
Traits::CRON_MIN_MONTHS,
|
||||||
|
Traits::CRON_MAX_MONTHS,
|
||||||
|
month,
|
||||||
|
cron_field::month,
|
||||||
|
cron_field::year,
|
||||||
|
marked_fields);
|
||||||
|
if (month != updated_month)
|
||||||
|
{
|
||||||
|
if (date.tm_year - dot > Traits::CRON_MAX_YEARS_DIFF)
|
||||||
|
return false;
|
||||||
|
|
||||||
|
res = find_next<Traits>(cex, date, dot);
|
||||||
|
if (!res) return res;
|
||||||
|
}
|
||||||
|
|
||||||
|
return res;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
template <typename Traits>
|
||||||
|
static cronexpr make_cron(CRONCPP_STRING_VIEW expr)
|
||||||
|
{
|
||||||
|
cronexpr cex;
|
||||||
|
|
||||||
|
if (expr.empty())
|
||||||
|
throw bad_cronexpr("Invalid empty cron expression");
|
||||||
|
|
||||||
|
auto fields = utils::split(expr, ' ');
|
||||||
|
fields.erase(
|
||||||
|
std::remove_if(std::begin(fields), std::end(fields),
|
||||||
|
[](CRONCPP_STRING_VIEW s) {return s.empty(); }),
|
||||||
|
std::end(fields));
|
||||||
|
if (fields.size() != 6)
|
||||||
|
throw bad_cronexpr("cron expression must have six fields");
|
||||||
|
|
||||||
|
detail::set_cron_field(fields[0], cex.seconds, Traits::CRON_MIN_SECONDS, Traits::CRON_MAX_SECONDS);
|
||||||
|
detail::set_cron_field(fields[1], cex.minutes, Traits::CRON_MIN_MINUTES, Traits::CRON_MAX_MINUTES);
|
||||||
|
detail::set_cron_field(fields[2], cex.hours, Traits::CRON_MIN_HOURS, Traits::CRON_MAX_HOURS);
|
||||||
|
|
||||||
|
detail::set_cron_days_of_week<Traits>(fields[5], cex.days_of_week);
|
||||||
|
|
||||||
|
detail::set_cron_days_of_month<Traits>(fields[3], cex.days_of_month);
|
||||||
|
|
||||||
|
detail::set_cron_month<Traits>(fields[4], cex.months);
|
||||||
|
|
||||||
|
cex.expr = expr;
|
||||||
|
|
||||||
|
return cex;
|
||||||
|
}
|
||||||
|
|
||||||
|
template <typename Traits = cron_standard_traits>
|
||||||
|
static std::tm cron_next(cronexpr const & cex, std::tm date)
|
||||||
|
{
|
||||||
|
time_t original = utils::tm_to_time(date);
|
||||||
|
if (INVALID_TIME == original) return {};
|
||||||
|
|
||||||
|
if (!detail::find_next<Traits>(cex, date, date.tm_year))
|
||||||
|
return {};
|
||||||
|
|
||||||
|
time_t calculated = utils::tm_to_time(date);
|
||||||
|
if (INVALID_TIME == calculated) return {};
|
||||||
|
|
||||||
|
if (calculated == original)
|
||||||
|
{
|
||||||
|
add_to_field(date, detail::cron_field::second, 1);
|
||||||
|
if (!detail::find_next<Traits>(cex, date, date.tm_year))
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
|
||||||
|
return date;
|
||||||
|
}
|
||||||
|
|
||||||
|
template <typename Traits = cron_standard_traits>
|
||||||
|
static std::time_t cron_next(cronexpr const & cex, std::time_t const & date)
|
||||||
|
{
|
||||||
|
std::tm val;
|
||||||
|
std::tm* dt = utils::time_to_tm(&date, &val);
|
||||||
|
if (dt == nullptr) return INVALID_TIME;
|
||||||
|
|
||||||
|
time_t original = utils::tm_to_time(*dt);
|
||||||
|
if (INVALID_TIME == original) return INVALID_TIME;
|
||||||
|
|
||||||
|
if(!detail::find_next<Traits>(cex, *dt, dt->tm_year))
|
||||||
|
return INVALID_TIME;
|
||||||
|
|
||||||
|
time_t calculated = utils::tm_to_time(*dt);
|
||||||
|
if (INVALID_TIME == calculated) return calculated;
|
||||||
|
|
||||||
|
if (calculated == original)
|
||||||
|
{
|
||||||
|
add_to_field(*dt, detail::cron_field::second, 1);
|
||||||
|
if(!detail::find_next<Traits>(cex, *dt, dt->tm_year))
|
||||||
|
return INVALID_TIME;
|
||||||
|
}
|
||||||
|
|
||||||
|
return utils::tm_to_time(*dt);
|
||||||
|
}
|
||||||
|
|
||||||
|
template <typename Traits = cron_standard_traits>
|
||||||
|
static std::chrono::system_clock::time_point cron_next(cronexpr const & cex, std::chrono::system_clock::time_point const & time_point) {
|
||||||
|
return std::chrono::system_clock::from_time_t(cron_next<Traits>(cex, std::chrono::system_clock::to_time_t(time_point)));
|
||||||
|
}
|
||||||
|
}
|
||||||
38
include/fsmount.h
Normal file
38
include/fsmount.h
Normal file
@@ -0,0 +1,38 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#define DEBUGLOG_DEFAULT_LOG_LEVEL_DEBUG
|
||||||
|
|
||||||
|
#include <DebugLog.h>
|
||||||
|
#include <Arduino.h>
|
||||||
|
#include <FFat.h>
|
||||||
|
#include <mutex>
|
||||||
|
|
||||||
|
class FSmount
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
FSmount()
|
||||||
|
{
|
||||||
|
if (!FFat.begin(false))
|
||||||
|
{
|
||||||
|
LOG_ERROR("Unable to mount filesystem without formatting");
|
||||||
|
if (!FFat.begin(true))
|
||||||
|
{
|
||||||
|
LOG_ERROR("Formatted and mounted filesystem");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
LOG_INFO("Local Filesystem Mounted Correctly");
|
||||||
|
const auto totalBytes = FFat.totalBytes();
|
||||||
|
const auto freeBytes = FFat.freeBytes();
|
||||||
|
const auto usedBytes = FFat.usedBytes();
|
||||||
|
const auto mountPoint = FFat.mountpoint();
|
||||||
|
LOG_INFO("Local filesystem, total", totalBytes / 1024, "KB - used", usedBytes / 1024, "KB - free", freeBytes / 1024, "KB");
|
||||||
|
LOG_INFO("Local filesystem, mountpoint", mountPoint);
|
||||||
|
}
|
||||||
|
|
||||||
|
~FSmount()
|
||||||
|
{
|
||||||
|
FFat.end(); // unmout filesystem to avoid corruption
|
||||||
|
LOG_INFO("Local Filesystem Unmounted Correctly");
|
||||||
|
}
|
||||||
|
};
|
||||||
83
lib/ETH/ETH_Driver.cpp
Normal file
83
lib/ETH/ETH_Driver.cpp
Normal 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
50
lib/ETH/ETH_Driver.h
Normal 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;
|
||||||
|
};
|
||||||
|
|
||||||
|
}
|
||||||
@@ -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", TZ*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(¤tTime);
|
|
||||||
//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);
|
|
||||||
}
|
|
||||||
@@ -1,40 +0,0 @@
|
|||||||
#pragma once
|
|
||||||
#include <Arduino.h>
|
|
||||||
#include <ETH.h>
|
|
||||||
#include <SPI.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 TZ 1 // rome
|
|
||||||
|
|
||||||
void ETH_Init(void);
|
|
||||||
void ETH_Loop(void);
|
|
||||||
void EthernetTask(void *parameter);
|
|
||||||
|
|
||||||
void Acquisition_time(void);
|
|
||||||
70
lib/GPIO/BUZZER_Driver.cpp
Normal file
70
lib/GPIO/BUZZER_Driver.cpp
Normal 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
39
lib/GPIO/BUZZER_Driver.h
Normal 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;
|
||||||
|
};
|
||||||
|
|
||||||
|
}
|
||||||
110
lib/GPIO/LED_Driver.cpp
Normal file
110
lib/GPIO/LED_Driver.cpp
Normal file
@@ -0,0 +1,110 @@
|
|||||||
|
#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;
|
||||||
|
}
|
||||||
|
|
||||||
|
Led::~Led()
|
||||||
|
{
|
||||||
|
setColor({0, 0, 0});
|
||||||
|
pinMode(c_ledPin, INPUT);
|
||||||
|
}
|
||||||
|
|
||||||
|
void Led::setColor(const color_t color)
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lock(m_ledMutex);
|
||||||
|
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);
|
||||||
|
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);
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
67
lib/GPIO/LED_Driver.h
Normal file
67
lib/GPIO/LED_Driver.h
Normal file
@@ -0,0 +1,67 @@
|
|||||||
|
#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_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 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;
|
||||||
|
|
||||||
|
std::mutex m_ledMutex;
|
||||||
|
};
|
||||||
|
|
||||||
|
}
|
||||||
@@ -9,11 +9,16 @@ namespace drivers
|
|||||||
writeRegister(TCA9554_CONFIG_REG, TCA9554_OUT_MODE); // set all pins as output (relay mode for this board)
|
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)
|
const bool TCA9554PWR::writeRegister(const uint8_t reg, const uint8_t val)
|
||||||
{
|
{
|
||||||
if (m_i2c.write(m_address, reg, {val}))
|
if (m_i2c.write(m_address, reg, {val}))
|
||||||
return true;
|
return true;
|
||||||
log_e("Unable to write register: reg[%d], val[%d] ", reg, val);
|
LOG_ERROR("Unable to write register: reg[%d], val[%d] ", reg, val);
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -25,7 +30,7 @@ namespace drivers
|
|||||||
val = data.back();
|
val = data.back();
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
log_e("Unable to read register: reg[%d]");
|
LOG_ERROR("Unable to read register: reg[%d]");
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -34,9 +39,9 @@ namespace drivers
|
|||||||
uint8_t currState(0);
|
uint8_t currState(0);
|
||||||
uint8_t newState(0);
|
uint8_t newState(0);
|
||||||
|
|
||||||
if (ch < EXIO_PIN1 || ch > EXIO_PIN8)
|
if (ch < DO1 || ch > DO8)
|
||||||
{
|
{
|
||||||
log_e("Invalid write to output channel: [%d]", ch);
|
LOG_ERROR("Invalid write to output channel: [%d]", ch);
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
if (!readPort(currState))
|
if (!readPort(currState))
|
||||||
@@ -48,32 +53,39 @@ namespace drivers
|
|||||||
return setPort(newState);
|
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)
|
const bool TCA9554PWR::setPort(const uint8_t state)
|
||||||
{
|
{
|
||||||
if (writeRegister(TCA9554_OUTPUT_REG, state))
|
if (writeRegister(TCA9554_OUTPUT_REG, state))
|
||||||
return true;
|
return true;
|
||||||
log_e("Unable to write IO port: state[%02x]", state);
|
LOG_ERROR("Unable to write IO port: state[%02x]", state);
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
const bool TCA9554PWR::readOut(const uint8_t ch)
|
const bool TCA9554PWR::readOut(const uint8_t ch, bool &state)
|
||||||
{
|
{
|
||||||
uint8_t currState(0);
|
uint8_t currState(0);
|
||||||
if (ch < EXIO_PIN1 || ch > EXIO_PIN8)
|
if (ch < DO1 || ch > DO8)
|
||||||
{
|
{
|
||||||
log_e("Invalid read to output channel: [%d]", ch);
|
LOG_ERROR("Invalid read to output channel: [%d]", ch);
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
if (!readPort(currState))
|
if (!readPort(currState))
|
||||||
return false;
|
return false;
|
||||||
return (currState && (High >> ch));
|
state = (currState && (High << ch));
|
||||||
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
const bool TCA9554PWR::readPort(uint8_t &state)
|
const bool TCA9554PWR::readPort(uint8_t &state)
|
||||||
{
|
{
|
||||||
if (readRegister(TCA9554_INPUT_REG, state))
|
if (readRegister(TCA9554_OUTPUT_REG, state))
|
||||||
return true;
|
return true;
|
||||||
log_e("Unable to read IO port: state[%02x]", state);
|
LOG_ERROR("Unable to read IO port: state[%02x]", state);
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,8 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
|
#define DEBUGLOG_DEFAULT_LOG_LEVEL_INFO
|
||||||
|
|
||||||
|
#include <DebugLog.h>
|
||||||
#include "I2C_Driver.h"
|
#include "I2C_Driver.h"
|
||||||
|
|
||||||
/****************************************************** The macro defines the TCA9554PWR information ******************************************************/
|
/****************************************************** The macro defines the TCA9554PWR information ******************************************************/
|
||||||
@@ -15,33 +19,39 @@
|
|||||||
#define Low 0x00
|
#define Low 0x00
|
||||||
#define High 0x01
|
#define High 0x01
|
||||||
|
|
||||||
#define EXIO_PIN1 0
|
|
||||||
#define EXIO_PIN2 1
|
|
||||||
#define EXIO_PIN3 2
|
|
||||||
#define EXIO_PIN4 3
|
|
||||||
#define EXIO_PIN5 4
|
|
||||||
#define EXIO_PIN6 5
|
|
||||||
#define EXIO_PIN7 6
|
|
||||||
#define EXIO_PIN8 7
|
|
||||||
|
|
||||||
namespace drivers
|
namespace drivers
|
||||||
{
|
{
|
||||||
class TCA9554PWR
|
class TCA9554PWR
|
||||||
{
|
{
|
||||||
I2C &m_i2c;
|
|
||||||
uint8_t m_address;
|
|
||||||
|
|
||||||
private:
|
|
||||||
const bool writeRegister(const uint8_t reg, const uint8_t val);
|
|
||||||
const bool readRegister(const uint8_t reg, uint8_t &val);
|
|
||||||
|
|
||||||
public:
|
public:
|
||||||
|
typedef enum
|
||||||
|
{
|
||||||
|
DO1,
|
||||||
|
DO2,
|
||||||
|
DO3,
|
||||||
|
DO4,
|
||||||
|
DO5,
|
||||||
|
DO6,
|
||||||
|
DO7,
|
||||||
|
DO8,
|
||||||
|
DO_MAX
|
||||||
|
} channel_t;
|
||||||
|
|
||||||
TCA9554PWR(I2C &i2c, const uint8_t address);
|
TCA9554PWR(I2C &i2c, const uint8_t address);
|
||||||
|
~TCA9554PWR();
|
||||||
|
|
||||||
const bool setOut(const uint8_t channel, const bool state);
|
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 setPort(const uint8_t state);
|
||||||
|
|
||||||
const bool readOut(const uint8_t channel);
|
const bool readOut(const uint8_t channel, bool &state);
|
||||||
const bool readPort(uint8_t &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);
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -3,21 +3,20 @@
|
|||||||
namespace drivers
|
namespace drivers
|
||||||
{
|
{
|
||||||
|
|
||||||
I2C::I2C()
|
I2C::I2C(): m_initialized(true)
|
||||||
{
|
{
|
||||||
Wire.begin(I2C_SDA_PIN, I2C_SCL_PIN);
|
Wire.begin(I2C_SDA_PIN, I2C_SCL_PIN);
|
||||||
isInitialized = true;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
I2C::~I2C()
|
I2C::~I2C()
|
||||||
{
|
{
|
||||||
Wire.end();
|
Wire.end();
|
||||||
isInitialized = true;
|
m_initialized = false;
|
||||||
}
|
}
|
||||||
|
|
||||||
const bool I2C::read(const uint8_t deviceAddr, const uint8_t deviceReg, const uint8_t len, std::vector<uint8_t> &data)
|
const bool I2C::read(const uint8_t deviceAddr, const uint8_t deviceReg, const uint8_t len, std::vector<uint8_t> &data)
|
||||||
{
|
{
|
||||||
busy.try_lock();
|
std::lock_guard<std::mutex> lock(m_mutex);
|
||||||
Wire.beginTransmission(deviceAddr);
|
Wire.beginTransmission(deviceAddr);
|
||||||
Wire.write(deviceReg);
|
Wire.write(deviceReg);
|
||||||
switch (Wire.endTransmission(true))
|
switch (Wire.endTransmission(true))
|
||||||
@@ -25,19 +24,19 @@ namespace drivers
|
|||||||
case 0:
|
case 0:
|
||||||
break; // no error, break switch
|
break; // no error, break switch
|
||||||
case 1:
|
case 1:
|
||||||
log_e("Data to long to fit in buffer: [%d]", len);
|
LOG_ERROR("Data to long to fit in buffer: [%d]", len);
|
||||||
case 2:
|
case 2:
|
||||||
log_e("Received NAK on address transmit");
|
LOG_ERROR("Received NAK on address transmit");
|
||||||
case 3:
|
case 3:
|
||||||
log_e("Received NAK on data transmit");
|
LOG_ERROR("Received NAK on data transmit");
|
||||||
case 4:
|
case 4:
|
||||||
log_e("Unknown Error");
|
LOG_ERROR("Unknown Error");
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
const uint8_t nBytes = Wire.requestFrom(deviceAddr, len);
|
const uint8_t nBytes = Wire.requestFrom(deviceAddr, len);
|
||||||
if (nBytes < len)
|
if (nBytes < len)
|
||||||
{
|
{
|
||||||
log_w("Received data is less than expected: len[%d], nBytes[%d]", len, nBytes);
|
LOG_ERROR("Received data is less than expected: len[%d], nBytes[%d]", len, nBytes);
|
||||||
}
|
}
|
||||||
data.clear();
|
data.clear();
|
||||||
data.resize(nBytes); // resize out buffer to received data len, no check if data len is correct
|
data.resize(nBytes); // resize out buffer to received data len, no check if data len is correct
|
||||||
@@ -45,13 +44,12 @@ namespace drivers
|
|||||||
{
|
{
|
||||||
data[i] = static_cast<uint8_t>(Wire.read());
|
data[i] = static_cast<uint8_t>(Wire.read());
|
||||||
}
|
}
|
||||||
busy.unlock();
|
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
const bool I2C::write(const uint8_t deviceAddr, const uint8_t deviceReg, const std::vector<uint8_t> &data)
|
const bool I2C::write(const uint8_t deviceAddr, const uint8_t deviceReg, const std::vector<uint8_t> &data)
|
||||||
{
|
{
|
||||||
busy.lock();
|
std::lock_guard<std::mutex> lock(m_mutex);
|
||||||
Wire.beginTransmission(deviceAddr);
|
Wire.beginTransmission(deviceAddr);
|
||||||
Wire.write(deviceReg);
|
Wire.write(deviceReg);
|
||||||
for (auto d : data)
|
for (auto d : data)
|
||||||
@@ -64,16 +62,15 @@ namespace drivers
|
|||||||
case 0:
|
case 0:
|
||||||
break; // no error, break switch
|
break; // no error, break switch
|
||||||
case 1:
|
case 1:
|
||||||
log_e("Data to long to fit in buffer: [%d]", data.size());
|
LOG_ERROR("Data to long to fit in buffer: [%d]", data.size());
|
||||||
case 2:
|
case 2:
|
||||||
log_e("Received NAK on address transmit");
|
LOG_ERROR("Received NAK on address transmit");
|
||||||
case 3:
|
case 3:
|
||||||
log_e("Received NAK on data transmit");
|
LOG_ERROR("Received NAK on data transmit");
|
||||||
case 4:
|
case 4:
|
||||||
log_e("Unknown Error");
|
LOG_ERROR("Unknown Error");
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
busy.unlock();
|
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,9 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
|
#define DEBUGLOG_DEFAULT_LOG_LEVEL_INFO
|
||||||
|
|
||||||
|
#include <DebugLog.h>
|
||||||
|
#include <Arduino.h>
|
||||||
#include <Wire.h>
|
#include <Wire.h>
|
||||||
#include <vector>
|
#include <vector>
|
||||||
#include <mutex>
|
#include <mutex>
|
||||||
@@ -11,16 +16,16 @@ namespace drivers
|
|||||||
|
|
||||||
class I2C
|
class I2C
|
||||||
{
|
{
|
||||||
private:
|
|
||||||
bool isInitialized = false;
|
|
||||||
std::mutex busy;
|
|
||||||
|
|
||||||
public:
|
public:
|
||||||
I2C(void);
|
I2C(void);
|
||||||
~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 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);
|
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;
|
||||||
};
|
};
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,32 +3,10 @@
|
|||||||
#include <cstring>
|
#include <cstring>
|
||||||
#include <endian.h>
|
#include <endian.h>
|
||||||
|
|
||||||
uint8_t data[][8] = {
|
#include <busdelay.h>
|
||||||
// ESP32-S3-POE-ETH-8DI-8RO Control Command (RS485 receiving data)
|
#include "utils.h"
|
||||||
{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
|
#define BUS_DELAY drivers::BusDelay(m_lastAccess, c_minDelay, "MODBUS")
|
||||||
{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
|
|
||||||
};
|
|
||||||
|
|
||||||
namespace drivers
|
namespace drivers
|
||||||
{
|
{
|
||||||
@@ -37,37 +15,46 @@ namespace drivers
|
|||||||
//////////// RS485 ////////////
|
//////////// RS485 ////////////
|
||||||
////////////////////////////////
|
////////////////////////////////
|
||||||
|
|
||||||
RS485::RS485(const uint32_t baud, const SerialConfig conf)
|
RS485::RS485(const uint32_t baud, const SerialConfig conf) : m_serial(Serial1)
|
||||||
{
|
{
|
||||||
log_i("Init serial port 1");
|
LOG_INFO("Init serial port 1");
|
||||||
m_serial = std::make_unique<HardwareSerial>(PORT); // RS485 is hardwired to serial port 1
|
// RS485 is hardwired to serial port 1
|
||||||
m_serial->begin(baud, conf);
|
m_serial.begin(baud, conf, 18, 17);
|
||||||
m_serial->setMode(UART_MODE_RS485_HALF_DUPLEX);
|
m_serial.setTimeout(1000);
|
||||||
|
m_serial.flush();
|
||||||
}
|
}
|
||||||
|
|
||||||
const bool RS485::write(const std::vector<uint8_t> data)
|
const bool RS485::write(const std::vector<uint8_t> data)
|
||||||
{
|
{
|
||||||
return data.size() == m_serial->write(data.data(), data.size());
|
return data.size() == m_serial.write(data.data(), data.size());
|
||||||
}
|
}
|
||||||
|
|
||||||
const bool RS485::readAll(std::vector<uint8_t> &data)
|
const bool RS485::readAll(std::vector<uint8_t> &data)
|
||||||
{
|
{
|
||||||
const uint32_t avail(m_serial->available());
|
const uint32_t avail(m_serial.available());
|
||||||
|
if (avail == 0)
|
||||||
|
return true;
|
||||||
data.resize(avail);
|
data.resize(avail);
|
||||||
return data.size() == m_serial->readBytes(data.data(), avail);
|
return data.size() == m_serial.readBytes(data.data(), avail);
|
||||||
}
|
}
|
||||||
|
|
||||||
const bool RS485::readN(const uint16_t nBytes, std::vector<uint8_t> &data)
|
const bool RS485::readN(const uint16_t nBytes, std::vector<uint8_t> &data)
|
||||||
{
|
{
|
||||||
data.resize(nBytes);
|
std::vector<uint8_t> buf;
|
||||||
return data.size() == m_serial->readBytes(data.data(), nBytes);
|
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 bool RS485::readUntil(const uint8_t ch, std::vector<uint8_t> &data)
|
||||||
{
|
{
|
||||||
const uint32_t avail(m_serial->available());
|
const uint32_t avail(m_serial.available());
|
||||||
data.resize(avail);
|
data.resize(avail);
|
||||||
m_serial->readBytesUntil(ch, data.data(), avail);
|
m_serial.readBytesUntil(ch, data.data(), avail);
|
||||||
data.shrink_to_fit();
|
data.shrink_to_fit();
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
@@ -75,100 +62,126 @@ namespace drivers
|
|||||||
////////////////////////////////
|
////////////////////////////////
|
||||||
//////////// MODBUS ////////////
|
//////////// MODBUS ////////////
|
||||||
////////////////////////////////
|
////////////////////////////////
|
||||||
|
|
||||||
MODBUS::MODBUS(const uint32_t baud, const SerialConfig conf) : RS485::RS485(baud, conf)
|
MODBUS::MODBUS(const uint32_t baud, const SerialConfig conf) : RS485::RS485(baud, conf)
|
||||||
{
|
{
|
||||||
log_i("Init MODBUS Master Mode");
|
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
|
// Func 0x01
|
||||||
const bool MODBUS::readCoils(const uint8_t device, const uint16_t reg, const uint16_t num, std::vector<bool> &coils)
|
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;
|
constexpr uint8_t func = 0x01;
|
||||||
log_d("Read coils: dev[%02x], reg[%04x], num[%d]", device, reg, num);
|
LOG_DEBUG("Read coils: dev[", printHex(device).c_str(), "], reg[", printHex(reg).c_str(), "], num[", num, "]");
|
||||||
return readBinary(func, device, reg, num, coils);
|
return readBinary(device, func, reg, num, coils);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Func 0x02
|
// Func 0x02
|
||||||
const bool MODBUS::readInputs(const uint8_t device, const uint16_t reg, const uint8_t num, std::vector<bool> &inputs)
|
const bool MODBUS::readInputs(const uint8_t device, const uint16_t reg, const uint8_t num, std::vector<bool> &inputs)
|
||||||
{
|
{
|
||||||
constexpr uint8_t func = 0x01;
|
constexpr uint8_t func = 0x02;
|
||||||
log_d("Read multi inputs: dev[%02x], reg[%04x], num[%d]", device, reg, num);
|
LOG_DEBUG("Read multi inputs: dev[", printHex(device).c_str(), "], reg[", printHex(reg).c_str(), "], num[", num, "]");
|
||||||
return readBinary(func, device, reg, num, inputs);
|
return readBinary(device, func, reg, num, inputs);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Func 0x03
|
// Func 0x03
|
||||||
const bool MODBUS::readHoldingRegisters(const uint8_t device, const uint16_t reg, const uint8_t num, std::vector<uint16_t> &values)
|
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;
|
constexpr uint8_t func = 0x03;
|
||||||
log_d("Read multi holding registers: dev[%02x], reg[%04x], num[%d]", device, reg, num);
|
LOG_DEBUG("Read multi holding registers: dev[", printHex(device).c_str(), "], reg[", printHex(reg).c_str(), "], num[", num, "]");
|
||||||
return readInteger(func, device, reg, num, values);
|
return readInteger(device, func, reg, num, values);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Func 0x04
|
// Func 0x04
|
||||||
const bool MODBUS::readInputRegisters(const uint8_t device, const uint16_t reg, const uint8_t num, std::vector<uint16_t> &values)
|
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;
|
constexpr uint8_t func = 0x04;
|
||||||
log_d("Read multi input registers: dev[%02x], reg[%04x], num[%d]", device, reg, num);
|
LOG_DEBUG("Read multi input registers: dev[", printHex(device).c_str(), "], reg[", printHex(reg).c_str(), "], num[", num, "]");
|
||||||
return readInteger(func, device, reg, num, values);
|
return readInteger(device, func, reg, num, values);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Func 0x05
|
// Func 0x05
|
||||||
const bool MODBUS::writeCoil(const uint8_t device, const uint16_t coil, const bool value)
|
const bool MODBUS::writeCoil(const uint8_t device, const uint16_t coil, const bool value)
|
||||||
{
|
{
|
||||||
constexpr uint8_t func = 0x05;
|
constexpr uint8_t func = 0x05;
|
||||||
log_d("Write single coil: dev[%02x], reg[%04x], val[...]", device, reg);
|
LOG_DEBUG("Write single coil: dev[", printHex(device).c_str(), "], coil[", printHex(coil).c_str(), "], value[", value ? "true" : "false", "]");
|
||||||
return writeBinary(device, func, coil, 1, {value});
|
return writeBinary(device, func, coil, {value});
|
||||||
}
|
}
|
||||||
|
|
||||||
// Func 0x06
|
// Func 0x06
|
||||||
const bool MODBUS::writeRegister(const uint8_t device, const uint16_t reg, const uint16_t value)
|
const bool MODBUS::writeRegister(const uint8_t device, const uint16_t reg, const uint16_t value)
|
||||||
{
|
{
|
||||||
constexpr uint8_t func = 0x06;
|
constexpr uint8_t func = 0x06;
|
||||||
log_d("Write single register: dev[%02x], reg[%04x], val[%04x]", device, reg, value);
|
LOG_DEBUG("Write single register: dev[", printHex(device).c_str(), "], reg[", printHex(reg).c_str(), "], value[", value, "]");
|
||||||
return writeInteger(device, func, reg, 1, {value});
|
return writeInteger(device, func, reg, {value}, false);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Func 0x0F
|
// Func 0x0F
|
||||||
const bool MODBUS::writeCoils(const uint8_t device, const uint16_t coils, const std::vector<bool> &values)
|
const bool MODBUS::writeCoils(const uint8_t device, const uint16_t coils, const std::vector<bool> &values)
|
||||||
{
|
{
|
||||||
constexpr uint8_t func = 0x0F;
|
constexpr uint8_t func = 0x0F;
|
||||||
log_d("Write multi coils: dev[%02x], reg[%04x], val[...]", device, reg);
|
LOG_DEBUG("Write multi coils: dev[", printHex(device).c_str(), "], start[", printHex(coils).c_str(), "], num[", values.size(), "]");
|
||||||
return writeBinary(device, func, coils, values.size(), values);
|
return writeBinary(device, func, coils, values);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Func 0x10
|
// Func 0x10
|
||||||
const bool MODBUS::writeRegisters(const uint8_t device, const uint16_t reg, const std::vector<uint16_t> &values)
|
const bool MODBUS::writeRegisters(const uint8_t device, const uint16_t reg, const std::vector<uint16_t> &values)
|
||||||
{
|
{
|
||||||
constexpr uint8_t func = 0x10;
|
constexpr uint8_t func = 0x10;
|
||||||
log_d("Write multi registers: dev[%02x], reg[%04x], val[...]", device, reg);
|
LOG_DEBUG("Write multi registers: dev[", printHex(device).c_str(), "], start[", printHex(reg).c_str(), "], num[", values.size(), "]");
|
||||||
return writeInteger(device, func, reg, values.size(), values);
|
return writeInteger(device, func, reg, values, true);
|
||||||
}
|
}
|
||||||
|
|
||||||
/////////////////////////////////////////////////////////////////
|
/////////////////////////////////////////////////////////////////
|
||||||
/////////////////////// Utility Functions ///////////////////////
|
/////////////////////// Utility Functions ///////////////////////
|
||||||
/////////////////////////////////////////////////////////////////
|
/////////////////////////////////////////////////////////////////
|
||||||
|
|
||||||
const bool MODBUS::readBinary(const uint8_t func, const uint8_t device, const uint16_t reg, const uint16_t bits, std::vector<bool> &out)
|
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)))
|
if (!write(singleRequest(device, func, reg, bits)))
|
||||||
{
|
{
|
||||||
log_e("Failed send readBinary command");
|
LOG_ERROR("Failed send readBinary command");
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
const uint16_t nRespDataBytes = 1 + (uint16_t)(bits / 8); // 1 bit for every coil, if not 8 mutiple padded with zeroes
|
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 = (RESP_HEADER_SIZE + RESP_CRC_SIZE) + nRespDataBytes; // device + function + nbytes + data[] + crc(16b)
|
const uint16_t expectedRespLen = (c_respHeaderSize + c_respCrcSize) + nRespDataBytes; // device + function + nbytes + data[] + crc(16b)
|
||||||
std::vector<uint8_t> response;
|
std::vector<uint8_t> response;
|
||||||
if (!readN(expectedRespLen, response))
|
if (!readN(expectedRespLen, response))
|
||||||
{
|
{
|
||||||
log_e("Failed receive readBinary response");
|
LOG_ERROR("Failed receive readBinary response, expected[", expectedRespLen, "], received[", response.size(), "]");
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
#ifdef DEBUGLOG_DEFAULT_LOG_LEVEL_TRACE
|
||||||
|
printBytes("readBinary Response", response);
|
||||||
|
#endif
|
||||||
|
|
||||||
// element 2 of response has the response data bytes expected
|
// element 2 of response has the response data bytes expected
|
||||||
if (response.at(2) != nRespDataBytes)
|
const uint8_t actualRespLen(response.at(2));
|
||||||
|
if (actualRespLen != nRespDataBytes)
|
||||||
{
|
{
|
||||||
log_e("Failed receive, data to short: bytes[%d], expected[%d]", response.at(2), nRespDataBytes);
|
LOG_ERROR("Failed receive, data to short: actual[", actualRespLen, "], expected[", nRespDataBytes, "]");
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -182,13 +195,12 @@ namespace drivers
|
|||||||
uint16_t bitNum(0);
|
uint16_t bitNum(0);
|
||||||
|
|
||||||
// get response data bytes excluding header and crc
|
// get response data bytes excluding header and crc
|
||||||
const std::vector<uint8_t> respData(response.begin() + RESP_HEADER_SIZE, response.end() - RESP_CRC_SIZE);
|
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 (auto it = respData.begin(); it < respData.end(); it++)
|
||||||
{
|
{
|
||||||
const auto v = *it;
|
|
||||||
for (uint8_t j(0); j < 8 && bitNum < bits; j++)
|
for (uint8_t j(0); j < 8 && bitNum < bits; j++)
|
||||||
{
|
{
|
||||||
const auto cv((0x01 << j) && v);
|
const bool cv((0x01 << j) & *it);
|
||||||
out.push_back(cv);
|
out.push_back(cv);
|
||||||
bitNum++;
|
bitNum++;
|
||||||
}
|
}
|
||||||
@@ -196,26 +208,37 @@ namespace drivers
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
const bool MODBUS::readInteger(const uint8_t func, const uint8_t device, const uint16_t reg, const uint16_t num, std::vector<uint16_t> &out)
|
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)))
|
if (!write(singleRequest(device, func, reg, num)))
|
||||||
{
|
{
|
||||||
log_e("Failed send readInteger command");
|
LOG_ERROR("Failed send readInteger command");
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
const uint16_t nRespDataBytes = num * sizeof(uint16_t);
|
const uint16_t nRespDataBytes = num * sizeof(uint16_t);
|
||||||
const uint16_t expectedRespLen = (RESP_HEADER_SIZE + RESP_CRC_SIZE) + nRespDataBytes; // device + function + nbytes + data[] + crc(16b)
|
const uint16_t expectedRespLen = (c_respHeaderSize + sizeof(crc_t)) + nRespDataBytes; // device + function + nbytes + data[] + crc(16b)
|
||||||
std::vector<uint8_t> response;
|
std::vector<uint8_t> response;
|
||||||
if (!readN(expectedRespLen, response))
|
if (!readN(expectedRespLen, response))
|
||||||
{
|
{
|
||||||
log_e("Failed receive readInteger response");
|
LOG_ERROR("Failed receive readInteger response, expected[", expectedRespLen, "], received[", response.size(), "]");
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
#ifdef DEBUGLOG_DEFAULT_LOG_LEVEL_TRACE
|
||||||
|
printBytes("readInteger Response", response);
|
||||||
|
#endif
|
||||||
|
|
||||||
// element 2 of response has the response data bytes expected
|
// element 2 of response has the response data bytes expected
|
||||||
if (response.at(2) != nRespDataBytes)
|
const uint8_t actualRespLen(response.at(2));
|
||||||
|
if (actualRespLen != nRespDataBytes)
|
||||||
{
|
{
|
||||||
log_e("Failed receive, data to short: bytes[%d], expected[%d]", response.at(2), nRespDataBytes);
|
LOG_ERROR("Failed receive, data to short: actual[", actualRespLen, "], expected[", nRespDataBytes, "]");
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -225,52 +248,70 @@ namespace drivers
|
|||||||
|
|
||||||
// extract coils data from data portion of response
|
// extract coils data from data portion of response
|
||||||
out.clear();
|
out.clear();
|
||||||
out.reserve(nRespDataBytes);
|
out.reserve(nRespDataBytes / sizeof(uint16_t));
|
||||||
// get response data bytes excluding header and crc
|
// get response data bytes excluding header and crc
|
||||||
const std::vector<uint8_t> respData(response.begin() + RESP_HEADER_SIZE, response.end() - RESP_CRC_SIZE);
|
const std::vector<uint8_t> respData(response.begin() + c_respHeaderSize, response.end() - c_respCrcSize);
|
||||||
for (auto i(0); i < nRespDataBytes; i++)
|
for (auto it = respData.begin(); it < respData.end(); it++)
|
||||||
{
|
{
|
||||||
const uint8_t hi(respData.at(i * sizeof(uint16_t)));
|
const uint8_t lo(*it++);
|
||||||
const uint8_t lo(respData.at(1 + i * sizeof(uint16_t)));
|
const uint8_t hi(*it);
|
||||||
const uint16_t val(0xFFFF & ((hi << 8) | lo));
|
const uint16_t val(0xFFFF & ((hi << 8) | lo));
|
||||||
out.push_back(be16toh(val));
|
out.push_back(be16toh(val));
|
||||||
}
|
}
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
const bool MODBUS::writeBinary(const uint8_t func, const uint8_t device, const uint16_t reg, const uint16_t bits, const std::vector<bool> &in)
|
const bool MODBUS::writeBinary(const uint8_t device, const uint8_t func, const uint16_t reg, const std::vector<bool> &in)
|
||||||
{
|
{
|
||||||
std::vector<uint16_t> bitsOut;
|
// Delay Bus Access between different devices
|
||||||
if (bits <= 1) // if single coil value must be 0x00FF[00] for on[off]
|
if (device != m_lastDevice)
|
||||||
{
|
{
|
||||||
bitsOut.push_back(htobe16(in.front() ? 0x00FF : 0x0000));
|
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
|
else // if multiple coils value is 0x01 shifted for the number of coil intended
|
||||||
{
|
{
|
||||||
const uint16_t numRegisters((uint16_t)(bits / 16) + 1);
|
const uint16_t numBytes((uint16_t)ceil(bits / 8.0f));
|
||||||
bitsOut.resize(numRegisters, 0);
|
bitsOut.resize(numBytes, 0x00);
|
||||||
for (uint16_t i(0); i < in.size(); i++)
|
for (uint16_t i(0); i < in.size(); i++)
|
||||||
{
|
{
|
||||||
if (!in[i]) // if value is false skip
|
if (!in[i]) // if value is false skip
|
||||||
continue;
|
continue;
|
||||||
const uint16_t curReg(i / 16);
|
bitsOut[i / 8] |= 0x01 << i % 8;
|
||||||
bitsOut[curReg] |= 0x01 << i % 16;
|
}
|
||||||
|
#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;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!write(multiRequest(device, func, reg, bits, bitsOut)))
|
const uint16_t expectedRespLen(sizeof(resp_t) + sizeof(crc_t));
|
||||||
{
|
|
||||||
log_e("Failed send writeBinary command");
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
const uint16_t expectedRespLen(sizeof(resp_t));
|
|
||||||
std::vector<uint8_t> response;
|
std::vector<uint8_t> response;
|
||||||
if (!readN(expectedRespLen, response))
|
if (!readN(expectedRespLen, response))
|
||||||
{
|
{
|
||||||
log_e("Failed receive writeBinary response");
|
LOG_ERROR("Failed receive writeBinary response, expected[", expectedRespLen, "], received[", response.size(), "]");
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
#ifdef DEBUGLOG_DEFAULT_LOG_LEVEL_TRACE
|
||||||
|
printBytes("writeBinary Response", response);
|
||||||
|
#endif
|
||||||
|
|
||||||
// compute crc of current message
|
// compute crc of current message
|
||||||
if (!verifyCrc(response))
|
if (!verifyCrc(response))
|
||||||
@@ -279,21 +320,53 @@ namespace drivers
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
const bool MODBUS::writeInteger(const uint8_t func, const uint8_t device, const uint16_t reg, const uint16_t num, const std::vector<uint16_t> &in)
|
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)
|
||||||
{
|
{
|
||||||
if (!write(multiRequest(device, func, reg, num, in)))
|
// Delay Bus Access between different devices
|
||||||
|
if (device != m_lastDevice)
|
||||||
{
|
{
|
||||||
log_e("Failed send writeInteger command");
|
LOG_DEBUG("MODBUS device change from ", printHex(m_lastDevice).c_str(), "to", printHex(device).c_str());
|
||||||
return false;
|
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));
|
const uint16_t expectedRespLen(sizeof(resp_t) + sizeof(crc_t));
|
||||||
std::vector<uint8_t> response;
|
std::vector<uint8_t> response;
|
||||||
if (!readN(expectedRespLen, response))
|
if (!readN(expectedRespLen, response))
|
||||||
{
|
{
|
||||||
log_e("Failed receive writeInteger response");
|
LOG_ERROR("Failed receive writeInteger response, expected[", expectedRespLen, "], received[", response.size(), "]");
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
#ifdef DEBUGLOG_DEFAULT_LOG_LEVEL_TRACE
|
||||||
|
printBytes("writeInteger Response", response);
|
||||||
|
#endif
|
||||||
|
|
||||||
// compute crc of current message
|
// compute crc of current message
|
||||||
if (!verifyCrc(response))
|
if (!verifyCrc(response))
|
||||||
@@ -314,67 +387,73 @@ namespace drivers
|
|||||||
const uint8_t crcBytes(sizeof(crc_t));
|
const uint8_t crcBytes(sizeof(crc_t));
|
||||||
|
|
||||||
// compute crc for header + data
|
// compute crc for header + data
|
||||||
m_crc.reset();
|
m_crc.restart();
|
||||||
m_crc.add((uint8_t *)&header, headerBytes); // exclude last two bytes of crc
|
m_crc.add((uint8_t *)&header, headerBytes); // exclude last two bytes of crc
|
||||||
const uint16_t crc(htole16(m_crc.calc()));
|
const uint16_t crc(htole16(m_crc.calc()));
|
||||||
|
|
||||||
std::vector<uint8_t> dataOut(headerBytes + crcBytes, 0);
|
std::vector<uint8_t> dataOut(headerBytes + crcBytes, 0);
|
||||||
std::memcpy(dataOut.data(), &header, headerBytes);
|
std::memcpy(dataOut.data(), &header, headerBytes);
|
||||||
std::memcpy(dataOut.data() + headerBytes, &crc, crcBytes);
|
std::memcpy(dataOut.data() + headerBytes, &crc, crcBytes);
|
||||||
|
|
||||||
|
#ifdef DEBUGLOG_DEFAULT_LOG_LEVEL_TRACE
|
||||||
|
printBytes("singleRequest", dataOut);
|
||||||
|
#endif
|
||||||
return dataOut;
|
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<uint16_t> &data)
|
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;
|
req_multi_t header;
|
||||||
header.device = device;
|
header.device = device;
|
||||||
header.func = func;
|
header.func = func;
|
||||||
header.reg = htobe16(reg);
|
header.reg = htobe16(reg);
|
||||||
header.qty = htobe16(qty);
|
header.qty = htobe16(qty);
|
||||||
header.bytes = (uint8_t)(data.size() * sizeof(uint16_t)); // 8 bit value
|
header.bytes = data.size(); // 8 bit value
|
||||||
|
|
||||||
// convert uint16_t values from host endianness to big endian
|
// const uint8_t headerBytes(sizeof(req_multi_t)); // sizeof not working because of memory padding
|
||||||
std::vector<uint16_t> dataBe;
|
const uint8_t headerBytes(7);
|
||||||
dataBe.reserve(data.size());
|
const uint8_t dataBytes(data.size());
|
||||||
std::for_each(data.begin(), data.end(), [&dataBe](auto v)
|
|
||||||
{ dataBe.push_back(htobe16(v)); });
|
|
||||||
|
|
||||||
const uint8_t headerBytes(sizeof(req_multi_t));
|
|
||||||
const uint8_t dataBytes(sizeof(uint16_t) * dataBe.size());
|
|
||||||
const uint8_t crcBytes(sizeof(crc_t));
|
const uint8_t crcBytes(sizeof(crc_t));
|
||||||
|
|
||||||
// compute crc for header + data
|
// compute crc for header + data
|
||||||
m_crc.reset();
|
m_crc.restart();
|
||||||
m_crc.add((uint8_t *)&header, headerBytes); // add the request excluding the CRC code
|
m_crc.add((uint8_t *)&header, headerBytes); // add the request excluding the CRC code
|
||||||
m_crc.add((uint8_t *)dataBe.data(), dataBytes);
|
m_crc.add((uint8_t *)data.data(), dataBytes);
|
||||||
const uint16_t crc(htole16(m_crc.calc()));
|
const uint16_t crc(htole16(m_crc.calc()));
|
||||||
|
|
||||||
std::vector<uint8_t> dataOut;
|
std::vector<uint8_t> dataOut;
|
||||||
dataOut.resize(headerBytes + dataBytes + crcBytes); // header message + data values + crc code
|
dataOut.resize(headerBytes + dataBytes + crcBytes); // header message + data values + crc code
|
||||||
std::memcpy(dataOut.data(), &header, headerBytes); // copy message
|
std::memcpy(dataOut.data(), &header, headerBytes); // copy message
|
||||||
std::memcpy(dataOut.data() + headerBytes, dataBe.data(), dataBytes); // copy data
|
std::memcpy(dataOut.data() + headerBytes, data.data(), dataBytes); // copy data
|
||||||
std::memcpy(dataOut.data() + headerBytes + dataBytes, &crc, crcBytes); // copy crc
|
std::memcpy(dataOut.data() + headerBytes + dataBytes, &crc, crcBytes); // copy crc
|
||||||
|
|
||||||
|
#ifdef DEBUGLOG_DEFAULT_LOG_LEVEL_TRACE
|
||||||
|
printBytes("multiRequest", dataOut);
|
||||||
|
#endif
|
||||||
return dataOut;
|
return dataOut;
|
||||||
}
|
}
|
||||||
|
|
||||||
const bool MODBUS::verifyCrc(const std::vector<uint8_t> &data)
|
const bool MODBUS::verifyCrc(const std::vector<uint8_t> &data)
|
||||||
{
|
{
|
||||||
// compute crc of current message
|
// compute crc of current message
|
||||||
m_crc.reset();
|
m_crc.restart();
|
||||||
m_crc.add(data.data(), data.size());
|
m_crc.add(data.data(), data.size() - sizeof(crc_t));
|
||||||
const uint16_t computedCrc(m_crc.calc());
|
const uint16_t computedCrc(m_crc.calc());
|
||||||
// extract crc from response
|
// extract crc from response
|
||||||
const uint16_t size(data.size());
|
const uint16_t size(data.size());
|
||||||
const uint8_t crcLo(data.at(size - 2));
|
const uint8_t crcLo(data.at(size - 2));
|
||||||
const uint8_t crcHi(data.at(size - 1));
|
const uint8_t crcHi(data.at(size - 1));
|
||||||
|
const uint16_t receivedCrc(0xFFFF & ((crcHi << 8) | crcLo));
|
||||||
|
|
||||||
// verify crc code
|
// verify crc code
|
||||||
if (highByte(computedCrc) != crcHi || lowByte(computedCrc) != crcLo)
|
if (highByte(computedCrc) != crcHi || lowByte(computedCrc) != crcLo)
|
||||||
{
|
{
|
||||||
log_e("Failed verify CRC code: comp[%04x], rec[%04x]", computedCrc, 0xFFFF & ((crcHi << 8) | crcLo));
|
LOG_ERROR("Failed verify CRC code: comp[", printHex(computedCrc).c_str(), "], rec[", printHex(receivedCrc).c_str(), "]");
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#undef BUS_DELAY
|
||||||
|
|||||||
@@ -1,29 +1,24 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
#include <HardwareSerial.h> // Reference the ESP32 built-in serial port library
|
#define DEBUGLOG_DEFAULT_LOG_LEVEL_INFO
|
||||||
|
|
||||||
|
#include <DebugLog.h>
|
||||||
#include <Arduino.h>
|
#include <Arduino.h>
|
||||||
|
#include <HardwareSerial.h> // Reference the ESP32 built-in serial port library
|
||||||
#include <CRC16.h>
|
#include <CRC16.h>
|
||||||
#include <memory>
|
#include <memory>
|
||||||
|
#include <mutex>
|
||||||
#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
|
|
||||||
|
|
||||||
namespace drivers
|
namespace drivers
|
||||||
{
|
{
|
||||||
class RS485
|
class RS485
|
||||||
{
|
{
|
||||||
static const uint8_t PORT = 1;
|
const uint8_t c_port = 1;
|
||||||
|
|
||||||
public:
|
public:
|
||||||
RS485(const uint32_t baud, const SerialConfig conf);
|
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 write(const std::vector<uint8_t> data);
|
||||||
const bool readAll(std::vector<uint8_t> &data);
|
const bool readAll(std::vector<uint8_t> &data);
|
||||||
@@ -31,14 +26,15 @@ namespace drivers
|
|||||||
const bool readUntil(const uint8_t ch, std::vector<uint8_t> &data);
|
const bool readUntil(const uint8_t ch, std::vector<uint8_t> &data);
|
||||||
|
|
||||||
private:
|
private:
|
||||||
std::unique_ptr<HardwareSerial> m_serial;
|
HardwareSerial &m_serial;
|
||||||
};
|
};
|
||||||
|
|
||||||
class MODBUS : public RS485
|
class MODBUS : private RS485
|
||||||
{
|
{
|
||||||
|
|
||||||
static const uint8_t RESP_HEADER_SIZE = 3;
|
const uint8_t c_respHeaderSize = 3;
|
||||||
static const uint8_t RESP_CRC_SIZE = 2;
|
const uint8_t c_respCrcSize = 2;
|
||||||
|
const uint32_t c_minDelay = 250;
|
||||||
|
|
||||||
typedef struct
|
typedef struct
|
||||||
{
|
{
|
||||||
@@ -62,6 +58,12 @@ namespace drivers
|
|||||||
|
|
||||||
public:
|
public:
|
||||||
MODBUS(const uint32_t baud, const SerialConfig conf);
|
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
|
// Func 0x01
|
||||||
const bool readCoils(const uint8_t device, const uint16_t reg, const uint16_t num, std::vector<bool> &coils);
|
const bool readCoils(const uint8_t device, const uint16_t reg, const uint16_t num, std::vector<bool> &coils);
|
||||||
@@ -89,12 +91,16 @@ namespace drivers
|
|||||||
|
|
||||||
private:
|
private:
|
||||||
CRC16 m_crc;
|
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> 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<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 func, const uint8_t device, const uint16_t reg, const uint16_t bits, std::vector<bool> &out);
|
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 func, const uint8_t device, const uint16_t reg, const uint16_t num, std::vector<uint16_t> &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 func, const uint8_t device, const uint16_t reg, const uint16_t bits, const std::vector<bool> &in);
|
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 func, const uint8_t device, const uint16_t reg, const uint16_t num, const std::vector<uint16_t> &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);
|
const bool verifyCrc(const std::vector<uint8_t> &data);
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
37
lib/RS485/busdelay.h
Normal file
37
lib/RS485/busdelay.h
Normal file
@@ -0,0 +1,37 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#define DEBUGLOG_DEFAULT_LOG_LEVEL_INFO
|
||||||
|
|
||||||
|
#include <DebugLog.h>
|
||||||
|
#include <Arduino.h>
|
||||||
|
|
||||||
|
namespace drivers
|
||||||
|
{
|
||||||
|
|
||||||
|
class BusDelay
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
BusDelay(uint32_t &lastAccess, const uint32_t minDelay, const char *title) : m_lastAccess(lastAccess)
|
||||||
|
{
|
||||||
|
const uint32_t now = millis();
|
||||||
|
const uint32_t wait = now - lastAccess;
|
||||||
|
if (wait < minDelay)
|
||||||
|
{
|
||||||
|
LOG_DEBUG(title, "delay", wait);
|
||||||
|
delay(wait);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
BusDelay(BusDelay &) = delete;
|
||||||
|
BusDelay operator=(BusDelay &) = delete;
|
||||||
|
|
||||||
|
~BusDelay()
|
||||||
|
{
|
||||||
|
m_lastAccess = millis();
|
||||||
|
}
|
||||||
|
|
||||||
|
private:
|
||||||
|
uint32_t &m_lastAccess;
|
||||||
|
};
|
||||||
|
|
||||||
|
}
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
#include "WS_PCF85063.h"
|
#include "PCF85063_Driver.h"
|
||||||
#include <ctime>
|
#include <ctime>
|
||||||
|
#include <utils.h>
|
||||||
|
|
||||||
namespace drivers
|
namespace drivers
|
||||||
{
|
{
|
||||||
@@ -18,16 +19,16 @@ namespace drivers
|
|||||||
success &= m_i2c.write(m_address, RTC_CTRL_2_ADDR, {def_conf2});
|
success &= m_i2c.write(m_address, RTC_CTRL_2_ADDR, {def_conf2});
|
||||||
}
|
}
|
||||||
if (!success)
|
if (!success)
|
||||||
log_e("RTC Init Failure");
|
LOG_ERROR("RTC Init Failure");
|
||||||
}
|
}
|
||||||
|
|
||||||
const bool PCF85063::reset(void)
|
const bool PCF85063::reset(void)
|
||||||
{
|
{
|
||||||
log_i("RTC Reset Initiated");
|
LOG_INFO("RTC Reset Initiated");
|
||||||
const uint8_t cfg = RTC_CTRL_1_DEFAULT | RTC_CTRL_1_CAP_SEL | RTC_CTRL_1_SR;
|
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}))
|
if (m_i2c.write(m_address, RTC_CTRL_1_ADDR, {cfg}))
|
||||||
return true;
|
return true;
|
||||||
log_e("RTC Reset Failure");
|
LOG_ERROR("RTC Reset Failure");
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -39,7 +40,7 @@ namespace drivers
|
|||||||
decToBcd(time.hour)};
|
decToBcd(time.hour)};
|
||||||
if (m_i2c.write(m_address, RTC_SECOND_ADDR, buf))
|
if (m_i2c.write(m_address, RTC_SECOND_ADDR, buf))
|
||||||
return true;
|
return true;
|
||||||
log_e("RTC setTime failure");
|
LOG_ERROR("RTC setTime failure");
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -52,7 +53,7 @@ namespace drivers
|
|||||||
decToBcd(date.year - YEAR_OFFSET)};
|
decToBcd(date.year - YEAR_OFFSET)};
|
||||||
if (m_i2c.write(m_address, RTC_DAY_ADDR, buf))
|
if (m_i2c.write(m_address, RTC_DAY_ADDR, buf))
|
||||||
return true;
|
return true;
|
||||||
log_e("RTC setDate failure");
|
LOG_ERROR("RTC setDate failure");
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -72,7 +73,7 @@ namespace drivers
|
|||||||
datetime.year = bcdToDec(buf[3]) + YEAR_OFFSET;
|
datetime.year = bcdToDec(buf[3]) + YEAR_OFFSET;
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
log_e("RTC readDate Failure");
|
LOG_ERROR("RTC readDate Failure");
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -86,7 +87,7 @@ namespace drivers
|
|||||||
datetime.hour = bcdToDec(buf[2] & 0x3F);
|
datetime.hour = bcdToDec(buf[2] & 0x3F);
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
log_e("RTC readTime Failure");
|
LOG_ERROR("RTC readTime Failure");
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -110,7 +111,7 @@ namespace drivers
|
|||||||
|
|
||||||
if (m_i2c.write(m_address, RTC_CTRL_2_ADDR, currStatus))
|
if (m_i2c.write(m_address, RTC_CTRL_2_ADDR, currStatus))
|
||||||
return true;
|
return true;
|
||||||
log_e("RTC enableAlarm failure");
|
LOG_ERROR("RTC enableAlarm failure");
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -125,7 +126,7 @@ namespace drivers
|
|||||||
};
|
};
|
||||||
if (m_i2c.write(m_address, RTC_SECOND_ALARM, buf))
|
if (m_i2c.write(m_address, RTC_SECOND_ALARM, buf))
|
||||||
return true;
|
return true;
|
||||||
log_e("RTC setAlarm failure");
|
LOG_ERROR("RTC setAlarm failure");
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -141,7 +142,7 @@ namespace drivers
|
|||||||
time.dotw = (uint8_t)bcdToDec(buf[4] & 0x07);
|
time.dotw = (uint8_t)bcdToDec(buf[4] & 0x07);
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
log_e("RTC readAlarm failure");
|
LOG_ERROR("RTC readAlarm failure");
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -153,11 +154,62 @@ namespace drivers
|
|||||||
flags = buf.at(0);
|
flags = buf.at(0);
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
log_e("RTC readAlarmFlags failure");
|
LOG_ERROR("RTC readAlarmFlags failure");
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
const std::string PCF85063::datetime2str(datetime_t &datetime)
|
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(¤tTime);
|
||||||
|
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;
|
tm dtime;
|
||||||
dtime.tm_sec = datetime.second;
|
dtime.tm_sec = datetime.second;
|
||||||
@@ -165,9 +217,9 @@ namespace drivers
|
|||||||
dtime.tm_hour = datetime.hour;
|
dtime.tm_hour = datetime.hour;
|
||||||
dtime.tm_wday = datetime.dotw;
|
dtime.tm_wday = datetime.dotw;
|
||||||
dtime.tm_mday = datetime.day;
|
dtime.tm_mday = datetime.day;
|
||||||
dtime.tm_mon = datetime.month;
|
dtime.tm_mon = datetime.month - 1;
|
||||||
dtime.tm_year = datetime.year - 1900; // time offset in structure according cpp reference
|
dtime.tm_year = datetime.year - 1900; // time offset in structure according cpp reference
|
||||||
return std::string(std::asctime(&dtime));
|
return dtime;
|
||||||
}
|
}
|
||||||
|
|
||||||
const uint8_t PCF85063::decToBcd(const int val)
|
const uint8_t PCF85063::decToBcd(const int val)
|
||||||
|
|||||||
@@ -1,7 +1,11 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
|
#define DEBUGLOG_DEFAULT_LOG_LEVEL_INFO
|
||||||
|
|
||||||
|
#include <DebugLog.h>
|
||||||
#include "I2C_Driver.h"
|
#include "I2C_Driver.h"
|
||||||
#include <string>
|
#include <string>
|
||||||
|
#include <time.h>
|
||||||
|
|
||||||
// PCF85063_ADDRESS
|
// PCF85063_ADDRESS
|
||||||
#define PCF85063_ADDRESS (0x51)
|
#define PCF85063_ADDRESS (0x51)
|
||||||
@@ -60,46 +64,13 @@
|
|||||||
|
|
||||||
#define RTC_TIMER_FLAG (0x08)
|
#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][4] = {"Sun", "Mon", "Tue", "Wed", "Thu", "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);
|
|
||||||
void PCF85063_Set_Alarm(datetime_t time);
|
|
||||||
void PCF85063_Read_Alarm(datetime_t *time);
|
|
||||||
|
|
||||||
void datetime_to_str(char *datetime_str, datetime_t time);
|
|
||||||
|
|
||||||
namespace drivers
|
namespace drivers
|
||||||
{
|
{
|
||||||
|
|
||||||
class PCF85063
|
class PCF85063
|
||||||
{
|
{
|
||||||
I2C &m_i2c;
|
|
||||||
uint8_t m_address;
|
|
||||||
|
|
||||||
|
public:
|
||||||
typedef struct
|
typedef struct
|
||||||
{
|
{
|
||||||
uint16_t year;
|
uint16_t year;
|
||||||
@@ -112,7 +83,7 @@ namespace drivers
|
|||||||
} datetime_t;
|
} datetime_t;
|
||||||
|
|
||||||
public:
|
public:
|
||||||
PCF85063(I2C &i2c, const uint8_t address, const uint8_t ctrl1 = RTC_CTRL_1_DEFAULT, const uint8_t ctrl2 = RTC_CTRL_2_DEFAULT);
|
PCF85063(I2C &i2c, const uint8_t address = PCF85063_ADDRESS, const uint8_t ctrl1 = RTC_CTRL_1_DEFAULT, const uint8_t ctrl2 = RTC_CTRL_2_DEFAULT);
|
||||||
|
|
||||||
const bool reset(void);
|
const bool reset(void);
|
||||||
|
|
||||||
@@ -129,10 +100,23 @@ namespace drivers
|
|||||||
const bool readAlarm(datetime_t &time);
|
const bool readAlarm(datetime_t &time);
|
||||||
const bool getAlarmFlag(uint8_t &flags);
|
const bool getAlarmFlag(uint8_t &flags);
|
||||||
|
|
||||||
|
const 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:
|
private:
|
||||||
const std::string datetime2str(datetime_t &datetime);
|
|
||||||
const uint8_t decToBcd(const int val);
|
const uint8_t decToBcd(const int val);
|
||||||
const int bcdToDec(const uint8_t val);
|
const int bcdToDec(const uint8_t val);
|
||||||
|
|
||||||
|
private:
|
||||||
|
I2C &m_i2c;
|
||||||
|
uint8_t m_address;
|
||||||
};
|
};
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
145
lib/SENECA/S50140_Driver.cpp
Normal file
145
lib/SENECA/S50140_Driver.cpp
Normal 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
|
||||||
85
lib/SENECA/S50140_Driver.h
Normal file
85
lib/SENECA/S50140_Driver.h
Normal 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
142
lib/TEMP/R4DCB08_Driver.cpp
Normal 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
56
lib/TEMP/R4DCB08_Driver.h
Normal 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
63
lib/utils/utils.cpp
Normal 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
22
lib/utils/utils.h
Normal 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);
|
||||||
@@ -17,7 +17,32 @@ lib_deps =
|
|||||||
arduino-libraries/NTPClient@^3.2.1
|
arduino-libraries/NTPClient@^3.2.1
|
||||||
knolleary/PubSubClient@^2.8
|
knolleary/PubSubClient@^2.8
|
||||||
robtillaart/CRC@^1.0.3
|
robtillaart/CRC@^1.0.3
|
||||||
|
hideakitai/DebugLog@^0.8.4
|
||||||
|
build_type = release
|
||||||
|
|
||||||
[env:native]
|
board_build.filesystem = ffat
|
||||||
platform = native
|
board_build.partitions = fatfs_partition.csv ; se stai usando uno custom
|
||||||
test_framework = doctest
|
|
||||||
|
|
||||||
|
[env:esp32-s3-waveshare8-debug]
|
||||||
|
platform = ${env:esp32-s3-waveshare8.platform}
|
||||||
|
board = ${env:esp32-s3-waveshare8.board}
|
||||||
|
framework = ${env:esp32-s3-waveshare8.framework}
|
||||||
|
lib_deps =
|
||||||
|
bblanchon/ArduinoJson@^7.4.2
|
||||||
|
arduino-libraries/NTPClient@^3.2.1
|
||||||
|
knolleary/PubSubClient@^2.8
|
||||||
|
robtillaart/CRC@^1.0.3
|
||||||
|
hideakitai/DebugLog@^0.8.4
|
||||||
|
build_type = debug
|
||||||
|
build_flags =
|
||||||
|
-O0
|
||||||
|
-g3
|
||||||
|
-ggdb
|
||||||
|
-fno-inline
|
||||||
|
-fno-ipa-sra
|
||||||
|
-fno-tree-sra
|
||||||
|
-fno-builtin
|
||||||
|
|
||||||
|
board_build.filesystem = ffat
|
||||||
|
board_build.partitions = fatfs_partition.csv ; se stai usando uno custom
|
||||||
|
|||||||
505
src/commands.cpp
Normal file
505
src/commands.cpp
Normal file
@@ -0,0 +1,505 @@
|
|||||||
|
#include <commands.h>
|
||||||
|
#include <cronjobs.h>
|
||||||
|
|
||||||
|
namespace commands
|
||||||
|
{
|
||||||
|
|
||||||
|
void restart(TimerHandle_t t)
|
||||||
|
{
|
||||||
|
esp_restart();
|
||||||
|
}
|
||||||
|
|
||||||
|
const ArduinoJson::JsonDocument Commands::setBuzz(const devices_t &dev, const ArduinoJson::JsonDocument ¶ms)
|
||||||
|
{
|
||||||
|
ArduinoJson::JsonDocument response;
|
||||||
|
dev.buzzer.beep(500, NOTE_Bb);
|
||||||
|
return response;
|
||||||
|
}
|
||||||
|
|
||||||
|
// CONFIG //
|
||||||
|
// CONFIG //
|
||||||
|
const ArduinoJson::JsonDocument Commands::setConfig(const devices_t &dev, const ArduinoJson::JsonDocument ¶ms)
|
||||||
|
{
|
||||||
|
ArduinoJson::JsonDocument response;
|
||||||
|
auto &conf = Config::getInstance();
|
||||||
|
std::string buf;
|
||||||
|
response["cmd"] = "setConfig";
|
||||||
|
auto values = response["values"].to<JsonObject>();
|
||||||
|
if (params.isNull())
|
||||||
|
{
|
||||||
|
values["status"] = "Invalid";
|
||||||
|
return response;
|
||||||
|
}
|
||||||
|
conf.setConfig(params);
|
||||||
|
values["status"] = "Valid";
|
||||||
|
serializeJson(params, buf);
|
||||||
|
LOG_INFO("setConfig ->", buf.c_str());
|
||||||
|
TimerHandle_t resetTimer(xTimerCreate("restartTimer", pdMS_TO_TICKS(5000), false, NULL, restart));
|
||||||
|
LOG_WARN("setConfig will cause restart!");
|
||||||
|
if (resetTimer)
|
||||||
|
{
|
||||||
|
xTimerStart(resetTimer, 0);
|
||||||
|
}
|
||||||
|
return response;
|
||||||
|
}
|
||||||
|
const ArduinoJson::JsonDocument Commands::getConfig(const devices_t &dev, const ArduinoJson::JsonDocument ¶ms)
|
||||||
|
{
|
||||||
|
ArduinoJson::JsonDocument response;
|
||||||
|
auto &conf = Config::getInstance();
|
||||||
|
std::string buf;
|
||||||
|
response["cmd"] = "getConfig";
|
||||||
|
response["values"] = conf.getConfig();
|
||||||
|
serializeJson(response["values"], buf);
|
||||||
|
LOG_INFO("getConfig ->", buf.c_str());
|
||||||
|
return response;
|
||||||
|
}
|
||||||
|
// CONFIG //
|
||||||
|
// CONFIG //
|
||||||
|
|
||||||
|
// CRONJOBS //
|
||||||
|
// CRONJOBS //
|
||||||
|
const ArduinoJson::JsonDocument Commands::loadCronJob(const devices_t &dev, const ArduinoJson::JsonDocument ¶ms)
|
||||||
|
{
|
||||||
|
ArduinoJson::JsonDocument response;
|
||||||
|
response["cmd"] = "loadCronJob";
|
||||||
|
auto &cron = Cron::getInstance(dev);
|
||||||
|
if (!cron.loadEvents())
|
||||||
|
{
|
||||||
|
LOG_ERROR("loadCronJob failed to load events from flash");
|
||||||
|
response["values"]["status"] = "invalid";
|
||||||
|
return response;
|
||||||
|
}
|
||||||
|
response["values"]["status"] = "valid";
|
||||||
|
return response;
|
||||||
|
}
|
||||||
|
|
||||||
|
const ArduinoJson::JsonDocument Commands::setCronJob(const devices_t &dev, const ArduinoJson::JsonDocument ¶ms)
|
||||||
|
{
|
||||||
|
ArduinoJson::JsonDocument response;
|
||||||
|
response["cmd"] = "setCronJob";
|
||||||
|
|
||||||
|
const auto &eventName = params["name"].as<std::string>();
|
||||||
|
const auto &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("setCronJob 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("setCronJob unable to add job [", actionStr.c_str(), "]");
|
||||||
|
response["values"]["status"] = "invalid";
|
||||||
|
return response;
|
||||||
|
}
|
||||||
|
LOG_INFO("setCronJob added job [", actionStr.c_str(), "]");
|
||||||
|
response["values"]["status"] = "valid";
|
||||||
|
return response;
|
||||||
|
}
|
||||||
|
const ArduinoJson::JsonDocument Commands::getCronJob(const devices_t &dev, const ArduinoJson::JsonDocument ¶ms)
|
||||||
|
{
|
||||||
|
ArduinoJson::JsonDocument response;
|
||||||
|
response["cmd"] = "getCronJob";
|
||||||
|
auto &cron = Cron::getInstance(dev);
|
||||||
|
auto eventName = params["name"].as<std::string>();
|
||||||
|
|
||||||
|
if (eventName.empty())
|
||||||
|
{
|
||||||
|
LOG_ERROR("getCronJob empty job name");
|
||||||
|
response["values"]["status"] = "invalid";
|
||||||
|
return response;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (eventName == "all")
|
||||||
|
{
|
||||||
|
const auto &eventMap = cron.getAllEvents();
|
||||||
|
uint8_t eventNum(0);
|
||||||
|
for (const auto &[name, event] : eventMap)
|
||||||
|
{
|
||||||
|
const auto cmd = std::get<0>(event);
|
||||||
|
response["values"][name] = cmd;
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
auto cmd = std::get<0>(event);
|
||||||
|
auto cronExpr = std::get<1>(event);
|
||||||
|
auto cmdParams = std::get<3>(event);
|
||||||
|
|
||||||
|
ArduinoJson::JsonDocument action;
|
||||||
|
action["cmd"] = cmd;
|
||||||
|
action["params"] = cmdParams;
|
||||||
|
response["values"]["cronExpr"] = cron::to_cronstr(cronExpr);
|
||||||
|
response["values"]["action"] = action;
|
||||||
|
|
||||||
|
LOG_INFO("getCronJob get job [", eventName.c_str(), "]");
|
||||||
|
return response;
|
||||||
|
}
|
||||||
|
const ArduinoJson::JsonDocument Commands::delCronJob(const devices_t &dev, const ArduinoJson::JsonDocument ¶ms)
|
||||||
|
{
|
||||||
|
ArduinoJson::JsonDocument response;
|
||||||
|
response["cmd"] = "delCronJob";
|
||||||
|
auto &cron = Cron::getInstance(dev);
|
||||||
|
auto eventName = params["name"].as<std::string>();
|
||||||
|
response["values"]["name"] = eventName;
|
||||||
|
if (eventName.empty() || !cron.delEvent(eventName))
|
||||||
|
{
|
||||||
|
LOG_ERROR("delCronJob failed to delete job [", eventName.c_str(), "]");
|
||||||
|
response["values"]["status"] = "invalid";
|
||||||
|
return response;
|
||||||
|
}
|
||||||
|
response["values"]["status"] = "valid";
|
||||||
|
return response;
|
||||||
|
}
|
||||||
|
|
||||||
|
const ArduinoJson::JsonDocument Commands::storeCronJob(const devices_t &dev, const ArduinoJson::JsonDocument ¶ms)
|
||||||
|
{
|
||||||
|
ArduinoJson::JsonDocument response;
|
||||||
|
response["cmd"] = "storeCronJob";
|
||||||
|
auto &cron = Cron::getInstance(dev);
|
||||||
|
if (!cron.storeEvents())
|
||||||
|
{
|
||||||
|
LOG_ERROR("storeCronJob failed to store events in flash");
|
||||||
|
response["values"]["status"] = "invalid";
|
||||||
|
return response;
|
||||||
|
}
|
||||||
|
response["values"]["status"] = "valid";
|
||||||
|
return response;
|
||||||
|
}
|
||||||
|
// CRONJOBS //
|
||||||
|
// CRONJOBS //
|
||||||
|
|
||||||
|
// SETTERS //
|
||||||
|
// SETTERS //
|
||||||
|
const ArduinoJson::JsonDocument Commands::setHPlimit(const devices_t &dev, const ArduinoJson::JsonDocument ¶ms)
|
||||||
|
{
|
||||||
|
ArduinoJson::JsonDocument response;
|
||||||
|
response["cmd"] = "setHPlimit";
|
||||||
|
if (!params["level"].is<std::string>())
|
||||||
|
{
|
||||||
|
LOG_ERROR("setHPlimit incorrect parameters");
|
||||||
|
return response;
|
||||||
|
}
|
||||||
|
const auto level = params["level"].as<std::string>();
|
||||||
|
response["values"]["level"] = level;
|
||||||
|
if (!c_hpLimitsMap.contains(level))
|
||||||
|
{
|
||||||
|
LOG_ERROR("setHPlimit invalid level", level.c_str());
|
||||||
|
response["values"]["status"] = "invalid";
|
||||||
|
return response;
|
||||||
|
}
|
||||||
|
for (const auto [lvl, ro] : c_hpLimitsMap)
|
||||||
|
{
|
||||||
|
if (level == lvl && level != "UNLIMITED")
|
||||||
|
dev.io.digitalOutWrite(ro, true);
|
||||||
|
else
|
||||||
|
dev.io.digitalOutWrite(ro, false);
|
||||||
|
}
|
||||||
|
LOG_INFO("setHPlimit -> level", level.c_str());
|
||||||
|
response["values"]["status"] = "valid";
|
||||||
|
return response;
|
||||||
|
}
|
||||||
|
|
||||||
|
const ArduinoJson::JsonDocument Commands::setHeating(const devices_t &dev, const ArduinoJson::JsonDocument ¶ms)
|
||||||
|
{
|
||||||
|
ArduinoJson::JsonDocument response;
|
||||||
|
response["cmd"] = "setHeating";
|
||||||
|
if (params.isNull())
|
||||||
|
{
|
||||||
|
LOG_ERROR("setHeating incorrect paramaters");
|
||||||
|
return response;
|
||||||
|
}
|
||||||
|
for (const auto [lvl, ro] : c_heatingValveMap)
|
||||||
|
{
|
||||||
|
if (params[lvl].isNull())
|
||||||
|
continue;
|
||||||
|
if (params[lvl] == "ON")
|
||||||
|
{
|
||||||
|
dev.io.digitalOutWrite(ro, true);
|
||||||
|
response["values"][lvl] = "ON";
|
||||||
|
LOG_INFO("setHeating -> ", lvl.c_str(), "ON");
|
||||||
|
}
|
||||||
|
else if (params[lvl] == "OFF")
|
||||||
|
{
|
||||||
|
dev.io.digitalOutWrite(ro, false);
|
||||||
|
response["values"][lvl] = "OFF";
|
||||||
|
LOG_INFO("setHeating -> ", lvl.c_str(), "OFF");
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
response["values"][lvl] = "invalid";
|
||||||
|
LOG_ERROR("setHeating invalid valve state");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return response;
|
||||||
|
}
|
||||||
|
|
||||||
|
void resetZone(TimerHandle_t th)
|
||||||
|
{
|
||||||
|
devices_t *dev = (devices_t *)pvTimerGetTimerID(th);
|
||||||
|
const char *timerName = pcTimerGetName(th);
|
||||||
|
LOG_INFO("setIrrigation shutdown zone [", timerName, "]");
|
||||||
|
if (!c_irrigationValveMap.contains(timerName))
|
||||||
|
{
|
||||||
|
LOG_ERROR("Irrigation timer name invalid");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
dev->io.digitalOutWrite(c_irrigationValveMap.at(timerName), false);
|
||||||
|
c_irrigationTimerMap.at(timerName).second = NULL; // reset timer handle for this timer
|
||||||
|
xTimerDelete(th, 0); // delete the timer on expiry
|
||||||
|
}
|
||||||
|
|
||||||
|
void resetWaterPump(TimerHandle_t th)
|
||||||
|
{
|
||||||
|
devices_t *dev = (devices_t *)pvTimerGetTimerID(th);
|
||||||
|
LOG_INFO("setIrrigation shutdown pump");
|
||||||
|
dev->io.digitalOutWrite(RO::IRR_PUMP, false);
|
||||||
|
s_irrigationPumpTimer = NULL;
|
||||||
|
xTimerDelete(th, 0); // delete the timer on expiry
|
||||||
|
}
|
||||||
|
|
||||||
|
const ArduinoJson::JsonDocument Commands::setIrrigation(const devices_t &dev, const ArduinoJson::JsonDocument ¶ms)
|
||||||
|
{
|
||||||
|
ArduinoJson::JsonDocument response;
|
||||||
|
auto &conf = Config::getInstance();
|
||||||
|
response["cmd"] = "setIrrigation";
|
||||||
|
if (params.isNull())
|
||||||
|
{
|
||||||
|
LOG_ERROR("setIrrigation incorrect paramaters");
|
||||||
|
return response;
|
||||||
|
}
|
||||||
|
const std::string zone(params["zone"].as<std::string>());
|
||||||
|
const uint16_t tOn(params["timeOn"].as<uint16_t>());
|
||||||
|
const uint16_t tPause(params["timePause"].as<uint16_t>());
|
||||||
|
|
||||||
|
response["values"]["zone"] = zone;
|
||||||
|
|
||||||
|
if (zone == "stop")
|
||||||
|
{ // stop all zones and reset timers
|
||||||
|
LOG_INFO("setIrrigation stop all zones");
|
||||||
|
for (auto &h : c_irrigationTimerMap)
|
||||||
|
{
|
||||||
|
const auto zoneName = h.first;
|
||||||
|
auto &timerHandle = h.second.second; // get the timer handle
|
||||||
|
if (timerHandle) // if handle is not null (not from a deleted timer)
|
||||||
|
{
|
||||||
|
if (xTimerIsTimerActive(timerHandle)) // stop the timer if active
|
||||||
|
{
|
||||||
|
LOG_INFO("setIrrigation stopping timer", zoneName.c_str());
|
||||||
|
xTimerStop(timerHandle, 0);
|
||||||
|
xTimerDelete(timerHandle, pdMS_TO_TICKS(10)); // delete it
|
||||||
|
timerHandle = NULL;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
LOG_INFO("setIrrigation closing", zoneName.c_str());
|
||||||
|
dev.io.digitalOutWrite(c_irrigationValveMap.at(zoneName), false); // shuto down 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;
|
||||||
|
}
|
||||||
|
|
||||||
|
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::IRR_PUMP, 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);
|
||||||
|
xTimerStart(shTimer, 0);
|
||||||
|
timerHandle = shTimer;
|
||||||
|
response["values"]["status"] = "valid";
|
||||||
|
LOG_INFO("setIrrigation zone [", timerName, "] tOn[", tOn, "] tPause[", tPause, "]");
|
||||||
|
}
|
||||||
|
return response;
|
||||||
|
}
|
||||||
|
|
||||||
|
const ArduinoJson::JsonDocument Commands::setTimeNTP(const devices_t &dev, const ArduinoJson::JsonDocument ¶ms)
|
||||||
|
{
|
||||||
|
ArduinoJson::JsonDocument response;
|
||||||
|
response["cmd"] = "setTimeNTP";
|
||||||
|
auto ð = dev.eth;
|
||||||
|
auto &rtc = dev.rtc;
|
||||||
|
|
||||||
|
time_t ntpTime;
|
||||||
|
auto ntpOk = eth.getNtpTime(ntpTime);
|
||||||
|
|
||||||
|
drivers::PCF85063::datetime_t rtcTime(drivers::PCF85063::fromEpoch(ntpTime));
|
||||||
|
auto rtcOk = rtc.setDatetime(rtcTime);
|
||||||
|
|
||||||
|
if (!rtcOk || !ntpOk)
|
||||||
|
{
|
||||||
|
response["values"]["status"] = "invalid";
|
||||||
|
return response;
|
||||||
|
}
|
||||||
|
|
||||||
|
response["values"]["status"] = "valid";
|
||||||
|
response["values"]["time"] = rtc.getTimeStr();
|
||||||
|
LOG_INFO("setTimeNTP -> RTC is [", response["status"]["time"].as<std::string>().c_str(), "]");
|
||||||
|
return response;
|
||||||
|
}
|
||||||
|
// SETTERS //
|
||||||
|
// SETTERS //
|
||||||
|
|
||||||
|
// GETTERS //
|
||||||
|
// GETTERS //
|
||||||
|
const ArduinoJson::JsonDocument Commands::getHPpower(const devices_t &dev, const ArduinoJson::JsonDocument ¶ms)
|
||||||
|
{
|
||||||
|
ArduinoJson::JsonDocument response;
|
||||||
|
response["cmd"] = "getHPpower";
|
||||||
|
const auto pinfo = dev.seneca.getAll();
|
||||||
|
auto values = response["values"].to<JsonObject>();
|
||||||
|
values["power"] = pinfo.pAct;
|
||||||
|
values["current"] = pinfo.a;
|
||||||
|
values["voltage"] = pinfo.v;
|
||||||
|
values["energy"] = pinfo.whPar;
|
||||||
|
LOG_INFO("getHPpower -> power", pinfo.pAct, "current", pinfo.a, "voltage", pinfo.v, "energy", pinfo.whPar);
|
||||||
|
return response;
|
||||||
|
}
|
||||||
|
|
||||||
|
const ArduinoJson::JsonDocument Commands::getInputStatus(const devices_t &dev, const ArduinoJson::JsonDocument ¶ms)
|
||||||
|
{
|
||||||
|
ArduinoJson::JsonDocument response;
|
||||||
|
LOG_WARN("Comand not yet implemented");
|
||||||
|
return response;
|
||||||
|
}
|
||||||
|
|
||||||
|
const ArduinoJson::JsonDocument Commands::getOutputStatus(const devices_t &dev, const ArduinoJson::JsonDocument ¶ms)
|
||||||
|
{
|
||||||
|
ArduinoJson::JsonDocument response;
|
||||||
|
LOG_WARN("Comand not yet implemented");
|
||||||
|
return response;
|
||||||
|
}
|
||||||
|
|
||||||
|
const ArduinoJson::JsonDocument Commands::getTemperatures(const devices_t &dev, const ArduinoJson::JsonDocument ¶ms)
|
||||||
|
{
|
||||||
|
ArduinoJson::JsonDocument response;
|
||||||
|
LOG_WARN("Comand not yet implemented");
|
||||||
|
return response;
|
||||||
|
}
|
||||||
|
|
||||||
|
const ArduinoJson::JsonDocument Commands::getWaterInfo(const devices_t &dev, const ArduinoJson::JsonDocument ¶ms)
|
||||||
|
{
|
||||||
|
ArduinoJson::JsonDocument response;
|
||||||
|
LOG_WARN("Comand not yet implemented");
|
||||||
|
return response;
|
||||||
|
}
|
||||||
|
|
||||||
|
const ArduinoJson::JsonDocument Commands::getTankInfo(const devices_t &dev, const ArduinoJson::JsonDocument ¶ms)
|
||||||
|
{
|
||||||
|
ArduinoJson::JsonDocument response;
|
||||||
|
LOG_WARN("Comand not yet implemented");
|
||||||
|
return response;
|
||||||
|
}
|
||||||
|
|
||||||
|
const ArduinoJson::JsonDocument Commands::getRainInfo(const devices_t &dev, const ArduinoJson::JsonDocument ¶ms)
|
||||||
|
{
|
||||||
|
ArduinoJson::JsonDocument response;
|
||||||
|
LOG_WARN("Comand not yet implemented");
|
||||||
|
return response;
|
||||||
|
}
|
||||||
|
|
||||||
|
const ArduinoJson::JsonDocument Commands::getIrrigation(const devices_t &dev, const ArduinoJson::JsonDocument ¶ms)
|
||||||
|
{
|
||||||
|
ArduinoJson::JsonDocument response;
|
||||||
|
LOG_WARN("Comand not yet implemented");
|
||||||
|
return response;
|
||||||
|
}
|
||||||
|
|
||||||
|
const ArduinoJson::JsonDocument Commands::getTimeDrift(const devices_t &dev, const ArduinoJson::JsonDocument ¶ms)
|
||||||
|
{
|
||||||
|
ArduinoJson::JsonDocument response;
|
||||||
|
response["cmd"] = "getTimeDrift";
|
||||||
|
auto ð = dev.eth;
|
||||||
|
auto &rtc = dev.rtc;
|
||||||
|
|
||||||
|
time_t ntpTime;
|
||||||
|
auto ntpOk = eth.getNtpTime(ntpTime);
|
||||||
|
|
||||||
|
drivers::PCF85063::datetime_t rtcTime;
|
||||||
|
auto rtcOk = rtc.readDatetime(rtcTime);
|
||||||
|
auto rtcTimeTm = drivers::PCF85063::datetime2tm(rtcTime);
|
||||||
|
|
||||||
|
if (!rtcOk || !ntpOk)
|
||||||
|
{
|
||||||
|
response["values"]["status"] = "invalid";
|
||||||
|
return response;
|
||||||
|
}
|
||||||
|
|
||||||
|
auto ntpTimePoint = std::chrono::system_clock::from_time_t(ntpTime);
|
||||||
|
auto rtcTimePoint = std::chrono::system_clock::from_time_t(std::mktime(&rtcTimeTm));
|
||||||
|
|
||||||
|
auto timeDiff = std::chrono::duration_cast<std::chrono::seconds>(ntpTimePoint - rtcTimePoint);
|
||||||
|
auto direction = timeDiff.count() >= 0 ? "BEYOND" : "AHEAD";
|
||||||
|
|
||||||
|
response["values"]["status"] = "valid";
|
||||||
|
response["values"]["drift"] = (uint32_t)timeDiff.count();
|
||||||
|
response["values"]["direction"] = "RTC is [" + std::string(direction) + "] NTP time";
|
||||||
|
|
||||||
|
LOG_INFO("getTimeDrift -> RTC is [", (int32_t)timeDiff.count(), "] sec, [", std::string(direction).c_str(), "] NTP time");
|
||||||
|
|
||||||
|
return response;
|
||||||
|
}
|
||||||
|
// GETTERS //
|
||||||
|
// GETTERS //
|
||||||
|
|
||||||
|
}
|
||||||
123
src/commands.h
Normal file
123
src/commands.h
Normal file
@@ -0,0 +1,123 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#define DEBUGLOG_DEFAULT_LOG_LEVEL_INFO
|
||||||
|
|
||||||
|
#include <DebugLog.h>
|
||||||
|
#include <Arduino.h>
|
||||||
|
#include <ArduinoJson.h>
|
||||||
|
|
||||||
|
#include <config.h>
|
||||||
|
#include <devices.h>
|
||||||
|
|
||||||
|
namespace commands
|
||||||
|
{
|
||||||
|
enum RO // relay output channels
|
||||||
|
{
|
||||||
|
P1,
|
||||||
|
P2,
|
||||||
|
P3,
|
||||||
|
P4,
|
||||||
|
NC_1,
|
||||||
|
FST_FLOOR,
|
||||||
|
GND_FLOOR,
|
||||||
|
PUMP_HT,
|
||||||
|
IRR_PUMP,
|
||||||
|
Z1,
|
||||||
|
Z2,
|
||||||
|
Z3,
|
||||||
|
AUX,
|
||||||
|
RETURN,
|
||||||
|
NC_3,
|
||||||
|
NC_4,
|
||||||
|
RO_MAX // unused to detect invalid values
|
||||||
|
};
|
||||||
|
|
||||||
|
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::P1}};
|
||||||
|
|
||||||
|
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::Z1},
|
||||||
|
{"zone2", RO::Z2},
|
||||||
|
{"zone3", RO::Z3},
|
||||||
|
{"rubinetti", RO::AUX}};
|
||||||
|
|
||||||
|
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;
|
||||||
|
|
||||||
|
// define command callback type
|
||||||
|
using Command = std::function<const ArduinoJson::JsonDocument(const devices_t &, const ArduinoJson::JsonDocument &)>;
|
||||||
|
|
||||||
|
class Commands
|
||||||
|
{
|
||||||
|
Commands() = delete;
|
||||||
|
|
||||||
|
public:
|
||||||
|
// TEST //
|
||||||
|
static const ArduinoJson::JsonDocument setBuzz(const devices_t &dev, const ArduinoJson::JsonDocument ¶ms);
|
||||||
|
|
||||||
|
// CONFIG //
|
||||||
|
static const ArduinoJson::JsonDocument setConfig(const devices_t &dev, const ArduinoJson::JsonDocument ¶ms);
|
||||||
|
static const ArduinoJson::JsonDocument getConfig(const devices_t &dev, const ArduinoJson::JsonDocument ¶ms);
|
||||||
|
|
||||||
|
// CRONJOBS //
|
||||||
|
static const ArduinoJson::JsonDocument loadCronJob(const devices_t &dev, const ArduinoJson::JsonDocument ¶ms);
|
||||||
|
static const ArduinoJson::JsonDocument setCronJob(const devices_t &dev, const ArduinoJson::JsonDocument ¶ms);
|
||||||
|
static const ArduinoJson::JsonDocument getCronJob(const devices_t &dev, const ArduinoJson::JsonDocument ¶ms);
|
||||||
|
static const ArduinoJson::JsonDocument delCronJob(const devices_t &dev, const ArduinoJson::JsonDocument ¶ms);
|
||||||
|
static const ArduinoJson::JsonDocument storeCronJob(const devices_t &dev, const ArduinoJson::JsonDocument ¶ms);
|
||||||
|
|
||||||
|
// SETTERS //
|
||||||
|
static const ArduinoJson::JsonDocument setHPlimit(const devices_t &dev, const ArduinoJson::JsonDocument ¶ms);
|
||||||
|
static const ArduinoJson::JsonDocument setHeating(const devices_t &dev, const ArduinoJson::JsonDocument ¶ms);
|
||||||
|
static const ArduinoJson::JsonDocument setIrrigation(const devices_t &dev, const ArduinoJson::JsonDocument ¶ms);
|
||||||
|
static const ArduinoJson::JsonDocument setTimeNTP(const devices_t &dev, const ArduinoJson::JsonDocument ¶ms);
|
||||||
|
|
||||||
|
// GETTERS //
|
||||||
|
static const ArduinoJson::JsonDocument getHPpower(const devices_t &dev, const ArduinoJson::JsonDocument ¶ms);
|
||||||
|
static const ArduinoJson::JsonDocument getInputStatus(const devices_t &dev, const ArduinoJson::JsonDocument ¶ms);
|
||||||
|
static const ArduinoJson::JsonDocument getOutputStatus(const devices_t &dev, const ArduinoJson::JsonDocument ¶ms);
|
||||||
|
static const ArduinoJson::JsonDocument getTemperatures(const devices_t &dev, const ArduinoJson::JsonDocument ¶ms);
|
||||||
|
static const ArduinoJson::JsonDocument getWaterInfo(const devices_t &dev, const ArduinoJson::JsonDocument ¶ms);
|
||||||
|
static const ArduinoJson::JsonDocument getTankInfo(const devices_t &dev, const ArduinoJson::JsonDocument ¶ms);
|
||||||
|
static const ArduinoJson::JsonDocument getRainInfo(const devices_t &dev, const ArduinoJson::JsonDocument ¶ms);
|
||||||
|
static const ArduinoJson::JsonDocument getIrrigation(const devices_t &dev, const ArduinoJson::JsonDocument ¶ms);
|
||||||
|
static const ArduinoJson::JsonDocument getTimeDrift(const devices_t &dev, const ArduinoJson::JsonDocument ¶ms);
|
||||||
|
};
|
||||||
|
|
||||||
|
static const std::map<const std::string, Command> s_commandMap = {
|
||||||
|
|
||||||
|
{"setBuzz", Commands::setBuzz},
|
||||||
|
|
||||||
|
{"setConfig", Commands::setConfig},
|
||||||
|
{"getConfig", Commands::getConfig},
|
||||||
|
|
||||||
|
{"loadCronJob", Commands::loadCronJob},
|
||||||
|
{"setCronJob", Commands::setCronJob},
|
||||||
|
{"getCronJob", Commands::getCronJob},
|
||||||
|
{"delCronJob", Commands::delCronJob},
|
||||||
|
{"storeCronJob", Commands::storeCronJob},
|
||||||
|
|
||||||
|
{"setHPlimit", Commands::setHPlimit},
|
||||||
|
{"setHeating", Commands::setHeating},
|
||||||
|
{"setIrrigation", Commands::setIrrigation},
|
||||||
|
|
||||||
|
{"getHPpower", Commands::getHPpower},
|
||||||
|
{"setHeating", Commands::setHeating},
|
||||||
|
|
||||||
|
{"getTimeDrift", Commands::getTimeDrift},
|
||||||
|
{"setTimeNTP", Commands::setTimeNTP},
|
||||||
|
};
|
||||||
|
|
||||||
|
}
|
||||||
239
src/cronjobs.cpp
Normal file
239
src/cronjobs.cpp
Normal file
@@ -0,0 +1,239 @@
|
|||||||
|
#include <cronjobs.h>
|
||||||
|
#include <chrono>
|
||||||
|
#include <fsmount.h>
|
||||||
|
|
||||||
|
#define STACK_DEPTH 4096
|
||||||
|
#define PRIORITY 3
|
||||||
|
|
||||||
|
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::serializeJsonPretty(cronFileContent, buf);
|
||||||
|
LOG_INFO("Cron loadEvents loaded cronjobs.json\n", 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>();
|
||||||
|
ArduinoJson::JsonDocument action(job["action"]);
|
||||||
|
if (!addEvent(eventName, cronExpr, action))
|
||||||
|
LOG_ERROR("Cron failed to load event [", eventName.c_str(), "]");
|
||||||
|
else
|
||||||
|
LOG_INFO("Cron loaded event [", eventName.c_str(), "]");
|
||||||
|
delay(10);
|
||||||
|
}
|
||||||
|
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 &job : m_cronMap) // convert cron events map to json file
|
||||||
|
{
|
||||||
|
const auto &eventName = job.first;
|
||||||
|
const auto ¶ms = job.second;
|
||||||
|
|
||||||
|
const auto &cmd = std::get<0>(params);
|
||||||
|
const auto &cronExpr = std::get<1>(params);
|
||||||
|
const auto &cmdParams = std::get<3>(params);
|
||||||
|
|
||||||
|
ArduinoJson::JsonDocument thisJob;
|
||||||
|
thisJob["name"] = eventName;
|
||||||
|
thisJob["cronExpr"] = cron::to_cronstr(cronExpr);
|
||||||
|
thisJob["action"]["cmd"] = cmd;
|
||||||
|
thisJob["action"]["params"] = cmdParams;
|
||||||
|
|
||||||
|
cronFileArray.add(thisJob);
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string buf;
|
||||||
|
ArduinoJson::serializeJsonPretty(cronFileContent, buf);
|
||||||
|
LOG_INFO("Cron storeEvents generated cronjobs.json\n", 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)
|
||||||
|
{
|
||||||
|
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 eventExpr(cron::make_cron(expr));
|
||||||
|
const auto cmd = action["cmd"].as<std::string>();
|
||||||
|
const auto params = action["params"];
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
std::tm nowTm = drivers::PCF85063::datetime2tm(now);
|
||||||
|
auto next = cron::cron_next(eventExpr, nowTm);
|
||||||
|
JsonDocument act(params);
|
||||||
|
LOG_INFO("Cron adding event [", name.c_str(), "] next execution [", drivers::PCF85063::tm2str(next).c_str(), "]");
|
||||||
|
m_cronMap[name] = std::make_tuple(cmd, eventExpr, next, act);
|
||||||
|
}
|
||||||
|
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::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(1000);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void Cron::startCron()
|
||||||
|
{
|
||||||
|
if (!m_cronTaskHandle)
|
||||||
|
{
|
||||||
|
LOG_INFO("Cron starting loop");
|
||||||
|
xTaskCreate(cronLoop, "cronLoop", STACK_DEPTH, this, PRIORITY, &m_cronTaskHandle);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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 &event : m_cronMap)
|
||||||
|
{
|
||||||
|
auto &eventName = event.first;
|
||||||
|
auto &eventAction = event.second;
|
||||||
|
|
||||||
|
auto &cmd = std::get<0>(eventAction);
|
||||||
|
auto &cronexrp = std::get<1>(eventAction);
|
||||||
|
auto &next = std::get<2>(eventAction);
|
||||||
|
auto &cmdParams = std::get<3>(eventAction);
|
||||||
|
|
||||||
|
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(&next));
|
||||||
|
|
||||||
|
LOG_DEBUG("Cron current time [", std::asctime(&nowTm), "]");
|
||||||
|
LOG_DEBUG("Cron checking event [", eventName.c_str(), "] executionTime [", drivers::PCF85063::tm2str(next).c_str(), "]");
|
||||||
|
|
||||||
|
if (nextEventPoint <= nowPoint) // execution time hs passed, run event
|
||||||
|
{
|
||||||
|
next = cron::cron_next(cronexrp, nowTm); // update next execution time only if event was executed
|
||||||
|
// otherwise time tracking is lost
|
||||||
|
LOG_INFO("Cron running event [", eventName.c_str(), "] next execution time [", drivers::PCF85063::tm2str(next).c_str(), "]");
|
||||||
|
auto action = commands::s_commandMap.at(cmd)(m_dev, cmdParams); // here the magic happens
|
||||||
|
ArduinoJson::JsonDocument resp;
|
||||||
|
resp["cmd"] = "logCronJob";
|
||||||
|
resp["values"]["name"] = eventName;
|
||||||
|
resp["values"]["now"] = drivers::PCF85063::tm2str(nowTm).c_str();
|
||||||
|
resp["values"]["next"] = drivers::PCF85063::tm2str(next).c_str();
|
||||||
|
resp["values"]["action"] = action;
|
||||||
|
if (m_callback)
|
||||||
|
{
|
||||||
|
m_callback(resp);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
58
src/cronjobs.h
Normal file
58
src/cronjobs.h
Normal file
@@ -0,0 +1,58 @@
|
|||||||
|
#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>
|
||||||
|
|
||||||
|
class Cron
|
||||||
|
{
|
||||||
|
public: // eventName cronExpression nextExec command parameters
|
||||||
|
using CronEvent = std::tuple<std::string, cron::cronexpr, std::tm, ArduinoJson::JsonDocument>;
|
||||||
|
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 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();
|
||||||
|
|
||||||
|
private:
|
||||||
|
const devices_t &m_dev;
|
||||||
|
CronCallback m_callback;
|
||||||
|
CronEventMap m_cronMap;
|
||||||
|
TaskHandle_t m_cronTaskHandle;
|
||||||
|
std::mutex m_mutex;
|
||||||
|
};
|
||||||
20
src/devices.h
Normal file
20
src/devices.h
Normal file
@@ -0,0 +1,20 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <PCF85063_Driver.h>
|
||||||
|
#include <R4DCB08_Driver.h>
|
||||||
|
#include <S50140_Driver.h>
|
||||||
|
#include <BUZZER_Driver.h>
|
||||||
|
#include <LED_Driver.h>
|
||||||
|
#include <ETH_Driver.h>
|
||||||
|
#include <digitalIO.h>
|
||||||
|
|
||||||
|
typedef struct
|
||||||
|
{
|
||||||
|
drivers::Ethernet ð
|
||||||
|
drivers::PCF85063 &rtc;
|
||||||
|
drivers::R4DCB08 &tmp;
|
||||||
|
drivers::S50140 &seneca;
|
||||||
|
drivers::Buzzer &buzzer;
|
||||||
|
drivers::Led &led;
|
||||||
|
digitalIO &io;
|
||||||
|
} devices_t;
|
||||||
368
src/digitalIO.cpp
Normal file
368
src/digitalIO.cpp
Normal 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
74
src/digitalIO.h
Normal 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;
|
||||||
|
};
|
||||||
230
src/main.cpp
230
src/main.cpp
@@ -1,38 +1,212 @@
|
|||||||
|
#define DEBUGLOG_DEFAULT_LOG_LEVEL_INFO
|
||||||
|
|
||||||
#include <Arduino.h>
|
#include <Arduino.h>
|
||||||
#include <RS485_Driver.h>
|
#include <DebugLog.h>
|
||||||
|
#include <DebugLogEnable.h>
|
||||||
|
|
||||||
void setup() {
|
#include <config.h>
|
||||||
bool success = true;
|
#include <commands.h>
|
||||||
|
#include <cronjobs.h>
|
||||||
|
#include <mqtt.h>
|
||||||
|
|
||||||
|
#include <devices.h>
|
||||||
|
#include "utils.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
|
||||||
|
}
|
||||||
|
|
||||||
|
void loop()
|
||||||
|
{
|
||||||
|
uint16_t k(0);
|
||||||
|
uint8_t sensors(0);
|
||||||
|
bool buzzing(false);
|
||||||
|
|
||||||
|
//////////////// 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 bus = drivers::MODBUS(9600, SERIAL_8N1);
|
||||||
const uint8_t devAddress(0x01);
|
auto rtc = drivers::PCF85063(i2c);
|
||||||
const uint8_t baseRegister(0x02);
|
auto eth = drivers::Ethernet(conf.m_ethHostname, conf.m_ntpPool, conf.m_ntpTimezone, conf.m_ntpUpdateInterval);
|
||||||
|
auto tmp = drivers::R4DCB08(bus, conf.m_modbusTemperatureAddr);
|
||||||
|
auto seneca = drivers::S50140(bus, conf.m_modbusSenecaAddr);
|
||||||
|
auto buzzer = drivers::Buzzer();
|
||||||
|
auto led = drivers::Led();
|
||||||
|
delay(500);
|
||||||
|
auto io = digitalIO(i2c, bus, {conf.m_modbusRelayAddr});
|
||||||
|
// 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);
|
||||||
|
|
||||||
log_i("Write single coil");
|
// Create device structure to pass all devices in the callbacks as needed
|
||||||
success &= bus.writeCoil(devAddress, baseRegister, true);
|
devices_t devices(eth, rtc, tmp, seneca, buzzer, led, io);
|
||||||
success &=bus.writeCoil(devAddress, baseRegister, false);
|
//////////////// DEVICES ////////////////
|
||||||
|
|
||||||
log_i("Write multiple coils");
|
//////////////// MQTT ////////////////
|
||||||
const uint16_t coilsNum(32);
|
auto mqtt = MQTTwrapper();
|
||||||
std::vector<bool> coilsValues(coilsNum, false);
|
//////////////// MQTT ////////////////
|
||||||
bool v=true;
|
|
||||||
for (auto i(0); i < coilsNum; i++) {
|
|
||||||
coilsValues[i] = v;
|
|
||||||
v=~v;
|
|
||||||
}
|
|
||||||
success &=bus.writeCoils(devAddress, baseRegister, coilsValues);
|
|
||||||
|
|
||||||
log_i("Write single register");
|
//////////////// MQTT //////////////
|
||||||
success &=bus.writeRegister(devAddress, baseRegister, 0xAA);
|
/////////////// 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());
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
log_i("Write multiple registers");
|
MQTTwrapper::MessageCallback onMessage = [&devices](const MQTTwrapper::Topic &topic, const MQTTwrapper::Message &message)
|
||||||
const uint16_t regNum(16);
|
{
|
||||||
std::vector<uint16_t> regValues(regNum, 0);
|
LOG_DEBUG("onMessage callback [", topic.c_str(), "]");
|
||||||
for (uint16_t i(0); i < regNum; i++) {
|
devices.led.setColor(devices.led.COLOR_MAGENTA);
|
||||||
regValues[i] = i*2;
|
};
|
||||||
|
|
||||||
|
MQTTwrapper::MessageCallback onPublish = [&devices](const MQTTwrapper::Topic &topic, const MQTTwrapper::Message &message)
|
||||||
|
{
|
||||||
|
LOG_DEBUG("onPublish callback [", topic.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);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// 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);
|
||||||
|
// rtc.setDatetime(drivers::PCF85063::fromEpoch(ntpTime));
|
||||||
|
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;
|
||||||
|
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(0);
|
||||||
|
ti["heating"] = tempinfo.at(0);
|
||||||
|
mqtt.publish(conf.m_mqttPublish["temperatures"], ti);
|
||||||
|
};
|
||||||
|
|
||||||
|
if (io.digitalInRead(0)) // ROSSO - Config Reset
|
||||||
|
{
|
||||||
|
LOG_WARN("Config RESET!");
|
||||||
|
buzzer.beep(450, NOTE_E);
|
||||||
|
delay(500);
|
||||||
|
conf.resetConfig();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (io.digitalInRead(1)) // 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 ////////
|
||||||
void loop() {
|
////////////////////////////////////////
|
||||||
|
|
||||||
}
|
}
|
||||||
200
src/mqtt.cpp
Normal file
200
src/mqtt.cpp
Normal file
@@ -0,0 +1,200 @@
|
|||||||
|
#include <mqtt.h>
|
||||||
|
|
||||||
|
#define STACK_DEPTH 8192
|
||||||
|
#define BUFFER_SIZE 2048
|
||||||
|
#define PRIORITY 2
|
||||||
|
|
||||||
|
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)
|
||||||
|
{
|
||||||
|
xTaskCreate(clientLoop, "mqttLoop", STACK_DEPTH, this, PRIORITY, &m_loopHandle);
|
||||||
|
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
84
src/mqtt.h
Normal 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;
|
||||||
|
};
|
||||||
114
src/remoteIO.cpp
Normal file
114
src/remoteIO.cpp
Normal 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
53
src/remoteIO.h
Normal 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;
|
||||||
|
};
|
||||||
Reference in New Issue
Block a user