6 Commits

Author SHA1 Message Date
Emanuele Trabattoni
8f5615a034 Lock position fix 2025-07-22 11:30:07 +02:00
Emanuele Trabattoni
16bb029e93 Fix lock on MODBUS 2025-07-22 11:15:57 +02:00
Emanuele Trabattoni
146a2b558b Improved reconnection 2025-07-22 11:15:36 +02:00
Emanuele Trabattoni
7c776e4787 fixed auto reconnect and resubscribe inside mqtt wrapper loop 2025-07-18 19:29:19 +02:00
Emanuele Trabattoni
e8f395f8ef mqtt wrapper first version working 2025-07-18 02:00:58 +02:00
Emanuele Trabattoni
52a89e58f7 Merge branch 'drivers-refactoring' into pro-develop 2025-07-17 20:59:31 +02:00
12 changed files with 309 additions and 206 deletions

View File

@@ -1,120 +0,0 @@
#include "WS_ETH.h"
#include <NTPClient.h>
#include <WiFiUdp.h>
static bool eth_connected = false;
static bool eth_connected_Old = false;
IPAddress ETH_ip;
// NTP setup
WiFiUDP udp;
NTPClient timeClient(udp, "pool.ntp.org", 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(&currentTime);
//static datetime_t PCF85063_Time = {0};
//PCF85063_Time.year = localTime->tm_year + 1900;
//PCF85063_Time.month = localTime->tm_mon + 1;
//PCF85063_Time.day = localTime->tm_mday;
//PCF85063_Time.dotw = localTime->tm_wday;
//PCF85063_Time.hour = localTime->tm_hour;
//PCF85063_Time.minute = localTime->tm_min;
//PCF85063_Time.second = localTime->tm_sec;
//PCF85063_Set_All(PCF85063_Time);
}

View File

@@ -1,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);

View File

@@ -14,7 +14,7 @@ namespace drivers
ledcAttach(buzzerPin, 1000, 8);
m_bp.pin = buzzerPin;
m_bp.beeperTask = NULL;
beep(50, NOTE_G);
//beep(50, NOTE_G);
}
Buzzer::~Buzzer()

View File

@@ -71,7 +71,6 @@ namespace drivers
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;
std::lock_guard<std::mutex> lock(m_mutex);
LOG_DEBUG("Read coils: dev[", device, "], reg[", reg, "], num[", num, "]");
return readBinary(device, func, reg, num, coils);
}
@@ -80,7 +79,6 @@ 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;
std::lock_guard<std::mutex> lock(m_mutex);
LOG_DEBUG("Read multi inputs: dev[", device, "], reg[", reg, "], num[", num, "]");
return readBinary(device, func, reg, num, inputs);
}
@@ -89,7 +87,6 @@ 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;
std::lock_guard<std::mutex> lock(m_mutex);
LOG_DEBUG("Read multi holding registers: dev[", device, "], reg[", reg, "], num[", num, "]");
return readInteger(device, func, reg, num, values);
}
@@ -98,7 +95,6 @@ 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;
std::lock_guard<std::mutex> lock(m_mutex);
LOG_DEBUG("Read multi input registers: dev[", device, "], reg[", reg, "], num[", num, "]");
return readInteger(device, func, reg, num, values);
}
@@ -107,7 +103,6 @@ namespace drivers
const bool MODBUS::writeCoil(const uint8_t device, const uint16_t coil, const bool value)
{
constexpr uint8_t func = 0x05;
std::lock_guard<std::mutex> lock(m_mutex);
LOG_DEBUG("Write single coil: dev[", device, "], coil[", coil, "], value[", value ? "true" : "false", "]");
return writeBinary(device, func, coil, {value});
}
@@ -116,7 +111,6 @@ namespace drivers
const bool MODBUS::writeRegister(const uint8_t device, const uint16_t reg, const uint16_t value)
{
constexpr uint8_t func = 0x06;
std::lock_guard<std::mutex> lock(m_mutex);
LOG_DEBUG("Write single register: dev[", device, "], reg[", reg, "], value[", value, "]");
return writeInteger(device, func, reg, {value}, false);
}
@@ -125,7 +119,6 @@ namespace drivers
const bool MODBUS::writeCoils(const uint8_t device, const uint16_t coils, const std::vector<bool> &values)
{
constexpr uint8_t func = 0x0F;
std::lock_guard<std::mutex> lock(m_mutex);
LOG_DEBUG("Write multi coils: dev[", device, "], start[", coils, "], num[", values.size(), "]");
return writeBinary(device, func, coils, values);
}
@@ -134,7 +127,6 @@ 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;
std::lock_guard<std::mutex> lock(m_mutex);
LOG_DEBUG("Write multi registers: dev[", device, "], start[", reg, "], num[", values.size(), "]");
return writeInteger(device, func, reg, values, true);
}

View File

