From 1955b8cb39b6f5e379ddff783a7bf6c26ef8d0aa Mon Sep 17 00:00:00 2001 From: Emanuele Trabattoni Date: Thu, 10 Jul 2025 23:06:37 +0200 Subject: [PATCH] MQTT Tesk OK --- src/main.cpp | 41 ++++++++++++++++++++++++++++++++++++----- 1 file changed, 36 insertions(+), 5 deletions(-) diff --git a/src/main.cpp b/src/main.cpp index 5550c72..2d9c48f 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -1,8 +1,10 @@ -#define DEBUGLOG_DEFAULT_LOG_LEVEL_DEBUG +#define DEBUGLOG_DEFAULT_LOG_LEVEL_INFO #include #include #include +#include + #include #include #include @@ -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);