MQTT Tesk OK

This commit is contained in:
Emanuele Trabattoni
2025-07-10 23:06:37 +02:00
parent 208f5f7534
commit 1955b8cb39

View File

@@ -1,8 +1,10 @@
#define DEBUGLOG_DEFAULT_LOG_LEVEL_DEBUG
#define DEBUGLOG_DEFAULT_LOG_LEVEL_INFO
#include <DebugLog.h>
#include <DebugLogEnable.h>
#include <Arduino.h>
#include <PubSubClient.h>
#include <RS485_Driver.h>
#include <TCA9554PWR_Driver.h>
#include <PCF85063_Driver.h>
@@ -10,6 +12,23 @@
#include "utils.h"
void callback(char *topic, uint8_t *payload, unsigned int length)
{
std::string pl;
pl.resize(length);
std::snprintf(pl.data(), length, "%s", payload);
LOG_INFO("Message: Topic [", topic, "], Payload [", pl.c_str(), "]");
}
void myTask(void *mqtt)
{
while (true)
{
((PubSubClient *)(mqtt))->loop();
vTaskDelay(pdMS_TO_TICKS(100));
}
};
/////////////// GLOBALS ///////////////
void setup()
{
@@ -22,6 +41,7 @@ void loop()
const uint8_t tempBoardAddr(0xAA);
const uint8_t relayBoardAddr(0x01);
const uint8_t baseRegister(0x00);
uint16_t k(0);
//////////////// DEVICES ////////////////
// Declared here to keep devices local to the main loop otherwise the kernel crashes //
@@ -39,13 +59,23 @@ void loop()
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
NetworkClient tcp;
PubSubClient mqtt(tcp);
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);
////////////////////////////////////////
///////// MAIN LOOP INSIDE LOOP ////////
////////////////////////////////////////
@@ -60,8 +90,9 @@ void loop()
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());
if (bus.readHoldingRegisters(tempBoardAddr, baseRegister, 8, results))
if (bus.readHoldingRegisters(tempBoardAddr, baseRegister, 1, results))
{
for (auto i(0); i < results.size(); i++)
{
@@ -70,8 +101,8 @@ void loop()
results.clear();
}
delay(100);
LOG_INFO("\n\n====>Read Inputs");
delay(500);
LOG_INFO("====>Read Inputs");
bus.readInputs(relayBoardAddr, 0x00, 8, values);
printBool("====>Inputs", values);