Compare commits
20 Commits
e4d28b55cb
...
mqtt-wrapp
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
cdbc904bec | ||
|
|
07dd200de8 | ||
|
|
71c7ff8756 | ||
|
|
59d8c2c2d4 | ||
|
|
8f5615a034 | ||
|
|
16bb029e93 | ||
|
|
146a2b558b | ||
|
|
7c776e4787 | ||
|
|
e8f395f8ef | ||
|
|
52a89e58f7 | ||
|
|
b7881355a2 | ||
|
|
92de57a760 | ||
|
|
0b5d725d3a | ||
|
|
30ed0d283a | ||
|
|
3923aa3c05 | ||
|
|
53b82c32c3 | ||
|
|
bdf3b9b41a | ||
|
|
7e02f3cef2 | ||
|
|
d2eba9085e | ||
|
|
1ad98799b4 |
3
data/example.json
Normal file
3
data/example.json
Normal file
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"data": "value"
|
||||
}
|
||||
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.
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,
|
||||
|
316
include/config.h
Normal file
316
include/config.h
Normal file
@@ -0,0 +1,316 @@
|
||||
#pragma once
|
||||
|
||||
#define DEBUGLOG_DEFAULT_LOG_LEVEL_DEBUG
|
||||
|
||||
#include <DebugLog.h>
|
||||
#include <Arduino.h>
|
||||
#include <ArduinoJson.h>
|
||||
#include <FFat.h>
|
||||
|
||||
#include <mutex>
|
||||
|
||||
class FSmount
|
||||
{
|
||||
public:
|
||||
FSmount()
|
||||
{
|
||||
if (!FFat.begin(false))
|
||||
{
|
||||
LOG_ERROR("Unable to mount filesystem without formatting");
|
||||
if (!FFat.begin(true))
|
||||
{
|
||||
LOG_ERROR("Formatted and mounted filesystem");
|
||||
}
|
||||
}
|
||||
|
||||
LOG_INFO("Local Filesystem Mounted Correctly");
|
||||
const auto totalBytes = FFat.totalBytes();
|
||||
const auto freeBytes = FFat.freeBytes();
|
||||
const auto usedBytes = FFat.usedBytes();
|
||||
const auto mountPoint = FFat.mountpoint();
|
||||
LOG_INFO("Local filesystem, total", totalBytes / 1024, "KB - used", usedBytes / 1024, "KB - free", freeBytes / 1024, "KB");
|
||||
LOG_INFO("Local filesystem, mountpoint", mountPoint);
|
||||
}
|
||||
|
||||
~FSmount()
|
||||
{
|
||||
FFat.end(); // unmout filesystem to avoid corruption
|
||||
LOG_INFO("Local Filesystem Unmounted Correctly");
|
||||
}
|
||||
};
|
||||
|
||||
class Config
|
||||
{
|
||||
|
||||
public:
|
||||
static Config &getInstance()
|
||||
{
|
||||
static Config instance;
|
||||
return instance;
|
||||
}
|
||||
|
||||
private:
|
||||
Config() = default;
|
||||
Config(const Config &) = delete;
|
||||
Config &operator=(const Config &) = delete;
|
||||
|
||||
public:
|
||||
void init()
|
||||
{
|
||||
FSmount mount; // scoped mount of the filesystem
|
||||
|
||||
// Initialize and mount filesystem
|
||||
LOG_INFO("Initializing Config");
|
||||
|
||||
if (!FFat.exists("/config.json"))
|
||||
{
|
||||
LOG_WARN("Initializing default config");
|
||||
saveConfig();
|
||||
}
|
||||
|
||||
File file = FFat.open("/config.json", FILE_READ, false);
|
||||
if (!file)
|
||||
{
|
||||
LOG_ERROR("Unable to open config.json");
|
||||
return;
|
||||
}
|
||||
|
||||
if (ArduinoJson::deserializeJson(m_configJson, file) != ArduinoJson::DeserializationError::Ok)
|
||||
{
|
||||
LOG_ERROR("Unable to load config.json");
|
||||
}
|
||||
|
||||
std::string loadedConf;
|
||||
ArduinoJson::serializeJsonPretty(m_configJson, loadedConf);
|
||||
LOG_INFO("Loaded Configuration\n", loadedConf.c_str());
|
||||
|
||||
deserialize(); // convert from json format to class members
|
||||
file.close(); // close config file before unmounting filesystem
|
||||
};
|
||||
|
||||
void updateConfig(ArduinoJson::JsonDocument &json)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(m_mutex);
|
||||
{
|
||||
FSmount mount;
|
||||
m_configJson = json;
|
||||
deserialize();
|
||||
saveConfig();
|
||||
}; // filesystem is unmounted here
|
||||
delay(500);
|
||||
esp_restart(); // configuration updates trigger a cpu restart
|
||||
}
|
||||
|
||||
void resetConfig()
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(m_mutex);
|
||||
{
|
||||
FSmount mount;
|
||||
LOG_WARN("Removing config.json");
|
||||
if (!FFat.remove("/config.json"))
|
||||
{
|
||||
LOG_ERROR("Unable to remove config.json");
|
||||
}
|
||||
LOG_WARN("Configuration reset, Restarting");
|
||||
}; // filesystem is unmounted here
|
||||
delay(500);
|
||||
esp_restart();
|
||||
}
|
||||
|
||||
private:
|
||||
void saveConfig() // write configuration to flash memory
|
||||
{
|
||||
File file = FFat.open("/config.json", FILE_WRITE, true);
|
||||
if (!file)
|
||||
{
|
||||
LOG_ERROR("Unable to open config.json for writing");
|
||||
return;
|
||||
}
|
||||
serialize(); // serialize default configuration
|
||||
if (ArduinoJson::serializeJson(m_configJson, file) == 0)
|
||||
{
|
||||
LOG_ERROR("Serialization Failed");
|
||||
}
|
||||
file.close();
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////
|
||||
////////////// SERIALIZATION + DESERIALIZATION ///////////////
|
||||
//////////////////////////////////////////////////////////////
|
||||
|
||||
void serialize()
|
||||
{
|
||||
// form class members to json document
|
||||
{
|
||||
auto globals = m_configJson["globals"].to<ArduinoJson::JsonObject>();
|
||||
globals["loopDelay"] = m_globalLoopDelay;
|
||||
};
|
||||
|
||||
{
|
||||
auto ethernet = m_configJson["ethernet"].to<ArduinoJson::JsonObject>();
|
||||
ethernet["hostname"] = m_ethHostname;
|
||||
ethernet["ipAddr"] = m_ethIpAddr;
|
||||
ethernet["netmask "] = m_ethNetmask;
|
||||
ethernet["gateway "] = m_ethGateway;
|
||||
};
|
||||
|
||||
{
|
||||
auto modbus = m_configJson["modbus"].to<ArduinoJson::JsonObject>();
|
||||
modbus["relayAddr"] = m_modbusRelayAddr;
|
||||
modbus["temperatureAddr"] = m_modbusTemperatureAddr;
|
||||
modbus["senecaAddr"] = m_modbusSenecaAddr;
|
||||
modbus["flowmeterAddr"] = m_modbusFlowmeterAddr;
|
||||
modbus["tankLevelAddr"] = m_modbusTankLevelAddr;
|
||||
};
|
||||
|
||||
{
|
||||
auto temperature = m_configJson["temperature"].to<ArduinoJson::JsonObject>();
|
||||
temperature["expectedSensors"] = m_tempExpectedSensors;
|
||||
auto values = temperature["correctionValues"].to<ArduinoJson::JsonArray>();
|
||||
for (auto v : m_tempCorrectionValues)
|
||||
{
|
||||
values.add(v);
|
||||
}
|
||||
};
|
||||
|
||||
{
|
||||
auto ntp = m_configJson["ntp"].to<ArduinoJson::JsonObject>();
|
||||
ntp["pool"] = m_ntpPool;
|
||||
ntp["timezone"] = m_ntpTimezone;
|
||||
ntp["updateInterval"] = m_ntpUpdateInterval;
|
||||
ntp["retries"] = m_ntpRetries;
|
||||
};
|
||||
|
||||
{
|
||||
auto mqtt = m_configJson["mqtt"].to<ArduinoJson::JsonObject>();
|
||||
mqtt["host"] = m_mqttHost;
|
||||
mqtt["port"] = m_mqttPort;
|
||||
mqtt["loopTime"] = m_mqttLoopTime;
|
||||
mqtt["clientName"] = m_mqttClientName;
|
||||
mqtt["retries"] = m_mqttRetries;
|
||||
auto publish = mqtt["publish"].to<ArduinoJson::JsonObject>();
|
||||
for (auto v : m_mqttSubscribe)
|
||||
{
|
||||
publish[v.first] = v.second;
|
||||
}
|
||||
auto subscribe = mqtt["subscribe"].to<ArduinoJson::JsonObject>();
|
||||
for (auto v : m_mqttPublish)
|
||||
{
|
||||
subscribe[v.first] = v.second;
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
void deserialize()
|
||||
{ // from json document to class members
|
||||
if (m_configJson.isNull())
|
||||
{
|
||||
LOG_ERROR("NUll config document");
|
||||
return;
|
||||
}
|
||||
|
||||
{
|
||||
auto globals = m_configJson["globals"];
|
||||
m_globalLoopDelay = globals["loopDelay"].as<uint16_t>();
|
||||
};
|
||||
|
||||
{
|
||||
auto ethernet = m_configJson["ethernet"];
|
||||
m_ethHostname = ethernet["hostname"].as<std::string>();
|
||||
m_ethIpAddr = ethernet["ipAddr"].as<std::string>();
|
||||
m_ethNetmask = ethernet["netmask"].as<std::string>();
|
||||
m_ethGateway = ethernet["gateway"].as<std::string>();
|
||||
};
|
||||
|
||||
{
|
||||
auto modbus = m_configJson["modbus"];
|
||||
m_modbusRelayAddr = modbus["relayAddr"].as<uint8_t>();
|
||||
m_modbusTemperatureAddr = modbus["temperatureAddr"].as<uint8_t>();
|
||||
m_modbusSenecaAddr = modbus["senecaAddr"].as<uint8_t>();
|
||||
m_modbusFlowmeterAddr = modbus["flowmeterAddr"].as<uint8_t>();
|
||||
m_modbusTankLevelAddr = modbus["tankLevelAddr"].as<uint8_t>();
|
||||
};
|
||||
|
||||
{
|
||||
auto temperature = m_configJson["temperature"];
|
||||
m_tempExpectedSensors = temperature["expectedSensors"].as<uint8_t>();
|
||||
auto values = temperature["correctionValues"].as<JsonArray>();
|
||||
m_tempCorrectionValues.reserve(values.size());
|
||||
for (auto v : values)
|
||||
{
|
||||
m_tempCorrectionValues.push_back(v.as<float>());
|
||||
}
|
||||
};
|
||||
|
||||
{
|
||||
auto ntp = m_configJson["ntp"];
|
||||
m_ntpPool = ntp["pool"].as<std::string>();
|
||||
m_ntpTimezone = ntp["timezone"].as<uint16_t>();
|
||||
m_ntpUpdateInterval = ntp["updateInterval"].as<uint16_t>();
|
||||
m_ntpRetries = ntp["retries"].as<uint8_t>();
|
||||
};
|
||||
|
||||
{
|
||||
auto mqtt = m_configJson["mqtt"];
|
||||
m_mqttHost = mqtt["host"].as<std::string>();
|
||||
m_mqttPort = mqtt["port"].as<uint16_t>();
|
||||
m_mqttLoopTime = mqtt["loopTime"].as<uint16_t>();
|
||||
m_mqttRetries = mqtt["retries"].as<uint16_t>();
|
||||
auto subscribe = mqtt["subsribe"].as<ArduinoJson::JsonObject>();
|
||||
for (auto v : subscribe)
|
||||
{
|
||||
m_mqttSubscribe[v.key().c_str()] = v.value().as<std::string>();
|
||||
}
|
||||
auto publish = mqtt["publish"].as<ArduinoJson::JsonObject>();
|
||||
for (auto v : publish)
|
||||
{
|
||||
m_mqttPublish[v.key().c_str()] = v.value().as<std::string>();
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
private:
|
||||
ArduinoJson::JsonDocument m_configJson;
|
||||
std::mutex m_mutex;
|
||||
|
||||
public:
|
||||
// Globals
|
||||
std::uint16_t m_globalLoopDelay = 1000; // in milliseconds
|
||||
|
||||
// Ethernet
|
||||
std::string m_ethHostname = "ETcontroller_PRO";
|
||||
std::string m_ethIpAddr = "10.0.2.251";
|
||||
std::string m_ethNetmask = "255.255.255.0";
|
||||
std::string m_ethGateway = "10.0.2.1";
|
||||
|
||||
// MODBUS
|
||||
uint8_t m_modbusRelayAddr = 0x01;
|
||||
uint8_t m_modbusTemperatureAddr = 0xAA;
|
||||
uint8_t m_modbusSenecaAddr = 0xBB;
|
||||
uint8_t m_modbusFlowmeterAddr = 0xCC;
|
||||
uint8_t m_modbusTankLevelAddr = 0xDD;
|
||||
|
||||
// Temperature Board
|
||||
uint8_t m_tempExpectedSensors = 1;
|
||||
std::vector<float> m_tempCorrectionValues = std::vector<float>(8, 0.0f);
|
||||
|
||||
// NTP
|
||||
std::string m_ntpPool = "pool.ntp.org";
|
||||
uint16_t m_ntpTimezone = 3600; // GTM +1
|
||||
uint16_t m_ntpUpdateInterval = 3600; // every hour
|
||||
uint8_t m_ntpRetries = 5;
|
||||
|
||||
// MQTT
|
||||
std::string m_mqttHost = "10.0.2.249";
|
||||
uint16_t m_mqttPort = 1883;
|
||||
uint16_t m_mqttLoopTime = 100; // in milliseconds
|
||||
uint8_t m_mqttRetries = 5;
|
||||
std::string m_mqttClientName = "etcontrollerPRO";
|
||||
|
||||
std::map<const std::string, std::string> m_mqttSubscribe = {
|
||||
{"commands", "test/etcontroller/commands"}};
|
||||
std::map<const std::string, std::string> m_mqttPublish = {
|
||||
{"heatpump", "test/etcontroller/heatpump"},
|
||||
{"temperature", "test/etcontroller/temperatures"},
|
||||
{"irrigation", "test/etcontroller/irrigation"}};
|
||||
};
|
||||
@@ -1,5 +1,7 @@
|
||||
#pragma once
|
||||
|
||||
#define DEBUGLOG_DEFAULT_LOG_LEVEL_INFO
|
||||
|
||||
#include <DebugLog.h>
|
||||
#include <Arduino.h>
|
||||
#include <Network.h>
|
||||
@@ -24,7 +26,7 @@
|
||||
namespace drivers
|
||||
{
|
||||
|
||||
class Ethernet
|
||||
class Ethernet : public ETHClass
|
||||
{
|
||||
|
||||
public:
|
||||
|
||||
@@ -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_G);
|
||||
}
|
||||
|
||||
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;
|
||||
};
|
||||
|
||||
}
|
||||
75
lib/GPIO/LED_Driver.cpp
Normal file
75
lib/GPIO/LED_Driver.cpp
Normal file
@@ -0,0 +1,75 @@
|
||||
#include <LED_Driver.h>
|
||||
|
||||
#define TASK_PRIORITY 20
|
||||
#define TASK_STACK 2048
|
||||
|
||||
namespace drivers
|
||||
{
|
||||
|
||||
Led::Led()
|
||||
{
|
||||
LOG_INFO("Inizializing RGB Led");
|
||||
pinMode(c_ledPin, OUTPUT);
|
||||
m_lp.pin = c_ledPin;
|
||||
m_lp.blinkTask = NULL;
|
||||
}
|
||||
|
||||
Led::~Led()
|
||||
{
|
||||
setColor({0, 0, 0});
|
||||
pinMode(c_ledPin, INPUT);
|
||||
}
|
||||
|
||||
void Led::setColor(const color_t color)
|
||||
{
|
||||
blinkStop();
|
||||
rgbLedWrite(c_ledPin, color.r, color.g, color.b);
|
||||
}
|
||||
|
||||
void Led::blinkColor(const uint16_t tOn, const uint16_t tOff, const color_t color)
|
||||
{
|
||||
blinkStop();
|
||||
m_lp.color1 = color;
|
||||
m_lp.color2 = {0, 0, 0};
|
||||
m_lp.tOn = tOn;
|
||||
m_lp.tOff = tOff;
|
||||
xTaskCreate(blinkTask, "blinker", TASK_STACK, static_cast<void *>(&m_lp), TASK_PRIORITY, &m_lp.blinkTask);
|
||||
}
|
||||
|
||||
void Led::blinkAlternate(const uint16_t tOn, const uint16_t tOff, const color_t color1, const color_t color2)
|
||||
{
|
||||
{
|
||||
blinkStop();
|
||||
m_lp.color1 = color1;
|
||||
m_lp.color2 = color2;
|
||||
m_lp.tOn = tOn;
|
||||
m_lp.tOff = tOff;
|
||||
xTaskCreate(blinkTask, "blinker", TASK_STACK, static_cast<void *>(&m_lp), TASK_PRIORITY, &m_lp.blinkTask);
|
||||
}
|
||||
}
|
||||
|
||||
void Led::blinkStop()
|
||||
{
|
||||
if (m_lp.blinkTask != NULL)
|
||||
vTaskDelete(m_lp.blinkTask);
|
||||
m_lp.blinkTask = NULL;
|
||||
}
|
||||
|
||||
void Led::blinkTask(void *params)
|
||||
{
|
||||
LOG_DEBUG("Blinker Task Created");
|
||||
led_params_t *lPar = static_cast<led_params_t *>(params);
|
||||
while (true)
|
||||
{
|
||||
rgbLedWrite(lPar->pin, lPar->color1.g, lPar->color1.r, lPar->color1.b);
|
||||
delay(lPar->tOn);
|
||||
rgbLedWrite(lPar->pin, lPar->color2.g, lPar->color2.r, lPar->color2.b); // off
|
||||
if (lPar->tOff == 0)
|
||||
break;
|
||||
delay(lPar->tOff);
|
||||
}
|
||||
LOG_DEBUG("Blinker Task Ended");
|
||||
lPar->blinkTask = NULL;
|
||||
vTaskDelete(NULL);
|
||||
}
|
||||
}
|
||||
50
lib/GPIO/LED_Driver.h
Normal file
50
lib/GPIO/LED_Driver.h
Normal file
@@ -0,0 +1,50 @@
|
||||
#pragma once
|
||||
|
||||
#include <Arduino.h>
|
||||
|
||||
#define DEBUGLOG_DEFAULT_LOG_LEVEL_INFO
|
||||
#include <DebugLog.h>
|
||||
|
||||
namespace drivers
|
||||
{
|
||||
|
||||
class Led
|
||||
{
|
||||
const uint8_t c_ledPin = 38;
|
||||
|
||||
public:
|
||||
typedef struct
|
||||
{
|
||||
uint8_t r;
|
||||
uint8_t g;
|
||||
uint8_t b;
|
||||
} color_t;
|
||||
|
||||
private:
|
||||
typedef struct
|
||||
{
|
||||
color_t color1;
|
||||
color_t color2;
|
||||
uint8_t pin;
|
||||
uint16_t tOn;
|
||||
uint16_t tOff;
|
||||
TaskHandle_t blinkTask;
|
||||
} led_params_t;
|
||||
|
||||
public:
|
||||
Led();
|
||||
~Led();
|
||||
|
||||
void setColor(const color_t color);
|
||||
void blinkColor(const uint16_t tOn, const uint16_t tOff, const color_t color);
|
||||
void blinkAlternate(const uint16_t tOn, const uint16_t tOff, const color_t color1, const color_t color2);
|
||||
void blinkStop();
|
||||
|
||||
private:
|
||||
static void blinkTask(void *params);
|
||||
|
||||
private:
|
||||
led_params_t m_lp;
|
||||
};
|
||||
|
||||
}
|
||||
@@ -53,6 +53,12 @@ namespace drivers
|
||||
return setPort(newState);
|
||||
}
|
||||
|
||||
const bool TCA9554PWR::toggleOut(const uint8_t channel)
|
||||
{
|
||||
bool value;
|
||||
return readOut(channel, value) && setOut(channel, value);
|
||||
}
|
||||
|
||||
const bool TCA9554PWR::setPort(const uint8_t state)
|
||||
{
|
||||
if (writeRegister(TCA9554_OUTPUT_REG, state))
|
||||
@@ -61,7 +67,7 @@ namespace drivers
|
||||
return false;
|
||||
}
|
||||
|
||||
const bool TCA9554PWR::readOut(const uint8_t ch)
|
||||
const bool TCA9554PWR::readOut(const uint8_t ch, bool &state)
|
||||
{
|
||||
uint8_t currState(0);
|
||||
if (ch < DO1 || ch > DO8)
|
||||
@@ -71,12 +77,13 @@ namespace drivers
|
||||
}
|
||||
if (!readPort(currState))
|
||||
return false;
|
||||
return (currState && (High >> ch));
|
||||
state = (currState && (High << ch));
|
||||
return true;
|
||||
}
|
||||
|
||||
const bool TCA9554PWR::readPort(uint8_t &state)
|
||||
{
|
||||
if (readRegister(TCA9554_INPUT_REG, state))
|
||||
if (readRegister(TCA9554_OUTPUT_REG, state))
|
||||
return true;
|
||||
LOG_ERROR("Unable to read IO port: state[%02x]", state);
|
||||
return false;
|
||||
|
||||
@@ -1,4 +1,8 @@
|
||||
#pragma once
|
||||
|
||||
#define DEBUGLOG_DEFAULT_LOG_LEVEL_INFO
|
||||
|
||||
#include <DebugLog.h>
|
||||
#include "I2C_Driver.h"
|
||||
|
||||
/****************************************************** The macro defines the TCA9554PWR information ******************************************************/
|
||||
@@ -38,9 +42,10 @@ namespace drivers
|
||||
~TCA9554PWR();
|
||||
|
||||
const bool setOut(const uint8_t channel, const bool state);
|
||||
const bool toggleOut(const uint8_t channel);
|
||||
const bool setPort(const uint8_t state);
|
||||
|
||||
const bool readOut(const uint8_t channel);
|
||||
const bool readOut(const uint8_t channel, bool &state);
|
||||
const bool readPort(uint8_t &state);
|
||||
|
||||
private:
|
||||
|
||||
@@ -3,21 +3,20 @@
|
||||
namespace drivers
|
||||
{
|
||||
|
||||
I2C::I2C()
|
||||
I2C::I2C(): m_initialized(true)
|
||||
{
|
||||
Wire.begin(I2C_SDA_PIN, I2C_SCL_PIN);
|
||||
isInitialized = true;
|
||||
}
|
||||
|
||||
I2C::~I2C()
|
||||
{
|
||||
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)
|
||||
{
|
||||
//busy.try_lock();
|
||||
std::lock_guard<std::mutex> lock(m_mutex);
|
||||
Wire.beginTransmission(deviceAddr);
|
||||
Wire.write(deviceReg);
|
||||
switch (Wire.endTransmission(true))
|
||||
@@ -45,13 +44,12 @@ namespace drivers
|
||||
{
|
||||
data[i] = static_cast<uint8_t>(Wire.read());
|
||||
}
|
||||
//busy.unlock();
|
||||
return true;
|
||||
}
|
||||
|
||||
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.write(deviceReg);
|
||||
for (auto d : data)
|
||||
@@ -73,7 +71,6 @@ namespace drivers
|
||||
LOG_ERROR("Unknown Error");
|
||||
return false;
|
||||
}
|
||||
//busy.unlock();
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
#pragma once
|
||||
|
||||
#define DEBUGLOG_DEFAULT_LOG_LEVEL_INFO
|
||||
|
||||
#include <DebugLog.h>
|
||||
#include <Arduino.h>
|
||||
#include <Wire.h>
|
||||
@@ -14,16 +16,16 @@ namespace drivers
|
||||
|
||||
class I2C
|
||||
{
|
||||
private:
|
||||
bool isInitialized = false;
|
||||
//std::mutex busy;
|
||||
|
||||
public:
|
||||
I2C(void);
|
||||
~I2C(void);
|
||||
|
||||
const bool read(const uint8_t deviceAddr, const uint8_t deviceReg, const uint8_t len, std::vector<uint8_t> &data);
|
||||
const bool write(const uint8_t deviceAddr, const uint8_t deviceReg, const std::vector<uint8_t> &data);
|
||||
|
||||
private:
|
||||
bool m_initialized;
|
||||
std::mutex m_mutex;
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
@@ -3,7 +3,6 @@
|
||||
#include <cstring>
|
||||
#include <endian.h>
|
||||
|
||||
//#define DEBUGLOG_DEFAULT_LOG_LEVEL_TRACE
|
||||
#include "utils.h"
|
||||
|
||||
namespace drivers
|
||||
@@ -18,6 +17,7 @@ namespace drivers
|
||||
LOG_INFO("Init serial port 1");
|
||||
// RS485 is hardwired to serial port 1
|
||||
m_serial.begin(baud, conf, 18, 17);
|
||||
m_serial.setTimeout(1000);
|
||||
m_serial.flush();
|
||||
}
|
||||
|
||||
@@ -65,12 +65,40 @@ namespace drivers
|
||||
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;
|
||||
}
|
||||
|
||||
void MODBUS::delayAccess(const uint8_t device)
|
||||
{
|
||||
if (device == m_lastDevice)
|
||||
return;
|
||||
auto now = millis();
|
||||
if ((now - m_lastAccess) < c_minDelay) // fixed milliseconds delay between commands to different devices
|
||||
{
|
||||
LOG_WARN("MODBUS access delay", (now - m_lastAccess), "device", device);
|
||||
delay(now - m_lastAccess);
|
||||
}
|
||||
m_lastDevice = device;
|
||||
m_lastAccess = millis();
|
||||
}
|
||||
|
||||
// Func 0x01
|
||||
const bool MODBUS::readCoils(const uint8_t device, const uint16_t reg, const uint16_t num, std::vector<bool> &coils)
|
||||
{
|
||||
constexpr uint8_t func = 0x01;
|
||||
delayAccess(device);
|
||||
LOG_DEBUG("Read coils: dev[", device, "], reg[", reg, "], num[", num, "]");
|
||||
return readBinary(device, func, reg, num, coils);
|
||||
}
|
||||
@@ -79,6 +107,7 @@ namespace drivers
|
||||
const bool MODBUS::readInputs(const uint8_t device, const uint16_t reg, const uint8_t num, std::vector<bool> &inputs)
|
||||
{
|
||||
constexpr uint8_t func = 0x02;
|
||||
delayAccess(device);
|
||||
LOG_DEBUG("Read multi inputs: dev[", device, "], reg[", reg, "], num[", num, "]");
|
||||
return readBinary(device, func, reg, num, inputs);
|
||||
}
|
||||
@@ -87,6 +116,7 @@ namespace drivers
|
||||
const bool MODBUS::readHoldingRegisters(const uint8_t device, const uint16_t reg, const uint8_t num, std::vector<uint16_t> &values)
|
||||
{
|
||||
constexpr uint8_t func = 0x03;
|
||||
delayAccess(device);
|
||||
LOG_DEBUG("Read multi holding registers: dev[", device, "], reg[", reg, "], num[", num, "]");
|
||||
return readInteger(device, func, reg, num, values);
|
||||
}
|
||||
@@ -95,6 +125,7 @@ namespace drivers
|
||||
const bool MODBUS::readInputRegisters(const uint8_t device, const uint16_t reg, const uint8_t num, std::vector<uint16_t> &values)
|
||||
{
|
||||
constexpr uint8_t func = 0x04;
|
||||
delayAccess(device);
|
||||
LOG_DEBUG("Read multi input registers: dev[", device, "], reg[", reg, "], num[", num, "]");
|
||||
return readInteger(device, func, reg, num, values);
|
||||
}
|
||||
@@ -103,6 +134,7 @@ namespace drivers
|
||||
const bool MODBUS::writeCoil(const uint8_t device, const uint16_t coil, const bool value)
|
||||
{
|
||||
constexpr uint8_t func = 0x05;
|
||||
delayAccess(device);
|
||||
LOG_DEBUG("Write single coil: dev[", device, "], coil[", coil, "], value[", value ? "true" : "false", "]");
|
||||
return writeBinary(device, func, coil, {value});
|
||||
}
|
||||
@@ -111,14 +143,16 @@ namespace drivers
|
||||
const bool MODBUS::writeRegister(const uint8_t device, const uint16_t reg, const uint16_t value)
|
||||
{
|
||||
constexpr uint8_t func = 0x06;
|
||||
delayAccess(device);
|
||||
LOG_DEBUG("Write single register: dev[", device, "], reg[", reg, "], value[", value, "]");
|
||||
return writeInteger(device, func, reg, {value});
|
||||
return writeInteger(device, func, reg, {value}, false);
|
||||
}
|
||||
|
||||
// Func 0x0F
|
||||
const bool MODBUS::writeCoils(const uint8_t device, const uint16_t coils, const std::vector<bool> &values)
|
||||
{
|
||||
constexpr uint8_t func = 0x0F;
|
||||
delayAccess(device);
|
||||
LOG_DEBUG("Write multi coils: dev[", device, "], start[", coils, "], num[", values.size(), "]");
|
||||
return writeBinary(device, func, coils, values);
|
||||
}
|
||||
@@ -127,8 +161,9 @@ namespace drivers
|
||||
const bool MODBUS::writeRegisters(const uint8_t device, const uint16_t reg, const std::vector<uint16_t> &values)
|
||||
{
|
||||
constexpr uint8_t func = 0x10;
|
||||
delayAccess(device);
|
||||
LOG_DEBUG("Write multi registers: dev[", device, "], start[", reg, "], num[", values.size(), "]");
|
||||
return writeInteger(device, func, reg, values);
|
||||
return writeInteger(device, func, reg, values, true);
|
||||
}
|
||||
|
||||
/////////////////////////////////////////////////////////////////
|
||||
@@ -143,22 +178,22 @@ namespace drivers
|
||||
return false;
|
||||
}
|
||||
const uint16_t nRespDataBytes = (uint16_t)ceil(bits / 8.0f); // 1 bit for every coil, if not 8 mutiple padded with zeroes
|
||||
const uint16_t expectedRespLen = (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;
|
||||
if (!readN(expectedRespLen, response))
|
||||
{
|
||||
LOG_ERROR("Failed receive readBinary response, expected[", expectedRespLen, "], received[", response.size(), "]");
|
||||
return false;
|
||||
}
|
||||
#ifdef DEBUGLOG_DEFAULT_LOG_LEVEL_TRACE
|
||||
printBytes("readBinary Response", response);
|
||||
#endif
|
||||
|
||||
// element 2 of response has the response data bytes expected
|
||||
const uint8_t actualRespLen(response.at(2));
|
||||
if (actualRespLen != nRespDataBytes)
|
||||
{
|
||||
LOG_ERROR("Failed receive, data to short: actual[", actualRespLen, "], expected[", nRespDataBytes, "]");
|
||||
#ifdef DEBUGLOG_DEFAULT_LOG_LEVEL_TRACE
|
||||
printBytes("readBinary Response", response);
|
||||
#endif
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -172,7 +207,7 @@ namespace drivers
|
||||
uint16_t bitNum(0);
|
||||
|
||||
// get response data bytes excluding header and crc
|
||||
const std::vector<uint8_t> respData(response.begin() + RESP_HEADER_SIZE, response.end() - sizeof(crc_t));
|
||||
const std::vector<uint8_t> respData(response.begin() + c_respHeaderSize, response.end() - sizeof(crc_t));
|
||||
for (auto it = respData.begin(); it < respData.end(); it++)
|
||||
{
|
||||
for (uint8_t j(0); j < 8 && bitNum < bits; j++)
|
||||
@@ -193,16 +228,16 @@ namespace drivers
|
||||
return false;
|
||||
}
|
||||
const uint16_t nRespDataBytes = num * sizeof(uint16_t);
|
||||
const uint16_t expectedRespLen = (RESP_HEADER_SIZE + sizeof(crc_t)) + 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;
|
||||
if (!readN(expectedRespLen, response))
|
||||
{
|
||||
LOG_ERROR("Failed receive readInteger response, expected[", expectedRespLen, "], received[", response.size(), "]");
|
||||
#ifdef DEBUGLOG_DEFAULT_LOG_LEVEL_TRACE
|
||||
printBytes("readInteger Response", response);
|
||||
#endif
|
||||
return false;
|
||||
}
|
||||
#ifdef DEBUGLOG_DEFAULT_LOG_LEVEL_TRACE
|
||||
printBytes("readInteger Response", response);
|
||||
#endif
|
||||
|
||||
// element 2 of response has the response data bytes expected
|
||||
const uint8_t actualRespLen(response.at(2));
|
||||
@@ -220,7 +255,7 @@ namespace drivers
|
||||
out.clear();
|
||||
out.reserve(nRespDataBytes / sizeof(uint16_t));
|
||||
// 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 it = respData.begin(); it < respData.end(); it++)
|
||||
{
|
||||
const uint8_t lo(*it++);
|
||||
@@ -270,11 +305,11 @@ namespace drivers
|
||||
if (!readN(expectedRespLen, response))
|
||||
{
|
||||
LOG_ERROR("Failed receive writeBinary response, expected[", expectedRespLen, "], received[", response.size(), "]");
|
||||
#ifdef DEBUGLOG_DEFAULT_LOG_LEVEL_TRACE
|
||||
printBytes("writeBinary Response", response);
|
||||
#endif
|
||||
return false;
|
||||
}
|
||||
#ifdef DEBUGLOG_DEFAULT_LOG_LEVEL_TRACE
|
||||
printBytes("writeBinary Response", response);
|
||||
#endif
|
||||
|
||||
// compute crc of current message
|
||||
if (!verifyCrc(response))
|
||||
@@ -283,10 +318,10 @@ namespace drivers
|
||||
return true;
|
||||
}
|
||||
|
||||
const bool MODBUS::writeInteger(const uint8_t device, const uint8_t func, const uint16_t reg, const std::vector<uint16_t> &in)
|
||||
const bool MODBUS::writeInteger(const uint8_t device, const uint8_t func, const uint16_t reg, const std::vector<uint16_t> &in, const bool multi)
|
||||
{
|
||||
const uint16_t num(in.size());
|
||||
if (num == 1)
|
||||
if (!multi)
|
||||
{
|
||||
if (!write(singleRequest(device, func, reg, in[0])))
|
||||
{
|
||||
@@ -298,14 +333,14 @@ namespace drivers
|
||||
{
|
||||
// build data vector for request, inverting bytes if necessary
|
||||
std::vector<uint8_t> requestData;
|
||||
requestData.resize(in.size() * sizeof(uint16_t));
|
||||
auto it=requestData.begin();
|
||||
std::for_each(in.begin(), in.end(), [requestData, &it](auto inV) {
|
||||
requestData.resize(in.size() * sizeof(uint16_t), 0xff);
|
||||
auto it = requestData.begin();
|
||||
for (auto inV : in)
|
||||
{
|
||||
const uint16_t beV(htobe16(inV));
|
||||
*it=highByte(beV);
|
||||
*(++it)=lowByte(beV);
|
||||
});
|
||||
|
||||
*(it++) = lowByte(beV);
|
||||
*(it++) = highByte(beV);
|
||||
}
|
||||
if (!write(multiRequest(device, func, reg, num, requestData)))
|
||||
{
|
||||
LOG_ERROR("Failed send writeMultiInteger command");
|
||||
@@ -318,11 +353,11 @@ namespace drivers
|
||||
if (!readN(expectedRespLen, response))
|
||||
{
|
||||
LOG_ERROR("Failed receive writeInteger response, expected[", expectedRespLen, "], received[", response.size(), "]");
|
||||
#ifdef DEBUGLOG_DEFAULT_LOG_LEVEL_TRACE
|
||||
printBytes("writeInteger Response", response);
|
||||
#endif
|
||||
return false;
|
||||
}
|
||||
#ifdef DEBUGLOG_DEFAULT_LOG_LEVEL_TRACE
|
||||
printBytes("writeInteger Response", response);
|
||||
#endif
|
||||
|
||||
// compute crc of current message
|
||||
if (!verifyCrc(response))
|
||||
@@ -366,7 +401,7 @@ namespace drivers
|
||||
header.qty = htobe16(qty);
|
||||
header.bytes = data.size(); // 8 bit value
|
||||
|
||||
//const uint8_t headerBytes(sizeof(req_multi_t)); // sizeof not working because of memory padding
|
||||
// const uint8_t headerBytes(sizeof(req_multi_t)); // sizeof not working because of memory padding
|
||||
const uint8_t headerBytes(7);
|
||||
const uint8_t dataBytes(data.size());
|
||||
const uint8_t crcBytes(sizeof(crc_t));
|
||||
@@ -380,7 +415,7 @@ namespace drivers
|
||||
std::vector<uint8_t> dataOut;
|
||||
dataOut.resize(headerBytes + dataBytes + crcBytes); // header message + data values + crc code
|
||||
std::memcpy(dataOut.data(), &header, headerBytes); // copy message
|
||||
std::memcpy(dataOut.data() + headerBytes, data.data(), dataBytes); // copy data
|
||||
std::memcpy(dataOut.data() + headerBytes, data.data(), dataBytes); // copy data
|
||||
std::memcpy(dataOut.data() + headerBytes + dataBytes, &crc, crcBytes); // copy crc
|
||||
|
||||
#ifdef DEBUGLOG_DEFAULT_LOG_LEVEL_TRACE
|
||||
|
||||
@@ -1,19 +1,25 @@
|
||||
#pragma once
|
||||
|
||||
#define DEBUGLOG_DEFAULT_LOG_LEVEL_INFO
|
||||
|
||||
#include <DebugLog.h>
|
||||
#include <Arduino.h>
|
||||
#include <HardwareSerial.h> // Reference the ESP32 built-in serial port library
|
||||
#include <CRC16.h>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
|
||||
namespace drivers
|
||||
{
|
||||
class RS485
|
||||
{
|
||||
static const uint8_t PORT = 1;
|
||||
const uint8_t c_port = 1;
|
||||
|
||||
public:
|
||||
RS485(const uint32_t baud, const SerialConfig conf);
|
||||
RS485(const RS485 &) = delete; // remove copy constructors
|
||||
RS485 &operator=(const RS485 &) = delete;
|
||||
|
||||
const bool write(const std::vector<uint8_t> data);
|
||||
const bool readAll(std::vector<uint8_t> &data);
|
||||
const bool readN(const uint16_t nBytes, std::vector<uint8_t> &data);
|
||||
@@ -26,8 +32,9 @@ namespace drivers
|
||||
class MODBUS : private RS485
|
||||
{
|
||||
|
||||
static const uint8_t RESP_HEADER_SIZE = 3;
|
||||
static const uint8_t RESP_CRC_SIZE = 2;
|
||||
const uint8_t c_respHeaderSize = 3;
|
||||
const uint8_t c_respCrcSize = 2;
|
||||
const uint32_t c_minDelay = 500;
|
||||
|
||||
typedef struct
|
||||
{
|
||||
@@ -50,8 +57,13 @@ namespace drivers
|
||||
typedef uint16_t crc_t;
|
||||
|
||||
public:
|
||||
|
||||
MODBUS(const uint32_t baud, const SerialConfig conf);
|
||||
MODBUS(const MODBUS &) = delete; // remove copy constructors
|
||||
MODBUS &operator=(const MODBUS &) = delete;
|
||||
|
||||
// Get transaction lock
|
||||
std::unique_lock<std::mutex> getLock();
|
||||
std::mutex &getMutex();
|
||||
|
||||
// Func 0x01
|
||||
const bool readCoils(const uint8_t device, const uint16_t reg, const uint16_t num, std::vector<bool> &coils);
|
||||
@@ -79,12 +91,16 @@ namespace drivers
|
||||
|
||||
private:
|
||||
CRC16 m_crc;
|
||||
std::mutex m_mutex;
|
||||
uint8_t m_lastDevice;
|
||||
uint32_t m_lastAccess;
|
||||
void delayAccess(const uint8_t device);
|
||||
const std::vector<uint8_t> singleRequest(const uint8_t device, const uint8_t func, const uint16_t reg, const uint16_t data);
|
||||
const std::vector<uint8_t> multiRequest(const uint8_t device, const uint8_t func, const uint16_t reg, const uint16_t qty, const std::vector<uint8_t> &data);
|
||||
const bool readBinary(const uint8_t device, const uint8_t func, const uint16_t reg, const uint16_t bits, std::vector<bool> &out);
|
||||
const bool readInteger(const uint8_t device, const uint8_t func, const uint16_t reg, const uint16_t num, std::vector<uint16_t> &out);
|
||||
const bool writeBinary(const uint8_t device, const uint8_t func, const uint16_t reg, const std::vector<bool> &in);
|
||||
const bool writeInteger(const uint8_t device, const uint8_t func, const uint16_t reg, const std::vector<uint16_t> &in);
|
||||
const bool 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);
|
||||
};
|
||||
}
|
||||
|
||||
@@ -164,7 +164,7 @@ namespace drivers
|
||||
return datetime2str(dt);
|
||||
}
|
||||
|
||||
PCF85063::datetime_t PCF85063::fromEpoch(time_t currentTime)
|
||||
const PCF85063::datetime_t PCF85063::fromEpoch(const time_t currentTime)
|
||||
{
|
||||
PCF85063::datetime_t tm;
|
||||
struct tm *localTime = std::localtime(¤tTime);
|
||||
@@ -178,7 +178,7 @@ namespace drivers
|
||||
return tm;
|
||||
}
|
||||
|
||||
const std::string PCF85063::datetime2str(datetime_t &datetime)
|
||||
const std::string PCF85063::datetime2str(const datetime_t &datetime)
|
||||
{
|
||||
tm dtime;
|
||||
dtime.tm_sec = datetime.second;
|
||||
@@ -188,7 +188,8 @@ namespace drivers
|
||||
dtime.tm_mday = datetime.day;
|
||||
dtime.tm_mon = datetime.month - 1;
|
||||
dtime.tm_year = datetime.year - 1900; // time offset in structure according cpp reference
|
||||
return std::string(std::asctime(&dtime));
|
||||
const std::string buf(std::asctime(&dtime));
|
||||
return buf.substr(0, std::min(buf.find('\n'),buf.find('\r')));
|
||||
}
|
||||
|
||||
const uint8_t PCF85063::decToBcd(const int val)
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
#pragma once
|
||||
|
||||
#define DEBUGLOG_DEFAULT_LOG_LEVEL_INFO
|
||||
|
||||
#include <DebugLog.h>
|
||||
#include "I2C_Driver.h"
|
||||
#include <string>
|
||||
|
||||
@@ -60,38 +63,6 @@
|
||||
|
||||
#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
|
||||
{
|
||||
|
||||
@@ -130,10 +101,10 @@ namespace drivers
|
||||
const bool readAlarm(datetime_t &time);
|
||||
const bool getAlarmFlag(uint8_t &flags);
|
||||
|
||||
const std::string datetime2str(datetime_t &datetime);
|
||||
const std::string getTimeStr();
|
||||
|
||||
static PCF85063::datetime_t fromEpoch(time_t currentTime);
|
||||
|
||||
static const std::string datetime2str(const datetime_t &datetime);
|
||||
static const PCF85063::datetime_t fromEpoch(const time_t currentTime);
|
||||
|
||||
private:
|
||||
const uint8_t decToBcd(const int val);
|
||||
|
||||
146
lib/SENECA/S50140_Driver.cpp
Normal file
146
lib/SENECA/S50140_Driver.cpp
Normal file
@@ -0,0 +1,146 @@
|
||||
#include <S50140_Driver.h>
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
void S50140::delayRequest()
|
||||
{
|
||||
auto now = millis();
|
||||
if ((now - m_lastRequest) < c_minDelay)
|
||||
{ // minimum m_lastRequest between requests
|
||||
LOG_DEBUG("S50140 delay request", (now-m_lastRequest));
|
||||
delay(now - m_lastRequest);
|
||||
}
|
||||
m_lastRequest = millis();
|
||||
}
|
||||
|
||||
const uint8_t S50140::getRegset()
|
||||
{
|
||||
std::vector<uint16_t> value;
|
||||
std::lock_guard<std::mutex> lock(m_bus.getMutex());
|
||||
delayRequest();
|
||||
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());
|
||||
delayRequest();
|
||||
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);
|
||||
delayRequest();
|
||||
LOG_WARN("Powermeter Counter STOP");
|
||||
ok &= m_bus.writeRegisters(m_address, REG_PartCount, {nullVal, stopAll});
|
||||
delayRequest();
|
||||
LOG_WARN("Powermeter Counter RESET");
|
||||
ok &= m_bus.writeRegisters(m_address, REG_PartCount, {nullVal, resetAll});
|
||||
delayRequest();
|
||||
LOG_WARN("Powermeter Counter START");
|
||||
ok &= m_bus.writeRegisters(m_address, REG_PartCount, {nullVal, startAll});
|
||||
if (ok)
|
||||
return;
|
||||
LOG_ERROR("Unable to Reset Powermeter Partial Counters, device", m_address);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
float_t S50140::readFloatReg(const uint16_t reg)
|
||||
{
|
||||
uint8_t retries(0);
|
||||
std::vector<uint16_t> values;
|
||||
|
||||
while (retries++ < c_maxRetries)
|
||||
{
|
||||
delayRequest();
|
||||
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", m_address);
|
||||
}
|
||||
return MAXFLOAT;
|
||||
}
|
||||
|
||||
}
|
||||
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>
|
||||
|
||||
namespace drivers
|
||||
{
|
||||
|
||||
class S50140
|
||||
{
|
||||
private:
|
||||
const uint8_t c_maxRetries = 5;
|
||||
const uint8_t c_dataWords = 2;
|
||||
const uint32_t c_minDelay = 500;
|
||||
|
||||
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:
|
||||
void delayRequest();
|
||||
float_t readFloatReg(const uint16_t reg);
|
||||
|
||||
private:
|
||||
const uint8_t m_address;
|
||||
drivers::MODBUS &m_bus;
|
||||
uint32_t m_lastRequest;
|
||||
};
|
||||
}
|
||||
148
lib/TEMP/R4DCB08_Driver.cpp
Normal file
148
lib/TEMP/R4DCB08_Driver.cpp
Normal file
@@ -0,0 +1,148 @@
|
||||
#include <R4DCB08_Driver.h>
|
||||
|
||||
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()
|
||||
{
|
||||
}
|
||||
|
||||
void R4DCB08::delayRequest()
|
||||
{
|
||||
auto now = millis();
|
||||
if ((now - m_lastRequest) < c_minDelay)
|
||||
{ // minimum m_lastRequest between requests
|
||||
LOG_DEBUG("R4DCB08 delay request", (now-m_lastRequest));
|
||||
delay(now - m_lastRequest);
|
||||
}
|
||||
m_lastRequest = millis();
|
||||
}
|
||||
|
||||
const float R4DCB08::getTemp(const uint8_t ch)
|
||||
{
|
||||
uint8_t retries(0);
|
||||
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)
|
||||
{
|
||||
delayRequest();
|
||||
if (m_bus.readHoldingRegisters(m_address, REG_TEMP + ch, 1, rawT) && !rawT.empty())
|
||||
{
|
||||
return rawT.front() / 10.0f;
|
||||
}
|
||||
LOG_ERROR("Failed to Read Temperature, device", m_address, "channel", ch);
|
||||
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)
|
||||
{
|
||||
delayRequest();
|
||||
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", m_address);
|
||||
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)
|
||||
{
|
||||
delayRequest();
|
||||
if (m_bus.writeRegister(m_address, REG_TEMPCORR + channel, v * 10)) // convert to decimal degreees to register value
|
||||
{
|
||||
channel++;
|
||||
break;
|
||||
}
|
||||
LOG_ERROR("Failed to Set Temperature Correction, device", m_address);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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)
|
||||
{
|
||||
delayRequest();
|
||||
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", m_address);
|
||||
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)
|
||||
{
|
||||
delayRequest();
|
||||
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", m_address);
|
||||
}
|
||||
LOG_ERROR("No Temperature Sensors Detected, device", m_address);
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
55
lib/TEMP/R4DCB08_Driver.h
Normal file
55
lib/TEMP/R4DCB08_Driver.h
Normal file
@@ -0,0 +1,55 @@
|
||||
#pragma once
|
||||
|
||||
#define DEBUGLOG_DEFAULT_LOG_LEVEL_INFO
|
||||
|
||||
#include <DebugLog.h>
|
||||
#include <RS485_Driver.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;
|
||||
};
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
#include "utils.h"
|
||||
|
||||
|
||||
void printBytes(const char title[], const std::vector<uint8_t> &b)
|
||||
{
|
||||
Serial0.flush();
|
||||
@@ -18,20 +19,32 @@ void printBytes(const char title[], const std::vector<uint16_t> &b)
|
||||
printf("%s: ", title);
|
||||
for (auto v : b)
|
||||
{
|
||||
printf("0x%04x ", v);
|
||||
}
|
||||
printf("\n");
|
||||
Serial0.flush();
|
||||
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();
|
||||
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;
|
||||
}
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
#pragma once
|
||||
|
||||
#define DEBUGLOG_DEFAULT_LOG_LEVEL_INFO
|
||||
|
||||
#include <Arduino.h>
|
||||
#include <DebugLog.h>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
///////////// UTIL Functions /////////////////
|
||||
@@ -11,3 +14,5 @@ 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);
|
||||
|
||||
@@ -18,6 +18,11 @@ lib_deps =
|
||||
knolleary/PubSubClient@^2.8
|
||||
robtillaart/CRC@^1.0.3
|
||||
hideakitai/DebugLog@^0.8.4
|
||||
build_type = release
|
||||
|
||||
board_build.filesystem = ffat
|
||||
board_build.partitions = fatfs_partition.csv ; se stai usando uno custom
|
||||
|
||||
|
||||
[env:esp32-s3-waveshare8-debug]
|
||||
platform = ${env:esp32-s3-waveshare8.platform}
|
||||
@@ -38,3 +43,6 @@ build_flags =
|
||||
-fno-ipa-sra
|
||||
-fno-tree-sra
|
||||
-fno-builtin
|
||||
|
||||
board_build.filesystem = ffat
|
||||
board_build.partitions = fatfs_partition.csv ; se stai usando uno custom
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
#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)
|
||||
{
|
||||
@@ -9,31 +10,76 @@ digitalIO::digitalIO(drivers::I2C &i2c, drivers::MODBUS &bus, std::vector<uint8_
|
||||
|
||||
for (auto a : remotes)
|
||||
{
|
||||
m_remotes.emplace_back(remoteIO(a, bus));
|
||||
m_remotes.emplace_back(a, bus);
|
||||
}
|
||||
LOG_INFO("Initialized digitalIO -> inputs", getInNum(), "outputs", getOutNum());
|
||||
}
|
||||
|
||||
digitalIO::~digitalIO()
|
||||
{
|
||||
}
|
||||
|
||||
void digitalIO::digitalIOWrite(const uint8_t ch, const bool value)
|
||||
void digitalIO::digitalOutWrite(const uint8_t ch, const bool value)
|
||||
{
|
||||
if (ch < 0 || ch > getOutNum())
|
||||
{
|
||||
LOG_ERROR("Invalid digitalIOWrite channel number", ch);
|
||||
LOG_ERROR("Invalid digitalOutWrite channel number", ch);
|
||||
return;
|
||||
}
|
||||
|
||||
if (ch < drivers::TCA9554PWR::DO_MAX) // write to i2c device for local outputs
|
||||
{
|
||||
digitalWriteLocal(ch, value);
|
||||
writeLocal(ch, value);
|
||||
}
|
||||
else
|
||||
{
|
||||
digitalWriteRemote(ch - drivers::TCA9554PWR::DO_MAX, value);
|
||||
writeRemote(ch - drivers::TCA9554PWR::DO_MAX, value);
|
||||
}
|
||||
}
|
||||
const bool digitalIO::digitalIORead(const uint8_t ch)
|
||||
|
||||
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 std::move(rv);
|
||||
}
|
||||
|
||||
const bool digitalIO::digitalInRead(const uint8_t ch)
|
||||
{
|
||||
if (ch < 0 || ch > getInNum())
|
||||
{
|
||||
@@ -42,83 +88,281 @@ const bool digitalIO::digitalIORead(const uint8_t ch)
|
||||
|
||||
if (ch < (DI_MAX - DI1)) // read from local inputs not as gpio numbers
|
||||
{
|
||||
return digitalReadLocal(ch);
|
||||
return readLocalIn(ch);
|
||||
}
|
||||
else
|
||||
{
|
||||
return digitalReadRemote(ch - (DI_MAX - DI1));
|
||||
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 std::move(rv);
|
||||
}
|
||||
|
||||
void digitalIO::reset()
|
||||
{
|
||||
// set all local and remote outputs to 0
|
||||
m_localOuts.setPort(0x00);
|
||||
for (auto r: m_remotes)
|
||||
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 drivers::TCA9554PWR::DO_MAX + m_remotes.size() * remoteIO::CH_MAX;
|
||||
return getLocalOutNum() + getRemoteOutNum();
|
||||
}
|
||||
|
||||
const uint8_t digitalIO::getInNum()
|
||||
{
|
||||
return DI_MAX + m_remotes.size() * remoteIO::CH_MAX;
|
||||
return getLocalInNum() + getRemoteInNum();
|
||||
}
|
||||
|
||||
void digitalIO::digitalWriteLocal(const uint8_t ch, const bool value)
|
||||
void digitalIO::writeLocal(const uint8_t ch, const bool value)
|
||||
{
|
||||
uint8_t retries(0);
|
||||
while (retries++ < maxRetries)
|
||||
while (retries++ < c_maxRetries)
|
||||
{
|
||||
if (m_localOuts.setOut(ch, value))
|
||||
{
|
||||
LOG_DEBUG("digitalWriteLocal channel", ch, " status", value ? "True" : "False");
|
||||
break;
|
||||
LOG_DEBUG("writeLocal channel", ch, " status", value ? "True" : "False");
|
||||
return;
|
||||
}
|
||||
LOG_ERROR("Failed digitalWriteLocal channel ", ch, " status", value ? "True" : "False");
|
||||
LOG_ERROR("Failed writeLocal channel ", ch, " status", value ? "True" : "False");
|
||||
}
|
||||
}
|
||||
|
||||
void digitalIO::digitalWriteRemote(const uint8_t ch, const bool value)
|
||||
void digitalIO::writeLocalPort(const std::vector<bool> &values)
|
||||
{
|
||||
uint8_t retries(0);
|
||||
const uint8_t selectedRemote(floor(ch / 8.0f));
|
||||
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++ < maxRetries)
|
||||
while (retries++ < c_maxRetries)
|
||||
{
|
||||
if (m_remotes[selectedRemote].setOut((remoteIO::channel_t)selectedChannel, value))
|
||||
{
|
||||
LOG_DEBUG("digitalWriteRemote remote", selectedRemote, " channel ", selectedChannel, " status", value ? "True" : "False");
|
||||
break;
|
||||
LOG_DEBUG("writeRemote remote", selectedRemote, " channel ", selectedChannel, " status", value ? "True" : "False");
|
||||
return;
|
||||
}
|
||||
LOG_ERROR("Failed digitalWriteRemote remote", selectedRemote, " channel ", selectedChannel, " status", value ? "True" : "False");
|
||||
LOG_ERROR("Failed writeRemote remote", selectedRemote, " channel ", selectedChannel, " status", value ? "True" : "False");
|
||||
}
|
||||
}
|
||||
|
||||
const bool digitalIO::digitalReadLocal(const uint8_t ch)
|
||||
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("digitalReadLocal pin", (ch + DI1), " status", value ? "True" : "False");
|
||||
LOG_DEBUG("readLocalIn pin", (ch + DI1), " status", value ? "True" : "False");
|
||||
return value;
|
||||
}
|
||||
|
||||
const bool digitalIO::digitalReadRemote(const uint8_t ch)
|
||||
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++ < maxRetries)
|
||||
while (retries++ < c_maxRetries)
|
||||
{
|
||||
if (m_remotes[selectedRemote].getIn((remoteIO::channel_t)selectedChannel, value))
|
||||
{
|
||||
LOG_DEBUG("digitalReadRemote remote", selectedRemote, " channel ", selectedChannel, " status", value ? "True" : "False");
|
||||
LOG_DEBUG("readRemoteIn remote", selectedRemote, " channel ", selectedChannel, " status", value ? "True" : "False");
|
||||
return value;
|
||||
}
|
||||
LOG_ERROR("Failed digitalReadRemote remote", selectedRemote, " channel ", selectedChannel, " status", value ? "True" : "False");
|
||||
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;
|
||||
}
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
#pragma once
|
||||
|
||||
#define DEBUGLOG_DEFAULT_LOG_LEVEL_INFO
|
||||
|
||||
#include <DebugLog.h>
|
||||
#include <Arduino.h>
|
||||
|
||||
#include <remoteIO.h>
|
||||
#include <TCA9554PWR_Driver.h>
|
||||
|
||||
@@ -25,25 +28,44 @@ private:
|
||||
DI_MAX
|
||||
};
|
||||
|
||||
const uint8_t maxRetries = 5;
|
||||
const uint8_t c_maxRetries = 5;
|
||||
|
||||
public:
|
||||
digitalIO(drivers::I2C &i2c, drivers::MODBUS &bus, std::vector<uint8_t> remotes);
|
||||
~digitalIO();
|
||||
|
||||
void digitalIOWrite(const uint8_t ch, const bool value);
|
||||
const bool digitalIORead(const uint8_t ch);
|
||||
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:
|
||||
void digitalWriteLocal(const uint8_t ch, const bool value);
|
||||
void digitalWriteRemote(const uint8_t ch, const bool value);
|
||||
private:
|
||||
const uint8_t getLocalInNum();
|
||||
const uint8_t getLocalOutNum();
|
||||
const uint8_t getRemoteInNum();
|
||||
const uint8_t getRemoteOutNum();
|
||||
|
||||
const bool digitalReadLocal(const uint8_t ch);
|
||||
const bool digitalReadRemote(const uint8_t ch);
|
||||
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;
|
||||
|
||||
210
src/main.cpp
210
src/main.cpp
@@ -1,79 +1,124 @@
|
||||
#define DEBUGLOG_DEFAULT_LOG_LEVEL_DEBUG
|
||||
|
||||
#include <Arduino.h>
|
||||
#include <DebugLog.h>
|
||||
#include <DebugLogEnable.h>
|
||||
#include <Arduino.h>
|
||||
#include <PubSubClient.h>
|
||||
|
||||
#include <config.h>
|
||||
#include <PCF85063_Driver.h>
|
||||
#include <R4DCB08_Driver.h>
|
||||
#include <S50140_Driver.h>
|
||||
#include <BUZZER_Driver.h>
|
||||
#include <LED_Driver.h>
|
||||
#include <ETH_Driver.h>
|
||||
|
||||
#include <digitalIO.h>
|
||||
|
||||
#include <mqtt.h>
|
||||
#include "utils.h"
|
||||
|
||||
void callback(char *topic, uint8_t *payload, unsigned int length)
|
||||
/////////////// GLOBALS ///////////////
|
||||
Config &conf = Config::getInstance();
|
||||
/////////////// GLOBALS ///////////////
|
||||
|
||||
void testAction(const ArduinoJson::JsonDocument &doc)
|
||||
{
|
||||
std::string pl;
|
||||
pl.resize(length);
|
||||
std::snprintf(pl.data(), length, "%s", payload);
|
||||
LOG_INFO("Message: Topic [", topic, "], Payload [", pl.c_str(), "]");
|
||||
std::string message;
|
||||
ArduinoJson::serializeJsonPretty(doc, message);
|
||||
LOG_INFO("Received on testAction\n", message.c_str());
|
||||
}
|
||||
|
||||
void myTask(void *mqtt)
|
||||
{
|
||||
while (true)
|
||||
{
|
||||
((PubSubClient *)(mqtt))->loop();
|
||||
vTaskDelay(pdMS_TO_TICKS(100));
|
||||
}
|
||||
};
|
||||
|
||||
/////////////// GLOBALS ///////////////
|
||||
void setup()
|
||||
{
|
||||
Serial.begin(9600);
|
||||
LOG_ATTACH_SERIAL(Serial);
|
||||
conf.init(); // read the configuration from internal flash
|
||||
}
|
||||
|
||||
void loop()
|
||||
{
|
||||
const uint8_t tempBoardAddr(0xAA);
|
||||
const uint8_t relayBoardAddr(0x01);
|
||||
const uint8_t baseRegister(0x00);
|
||||
uint16_t k(0);
|
||||
uint8_t ethRetries(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 rtc = drivers::PCF85063(i2c, PCF85063_ADDRESS);
|
||||
auto eth = drivers::Ethernet("waveshare-test");
|
||||
auto io = digitalIO(i2c, bus, {relayBoardAddr});
|
||||
auto eth = drivers::Ethernet(conf.m_ethHostname);
|
||||
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});
|
||||
// Initialize temperature sensors
|
||||
sensors = tmp.getNum();
|
||||
LOG_INFO("Temperature sensors connected ->", sensors);
|
||||
//////////////// DEVICES ////////////////
|
||||
|
||||
Network.onEvent([ð](arduino_event_id_t event, arduino_event_info_t info)
|
||||
{ eth.onEvent(event, info); });
|
||||
//////////////// NETWORK ////////////////
|
||||
auto mqtt = MQTTwrapper();
|
||||
//////////////// NETWORK ////////////////
|
||||
|
||||
while (!eth.isConnected() && ethRetries++ < 5)
|
||||
std::function<void(const ArduinoJson::JsonDocument &)> mycallback =
|
||||
[&io](const ArduinoJson::JsonDocument &doc)
|
||||
{
|
||||
LOG_WARN("Waiting for Ethernet retry", ethRetries);
|
||||
delay(1000);
|
||||
}
|
||||
std::vector<bool> v1 = {1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0};
|
||||
std::vector<bool> v2 = {0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1};
|
||||
std::vector<bool> v0(io.getOutNum(), 0);
|
||||
|
||||
// Get RTC time at startup
|
||||
time_t ntpTime;
|
||||
drivers::PCF85063::datetime_t dt;
|
||||
LOG_INFO("SET Digital Outputs V1: ", printBoolVec(v1).c_str());
|
||||
io.digitalOutWritePort(v1);
|
||||
delay(100);
|
||||
LOG_INFO("GET Digital Outputs V1: ", printBoolVec(io.digitalOutReadPort()).c_str());
|
||||
delay(2000);
|
||||
|
||||
// MQTT Test
|
||||
NetworkClient tcp;
|
||||
PubSubClient mqtt(tcp);
|
||||
LOG_INFO("SET Digital Outputs V2: ", printBoolVec(v2).c_str());
|
||||
io.digitalOutWritePort(v2);
|
||||
delay(100);
|
||||
LOG_INFO("GET Digital Outputs V2: ", printBoolVec(io.digitalOutReadPort()).c_str());
|
||||
delay(2000);
|
||||
|
||||
mqtt.setServer("10.0.2.249", 1883);
|
||||
mqtt.setCallback(callback);
|
||||
mqtt.connect("esp32-client");
|
||||
mqtt.subscribe("test/esp32-in");
|
||||
xTaskCreatePinnedToCore(myTask, "mqttLoop", 4096, &mqtt, 2, NULL, 1);
|
||||
LOG_INFO("GET Digital Inputs: ", printBoolVec(io.digitalInReadPort()).c_str());
|
||||
io.digitalOutWritePort(v0);
|
||||
};
|
||||
|
||||
//////////////// NETWORK ////////////////
|
||||
/////////////// CALLBACK ////////////////
|
||||
Network.onEvent(
|
||||
[ð, &rtc, &mqtt, &buzzer, &led, &mycallback](arduino_event_id_t event, arduino_event_info_t info) -> void
|
||||
{
|
||||
eth.onEvent(event, info); // Arduino Ethernet event handler
|
||||
if (!eth.isConnected())
|
||||
return;
|
||||
// Get RTC time at ethernet connection
|
||||
time_t ntpTime;
|
||||
uint8_t timeRetries(0);
|
||||
uint8_t mqttRetries(0);
|
||||
while (timeRetries++ < conf.m_ntpRetries)
|
||||
{
|
||||
if (eth.getNtpTime(ntpTime) && rtc.setDatetime(drivers::PCF85063::fromEpoch(ntpTime)))
|
||||
{
|
||||
// buzzer.beep(250, NOTE_F);
|
||||
led.setColor({255, 255, 0});
|
||||
const drivers::PCF85063::datetime_t dt(drivers::PCF85063::fromEpoch(ntpTime));
|
||||
LOG_INFO("NTP Time: ", drivers::PCF85063::datetime2str(dt).c_str());
|
||||
delay(100);
|
||||
}
|
||||
break;
|
||||
}
|
||||
while (mqttRetries++ < conf.m_mqttRetries)
|
||||
{
|
||||
if (mqtt.connect())
|
||||
{
|
||||
mqtt.subscribe("test/esp32-in", testAction);
|
||||
mqtt.subscribe("test/esp32-functional", mycallback);
|
||||
break;
|
||||
}
|
||||
delay(100);
|
||||
}
|
||||
});
|
||||
|
||||
////////////////////////////////////////
|
||||
///////// MAIN LOOP INSIDE LOOP ////////
|
||||
@@ -82,33 +127,78 @@ void loop()
|
||||
while (true)
|
||||
{
|
||||
LOG_INFO("[", k++, "] Loop");
|
||||
std::vector<uint16_t> results;
|
||||
std::vector<bool> values;
|
||||
|
||||
eth.getNtpTime(ntpTime);
|
||||
dt = drivers::PCF85063::fromEpoch(ntpTime);
|
||||
LOG_INFO("Netwrok Datetime", rtc.datetime2str(dt).c_str());
|
||||
LOG_INFO("Current Datetime", rtc.getTimeStr().c_str());
|
||||
mqtt.publish("test/esp32-out", ("[" + std::to_string(k) + "] -> " + rtc.getTimeStr()).c_str());
|
||||
const std::string timeStr(rtc.getTimeStr());
|
||||
LOG_INFO("Current Datetime", timeStr.c_str());
|
||||
ArduinoJson::JsonDocument ts;
|
||||
ts["loopIterator"] = k;
|
||||
ts["currentTime"] = timeStr;
|
||||
mqtt.publish("test/esp32-out", ts);
|
||||
|
||||
if (bus.readHoldingRegisters(tempBoardAddr, baseRegister, 1, results))
|
||||
uint8_t i(0);
|
||||
for (auto v : tmp.getTempAll())
|
||||
{
|
||||
for (auto i(0); i < results.size(); i++)
|
||||
LOG_INFO("Temperature channel", i++, "->", v);
|
||||
}
|
||||
|
||||
LOG_INFO("Read Red");
|
||||
if (io.digitalInRead(0)) // rosso
|
||||
{
|
||||
std::vector<bool> v1 = {1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0};
|
||||
std::vector<bool> v2 = {0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1};
|
||||
std::vector<bool> v0(16, 0);
|
||||
|
||||
LOG_INFO("SET Digital Outputs V1: ", printBoolVec(v1).c_str());
|
||||
io.digitalOutWritePort(v1);
|
||||
LOG_INFO("GET Digital Outputs V1: ", printBoolVec(io.digitalOutReadPort()).c_str());
|
||||
delay(2000);
|
||||
|
||||
LOG_INFO("SET Digital Outputs V2: ", printBoolVec(v2).c_str());
|
||||
io.digitalOutWritePort(v2);
|
||||
LOG_INFO("GET Digital Outputs V2: ", printBoolVec(io.digitalOutReadPort()).c_str());
|
||||
delay(2000);
|
||||
|
||||
LOG_INFO("GET Digital Inputs: ", printBoolVec(io.digitalInReadPort()).c_str());
|
||||
delay(2000);
|
||||
|
||||
io.digitalOutWritePort(v0);
|
||||
delay(2000);
|
||||
}
|
||||
|
||||
LOG_INFO("Read Blue");
|
||||
if (io.digitalInRead(8)) // blu
|
||||
{
|
||||
if (!buzzing)
|
||||
{
|
||||
LOG_INFO("[", i, "]Temperature: ", results.at(i) / 10.0f);
|
||||
buzzing = true;
|
||||
buzzer.beepRepeat(100, 1000, NOTE_C);
|
||||
led.blinkColor(100, 500, {255, 0, 255});
|
||||
}
|
||||
results.clear();
|
||||
else
|
||||
{
|
||||
buzzer.beepStop();
|
||||
led.blinkAlternate(500, 500, {255, 255, 0}, {0, 255, 255});
|
||||
buzzing = false;
|
||||
}
|
||||
LOG_INFO("Buzzing -> ", buzzing ? "True" : "False");
|
||||
}
|
||||
|
||||
LOG_INFO("Read Green");
|
||||
if (io.digitalInRead(9))
|
||||
{ // verde
|
||||
conf.resetConfig();
|
||||
}
|
||||
|
||||
LOG_INFO("Read Yellow");
|
||||
if (io.digitalInRead(10))
|
||||
{ // giallo
|
||||
esp_restart();
|
||||
}
|
||||
|
||||
for (auto j(0); j < io.getOutNum(); j++)
|
||||
{
|
||||
//io.digitalIOWrite(j, true);
|
||||
LOG_INFO("Input", j, io.digitalIORead(j) ? "True" : "False");
|
||||
delay(500);
|
||||
}
|
||||
drivers::S50140::powerinfo_t pinfo = seneca.getAll();
|
||||
LOG_INFO("Power Info ==> V:", pinfo.v, "- A:", pinfo.a, "- W:", pinfo.pAct, "- F:", pinfo.f, "- Wh_t:", pinfo.whTot, "- Wh_p:", pinfo.whPar);
|
||||
|
||||
|
||||
delay(5000);
|
||||
delay(conf.m_globalLoopDelay);
|
||||
}
|
||||
|
||||
////////////////////////////////////////
|
||||
|
||||
176
src/mqtt.cpp
Normal file
176
src/mqtt.cpp
Normal file
@@ -0,0 +1,176 @@
|
||||
#include <mqtt.h>
|
||||
|
||||
#define STACK_DEPTH 4096
|
||||
#define PRIOTITY 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(15);
|
||||
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, PRIOTITY, &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(topic_t topic, action_t 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(topic_t 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(topic_t 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(), "]");
|
||||
return true;
|
||||
}
|
||||
LOG_ERROR("MQTT failed to publish topic [", topic.c_str(), "] - message [", message.c_str(), "]");
|
||||
return false;
|
||||
}
|
||||
|
||||
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 std::string topic, const std::string 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);
|
||||
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
|
||||
}
|
||||
75
src/mqtt.h
Normal file
75
src/mqtt.h
Normal file
@@ -0,0 +1,75 @@
|
||||
#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>
|
||||
|
||||
typedef std::string topic_t;
|
||||
typedef std::function<void(const ArduinoJson::JsonDocument &)> action_t; // the actions receive a JsonObject containing the received message
|
||||
typedef std::map<topic_t, action_t> action_map_t;
|
||||
|
||||
class MQTTwrapper
|
||||
{
|
||||
|
||||
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(topic_t topic, action_t action);
|
||||
const bool unsubscribe(topic_t topic);
|
||||
|
||||
const bool publish(topic_t topic, const ArduinoJson::JsonDocument obj);
|
||||
|
||||
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;
|
||||
action_map_t m_actionMap;
|
||||
NetworkClient m_tcp;
|
||||
PubSubClient m_client;
|
||||
TaskHandle_t m_loopHandle;
|
||||
};
|
||||
@@ -4,12 +4,14 @@ remoteIO::remoteIO(const uint8_t address, drivers::MODBUS &bus) : m_address(addr
|
||||
{
|
||||
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);
|
||||
}
|
||||
|
||||
@@ -19,10 +21,23 @@ remoteIO::~remoteIO()
|
||||
resetAll(false);
|
||||
}
|
||||
|
||||
void remoteIO::delayRequest()
|
||||
{
|
||||
auto now = millis();
|
||||
if ((now - m_lastRequest) < c_minDelay)
|
||||
{ // minimum m_lastRequest between requests
|
||||
LOG_DEBUG("remoteIO delay request", (now - m_lastRequest));
|
||||
delay(now - m_lastRequest);
|
||||
}
|
||||
m_lastRequest = millis();
|
||||
}
|
||||
|
||||
const bool remoteIO::setOut(const channel_t ch, const bool value)
|
||||
{
|
||||
if (!m_initialized)
|
||||
return false;
|
||||
std::lock_guard<std::mutex> lock(m_bus.getMutex());
|
||||
delayRequest();
|
||||
LOG_DEBUG("Write Channel", ch, "->", value ? "True" : "False");
|
||||
return m_bus.writeCoil(m_address, REG_COILS + ch, value);
|
||||
}
|
||||
@@ -31,6 +46,8 @@ const bool remoteIO::toggleOut(const channel_t ch)
|
||||
{
|
||||
if (!m_initialized)
|
||||
return false;
|
||||
std::lock_guard<std::mutex> lock(m_bus.getMutex());
|
||||
delayRequest();
|
||||
std::vector<bool> value;
|
||||
if (!m_bus.readCoils(m_address, REG_COILS + ch, 1, value))
|
||||
return false;
|
||||
@@ -42,14 +59,18 @@ const bool remoteIO::setOutPort(const std::vector<bool> values)
|
||||
{
|
||||
if (!m_initialized)
|
||||
return false;
|
||||
std::lock_guard<std::mutex> lock(m_bus.getMutex());
|
||||
delayRequest();
|
||||
LOG_DEBUG("Write Port", CH_MAX);
|
||||
return m_bus.writeCoils(m_address, CH_MAX, values);
|
||||
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());
|
||||
delayRequest();
|
||||
std::vector<bool> values;
|
||||
if (!m_bus.readCoils(m_address, REG_COILS + ch, 1, values))
|
||||
return false;
|
||||
@@ -62,14 +83,18 @@ const bool remoteIO::getOutPort(std::vector<bool> &values)
|
||||
{
|
||||
if (!m_initialized)
|
||||
return false;
|
||||
std::lock_guard<std::mutex> lock(m_bus.getMutex());
|
||||
delayRequest();
|
||||
LOG_DEBUG("Read Port", CH_MAX);
|
||||
return m_bus.readCoils(m_address, REG_COILS, 8, values);
|
||||
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());
|
||||
delayRequest();
|
||||
std::vector<bool> values;
|
||||
if (!m_bus.readInputs(m_address, REG_INPUT + input, 1, values))
|
||||
return false;
|
||||
@@ -82,6 +107,8 @@ const bool remoteIO::getInPort(std::vector<bool> &values)
|
||||
{
|
||||
if (!m_initialized)
|
||||
return false;
|
||||
std::lock_guard<std::mutex> lock(m_bus.getMutex());
|
||||
delayRequest();
|
||||
LOG_DEBUG("Read Inputs", CH_MAX);
|
||||
return m_bus.readInputs(m_address, REG_INPUT, CH_MAX, values);
|
||||
}
|
||||
|
||||
@@ -1,14 +1,28 @@
|
||||
#pragma once
|
||||
|
||||
#define DEBUGLOG_DEFAULT_LOG_LEVEL_INFO
|
||||
|
||||
#include <DebugLog.h>
|
||||
#include <RS485_Driver.h>
|
||||
|
||||
class remoteIO
|
||||
{
|
||||
public:
|
||||
typedef enum {CH1, CH2, CH3, CH4, CH5, CH6, CH7, CH8, CH_MAX} channel_t;
|
||||
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;
|
||||
@@ -30,8 +44,12 @@ public:
|
||||
|
||||
void resetAll(const bool value);
|
||||
|
||||
private:
|
||||
void delayRequest();
|
||||
|
||||
private:
|
||||
bool m_initialized;
|
||||
drivers::MODBUS &m_bus;
|
||||
const uint8_t m_address;
|
||||
uint32_t m_lastRequest;
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user