Compare commits
12 Commits
1955b8cb39
...
drivers-re
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b7881355a2 | ||
|
|
92de57a760 | ||
|
|
0b5d725d3a | ||
|
|
30ed0d283a | ||
|
|
3923aa3c05 | ||
|
|
53b82c32c3 | ||
|
|
bdf3b9b41a | ||
|
|
7e02f3cef2 | ||
|
|
d2eba9085e | ||
|
|
1ad98799b4 | ||
|
|
e4d28b55cb | ||
|
|
ef7b9506b6 |
3
data/example.json
Normal file
3
data/example.json
Normal file
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"data": "value"
|
||||
}
|
||||
101
docs/commands.json
Normal file
101
docs/commands.json
Normal file
@@ -0,0 +1,101 @@
|
||||
[
|
||||
{
|
||||
"cmd": "setHPlimit",
|
||||
"params": {
|
||||
"level": [
|
||||
"UNLIMITED",
|
||||
"P1",
|
||||
"P2",
|
||||
"P3",
|
||||
"P4"
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"cmd": "setHeating",
|
||||
"params": {
|
||||
"pump": [
|
||||
"ON",
|
||||
"OFF"
|
||||
],
|
||||
"ground": [
|
||||
"ON",
|
||||
"OFF"
|
||||
],
|
||||
"first": [
|
||||
"ON",
|
||||
"OFF"
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"cmd": "getHPpower",
|
||||
"params": null
|
||||
},
|
||||
{
|
||||
"cmd": "getHPlimit",
|
||||
"params": null
|
||||
},
|
||||
{
|
||||
"cmd": "getInputStatus",
|
||||
"params": null
|
||||
},
|
||||
{
|
||||
"cmd": "getOutputStatus",
|
||||
"params": null
|
||||
},
|
||||
{
|
||||
"cmd": "getTemperatures",
|
||||
"params": null
|
||||
},
|
||||
{
|
||||
"cmd": "getWaterInfo",
|
||||
"params": null
|
||||
},
|
||||
{
|
||||
"cmd": "getTankLevel",
|
||||
"params": null
|
||||
},
|
||||
{
|
||||
"cmd": "getRainInfo",
|
||||
"params": null
|
||||
},
|
||||
{
|
||||
"cmd": "setIrrigation",
|
||||
"params": {
|
||||
"zone": [
|
||||
"Ricircolo",
|
||||
"1",
|
||||
"2",
|
||||
"3",
|
||||
"Rubinetti"
|
||||
],
|
||||
"timeOn": 120,
|
||||
"timePause": 2
|
||||
}
|
||||
},
|
||||
{
|
||||
"cmd": "getIrrigation",
|
||||
"params": null
|
||||
},
|
||||
{
|
||||
"cmd": "setCronJob",
|
||||
"params": {
|
||||
"name": "nomedeljob",
|
||||
"timeStr": "* * * 10,45 5 *",
|
||||
"action": "qua ci va un dizionario come se arrivasse da mqtt, cosi li interpreto alla stessa maniera"
|
||||
}
|
||||
},
|
||||
{
|
||||
"cmd": "getCronJob",
|
||||
"params": {
|
||||
"name": "nomedeljob"
|
||||
}
|
||||
},
|
||||
{
|
||||
"cmd": "delCronJob",
|
||||
"params": {
|
||||
"name": "nomedeljob"
|
||||
}
|
||||
}
|
||||
]
|
||||
BIN
docs/mi00383-11-en.pdf
Normal file
BIN
docs/mi00383-11-en.pdf
Normal file
Binary file not shown.
BIN
docs/mi004700-i-e.pdf
Normal file
BIN
docs/mi004700-i-e.pdf
Normal file
Binary file not shown.
123
docs/response.json
Normal file
123
docs/response.json
Normal file
@@ -0,0 +1,123 @@
|
||||
[
|
||||
{
|
||||
"cmd": "POLL",
|
||||
"values": {
|
||||
"number": 1234,
|
||||
"date": "20250810-123512"
|
||||
}
|
||||
},
|
||||
{
|
||||
"cmd": "getHPpower",
|
||||
"values": {
|
||||
"power": 3200,
|
||||
"current": 16,
|
||||
"energy": 12341234
|
||||
}
|
||||
},
|
||||
{
|
||||
"cmd": "getHPlimit",
|
||||
"values": {
|
||||
"level": [
|
||||
"UNLIMITED",
|
||||
"P1",
|
||||
"P2",
|
||||
"P3",
|
||||
"P4"
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"cmd": "getInputStatus",
|
||||
"values": {
|
||||
"rain": [
|
||||
"ON",
|
||||
"OFF"
|
||||
],
|
||||
"waterPressure": [
|
||||
"ON",
|
||||
"OFF"
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"cmd": "getOutputStatus",
|
||||
"values": {
|
||||
"pump": [
|
||||
"ON",
|
||||
"OFF"
|
||||
],
|
||||
"ground": [
|
||||
"ON",
|
||||
"OFF"
|
||||
],
|
||||
"first": [
|
||||
"ON",
|
||||
"OFF"
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"cmd": "getTemperatures",
|
||||
"values": {
|
||||
"solar": 1234,
|
||||
"acs": 1234,
|
||||
"heating": 1234
|
||||
}
|
||||
},
|
||||
{
|
||||
"cmd": "getWaterInfo",
|
||||
"values": {
|
||||
"flow": 1234,
|
||||
"consumption": 1234,
|
||||
"temperature": 1234
|
||||
}
|
||||
},
|
||||
{
|
||||
"cmd": "getTankLevel",
|
||||
"values": {
|
||||
"level": 10
|
||||
}
|
||||
},
|
||||
{
|
||||
"cmd": "getRainInfo",
|
||||
"values": {
|
||||
"rain": [
|
||||
"ON",
|
||||
"OFF"
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"cmd": "getIrrigation",
|
||||
"values": {
|
||||
"Ricircolo": [
|
||||
"ON",
|
||||
"OFF"
|
||||
],
|
||||
"1": [
|
||||
"ON",
|
||||
"OFF"
|
||||
],
|
||||
"2": [
|
||||
"ON",
|
||||
"OFF"
|
||||
],
|
||||
"3": [
|
||||
"ON",
|
||||
"OFF"
|
||||
],
|
||||
"Rubinetti": [
|
||||
"ON",
|
||||
"OFF"
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"cmd": "getCronJob",
|
||||
"values": {
|
||||
"name": "nomedeljob",
|
||||
"timeStr": "* * * 10,45 5 *",
|
||||
"action": "dizionario che dice cosa deve fare come e' salvato nel micro"
|
||||
}
|
||||
}
|
||||
]
|
||||
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,
|
||||
|
@@ -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:
|
||||
|
||||
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(buzzerPin, OUTPUT);
|
||||
ledcAttach(buzzerPin, 1000, 8);
|
||||
m_bp.pin = buzzerPin;
|
||||
m_bp.beeperTask = NULL;
|
||||
beep(50, NOTE_G);
|
||||
}
|
||||
|
||||
Buzzer::~Buzzer()
|
||||
{
|
||||
beepStop();
|
||||
ledcDetach(buzzerPin);
|
||||
pinMode(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
|
||||
vTaskDelay(pdMS_TO_TICKS(bPar->tOn));
|
||||
ledcWriteTone(bPar->pin, 0); // off
|
||||
if (bPar->tOff == 0)
|
||||
break;
|
||||
vTaskDelay(pdMS_TO_TICKS(bPar->tOff));
|
||||
}
|
||||
LOG_DEBUG("Beeper Task Ended");
|
||||
bPar->beeperTask = NULL;
|
||||
vTaskDelete(NULL);
|
||||
}
|
||||
}
|
||||
38
lib/GPIO/BUZZER_Driver.h
Normal file
38
lib/GPIO/BUZZER_Driver.h
Normal file
@@ -0,0 +1,38 @@
|
||||
#pragma once
|
||||
|
||||
#include <Arduino.h>
|
||||
|
||||
#define DEBUGLOG_DEFAULT_LOG_LEVEL_INFO
|
||||
#include <DebugLog.h>
|
||||
|
||||
namespace drivers
|
||||
{
|
||||
|
||||
class Buzzer
|
||||
{
|
||||
const uint8_t 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(ledPin, OUTPUT);
|
||||
m_lp.pin = ledPin;
|
||||
m_lp.blinkTask = NULL;
|
||||
}
|
||||
|
||||
Led::~Led()
|
||||
{
|
||||
setColor({0, 0, 0});
|
||||
pinMode(ledPin, INPUT);
|
||||
}
|
||||
|
||||
void Led::setColor(const color_t color)
|
||||
{
|
||||
blinkStop();
|
||||
rgbLedWrite(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);
|
||||
vTaskDelay(pdMS_TO_TICKS(lPar->tOn));
|
||||
rgbLedWrite(lPar->pin, lPar->color2.g, lPar->color2.r, lPar->color2.b); // off
|
||||
if (lPar->tOff == 0)
|
||||
break;
|
||||
vTaskDelay(pdMS_TO_TICKS(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 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;
|
||||
};
|
||||
|
||||
}
|
||||
@@ -39,7 +39,7 @@ namespace drivers
|
||||
uint8_t currState(0);
|
||||
uint8_t newState(0);
|
||||
|
||||
if (ch < OUT_PIN1 || ch > OUT_PIN8)
|
||||
if (ch < DO1 || ch > DO8)
|
||||
{
|
||||
LOG_ERROR("Invalid write to output channel: [%d]", ch);
|
||||
return false;
|
||||
@@ -64,7 +64,7 @@ namespace drivers
|
||||
const bool TCA9554PWR::readOut(const uint8_t ch)
|
||||
{
|
||||
uint8_t currState(0);
|
||||
if (ch < OUT_PIN1 || ch > OUT_PIN8)
|
||||
if (ch < DO1 || ch > DO8)
|
||||
{
|
||||
LOG_ERROR("Invalid read to output channel: [%d]", ch);
|
||||
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 ******************************************************/
|
||||
@@ -21,18 +25,18 @@ namespace drivers
|
||||
{
|
||||
|
||||
public:
|
||||
enum
|
||||
typedef enum
|
||||
{
|
||||
OUT_PIN1,
|
||||
OUT_PIN2,
|
||||
OUT_PIN3,
|
||||
OUT_PIN4,
|
||||
OUT_PIN5,
|
||||
OUT_PIN6,
|
||||
OUT_PIN7,
|
||||
OUT_PIN8,
|
||||
OUT_PIN_MAX
|
||||
};
|
||||
DO1,
|
||||
DO2,
|
||||
DO3,
|
||||
DO4,
|
||||
DO5,
|
||||
DO6,
|
||||
DO7,
|
||||
DO8,
|
||||
DO_MAX
|
||||
} channel_t;
|
||||
|
||||
TCA9554PWR(I2C &i2c, const uint8_t address);
|
||||
~TCA9554PWR();
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
|
||||
@@ -71,6 +71,7 @@ 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);
|
||||
}
|
||||
@@ -79,6 +80,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;
|
||||
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);
|
||||
}
|
||||
@@ -87,6 +89,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;
|
||||
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);
|
||||
}
|
||||
@@ -95,6 +98,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;
|
||||
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);
|
||||
}
|
||||
@@ -103,6 +107,7 @@ 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});
|
||||
}
|
||||
@@ -111,14 +116,16 @@ 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});
|
||||
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;
|
||||
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);
|
||||
}
|
||||
@@ -127,8 +134,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;
|
||||
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);
|
||||
return writeInteger(device, func, reg, values, true);
|
||||
}
|
||||
|
||||
/////////////////////////////////////////////////////////////////
|
||||
@@ -150,15 +158,15 @@ namespace drivers
|
||||
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;
|
||||
}
|
||||
|
||||
@@ -198,11 +206,11 @@ namespace drivers
|
||||
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));
|
||||
@@ -270,11 +278,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 +291,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 +306,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 +326,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 +374,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 +388,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,21 +1,13 @@
|
||||
#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>
|
||||
|
||||
#define Extension_CH1 1 // Expansion Channel 1
|
||||
#define Extension_CH2 2 // Expansion Channel 2
|
||||
#define Extension_CH3 3 // Expansion Channel 3
|
||||
#define Extension_CH4 4 // Expansion Channel 4
|
||||
#define Extension_CH5 5 // Expansion Channel 5
|
||||
#define Extension_CH6 6 // Expansion Channel 6
|
||||
#define Extension_CH7 7 // Expansion Channel 7
|
||||
#define Extension_CH8 8 // Expansion Channel 8
|
||||
#define Extension_ALL_ON 9 // Expansion ALL ON
|
||||
#define Extension_ALL_OFF 10 // Expansion ALL OFF
|
||||
#include <mutex>
|
||||
|
||||
namespace drivers
|
||||
{
|
||||
@@ -34,7 +26,7 @@ namespace drivers
|
||||
HardwareSerial &m_serial;
|
||||
};
|
||||
|
||||
class MODBUS : public RS485
|
||||
class MODBUS : private RS485
|
||||
{
|
||||
|
||||
static const uint8_t RESP_HEADER_SIZE = 3;
|
||||
@@ -61,7 +53,6 @@ namespace drivers
|
||||
typedef uint16_t crc_t;
|
||||
|
||||
public:
|
||||
|
||||
MODBUS(const uint32_t baud, const SerialConfig conf);
|
||||
|
||||
// Func 0x01
|
||||
@@ -90,12 +81,13 @@ namespace drivers
|
||||
|
||||
private:
|
||||
CRC16 m_crc;
|
||||
std::mutex m_mutex;
|
||||
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>
|
||||
|
||||
@@ -130,10 +133,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);
|
||||
|
||||
141
lib/SENECA/S50140_Driver.cpp
Normal file
141
lib/SENECA/S50140_Driver.cpp
Normal file
@@ -0,0 +1,141 @@
|
||||
#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};
|
||||
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) < minDelay)
|
||||
{ // minimum m_lastRequest between requests
|
||||
vTaskDelay(pdMS_TO_TICKS(now - m_lastRequest));
|
||||
}
|
||||
m_lastRequest = now;
|
||||
}
|
||||
|
||||
const uint8_t S50140::getRegset()
|
||||
{
|
||||
std::vector<uint16_t> value;
|
||||
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;
|
||||
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;
|
||||
while (retries++ < 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++ < maxRetries)
|
||||
{
|
||||
delayRequest();
|
||||
if (m_bus.readHoldingRegisters(m_address, reg, dataWords, values) && values.size() == 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 maxRetries = 5;
|
||||
const uint8_t dataWords = 2;
|
||||
const uint16_t 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;
|
||||
uint64_t m_lastRequest;
|
||||
};
|
||||
}
|
||||
133
lib/TEMP/R4DCB08_Driver.cpp
Normal file
133
lib/TEMP/R4DCB08_Driver.cpp
Normal file
@@ -0,0 +1,133 @@
|
||||
#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();
|
||||
}
|
||||
|
||||
R4DCB08::~R4DCB08()
|
||||
{
|
||||
}
|
||||
|
||||
const float R4DCB08::getTemp(const uint8_t ch)
|
||||
{
|
||||
uint8_t retries(0);
|
||||
std::vector<uint16_t> rawT;
|
||||
if (ch < 0 || ch > getNum())
|
||||
{
|
||||
LOG_ERROR("Invalid Temperature Channel number", ch);
|
||||
return MAXFLOAT;
|
||||
}
|
||||
while (retries++ < maxRetries)
|
||||
{
|
||||
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();
|
||||
delay(50);
|
||||
}
|
||||
return MAXFLOAT;
|
||||
}
|
||||
|
||||
const std::vector<float> R4DCB08::getTempAll()
|
||||
{
|
||||
uint8_t retries(0);
|
||||
std::vector<uint16_t> rawT;
|
||||
std::vector<float> out;
|
||||
while (retries++ < maxRetries)
|
||||
{
|
||||
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();
|
||||
delay(50);
|
||||
}
|
||||
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
|
||||
|
||||
for (auto v : corr)
|
||||
{ // convert to decimal degreees to register value
|
||||
while (retries++ < maxRetries)
|
||||
{
|
||||
if (m_bus.writeRegister(m_address, REG_TEMPCORR + channel, v*10))
|
||||
{
|
||||
channel++;
|
||||
delay(50);
|
||||
break;
|
||||
}
|
||||
LOG_ERROR("Failed to Set Temperature Correction, device", m_address);
|
||||
delay(50);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
std::vector<float> R4DCB08::getCorrection()
|
||||
{
|
||||
uint8_t retries(0);
|
||||
std::vector<uint16_t> rawV;
|
||||
std::vector<float> out;
|
||||
rawV.reserve(getNum());
|
||||
|
||||
while (retries++ < maxRetries)
|
||||
{
|
||||
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();
|
||||
delay(50);
|
||||
}
|
||||
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;
|
||||
while (retries++ < maxRetries)
|
||||
{
|
||||
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);
|
||||
delay(50);
|
||||
}
|
||||
LOG_ERROR("No Temperature Sensors Detected, device", m_address);
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
49
lib/TEMP/R4DCB08_Driver.h
Normal file
49
lib/TEMP/R4DCB08_Driver.h
Normal file
@@ -0,0 +1,49 @@
|
||||
#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
|
||||
};
|
||||
|
||||
const uint8_t maxRetries = 5;
|
||||
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:
|
||||
const uint8_t m_address;
|
||||
uint8_t m_sensors;
|
||||
MODBUS &m_bus;
|
||||
};
|
||||
}
|
||||
@@ -1,5 +1,7 @@
|
||||
#pragma once
|
||||
|
||||
#define DEBUGLOG_DEFAULT_LOG_LEVEL_INFO
|
||||
|
||||
#include <Arduino.h>
|
||||
#include <DebugLog.h>
|
||||
#include <vector>
|
||||
|
||||
@@ -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
|
||||
|
||||
316
src/config.h
Normal file
316
src/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"}};
|
||||
};
|
||||
124
src/digitalIO.cpp
Normal file
124
src/digitalIO.cpp
Normal file
@@ -0,0 +1,124 @@
|
||||
#include <digitalIO.h>
|
||||
|
||||
digitalIO::digitalIO(drivers::I2C &i2c, drivers::MODBUS &bus, std::vector<uint8_t> remotes) : m_localOuts(drivers::TCA9554PWR(i2c, TCA9554_ADDRESS)), m_remoteAddrs(remotes)
|
||||
{
|
||||
for (uint8_t i(DI1); i < DI_MAX; i++)
|
||||
{
|
||||
pinMode(i, INPUT_PULLUP); // set all local pins as digitalInput
|
||||
}
|
||||
|
||||
for (auto a : remotes)
|
||||
{
|
||||
m_remotes.emplace_back(remoteIO(a, bus));
|
||||
}
|
||||
}
|
||||
|
||||
digitalIO::~digitalIO()
|
||||
{
|
||||
}
|
||||
|
||||
void digitalIO::digitalIOWrite(const uint8_t ch, const bool value)
|
||||
{
|
||||
if (ch < 0 || ch > getOutNum())
|
||||
{
|
||||
LOG_ERROR("Invalid digitalIOWrite channel number", ch);
|
||||
}
|
||||
|
||||
if (ch < drivers::TCA9554PWR::DO_MAX) // write to i2c device for local outputs
|
||||
{
|
||||
digitalWriteLocal(ch, value);
|
||||
}
|
||||
else
|
||||
{
|
||||
digitalWriteRemote(ch - drivers::TCA9554PWR::DO_MAX, value);
|
||||
}
|
||||
}
|
||||
const bool digitalIO::digitalIORead(const uint8_t ch)
|
||||
{
|
||||
if (ch < 0 || ch > getInNum())
|
||||
{
|
||||
LOG_ERROR("Invalid digitalIORead channel number", ch);
|
||||
}
|
||||
|
||||
if (ch < (DI_MAX - DI1)) // read from local inputs not as gpio numbers
|
||||
{
|
||||
return digitalReadLocal(ch);
|
||||
}
|
||||
else
|
||||
{
|
||||
return digitalReadRemote(ch - (DI_MAX - DI1));
|
||||
}
|
||||
}
|
||||
|
||||
void digitalIO::reset()
|
||||
{
|
||||
// set all local and remote outputs to 0
|
||||
m_localOuts.setPort(0x00);
|
||||
for (auto r: m_remotes)
|
||||
r.resetAll(false);
|
||||
}
|
||||
|
||||
const uint8_t digitalIO::getOutNum()
|
||||
{
|
||||
return drivers::TCA9554PWR::DO_MAX + m_remotes.size() * remoteIO::CH_MAX;
|
||||
}
|
||||
|
||||
const uint8_t digitalIO::getInNum()
|
||||
{
|
||||
return DI_MAX + m_remotes.size() * remoteIO::CH_MAX;
|
||||
}
|
||||
|
||||
void digitalIO::digitalWriteLocal(const uint8_t ch, const bool value)
|
||||
{
|
||||
uint8_t retries(0);
|
||||
while (retries++ < maxRetries)
|
||||
{
|
||||
if (m_localOuts.setOut(ch, value))
|
||||
{
|
||||
LOG_DEBUG("digitalWriteLocal channel", ch, " status", value ? "True" : "False");
|
||||
break;
|
||||
}
|
||||
LOG_ERROR("Failed digitalWriteLocal channel ", ch, " status", value ? "True" : "False");
|
||||
}
|
||||
}
|
||||
|
||||
void digitalIO::digitalWriteRemote(const uint8_t ch, const bool value)
|
||||
{
|
||||
uint8_t retries(0);
|
||||
const uint8_t selectedRemote(floor(ch / 8.0f));
|
||||
const uint8_t selectedChannel(ch % remoteIO::CH_MAX);
|
||||
while (retries++ < maxRetries)
|
||||
{
|
||||
if (m_remotes[selectedRemote].setOut((remoteIO::channel_t)selectedChannel, value))
|
||||
{
|
||||
LOG_DEBUG("digitalWriteRemote remote", selectedRemote, " channel ", selectedChannel, " status", value ? "True" : "False");
|
||||
break;
|
||||
}
|
||||
LOG_ERROR("Failed digitalWriteRemote remote", selectedRemote, " channel ", selectedChannel, " status", value ? "True" : "False");
|
||||
}
|
||||
}
|
||||
|
||||
const bool digitalIO::digitalReadLocal(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");
|
||||
return value;
|
||||
}
|
||||
|
||||
const bool digitalIO::digitalReadRemote(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)
|
||||
{
|
||||
if (m_remotes[selectedRemote].getIn((remoteIO::channel_t)selectedChannel, value))
|
||||
{
|
||||
LOG_DEBUG("digitalReadRemote remote", selectedRemote, " channel ", selectedChannel, " status", value ? "True" : "False");
|
||||
return value;
|
||||
}
|
||||
LOG_ERROR("Failed digitalReadRemote remote", selectedRemote, " channel ", selectedChannel, " status", value ? "True" : "False");
|
||||
}
|
||||
return false;
|
||||
}
|
||||
55
src/digitalIO.h
Normal file
55
src/digitalIO.h
Normal file
@@ -0,0 +1,55 @@
|
||||
#pragma once
|
||||
|
||||
#define DEBUGLOG_DEFAULT_LOG_LEVEL_INFO
|
||||
|
||||
#include <DebugLog.h>
|
||||
#include <Arduino.h>
|
||||
|
||||
#include <remoteIO.h>
|
||||
#include <TCA9554PWR_Driver.h>
|
||||
|
||||
#define ON true
|
||||
#define OFF false
|
||||
|
||||
class digitalIO
|
||||
{
|
||||
|
||||
private:
|
||||
enum localInputs
|
||||
{
|
||||
DI1 = 4, // gpio for local inputs starts at 4 as per manufacturer documentation
|
||||
DI2,
|
||||
DI3,
|
||||
DI4,
|
||||
DI5,
|
||||
DI6,
|
||||
DI7,
|
||||
DI8,
|
||||
DI_MAX
|
||||
};
|
||||
|
||||
const uint8_t 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 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);
|
||||
|
||||
const bool digitalReadLocal(const uint8_t ch);
|
||||
const bool digitalReadRemote(const uint8_t ch);
|
||||
|
||||
private:
|
||||
std::vector<uint8_t> m_remoteAddrs;
|
||||
drivers::TCA9554PWR m_localOuts;
|
||||
std::vector<remoteIO> m_remotes;
|
||||
};
|
||||
172
src/main.cpp
172
src/main.cpp
@@ -1,17 +1,27 @@
|
||||
#define DEBUGLOG_DEFAULT_LOG_LEVEL_INFO
|
||||
#define DEBUGLOG_DEFAULT_LOG_LEVEL_DEBUG
|
||||
|
||||
#include <DebugLog.h>
|
||||
#include <DebugLogEnable.h>
|
||||
|
||||
#include <Arduino.h>
|
||||
#include <PubSubClient.h>
|
||||
|
||||
#include <RS485_Driver.h>
|
||||
#include <TCA9554PWR_Driver.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 "utils.h"
|
||||
|
||||
/////////////// GLOBALS ///////////////
|
||||
Config& conf = Config::getInstance();
|
||||
/////////////// GLOBALS ///////////////
|
||||
|
||||
void callback(char *topic, uint8_t *payload, unsigned int length)
|
||||
{
|
||||
std::string pl;
|
||||
@@ -22,59 +32,91 @@ void callback(char *topic, uint8_t *payload, unsigned int length)
|
||||
|
||||
void myTask(void *mqtt)
|
||||
{
|
||||
while (true)
|
||||
auto client = (PubSubClient *)(mqtt);
|
||||
while (client->connected())
|
||||
{
|
||||
((PubSubClient *)(mqtt))->loop();
|
||||
client->loop();
|
||||
vTaskDelay(pdMS_TO_TICKS(100));
|
||||
}
|
||||
LOG_ERROR("Mqtt Loop Ended, client disconnected");
|
||||
vTaskDelete(NULL); // delete the current task
|
||||
};
|
||||
|
||||
/////////////// GLOBALS ///////////////
|
||||
void setup()
|
||||
{
|
||||
Serial.begin(9600);
|
||||
LOG_ATTACH_SERIAL(Serial);
|
||||
conf.init();
|
||||
}
|
||||
|
||||
void loop()
|
||||
{
|
||||
const uint8_t tempBoardAddr(0xAA);
|
||||
const uint8_t relayBoardAddr(0x01);
|
||||
const uint8_t baseRegister(0x00);
|
||||
uint16_t k(0);
|
||||
uint8_t sensors(0);
|
||||
bool buzzing(false);
|
||||
|
||||
//////////////// DEVICES ////////////////
|
||||
// Declared here to keep devices local to the main loop otherwise the kernel crashes //
|
||||
auto i2c = drivers::I2C();
|
||||
auto relays = drivers::TCA9554PWR(i2c, TCA9554_ADDRESS);
|
||||
auto bus = drivers::MODBUS(9600, SERIAL_8N1);
|
||||
auto rtc = drivers::PCF85063(i2c, PCF85063_ADDRESS);
|
||||
auto eth = drivers::Ethernet("waveshare-test");
|
||||
auto eth = drivers::Ethernet(conf.m_ethHostname);
|
||||
auto tmp = drivers::R4DCB08(bus, conf.m_modbusTemperatureAddr);
|
||||
delay(100);
|
||||
auto io = digitalIO(i2c, bus, {conf.m_modbusRelayAddr});
|
||||
delay(100);
|
||||
auto seneca = drivers::S50140(bus, conf.m_modbusSenecaAddr);
|
||||
auto buzzer = drivers::Buzzer();
|
||||
auto led = drivers::Led();
|
||||
//////////////// DEVICES ////////////////
|
||||
// Initialize temperature sensors
|
||||
sensors = tmp.getNum();
|
||||
LOG_INFO("Temperature sensors connected ->", sensors);
|
||||
|
||||
Network.onEvent([ð](arduino_event_id_t event, arduino_event_info_t info)
|
||||
{ eth.onEvent(event, info); });
|
||||
|
||||
while (!eth.isConnected())
|
||||
{
|
||||
LOG_WARN("Waiting for Ethernet");
|
||||
delay(1000);
|
||||
}
|
||||
|
||||
// Set RTC time at startup
|
||||
time_t ntpTime;
|
||||
drivers::PCF85063::datetime_t dt;
|
||||
eth.getNtpTime(ntpTime);
|
||||
rtc.setDatetime(drivers::PCF85063::fromEpoch(ntpTime));
|
||||
|
||||
// MQTT Test
|
||||
//////////////// NETWORK ////////////////
|
||||
// MQTT Test //
|
||||
NetworkClient tcp;
|
||||
PubSubClient mqtt(tcp);
|
||||
|
||||
mqtt.setServer("10.0.2.249", 1883);
|
||||
mqtt.setServer(conf.m_mqttHost.c_str(), conf.m_mqttPort);
|
||||
mqtt.setCallback(callback);
|
||||
mqtt.connect("esp32-client");
|
||||
mqtt.subscribe("test/esp32-in");
|
||||
xTaskCreatePinnedToCore(myTask, "mqttLoop", 4096, &mqtt, 2, NULL, 1);
|
||||
//////////////// NETWORK ////////////////
|
||||
|
||||
//////////////// NETWORK ////////////////
|
||||
/////////////// CALLBACK ////////////////
|
||||
Network.onEvent(
|
||||
[ð, &rtc, &mqtt, &buzzer, &led](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.connected() && mqtt.connect(conf.m_mqttClientName.c_str()))
|
||||
{
|
||||
mqtt.subscribe("test/esp32-in");
|
||||
xTaskCreatePinnedToCore(myTask, "mqttLoop", 4096, &mqtt, 2, NULL, 1);
|
||||
break;
|
||||
}
|
||||
delay(100);
|
||||
}
|
||||
});
|
||||
|
||||
////////////////////////////////////////
|
||||
///////// MAIN LOOP INSIDE LOOP ////////
|
||||
@@ -83,30 +125,62 @@ 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());
|
||||
mqtt.publish("test/esp32-out", ("[" + std::to_string(k) + "] -> " + timeStr).c_str());
|
||||
|
||||
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("[", i, "]Temperature: ", results.at(i) / 10.0f);
|
||||
}
|
||||
results.clear();
|
||||
LOG_INFO("Temperature channel", i++, "->", v);
|
||||
}
|
||||
i = 0;
|
||||
delay(10);
|
||||
for (auto v : tmp.getCorrection())
|
||||
{
|
||||
LOG_INFO("Temperature correction channel", i++, "tc", v);
|
||||
}
|
||||
|
||||
delay(500);
|
||||
LOG_INFO("====>Read Inputs");
|
||||
bus.readInputs(relayBoardAddr, 0x00, 8, values);
|
||||
printBool("====>Inputs", values);
|
||||
delay(100);
|
||||
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);
|
||||
if (io.digitalIORead(0)) // rosso
|
||||
{
|
||||
uint8_t regset(seneca.getRegset());
|
||||
uint16_t countStat(seneca.getCounterStatus());
|
||||
LOG_INFO("Register Set: ", regset);
|
||||
LOG_INFO("Counter Status: ", countStat);
|
||||
seneca.resetPartialCounters();
|
||||
}
|
||||
delay(100);
|
||||
if (io.digitalIORead(8)) // blu
|
||||
{
|
||||
if (!buzzing)
|
||||
{
|
||||
buzzing = true;
|
||||
buzzer.beepRepeat(100, 1000, NOTE_C);
|
||||
led.blinkColor(100, 500, {255, 0, 255});
|
||||
}
|
||||
else
|
||||
{
|
||||
buzzer.beepStop();
|
||||
led.blinkAlternate(500, 500, {255, 255, 0}, {0, 255, 255});
|
||||
buzzing = false;
|
||||
}
|
||||
LOG_INFO("Buzzing -> ", buzzing ? "True" : "False");
|
||||
}
|
||||
|
||||
if(io.digitalIORead(9)) { // verde
|
||||
conf.resetConfig();
|
||||
}
|
||||
|
||||
if(io.digitalIORead(10)) { // giallo
|
||||
esp_restart();
|
||||
}
|
||||
|
||||
delay(conf.m_globalLoopDelay);
|
||||
}
|
||||
|
||||
////////////////////////////////////////
|
||||
|
||||
93
src/remoteIO.cpp
Normal file
93
src/remoteIO.cpp
Normal file
@@ -0,0 +1,93 @@
|
||||
#include <remoteIO.h>
|
||||
|
||||
remoteIO::remoteIO(const uint8_t address, drivers::MODBUS &bus) : m_address(address), m_initialized(false), m_bus(bus)
|
||||
{
|
||||
LOG_INFO("Initializing relay module");
|
||||
std::vector<uint16_t> response;
|
||||
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;
|
||||
resetAll(false);
|
||||
}
|
||||
|
||||
remoteIO::~remoteIO()
|
||||
{
|
||||
m_initialized = false;
|
||||
resetAll(false);
|
||||
}
|
||||
|
||||
const bool remoteIO::setOut(const channel_t ch, const bool value)
|
||||
{
|
||||
if (!m_initialized)
|
||||
return false;
|
||||
LOG_DEBUG("Write Channel", ch, "->", value ? "True" : "False");
|
||||
return m_bus.writeCoil(m_address, REG_COILS + ch, value);
|
||||
}
|
||||
|
||||
const bool remoteIO::toggleOut(const channel_t ch)
|
||||
{
|
||||
if (!m_initialized)
|
||||
return false;
|
||||
std::vector<bool> value;
|
||||
if (!m_bus.readCoils(m_address, REG_COILS + ch, 1, value))
|
||||
return false;
|
||||
LOG_DEBUG("Toggle Channel", ch, "->", !value.front() ? "True" : "False");
|
||||
return m_bus.writeCoil(m_address, REG_COILS + ch, !value.front());
|
||||
}
|
||||
|
||||
const bool remoteIO::setOutPort(const std::vector<bool> values)
|
||||
{
|
||||
if (!m_initialized)
|
||||
return false;
|
||||
LOG_DEBUG("Write Port", CH_MAX);
|
||||
return m_bus.writeCoils(m_address, CH_MAX, values);
|
||||
}
|
||||
|
||||
const bool remoteIO::getOut(const channel_t ch, bool &value)
|
||||
{
|
||||
if (!m_initialized)
|
||||
return false;
|
||||
std::vector<bool> values;
|
||||
if (!m_bus.readCoils(m_address, REG_COILS + ch, 1, values))
|
||||
return false;
|
||||
value = values.front();
|
||||
LOG_DEBUG("Read Channel", ch, "->", value ? "True" : "False");
|
||||
return true;
|
||||
}
|
||||
|
||||
const bool remoteIO::getOutPort(std::vector<bool> &values)
|
||||
{
|
||||
if (!m_initialized)
|
||||
return false;
|
||||
LOG_DEBUG("Read Port", CH_MAX);
|
||||
return m_bus.readCoils(m_address, REG_COILS, 8, values);
|
||||
}
|
||||
|
||||
const bool remoteIO::getIn(const channel_t input, bool &value)
|
||||
{
|
||||
if (!m_initialized)
|
||||
return false;
|
||||
std::vector<bool> values;
|
||||
if (!m_bus.readInputs(m_address, REG_INPUT + input, 1, values))
|
||||
return false;
|
||||
value = values.front();
|
||||
LOG_DEBUG("Read Input", input, "->", values.front() ? "True" : "False");
|
||||
return true;
|
||||
}
|
||||
|
||||
const bool remoteIO::getInPort(std::vector<bool> &values)
|
||||
{
|
||||
if (!m_initialized)
|
||||
return false;
|
||||
LOG_DEBUG("Read Inputs", CH_MAX);
|
||||
return m_bus.readInputs(m_address, REG_INPUT, CH_MAX, values);
|
||||
}
|
||||
|
||||
void remoteIO::resetAll(const bool value)
|
||||
{
|
||||
LOG_DEBUG("Reset All ->", value ? "True" : "False");
|
||||
m_bus.writeCoil(m_address, REG_ALLCOILS, value);
|
||||
}
|
||||
39
src/remoteIO.h
Normal file
39
src/remoteIO.h
Normal file
@@ -0,0 +1,39 @@
|
||||
#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;
|
||||
|
||||
private:
|
||||
const uint16_t REG_VERSION = 0x8000;
|
||||
const uint16_t REG_COILS = 0x0000;
|
||||
const uint16_t REG_INPUT = 0x0000;
|
||||
const uint16_t REG_ALLCOILS = 0x00FF;
|
||||
|
||||
public:
|
||||
remoteIO(const uint8_t address, drivers::MODBUS &bus);
|
||||
~remoteIO();
|
||||
|
||||
const bool setOut(const channel_t ch, const bool value);
|
||||
const bool toggleOut(const channel_t ch);
|
||||
const bool setOutPort(const std::vector<bool> values);
|
||||
|
||||
const bool getOut(const channel_t ch, bool &value);
|
||||
const bool getOutPort(std::vector<bool> &values);
|
||||
|
||||
const bool getIn(const channel_t input, bool &value);
|
||||
const bool getInPort(std::vector<bool> &values);
|
||||
|
||||
void resetAll(const bool value);
|
||||
|
||||
private:
|
||||
bool m_initialized;
|
||||
drivers::MODBUS &m_bus;
|
||||
const uint8_t m_address;
|
||||
};
|
||||
Reference in New Issue
Block a user