From eb1a10212026b41e6d27841681b97fbd7495fe73 Mon Sep 17 00:00:00 2001 From: rxf Date: Mon, 19 Aug 2024 17:23:13 +0200 Subject: [PATCH] MQTT nun mit PubSub Grafik etwas angepasst --- platformio.ini | 4 +- src/grafik.cpp | 60 ++++++++++--------- src/grafik.h | 9 ++- src/main.cpp | 21 ++++--- src/main.h | 4 +- src/mqtt.cpp | 153 ++++++++++++++++++++++--------------------------- src/mqtt.h | 40 ++++++------- 7 files changed, 145 insertions(+), 146 deletions(-) diff --git a/platformio.ini b/platformio.ini index 70ea1d5..daf1577 100644 --- a/platformio.ini +++ b/platformio.ini @@ -18,6 +18,6 @@ lib_deps = bblanchon/ArduinoJson@^7.1.0 adafruit/Adafruit BME280 Library@^2.2.4 lvgl/lvgl@^9.1.0 - bodmer/TFT_eSPI@^2.5.43 - + bodmer/TFT_eSPI@^2.5.43 + knolleary/PubSubClient@^2.8 monitor_speed = 115200 diff --git a/src/grafik.cpp b/src/grafik.cpp index 59bd47b..83a66c5 100644 --- a/src/grafik.cpp +++ b/src/grafik.cpp @@ -31,7 +31,7 @@ void buildarc(ARC arc) lv_obj_set_size(arc.arc, arc.size, arc.size); lv_arc_set_rotation(arc.arc, 180); lv_arc_set_bg_angles(arc.arc, 0, 180); - lv_arc_set_value(arc.arc, arc.value); + lv_arc_set_value(arc.arc, arc.value+arc.value_offset); lv_obj_align(arc.arc, LV_ALIGN_LEFT_MID, arc.x, arc.y); lv_obj_remove_style(arc.arc, NULL, LV_PART_KNOB); @@ -55,10 +55,10 @@ void buildarc(ARC arc) lv_obj_t *value_label = lv_label_create(arc.arc); char value[10]; - sprintf(value, arc.valformat, arc.value); + sprintf(value, arc.valformat, arc.value + arc.value_offset); // Serial.println(value); lv_label_set_text(value_label, value); - lv_obj_align(value_label, LV_ALIGN_LEFT_MID, 38 + arc.value_offset, 0); + lv_obj_align(value_label, LV_ALIGN_LEFT_MID, 38 + arc.value_xoffset, 0); static lv_style_t style_value_label; lv_style_init(&style_value_label); lv_style_set_text_font(&style_value_label, &lv_font_montserrat_18); @@ -141,27 +141,6 @@ void lv_create_main_gui(void) lv_obj_align(refresh_label, LV_ALIGN_CENTER, 0, -45); */ - // Text als Überschrift an die Axen - lv_obj_t *feuchte_label = lv_label_create(lv_screen_active()); - lv_label_set_text(feuchte_label, "Feuchte"); - lv_obj_align(feuchte_label, LV_ALIGN_RIGHT_MID, -3, 15); - - // Set font type and font size. More information: https://docs.lvgl.io/master/overview/font.html - static lv_style_t style_feuchte_label; - lv_style_init(&style_feuchte_label); - lv_style_set_text_font(&style_feuchte_label, &lv_font_montserrat_10); - lv_obj_add_style(feuchte_label, &style_feuchte_label, 0); - - lv_obj_t *temp_label = lv_label_create(lv_screen_active()); - lv_label_set_text(temp_label, "Temperatur"); - lv_obj_align(temp_label, LV_ALIGN_LEFT_MID, 3, 15); - - // Set font type and font size. More information: https://docs.lvgl.io/master/overview/font.html - static lv_style_t style_temp_label; - lv_style_init(&style_temp_label); - lv_style_set_text_font(&style_temp_label, &lv_font_montserrat_10); - lv_obj_add_style(temp_label, &style_temp_label, 0); - /*Create an Arc*/ lv_obj_t *aTemp = lv_arc_create(lv_screen_active()); arcTemp.arc = aTemp; @@ -220,7 +199,7 @@ void drawChart() // Create a container to display the chart and scale lv_obj_t *container_row = lv_obj_create(lv_screen_active()); lv_obj_set_size(container_row, CONTAINER_WIDTH, CONTAINER_HEIGHT); - lv_obj_align(container_row, LV_ALIGN_BOTTOM_MID, 0, 0); + lv_obj_align(container_row, LV_ALIGN_BOTTOM_MID, 0, -4); // Set the container in a flexbox row layout aligned center lv_obj_set_flex_flow(container_row, LV_FLEX_FLOW_ROW); lv_obj_set_flex_align(container_row, LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_CENTER); @@ -229,7 +208,7 @@ void drawChart() lv_style_set_pad_row(&style_container_row, 0); // lv_style_set_bg_color(&style_container_row, lv_palette_lighten(LV_PALETTE_LIGHT_BLUE, 4)); lv_obj_add_style(container_row, &style_container_row, 0); - lv_obj_set_style_border_side(container_row, LV_BORDER_SIDE_BOTTOM, LV_PART_MAIN); + lv_obj_set_style_border_side(container_row, LV_BORDER_SIDE_NONE, LV_PART_MAIN); lv_obj_set_style_bg_color(container_row, lv_color_hex(BACKGROUND_COLOR), LV_PART_MAIN); // linke Axe @@ -335,6 +314,21 @@ void drawChart() lv_style_set_text_color(&style_xscale, lv_color_hex(0x0000FF)); lv_obj_add_style(xscale, &style_xscale, 0); + // Text als Überschrift an die Axen + lv_obj_t *feuchte_label = lv_label_create(lv_screen_active()); + lv_label_set_text(feuchte_label, "Feuchte"); + lv_obj_align(feuchte_label, LV_ALIGN_RIGHT_MID, -3, 8); + + lv_obj_t *temp_label = lv_label_create(lv_screen_active()); + lv_label_set_text(temp_label, "Temperatur"); + lv_obj_align(temp_label, LV_ALIGN_LEFT_MID, 3, 8); + + // Set font type and font size. More information: https://docs.lvgl.io/master/overview/font.html + static lv_style_t style_tf_label; + lv_style_init(&style_tf_label); + lv_style_set_text_font(&style_tf_label, &lv_font_montserrat_10); + lv_obj_add_style(feuchte_label, &style_tf_label, 0); + lv_obj_add_style(temp_label, &style_tf_label, 0); /* ganz unten etwas Info anzeigen */ // Style dafür @@ -420,4 +414,18 @@ void show2lines() { lv_obj_add_style(line2, &style_line, 0); } +void showResetTime(struct tm tinfo) { + static lv_style_t style_info_label; + lv_style_init(&style_info_label); + lv_style_set_text_font(&style_info_label, &lv_font_montserrat_8); + lv_style_set_text_color(&style_info_label, LV_COLOR_MAKE(0x40, 0x40, 0x40)); + + char date[20]; + strftime(date, 20, "%d-%m-%Y %H:%M", &tinfo); + + lv_obj_t *resdate_label = lv_label_create(lv_screen_active()); + lv_label_set_text(resdate_label, date); + lv_obj_align(resdate_label, LV_ALIGN_BOTTOM_LEFT, 4, 0); + lv_obj_add_style(resdate_label, &style_info_label, LV_PART_MAIN); +} diff --git a/src/grafik.h b/src/grafik.h index 336b0a5..1bdbedc 100644 --- a/src/grafik.h +++ b/src/grafik.h @@ -26,7 +26,8 @@ typedef struct { int highvalue; int green; int yellow; - int value_offset; + int value_xoffset; + float value_offset; } ARC; @@ -36,8 +37,8 @@ typedef struct { #define BACKGROUND_COLOR 0xD3F0FF #ifdef MAIN -ARC arcTemp = {NULL, "temp", 40, -6, 110, 30.0, "%.1f°C", "°C", 15, 35, 20, 25, -11}; -ARC arcHum = {NULL, "humi", 170, -6, 110, 60.0, "%.0f%%", "%", 40, 100, 65, 70, 2}; +ARC arcTemp = {NULL, "temp", 40, -10, 110, 30.0, "%.1f°C", "°C", 15, 35, 20, 25, -11, 0.0}; +ARC arcHum = {NULL, "humi", 170, -10, 110, 60.0, "%.0f%%", "%", 40, 100, 65, 70, 2, 0.0}; lv_obj_t * date_label; lv_obj_t * time_label; lv_obj_t * ta_label; @@ -66,6 +67,8 @@ void updatechartData(float value, float value_hum); void setAussenDataValues(float val, bool what, struct tm t); void showRate(int r); void show2lines(); +void showResetTime(struct tm tinfo); + diff --git a/src/main.cpp b/src/main.cpp index 3ed2622..aeee265 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -75,16 +75,15 @@ void setup() { connectToWifi(); // Start MQTT - setupMQTT(); - connectToMqtt(); - Serial.println("MQTT started"); - + setup_mqtt(); + timeinfo = gettheTime(NTPREADTIME); showDateTime(timeinfo); bmeReadtimer = millis(); drawChart(); + showResetTime(timeinfo); /* // Register print function for debugging @@ -108,15 +107,21 @@ void loop() { if (millis() - bmeReadtimer > bmeReadTime) { bmeReadtimer = millis(); bmedata = readBME280(); - publishMQTTmessage(bmedata.temp, bmedata.hum); + doPublish(bmedata.temp+arcTemp.value_offset, bmedata.hum+arcHum.value_offset); } if (millis() - updatetimer > updateTime) { updatetimer = millis(); - updatechartData(bmedata.temp, bmedata.hum); - setValuetoArc(arcTemp, bmedata.temp); - setValuetoArc(arcHum, bmedata.hum); + updatechartData(bmedata.temp+arcTemp.value_offset, bmedata.hum+arcHum.value_offset); + setValuetoArc(arcTemp, bmedata.temp+arcTemp.value_offset); + setValuetoArc(arcHum, bmedata.hum+arcHum.value_offset); } + if (!client.connected()) + { + reconnect(); + } + client.loop(); + lv_task_handler(); // let the GUI do its work lv_tick_inc(5); // tell LVGL how much time has passed delay(5); // let this time pass diff --git a/src/main.h b/src/main.h index 94df31d..19aeceb 100644 --- a/src/main.h +++ b/src/main.h @@ -6,8 +6,8 @@ extern "C" { #include "freertos/timers.h" } -#define VERSION "1.3.3" -#define VDATE "2024-07-23" +#define VERSION "1.4.0" +#define VDATE "2024-08-19" //#define MAXREADINGS 224 #define MAXREADINGS 200 diff --git a/src/mqtt.cpp b/src/mqtt.cpp index bc91ba1..7a78954 100644 --- a/src/mqtt.cpp +++ b/src/mqtt.cpp @@ -5,79 +5,27 @@ #include "weifi.h" #include "mqtt.h" -void setupMQTT() { - mqttReconnectTimer = xTimerCreate("mqttTimer", pdMS_TO_TICKS(2000), pdFALSE, (void*)0, reinterpret_cast(connectToMqtt)); -// wifiReconnectTimer = xTimerCreate("wifiTimer", pdMS_TO_TICKS(2000), pdFALSE, (void*)0, reinterpret_cast(connectToWifi)); -// WiFi.onEvent(WiFiEvent); - mqttClient.onConnect(onMqttConnect); - mqttClient.onDisconnect(onMqttDisconnect); - mqttClient.onSubscribe(onMqttSubscribe); - mqttClient.onUnsubscribe(onMqttUnsubscribe); - mqttClient.onMessage(onMqttMessage); - mqttClient.setServer(MQTT_HOST, MQTT_PORT); - mqttClient.setCredentials(BROKER_USER, BROKER_PASS); -// connectToWifi(); -} - -void connectToMqtt() { - Serial.println("Connecting to MQTT..."); - mqttClient.connect(); -} - -void onMqttConnect(bool sessionPresent) { - Serial.println("Connected to MQTT."); - /*Serial.print("Session present: "); - Serial.println(sessionPresent);*/ - - // Subscribe to topic "message" when it connects to the broker - char topic[50]; - strcpy(topic, MQTT_TOPIC); - strcat(topic,"#"); - Serial.println(topic); - uint16_t packetIdSub = mqttClient.subscribe(topic, 2); - //Serial.print("Subscribing at QoS 2, packetId: "); - //Serial.println(packetIdSub); -} - -void onMqttDisconnect(AsyncMqttClientDisconnectReason reason) { - Serial.println("Disconnected from MQTT."); - Serial.printf("Wifi-Connected: %d\n", WiFi.isConnected()); - if (WiFi.isConnected()) { - xTimerStart(mqttReconnectTimer, 0); - } else { - connectToWifi(); - xTimerStart(mqttReconnectTimer, 0); - } -} - -void onMqttSubscribe(uint16_t packetId, uint8_t qos) { - /*Serial.println("Subscribe acknowledged."); - Serial.print(" packetId: "); - Serial.println(packetId); - Serial.print(" qos: "); - Serial.println(qos);*/ -} - -void onMqttUnsubscribe(uint16_t packetId) { - /*Serial.println("Unsubscribe acknowledged."); - Serial.print(" packetId: "); - Serial.println(packetId);*/ -} JsonDocument doc; -void parseMQTTmessages(char *topic, String msg) { - // Parse the JSON message - DeserializationError error = deserializeJson(doc, msg); +//----------------------------------------- +// MQTT message arrives +void onmessage(char *tp, byte *msg, unsigned int length) +{ + String topic = String(tp); + msg[length] = '\0'; + String message = String((char *)(msg)); + Serial.printf("Message arrived: %s %s\n", topic.c_str(), message.c_str()); + DeserializationError error = deserializeJson(doc, message); if (error) { Serial.print(F("deserializeJson() failed: ")); Serial.println(error.c_str()); return; } - // Extract values bool istemp = true; float val = 0.0; - if (strcmp(topic, "CYD/set/hm/aussen") == 0) { + + if (topic == "CYD/set/hm/aussen") { if(doc.containsKey("temperature")) { istemp = true; val = doc["temperature"]; @@ -87,7 +35,7 @@ void parseMQTTmessages(char *topic, String msg) { val = doc["humidity"]; } setAussenDataValues(val, istemp, timeinfo); - } else if (strcmp(topic, "CYD/set/parameter") == 0) { + } else if (topic == "CYD/set/parameter") { if(doc.containsKey("bmerate")) { setBMEreadtime(doc["bmerate"]); // showRate(doc["bmerate"]); @@ -96,28 +44,65 @@ void parseMQTTmessages(char *topic, String msg) { setBMEreadtime(doc["updaterate"]); // showRate(doc["updaterate"]); } + if(doc.containsKey("isttemp")) { + arcTemp.value_offset = (float)doc["isttemp"] - arcTemp.value; + } + if(doc.containsKey("isthum")) { + arcHum.value_offset = (float)doc["isthum"] - arcHum.value; + } + Serial.printf("tempoffset: %.1f, humoffset: %.1f\n", arcTemp.value_offset, arcHum.value_offset); } } -void onMqttMessage(char* topic, char* payload, AsyncMqttClientMessageProperties properties, size_t len, size_t index, size_t total) { - // Do whatever you want when you receive a message - // Save the message in a variable - String received_message; - for (int i = 0; i < len; i++) { - received_message += (char)payload[i]; - } - Serial.printf("%s:%s\n", topic, received_message.c_str()); - // Display the text message on the display receive from the MQTT topic "message" - parseMQTTmessages(topic, received_message); - } +// Connect or reconnect to MQTT and subscribe +void reconnect(void) +{ + while (!client.connected()) + { + Serial.print("Reconnecting..."); + bool erg = client.connect(CLIENT_ID, MQTT_USER, MQTT_PASSWD); + Serial.println(erg); -#define MQTT_PUB_TEMP "CYD/get/bme280" + if (!client.connect(CLIENT_ID, MQTT_USER, MQTT_PASSWD)) + { + Serial.print("failed, rc="); + Serial.print(client.state()); + Serial.println(" retrying in 5 seconds"); + delay(5000); + } + } + Serial.println("Connected"); + client.subscribe(MQTT_TOPIC "#"); +} + +void doPublish(float temp, float hum) { + char payload[50]; + sprintf(payload, "{\"temperature\":%.1f,\"humidity\":%.1f}", temp, hum); + + client.publish(MQTT_PUB_TEMP, payload); + Serial.printf("Published: %s %s\n", MQTT_PUB_TEMP, payload); +} + + +// check MQTT in the loop +void checkMQTT(void) { + Serial.println("Try connected ..."); + + if (!client.connected()) + { + + Serial.println("try to reconnect"); + reconnect(); + } + client.loop(); +} + + +// Setup MQTT client +void setup_mqtt(void) { + Serial.printf("Setup MQTT to broker %s ...\n", MQTT_BROKER); + client.setClient(espClient); + client.setServer(MQTT_BROKER, MQTT_PORT); + client.setCallback(onmessage); +} -void publishMQTTmessage(float temp, float hum) { - // Publish an MQTT message on topic esp32/ds18b20/temperature - char payload[50]; - sprintf(payload, "{\"temperature\":%.1f,\"humidity\":%.1f}", temp, hum); - uint16_t packetIdPub1 = mqttClient.publish(MQTT_PUB_TEMP, 1, true, payload); -// Serial.printf("Publishing on topic %s at QoS 1, packetId: ", MQTT_PUB_TEMP); -// Serial.println(packetIdPub1); - } \ No newline at end of file diff --git a/src/mqtt.h b/src/mqtt.h index 152cb22..c986658 100644 --- a/src/mqtt.h +++ b/src/mqtt.h @@ -1,33 +1,31 @@ -#ifndef MQTT_H -#define MQTT_H +#pragma once #include -#include +#include #include -#include "main.h" -#define MQTT_HOST IPAddress(192,168,178,92) // MQTT BROKER IP ADDRESS -//#define MQTT_HOST "example.com" // MQTT BROKER URL -#define MQTT_PORT 1883 -#define BROKER_USER "rxf" -#define BROKER_PASS "Tux4S!ech" +//#define MQTT_BROKER "rexfue.de" +#define MQTT_BROKER "nuccy" +#define MQTT_PORT 1883 +//#define MQTT_USER "stzuhr" +//#define MQTT_PASSWD "74chQCYb" +#define MQTT_USER "rxf" +#define MQTT_PASSWD "Tux4S!ech" #define MQTT_TOPIC "CYD/set/" +#define MQTT_PUB_TEMP "CYD/get/bme280" + +#define CLIENT_ID "ESP32Client7" #ifdef MQTT -AsyncMqttClient mqttClient; +WiFiClient espClient; +PubSubClient client(espClient); #else -extern AsyncMqttClient mqttClient; +extern PubSubClient client; #endif -void setupMQTT(); -void connectToMqtt(); -void onMqttConnect(bool sessionPresent); -void onMqttDisconnect(AsyncMqttClientDisconnectReason reason); -void onMqttSubscribe(uint16_t packetId, uint8_t qos); -void onMqttUnsubscribe(uint16_t packetId); -void onMqttMessage(char* topic, char* payload, AsyncMqttClientMessageProperties properties, size_t len, size_t index, size_t total); -void publishMQTTmessage(float temp, float hum); - -#endif \ No newline at end of file +void reconnect(void); +void doPublish(float temp, float hum); +void checkMQTT(void); +void setup_mqtt(void); \ No newline at end of file