@@ -17,6 +17,9 @@ namespace drivers
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);
@@ -54,6 +57,13 @@ namespace drivers
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() {
return std::unique_lock<std::mutex>(m_mutex);
}
// Func 0x01
const bool readCoils(const uint8_t device, const uint16_t reg, const uint16_t num, std::vector<bool> &coils);

View File

@@ -76,6 +76,7 @@ namespace drivers
{
std::vector<uint16_t> value;
delayRequest();
auto lock = m_bus.getLock();
m_bus.readHoldingRegisters(m_address, REG_Regset, 2, value);
if (value.empty())
return UINT8_MAX;
@@ -86,6 +87,7 @@ namespace drivers
{
std::vector<uint16_t> value;
delayRequest();
auto lock = m_bus.getLock();
m_bus.readHoldingRegisters(m_address, REG_PartCount, 2, value);
if (value.empty())
return UINT16_MAX;
@@ -103,6 +105,7 @@ namespace drivers
{
bool ok(true);
delayRequest();
auto lock = m_bus.getLock();
LOG_WARN("Powermeter Counter STOP");
ok &= m_bus.writeRegisters(m_address, REG_PartCount, {nullVal, stopAll});
delayRequest();
@@ -126,6 +129,7 @@ namespace drivers
while (retries++ < maxRetries)
{
delayRequest();
auto lock = m_bus.getLock();
if (m_bus.readHoldingRegisters(m_address, reg, dataWords, values) && values.size() == dataWords)
{
floatval_t fv; // potrebbe essere il contrario, vedremo

View File

@@ -22,6 +22,7 @@ namespace drivers
}
while (retries++ < maxRetries)
{
auto lock = m_bus.getLock();
if (m_bus.readHoldingRegisters(m_address, REG_TEMP + ch, 1, rawT) && !rawT.empty())
{
return rawT.front() / 10.0f;
@@ -40,6 +41,7 @@ namespace drivers
std::vector<float> out;
while (retries++ < maxRetries)
{
auto lock = m_bus.getLock();
if (m_bus.readHoldingRegisters(m_address, REG_TEMP, getNum(), rawT) && !rawT.empty())
{
out.reserve(rawT.size());
@@ -67,6 +69,7 @@ namespace drivers
{ // convert to decimal degreees to register value
while (retries++ < maxRetries)
{
auto lock = m_bus.getLock();
if (m_bus.writeRegister(m_address, REG_TEMPCORR + channel, v*10))
{
channel++;
@@ -88,6 +91,7 @@ namespace drivers
while (retries++ < maxRetries)
{
auto lock = m_bus.getLock();
if (m_bus.readHoldingRegisters(m_address, REG_TEMPCORR, getNum(), rawV))
{
out.reserve(rawV.size());
@@ -114,6 +118,7 @@ namespace drivers
std::vector<uint16_t> rawT;
while (retries++ < maxRetries)
{
auto lock = m_bus.getLock();
if (m_bus.readHoldingRegisters(m_address, REG_TEMP, T_MAX, rawT))
{
for (auto v : rawT)

View File

@@ -4,7 +4,6 @@
#include <DebugLogEnable.h>
#include <Arduino.h>
#include <PubSubClient.h>
#include <config.h>
#include <PCF85063_Driver.h>
@@ -16,42 +15,30 @@
#include <digitalIO.h>
#define DEBUGLOG_DEFAULT_LOG_LEVEL_DEBUG
#include <mqtt.h>
#include "utils.h"
/////////////// GLOBALS ///////////////
Config& conf = Config::getInstance();
Config &conf = Config::getInstance();
/////////////// GLOBALS ///////////////
void callback(char *topic, uint8_t *payload, unsigned int length)
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)
{
auto client = (PubSubClient *)(mqtt);
while (client->connected())
{
client->loop();
vTaskDelay(pdMS_TO_TICKS(100));
}
LOG_ERROR("Mqtt Loop Ended, client disconnected");
vTaskDelete(NULL); // delete the current task
};
void setup()
{
Serial.begin(9600);
LOG_ATTACH_SERIAL(Serial);
conf.init();
conf.init(); // read the configuration from internal flash
}
void loop()
{
const uint8_t baseRegister(0x00);
uint16_t k(0);
uint8_t sensors(0);
bool buzzing(false);
@@ -75,17 +62,20 @@ void loop()
LOG_INFO("Temperature sensors connected ->", sensors);
//////////////// NETWORK ////////////////
// MQTT Test //
NetworkClient tcp;
PubSubClient mqtt(tcp);
mqtt.setServer(conf.m_mqttHost.c_str(), conf.m_mqttPort);
mqtt.setCallback(callback);
auto mqtt = MQTTwrapper();
//////////////// NETWORK ////////////////
std::function<void(const ArduinoJson::JsonDocument &)> mycallback =
[&io](const ArduinoJson::JsonDocument &doc) {
io.digitalIOWrite(0, doc["stat"].as<bool>());
io.digitalIOWrite(15, doc["stat"].as<bool>());
};
//////////////// NETWORK ////////////////
/////////////// CALLBACK ////////////////
Network.onEvent(
[&eth, &rtc, &mqtt, &buzzer, &led](arduino_event_id_t event, arduino_event_info_t info) -> void
[&eth, &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())
@@ -98,7 +88,7 @@ void loop()
{
if (eth.getNtpTime(ntpTime) && rtc.setDatetime(drivers::PCF85063::fromEpoch(ntpTime)))
{
buzzer.beep(250, NOTE_F);
//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());
@@ -108,10 +98,10 @@ void loop()
}
while (mqttRetries++ < conf.m_mqttRetries)
{
if (!mqtt.connected() && mqtt.connect(conf.m_mqttClientName.c_str()))
if (mqtt.connect())
{
mqtt.subscribe("test/esp32-in");
xTaskCreatePinnedToCore(myTask, "mqttLoop", 4096, &mqtt, 2, NULL, 1);
mqtt.subscribe("test/esp32-in", testAction);
mqtt.subscribe("test/esp32-functional", mycallback);
break;
}
delay(100);
@@ -128,7 +118,10 @@ void loop()
const std::string timeStr(rtc.getTimeStr());
LOG_INFO("Current Datetime", timeStr.c_str());
mqtt.publish("test/esp32-out", ("[" + std::to_string(k) + "] -> " + timeStr).c_str());
ArduinoJson::JsonDocument ts;
ts["loopIterator"] = k;
ts["currentTime"] = timeStr;
mqtt.publish("test/esp32-out", ts);
uint8_t i(0);
for (auto v : tmp.getTempAll())
@@ -172,11 +165,13 @@ void loop()
LOG_INFO("Buzzing -> ", buzzing ? "True" : "False");
}
if(io.digitalIORead(9)) { // verde
if (io.digitalIORead(9))
{ // verde
conf.resetConfig();
}
if(io.digitalIORead(10)) { // giallo
if (io.digitalIORead(10))
{ // giallo
esp_restart();
}

174
src/mqtt.cpp Normal file
View File

@@ -0,0 +1,174 @@
#include <mqtt.h>
#define STACK_DEPTH 4096
#define PRIOTITY 0
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();
vTaskDelay(pdMS_TO_TICKS(loopTime));
}
if (client.state() != MQTT_CONNECTED)
{
LOG_ERROR("MQTT disconnect reason ", stateMap.at(client.state()));
vTaskDelay(pdMS_TO_TICKS(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
View 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;
};

View File

@@ -4,6 +4,7 @@ remoteIO::remoteIO(const uint8_t address, drivers::MODBUS &bus) : m_address(addr
{
LOG_INFO("Initializing relay module");
std::vector<uint16_t> response;
auto lock = m_bus.getLock();
if (!m_bus.readHoldingRegisters(m_address, REG_VERSION, 1, response))
{
LOG_ERROR("Unable to inizialize relay module");
@@ -23,6 +24,7 @@ const bool remoteIO::setOut(const channel_t ch, const bool value)
{
if (!m_initialized)
return false;
auto lock = m_bus.getLock();
LOG_DEBUG("Write Channel", ch, "->", value ? "True" : "False");
return m_bus.writeCoil(m_address, REG_COILS + ch, value);
}
@@ -31,6 +33,7 @@ const bool remoteIO::toggleOut(const channel_t ch)
{
if (!m_initialized)
return false;
auto lock = m_bus.getLock();
std::vector<bool> value;
if (!m_bus.readCoils(m_address, REG_COILS + ch, 1, value))
return false;
@@ -42,6 +45,7 @@ const bool remoteIO::setOutPort(const std::vector<bool> values)
{
if (!m_initialized)
return false;
auto lock = m_bus.getLock();
LOG_DEBUG("Write Port", CH_MAX);
return m_bus.writeCoils(m_address, CH_MAX, values);
}
@@ -50,6 +54,7 @@ const bool remoteIO::getOut(const channel_t ch, bool &value)
{
if (!m_initialized)
return false;
auto lock = m_bus.getLock();
std::vector<bool> values;
if (!m_bus.readCoils(m_address, REG_COILS + ch, 1, values))
return false;
@@ -62,6 +67,7 @@ const bool remoteIO::getOutPort(std::vector<bool> &values)
{
if (!m_initialized)
return false;
auto lock = m_bus.getLock();
LOG_DEBUG("Read Port", CH_MAX);
return m_bus.readCoils(m_address, REG_COILS, 8, values);
}
@@ -70,6 +76,7 @@ const bool remoteIO::getIn(const channel_t input, bool &value)
{
if (!m_initialized)
return false;
auto lock = m_bus.getLock();
std::vector<bool> values;
if (!m_bus.readInputs(m_address, REG_INPUT + input, 1, values))
return false;
@@ -82,6 +89,7 @@ const bool remoteIO::getInPort(std::vector<bool> &values)
{
if (!m_initialized)
return false;
auto lock = m_bus.getLock();
LOG_DEBUG("Read Inputs", CH_MAX);
return m_bus.readInputs(m_address, REG_INPUT, CH_MAX, values);
}