commit 8277a07417f0bafeefcf446c23e90dad086982f6 Author: Thorsten Date: Sat Dec 21 20:33:38 2024 +0100 Initial commit diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..8256337 --- /dev/null +++ b/.gitignore @@ -0,0 +1,6 @@ +.pio +.vscode/.browse.c_cpp.db* +.vscode/c_cpp_properties.json +.vscode/launch.json +.vscode/ipch +settings-my-ignore.h diff --git a/.vscode/extensions.json b/.vscode/extensions.json new file mode 100644 index 0000000..080e70d --- /dev/null +++ b/.vscode/extensions.json @@ -0,0 +1,10 @@ +{ + // See http://go.microsoft.com/fwlink/?LinkId=827846 + // for the documentation about the extensions.json format + "recommendations": [ + "platformio.platformio-ide" + ], + "unwantedRecommendations": [ + "ms-vscode.cpptools-extension-pack" + ] +} diff --git a/README.md b/README.md new file mode 100644 index 0000000..0265543 --- /dev/null +++ b/README.md @@ -0,0 +1,51 @@ +# ESP8266 LCD Energymeter + +Ein Projekt zur Visualisierung von Energiedaten von **Tasmota-Messgeräten** mit einem **ESP8266** und einem 1602 LCD. +Das Script fragt periodisch zwei Tasmota-Geräte nach ihrer gemessenen Leistung und zeigt diese auf dem Display an. +Ein einfacher Energie-Monitor. + +Projektbild + +## Funktionen +- **Anzeige des Netzbezugs** (gemessen am Stromzähler) +- **Anzeige der Erzeugung** (gemessen am Balkonkraftwerk) +- **Taster** zum Ändern der Pull-Rate (Optional) + + +## Konfiguration + +Passe die `settings.h` auf deine Bedürfnisse an +```cpp +// ######################## WLAN-Daten ######################## + +const char* hostname = "ESP32_WLAN_Test"; + +const char* ssidList[] = { + "SSID_1", // Netzwerk 1 + "SSID_2", // Netzwerk 2 + "SSID_3" // Netzwerk 3 + // Weitere SSID hier hinzufügen +}; + +const char* passwordList[] = { + "Passwort_1", // Passwort für SSID 1 + "Passwort_2", // Passwort für SSID 2 + "Passwort_3" // Passwort für SSID 3 + // Weitere Passwörter hier hinzufügen +}; + +// ####################### Tasmota IPs ######################## + +String ip_netzbezug = "192.168.178.236"; +String ip_erzeugung = "192.168.178.237"; + +// ############################################################ +``` + +## Schaltplan + +Schaltplan + +#### Hinweise: +- Der **MT3608** (Step-Up-Wandler) ist optional. Er sorgt für eine stabile Spannung von 5V für das LCD, selbst wenn die Batterie schwächer wird. +- Der **ESP8266** muss nicht zwingend hinter dem MT3608 geschaltet sein, da er weniger empfindlich auf Spannungsschwankungen reagiert als das Display. \ No newline at end of file diff --git a/circuit-diagram/circuit-diagram.spl8 b/circuit-diagram/circuit-diagram.spl8 new file mode 100644 index 0000000..6fd78e8 Binary files /dev/null and b/circuit-diagram/circuit-diagram.spl8 differ diff --git a/images/image_1.jpg b/images/image_1.jpg new file mode 100644 index 0000000..918c60c Binary files /dev/null and b/images/image_1.jpg differ diff --git a/images/image_2.png b/images/image_2.png new file mode 100644 index 0000000..a69fe69 Binary files /dev/null and b/images/image_2.png differ diff --git a/include/README b/include/README new file mode 100644 index 0000000..194dcd4 --- /dev/null +++ b/include/README @@ -0,0 +1,39 @@ + +This directory is intended for project header files. + +A header file is a file containing C declarations and macro definitions +to be shared between several project source files. You request the use of a +header file in your project source file (C, C++, etc) located in `src` folder +by including it, with the C preprocessing directive `#include'. + +```src/main.c + +#include "header.h" + +int main (void) +{ + ... +} +``` + +Including a header file produces the same results as copying the header file +into each source file that needs it. Such copying would be time-consuming +and error-prone. With a header file, the related declarations appear +in only one place. If they need to be changed, they can be changed in one +place, and programs that include the header file will automatically use the +new version when next recompiled. The header file eliminates the labor of +finding and changing all the copies as well as the risk that a failure to +find one copy will result in inconsistencies within a program. + +In C, the usual convention is to give header files names that end with `.h'. +It is most portable to use only letters, digits, dashes, and underscores in +header file names, and at most one dot. + +Read more about using header files in official GCC documentation: + +* Include Syntax +* Include Operation +* Once-Only Headers +* Computed Includes + +https://gcc.gnu.org/onlinedocs/cpp/Header-Files.html diff --git a/lib/README b/lib/README new file mode 100644 index 0000000..2593a33 --- /dev/null +++ b/lib/README @@ -0,0 +1,46 @@ + +This directory is intended for project specific (private) libraries. +PlatformIO will compile them to static libraries and link into executable file. + +The source code of each library should be placed in an own separate directory +("lib/your_library_name/[here are source files]"). + +For example, see a structure of the following two libraries `Foo` and `Bar`: + +|--lib +| | +| |--Bar +| | |--docs +| | |--examples +| | |--src +| | |- Bar.c +| | |- Bar.h +| | |- library.json (optional, custom build options, etc) https://docs.platformio.org/page/librarymanager/config.html +| | +| |--Foo +| | |- Foo.c +| | |- Foo.h +| | +| |- README --> THIS FILE +| +|- platformio.ini +|--src + |- main.c + +and a contents of `src/main.c`: +``` +#include +#include + +int main (void) +{ + ... +} + +``` + +PlatformIO Library Dependency Finder will find automatically dependent +libraries scanning project source files. + +More information about PlatformIO Library Dependency Finder +- https://docs.platformio.org/page/librarymanager/ldf.html diff --git a/platformio.ini b/platformio.ini new file mode 100644 index 0000000..a043c76 --- /dev/null +++ b/platformio.ini @@ -0,0 +1,18 @@ +; PlatformIO Project Configuration File +; +; Build options: build flags, source filter +; Upload options: custom upload port, speed and extra flags +; Library options: dependencies, extra library storages +; Advanced options: extra scripting +; +; Please visit documentation for the other options and examples +; https://docs.platformio.org/page/projectconf.html + +[env:nodemcuv2] +platform = espressif8266 +board = nodemcuv2 +framework = arduino +upload_speed = 115200 +monitor_speed = 115200 +lib_deps = + LiquidCrystal_I2C \ No newline at end of file diff --git a/src/main.cpp b/src/main.cpp new file mode 100644 index 0000000..5f839b2 --- /dev/null +++ b/src/main.cpp @@ -0,0 +1,303 @@ +#include +#include +#include +#include + + +#define BUTTON_PIN D3 // GPIO-Pin verbunden mit Taster (D3 entspricht GPIO0) + +const uint32_t connectTimeoutMs = 10000; // WLAN Timeout + +// Globale Variablen +unsigned long lastUpdateTime = 0; // Zeitstempel der letzten Aktion +unsigned long refreshRate = 5000; // Anfangsverzögerung in Millisekunden +unsigned long messageDisplayTime = 0; // Zeitstempel für die 5-Sekunden-Anzeige +bool isMessageDisplayed = false; // Zustand, ob die Aktualisierungsrate angezeigt wird + +int currentDelayIndex = 0; // Aktueller Index im Delay-Array +const unsigned long delayOptions[] = {5000, 10000, 15000, 20000, 30000, 45000, 60000, 1000, 2000}; +const int delayOptionsSize = sizeof(delayOptions) / sizeof(delayOptions[0]); + +int lastButtonState = HIGH; // Letzter Zustand des Buttons +int currentButtonState; + +String netzbezug; +String netzbezug_alt; +String erzeugung; +String erzeugung_alt; + +// LCD initialisieren (16x2 Display) +LiquidCrystal_I2C lcd(0x27, 16, 2); + +int numNetworks = sizeof(ssidList) / sizeof(ssidList[0]); +int current_ap = 0; // Start mit der ersten SSID +bool reconnecting = false; // Flag für den Reconnect-Status + +// WLAN Symbol +byte customChar_wlan[] = { + B00000, + B01110, + B10001, + B00100, + B01010, + B00000, + B00100, + B00000 +}; + +// Funktion zum Anzeigen von Text auf einem 1602 LCD Display +// +// _lcd_display_text(TEXT, ROW, RETURNTOSTART, ALIGNMENT) +// +// row = 0 Zeile 0 wir beschrieben [default] +// = 1 Zeile 1 wir beschrieben [default] +// text = Der anzuzeigende Text (default löscht die komplette Zeile) +// alignment = left Text Ausrichtung links (Bei <= 16 Zeichen) [default] +// = center Text Ausrichtung zentriert (Bei <= 16 Zeichen) +// = right Text Ausrichtung links (Bei <= 16 Zeichen) +// returnToStart = false Zu langer Text der durchgescrollt wird stoppt am Ende [default] +// true Zu langer Text der durchgescrollt wird springt zum 1. Buchstaben zurück +void _lcd_display_text(int row = 0, const char* text = " ", const char* alignment = "left", bool returnToStart = false) { + + // Textlänge ermitteln + int textLength = strlen(text); + + // Sicherstellen, dass die Zeile gültig ist (0 oder 1) + if (row < 0 || row > 1) { + return; + } + + lcd.setCursor(0, row); + + // Wenn der Text <= 16 Zeichen ist, ausrichten + if (textLength <= 16) { + int padding = 0; + + if (strcmp(alignment, "center") == 0) { + padding = (16 - textLength) / 2; // Zentriert + } else if (strcmp(alignment, "right") == 0) { + padding = 16 - textLength; // Rechtsbündig + } + + //lcd.clear(); + lcd.setCursor(0, row); + + // Leerzeichen vor dem Text für Ausrichtung + for (int i = 0; i < padding; i++) { + lcd.print(" "); + } + + // Text ausgeben + lcd.print(text); + + } else { + // Wenn der Text > 16 Zeichen ist, zuerst die ersten 16 Zeichen anzeigen + lcd.setCursor(0, row); + lcd.print(text); + delay(2000); // Kurze Pause, damit der Anfang lesbar ist + + // Danach scrollen + for (int i = 1; i <= textLength - 16; i++) { + lcd.setCursor(0, row); + lcd.print(text + i); // Ab Offset i den Text anzeigen + delay(300); // Verzögerung für Scroll-Geschwindigkeit + } + + // Verhalten nach dem Scrollen festlegen + if (returnToStart) { + lcd.setCursor(0, row); + lcd.print(text); // Anfang des Textes wieder anzeigen + } else { + lcd.setCursor(0, row); + lcd.print(text + (textLength - 16)); // Text hinten stehen lassen + } + } +} + +// Funktion zum Extrahieren eines Wertes aus der GET-Anfrage von Tasmota-Geräten +String _extract_value_tasmota_json(const String& url, const String& key) { + WiFiClient client; // WiFiClient-Objekt erstellen + HTTPClient http; + + if (http.begin(client, url)) { // Begin mit WiFiClient und URL + int httpResponseCode = http.GET(); + + if (httpResponseCode == 200) { + String response = http.getString(); + http.end(); + + int startIndex = response.indexOf("\"" + key + "\":"); + if (startIndex == -1) { + return "?"; // Key nicht gefunden + } + startIndex += key.length() + 3; + int endIndex = response.indexOf(",", startIndex); + if (endIndex == -1) { + endIndex = response.indexOf("}", startIndex); + } + if (endIndex == -1) { + return "?"; + } + String value = response.substring(startIndex, endIndex); + value.trim(); + return String((int)value.toFloat()); // Nachkommastellen abschneiden + } else { + //Serial.println("Fehler bei der Anfrage: " + String(httpResponseCode)); + } + http.end(); + } else { + Serial.println("Verbindung zur URL fehlgeschlagen: " + url); + } + + return "?"; +} + +// WLAN-Verbindung herstellen +void connectToWiFi() { + Serial.println("WLAN Verbindungsaufbau zu: " + String(ssidList[current_ap])); + Serial.println("Passwort: " + String(passwordList[current_ap])); + + _lcd_display_text(0, "Bitte warten", "center"); + _lcd_display_text(1, "WLAN verbinden ", "left"); + + lcd.createChar(0, customChar_wlan); + lcd.setCursor(15, 1); + lcd.write(byte(0)); + + WiFi.begin(ssidList[current_ap], passwordList[current_ap]); + + //Blinkendes WLAN Symbol wärend das WLAN versucht zu verbinden + int attempt = 0; + while (WiFi.status() != WL_CONNECTED && attempt < 10) { + delay(500); + Serial.print("."); + lcd.setCursor(15, 1); + lcd.print(" "); + delay(500); + lcd.setCursor(15, 1); + lcd.write(byte(0)); + attempt++; + } + + //Verbindung fehlgeschlagen (current_ap erhöhen) + if (WiFi.status() != WL_CONNECTED) { + WiFi.disconnect(); + delay(500); + Serial.println("\nVerbindung fehlgeschlagen."); + current_ap = (current_ap + 1) % numNetworks; + reconnecting = false; + //Verbunden + } else { + Serial.print("\nWLAN verbunden: "); + Serial.print(WiFi.SSID()); + Serial.print(" "); + Serial.println(WiFi.RSSI()); + + _lcd_display_text(0, "WLAN verbunden", "center"); + _lcd_display_text(1); + _lcd_display_text(1, WiFi.SSID().c_str()); + + reconnecting = false; + delay(2500); + + _lcd_display_text(0, "Netzbezug: ?W"); + _lcd_display_text(1, "Erzeugung: ?W"); + } +} + +void update_power_values() { + + Serial.print("SmartMeterReader auslesen: "); + netzbezug = _extract_value_tasmota_json("http://" + ip_netzbezug + "/cm?cmnd=Status%208", "Power"); + Serial.print(netzbezug + "W\n"); + + + Serial.print("Zwischenstecker auslesen : "); + erzeugung = _extract_value_tasmota_json("http://" + ip_erzeugung + "/cm?cmnd=Status%208", "Power"); + Serial.print(erzeugung + "W\n"); + + if (netzbezug != netzbezug_alt) { + lcd.setCursor(10, 0); + lcd.print(" "); + lcd.setCursor(16 - (netzbezug.length() + 1), 0); + lcd.print(netzbezug); + } + + + if (erzeugung != erzeugung_alt) { + lcd.setCursor(10, 1); + lcd.print(" "); + lcd.setCursor(16 - (erzeugung.length() + 1), 1); + lcd.print(erzeugung); + } + + netzbezug_alt = netzbezug; + erzeugung_alt = erzeugung; + +} + +void handleButtonPress() { + currentButtonState = digitalRead(BUTTON_PIN); + + if (currentButtonState == LOW && lastButtonState == HIGH) { + currentDelayIndex = (currentDelayIndex + 1) % delayOptionsSize; + refreshRate = delayOptions[currentDelayIndex]; + + Serial.print("Neue Aktualisierungsrate: "); + Serial.println(refreshRate); + + _lcd_display_text(0, " Aktual. Rate "); + _lcd_display_text(1); + _lcd_display_text(1, (String(refreshRate / 1000) + " Sekunden").c_str(), "center"); + + isMessageDisplayed = true; + messageDisplayTime = millis(); + + delay(200); + } + + lastButtonState = currentButtonState; +} + +void setup() { + pinMode(BUTTON_PIN, INPUT_PULLUP); + + Serial.begin(115200); + delay(1000); + + lcd.init(); + lcd.backlight(); + lcd.createChar(0, customChar_wlan); + + WiFi.setHostname(hostname); + WiFi.mode(WIFI_STA); + + lcd.setCursor(0, 0); + _lcd_display_text(0, "Bereit", "center"); +} + +void loop() { + handleButtonPress(); + + if (WiFi.status() != WL_CONNECTED && !reconnecting) { + reconnecting = true; + connectToWiFi(); + } + + if (isMessageDisplayed && millis() - messageDisplayTime >= 2500) { + isMessageDisplayed = false; + _lcd_display_text(0, "Netzbezug: ?W"); + _lcd_display_text(1, "Erzeugung: ?W"); + update_power_values(); + } + + if (WiFi.status() == WL_CONNECTED && !reconnecting) { + + if (!isMessageDisplayed && millis() - lastUpdateTime >= refreshRate) { + lastUpdateTime = millis(); + + update_power_values(); + } + + } +} diff --git a/src/settings.h b/src/settings.h new file mode 100644 index 0000000..5ebab9e --- /dev/null +++ b/src/settings.h @@ -0,0 +1,31 @@ +#include +#ifndef SETTINGS_H +#define SETTINGS_H + + +// ######################## WLAN-Daten ######################## + +const char* hostname = "ESP8266_Energiemeter"; + +const char* ssidList[] = { + "SSID_1", // Netzwerk 1 + "SSID_2", // Netzwerk 2 + "SSID_3" // Netzwerk 3 + // Weitere SSID hier hinzufügen +}; + +const char* passwordList[] = { + "Passwort_1", // Passwort für SSID 1 + "Passwort_2", // Passwort für SSID 2 + "Passwort_3" // Passwort für SSID 3 + // Weitere Passwörter hier hinzufügen +}; + +// ####################### Tasmota IPs ######################## + +String ip_netzbezug = "192.168.178.236"; +String ip_erzeugung = "192.168.178.237"; + +// ############################################################ + +#endif // SETTINGS_H \ No newline at end of file diff --git a/test/README b/test/README new file mode 100644 index 0000000..9b1e87b --- /dev/null +++ b/test/README @@ -0,0 +1,11 @@ + +This directory is intended for PlatformIO Test Runner and project tests. + +Unit Testing is a software testing method by which individual units of +source code, sets of one or more MCU program modules together with associated +control data, usage procedures, and operating procedures, are tested to +determine whether they are fit for use. Unit testing finds problems early +in the development cycle. + +More information about PlatformIO Unit Testing: +- https://docs.platformio.org/en/latest/advanced/unit-testing/index.html