5 Commits

10 changed files with 437 additions and 91 deletions

View File

@@ -0,0 +1,97 @@
# Flash ESP8266 Script
## Version: 1.0.0
### Author: Marcel Peterkau
### Copyright: 2024
### License: MIT
---
## Beschreibung
Dieses Skript entpackt ein ZIP-Archiv, das Firmware- und Dateisystem-Dateien für einen ESP8266 enthält, und flasht diese auf das Gerät. Nach dem Flashen werden die entpackten Dateien automatisch gelöscht.
---
## Benutzung
```sh
python flash_esp8266.py <zip_file> [-v]
```
### Parameter
- `<zip_file>`: Der Name der ZIP-Datei, die die Firmware- und Dateisystem-Dateien enthält.
- `-v`: Aktiviert Debug-Ausgaben (optional).
### Beispiel
```sh
python flash_esp8266.py firmware_1.07_cbcdc34.zip -v
```
---
## Voraussetzungen
- Python 3.x
- Die folgenden Python-Bibliotheken müssen installiert sein:
- esptool
- pyserial
Installiere die benötigten Bibliotheken mit:
```sh
pip install esptool pyserial
```
---
## Funktionen
- **get_com_ports**: Ermittelt die verfügbaren COM-Ports.
- **find_new_com_port**: Findet den neuen COM-Port, wenn der ESP8266 angeschlossen wird.
- **extract_files**: Entpackt die ZIP-Datei und gibt die enthaltenen Dateien zurück.
- **decompress_gz**: Entpackt eine GZ-Datei.
- **clean_up**: Löscht die angegebenen Dateien nach dem Flashen.
---
## Ablauf
1. Das Skript überprüft, ob die angegebene ZIP-Datei existiert.
2. Die ZIP-Datei wird entpackt und die Firmware- und Dateisystem-Dateien werden identifiziert.
3. Die Dateisystem-Datei (GZ) wird entpackt.
4. Der Benutzer wird aufgefordert, den ESP8266 abzustecken und erneut anzustecken, um den neuen COM-Port zu ermitteln.
5. Die Firmware- und Dateisystem-Dateien werden auf den ESP8266 geflasht.
6. Die temporären Dateien werden nach dem erfolgreichen Flashen gelöscht.
---
## Fehlerbehebung
- **ZIP-Datei nicht gefunden**: Stelle sicher, dass der Pfad zur ZIP-Datei korrekt angegeben ist.
- **Erforderliche Dateien nicht im ZIP-Archiv**: Überprüfe, ob die ZIP-Datei die richtigen Dateien (`.fw.bin` und `.fs.gz`) enthält.
- **Kein neuer COM-Port gefunden**: Stelle sicher, dass der ESP8266 korrekt angeschlossen ist und warte, bis der neue COM-Port erkannt wird.
---
## Lizenz
Dieses Projekt ist unter der MIT-Lizenz lizenziert
---
## Versionshistorie
- **1.0.0** - Initiale Version
---
## Haftungsausschluss
Dieses Skript wird ohne Garantie bereitgestellt. Der Autor übernimmt keine Verantwortung für Schäden oder Datenverlust, die durch die Nutzung dieses Skripts entstehen könnten.
---

View File

@@ -0,0 +1,156 @@
"""
flash_esp8266.py
Version: 1.0.0
Author: Marcel Peterkau
Copyright: 2024
License: MIT
Beschreibung:
Dieses Skript entpackt ein ZIP-Archiv mit Firmware- und Dateisystem-Dateien und flasht diese auf einen ESP8266.
Die entpackten Dateien werden nach dem Flashen gelöscht.
Versionshistorie:
1.0.0 - Initiale Version
Benutzung:
python flash_esp8266.py <zip_file> [-v]
Optionen:
-v Aktiviert Debug-Ausgaben
"""
import esptool
import sys
import serial.tools.list_ports
import zipfile
import os
import gzip
import shutil
BAUD_RATE = 921600 # Erhöhte Baudrate
DEBUG = '-v' in sys.argv
def debug_print(message):
if DEBUG:
print(message)
def get_com_ports():
ports = [comport.device for comport in serial.tools.list_ports.comports()]
debug_print(f"Verfügbare COM-Ports: {ports}")
return ports
def find_new_com_port(old_ports, timeout=15):
debug_print("Suche nach neuen COM-Ports...")
import time
start_time = time.time()
while time.time() - start_time < timeout:
new_ports = get_com_ports()
added_ports = list(set(new_ports) - set(old_ports))
if added_ports:
new_port = added_ports[0]
print(f"Neuer COM-Port gefunden: {new_port}")
return new_port
time.sleep(1)
return None
def extract_files(zip_file):
with zipfile.ZipFile(zip_file, 'r') as zip_ref:
zip_ref.extractall()
debug_print(f"Entpackt: {zip_ref.namelist()}")
return zip_ref.namelist()
def decompress_gz(file_path):
output_file = file_path.replace('.gz', '')
with gzip.open(file_path, 'rb') as f_in:
with open(output_file, 'wb') as f_out:
shutil.copyfileobj(f_in, f_out)
debug_print(f"Entpackt {file_path} zu {output_file}")
return output_file
def clean_up(files):
for file in files:
if os.path.isfile(file):
os.remove(file)
debug_print(f"Gelöscht: {file}")
if __name__ == "__main__":
if len(sys.argv) < 2:
print("Verwendung: python flash_esp8266.py <zip_file> [-v]")
sys.exit(1)
ZIP_FILE = sys.argv[1]
# Überprüfe, ob das ZIP-Archiv existiert
if not os.path.isfile(ZIP_FILE):
print(f"ZIP-Archiv {ZIP_FILE} nicht gefunden.")
sys.exit(1)
# Entpacke das ZIP-Archiv
extracted_files = extract_files(ZIP_FILE)
# Finde die .fw.bin- und .fs.gz-Dateien
bin_file = None
fs_file = None
for file in extracted_files:
if file.endswith('.fw.bin'):
bin_file = file
elif file.endswith('.fs.gz'):
fs_file = file
if not bin_file or not fs_file:
print(f"Die erforderlichen Dateien (.fw.bin und .fs.gz) wurden nicht im ZIP-Archiv {ZIP_FILE} gefunden.")
sys.exit(1)
print(f"Gefundene Firmware-Datei: {bin_file}")
print(f"Gefundene Dateisystem-Datei: {fs_file}")
# Entpacke die .fs.gz-Datei
decompressed_fs_file = decompress_gz(fs_file)
print("Bitte stecke den ESP8266 ab, falls er angeschlossen ist, und drücke Enter.")
input()
print("Suche nach verfügbaren COM-Ports...")
old_ports = get_com_ports()
print("Bitte stecke den ESP8266 jetzt an und warte, bis der neue COM-Port erkannt wird...")
port = find_new_com_port(old_ports, timeout=15)
if port is None:
print("Kein neuer COM-Port gefunden. Bitte versuche es erneut.")
sys.exit(1)
print(f"Neuer COM-Port gefunden: {port}")
# Benutze esptool zum Flashen der Firmware und des Dateisystems
try:
# Flashen der Firmware
esptool_args_bin = [
'--port', port,
'--baud', str(BAUD_RATE),
'write_flash', '-fm', 'dout', '0x00000', bin_file
]
esptool.main(esptool_args_bin)
print("Firmware erfolgreich geflasht!")
# Flashen des Dateisystems
esptool_args_fs = [
'--port', port,
'--baud', str(BAUD_RATE),
'write_flash', '0x300000', decompressed_fs_file
]
esptool.main(esptool_args_fs)
print("Dateisystem erfolgreich geflasht!")
# Bereinigen der entpackten Dateien
clean_up(extracted_files)
clean_up([decompressed_fs_file])
except Exception as e:
print(f"Fehler beim Flashen: {e}")
sys.exit(1)
input("Drücke Enter, um das Fenster zu schließen...") # Hält das Fenster offen

View File

@@ -102,7 +102,6 @@ uint32_t Checksum_EEPROM(uint8_t const *data, size_t len);
void dumpEEPROM(uint16_t memoryAddress, uint16_t length);
void MovePersistencePage_EEPROM(boolean reset);
uint32_t ConfigSanityCheck(bool autocorrect = false);
bool validateWiFiString(char *string, size_t size);
void writeSequentialToEEPROM(uint16_t memoryAddress, uint16_t length);
void writeZeroToEEPROM(uint16_t memoryAddress, uint16_t length);

View File

@@ -10,7 +10,7 @@ typedef struct Globals_s
tSystem_Status resumeStatus = sysStat_Startup; /**< Status to resume after rain mode */
char systemStatustxt[16] = ""; /**< Text representation of system status */
EERequest_t requestEEAction = EE_IDLE; /**< EEPROM-related request */
char DeviceName[33]; /**< Device name */
char DeviceName[25]; /**< Device name */
char DeviceNameId[sizeof(DeviceName) + 8]; /**< Device name plus 8 chars chipID */
char FlashVersion[10]; /**< Flash version */
uint16_t eePersistanceAdress; /**< EEPROM persistence address */

View File

@@ -0,0 +1,36 @@
#ifndef UTILITIES_H
#define UTILITIES_H
#include <Arduino.h>
/**
* @brief Validates whether a given string contains only characters allowed in WiFi SSIDs and passwords.
*
* This function checks each character in the provided string to ensure
* that it contains only characters allowed in WiFi SSIDs and passwords.
* It considers characters from 'A' to 'Z', 'a' to 'z', '0' to '9', as well as
* the following special characters: ! " # $ % & ' ( ) * + , - . / : ; < = > ? @ [ \ ] ^ _ ` { | } ~
*
* @param string Pointer to the string to be validated.
* @param size Size of the string including the null-terminator.
* @return true if the string contains only allowed characters or is NULL,
* false otherwise.
*/
bool validateWiFiString(char *string, size_t size);
/**
* @brief Copies a string to a buffer, replacing invalid WiFi SSID characters with a placeholder.
*
* This function checks each character in the provided input string to ensure
* that it contains only characters allowed in WiFi SSIDs and passwords. If a character
* is invalid, it replaces it with a placeholder character (e.g., '_').
* It considers characters from 'A' to 'Z', 'a' to 'z', '0' to '9', as well as
* the following special characters: ! " # $ % & ' ( ) * + , - . / : ; < = > ? @ [ \ ] ^ _ ` { | } ~
*
* @param input Pointer to the input string to be validated and copied.
* @param buffer Pointer to the buffer where the output string will be copied.
* @param bufferSize Size of the buffer including the null-terminator.
*/
void sanitizeWiFiString(const char *input, char *buffer, size_t bufferSize);
#endif // UTILITIES_H

View File

@@ -9,6 +9,7 @@
#include "eeprom.h"
#include "debugger.h"
#include "globals.h"
#include "utilities.h"
// Instance of I2C_eeprom for EEPROM access
I2C_eeprom ee(I2C_EE_ADDRESS, EEPROM_SIZE_BYTES);
@@ -430,48 +431,6 @@ uint32_t ConfigSanityCheck(bool autocorrect)
return setting_reset_bits;
}
/**
* @brief Validates whether a given string contains only characters allowed in WiFi SSIDs and passwords.
*
* This function checks each character in the provided string to ensure
* that it contains only characters allowed in WiFi SSIDs and passwords.
* It considers characters from 'A' to 'Z', 'a' to 'z', '0' to '9', as well as
* the following special characters: ! " # $ % & ' ( ) * + , - . / : ; < = > ? @ [ \ ] ^ _ ` { | } ~
*
* @param string Pointer to the string to be validated.
* @param size Size of the string including the null-terminator.
* @return true if the string contains only allowed characters or is NULL,
* false otherwise.
*/
bool validateWiFiString(char *string, size_t size)
{
if (string == NULL)
return false;
for (size_t i = 0; i < size; i++)
{
char c = string[i];
if (c == '\0')
{
// Reached the end of the string, all characters were valid WiFi characters.
return true;
}
if (!((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') ||
(c >= '0' && c <= '9') || c == '!' || c == '"' || c == '#' ||
c == '$' || c == '%' || c == '&' || c == '\'' || c == '(' ||
c == ')' || c == '*' || c == '+' || c == ',' || c == '-' ||
c == '.' || c == '/' || c == ':' || c == ';' || c == '<' ||
c == '=' || c == '>' || c == '?' || c == '@' || c == '[' ||
c == '\\' || c == ']' || c == '^' || c == '_' || c == '`' ||
c == '{' || c == '|' || c == '}' || c == '~'))
{
// Found a character that is not a valid WiFi character.
return false;
}
}
// If the loop completes without finding a null terminator, the string is invalid.
return false;
}
/**
* @brief Write sequential numbers to a portion of EEPROM.

View File

@@ -249,7 +249,7 @@ void printParameters(struct Configuration configuration)
void Parse_LoRa_UartCommand(char input[], int size)
{
Debug_pushMessage("Start parsing, size: %d", size);
Debug_pushMessage("Start parsing, size: %d\n", size);
char delimiter[] = ";";
char *ptr;
char command[8];
@@ -278,7 +278,7 @@ void Parse_LoRa_UartCommand(char input[], int size)
}
// Hier kannst du den Wert und das Kommando verarbeiten
Debug_pushMessage("Command: %s, Value: %s", command, value);
Debug_pushMessage("Command: %s, Value: %s\n", command, value);
}
Debug_pushMessage("Parsed LoRa UART Command: %s Value: %s\n", command, value);
@@ -286,12 +286,12 @@ void Parse_LoRa_UartCommand(char input[], int size)
if (!strcmp(command, "ENABLE"))
{
globals.timer_disabled = false;
Debug_pushMessage("Enabled by LoRa");
Debug_pushMessage("Enabled by LoRa\n");
}
else if (!strcmp(command, "DISABLE"))
{
globals.timer_disabled = true;
Debug_pushMessage("Disabled by LoRa");
Debug_pushMessage("Disabled by LoRa\n");
}
else if (!strcmp(command, "RESET"))
{
@@ -299,7 +299,7 @@ void Parse_LoRa_UartCommand(char input[], int size)
PersistenceData.faction_1_timer = 0;
PersistenceData.faction_2_timer = 0;
PersistenceData.faction_3_timer = 0;
Debug_pushMessage("Reset by LoRa");
Debug_pushMessage("Reset by LoRa\n");
}
else if (!strcmp(command, "TMRSTP"))
{

View File

@@ -19,6 +19,7 @@
#include "globals.h"
#include "dtc.h"
#include "debugger.h"
#include "utilities.h"
#if defined(FEATURE_ENABLE_LORA) || defined(FEATURE_ENABLE_UARTLORA)
#include "lora_net.h"
#endif
@@ -420,7 +421,7 @@ void tmrCallback_InputGetter()
if (keysPressed > 1)
{
Debug_pushMessage("ERROR: More than one Flag active - setting no Faction active");
Debug_pushMessage("ERROR: More than one Flag active - setting no Faction active\n");
PersistenceData.activeFaction = NONE;
return;
}
@@ -429,7 +430,7 @@ void tmrCallback_InputGetter()
{
if (PersistenceData.activeFaction != FACTION_1)
{
Debug_pushMessage("Faction 1 captured !");
Debug_pushMessage("Faction 1 captured !\n");
globals.requestEEAction = EE_PDS_SAVE;
}
PersistenceData.activeFaction = FACTION_1;
@@ -439,7 +440,7 @@ void tmrCallback_InputGetter()
{
if (PersistenceData.activeFaction != FACTION_2)
{
Debug_pushMessage("Faction 2 captured !");
Debug_pushMessage("Faction 2 captured !\n");
globals.requestEEAction = EE_PDS_SAVE;
}
PersistenceData.activeFaction = FACTION_2;
@@ -449,7 +450,7 @@ void tmrCallback_InputGetter()
{
if (PersistenceData.activeFaction != FACTION_3)
{
Debug_pushMessage("Faction 3 captured !");
Debug_pushMessage("Faction 3 captured !\n");
globals.requestEEAction = EE_PDS_SAVE;
}
PersistenceData.activeFaction = FACTION_3;
@@ -571,6 +572,7 @@ void wifiMaintainConnectionTicker_callback()
*/
void toggleWiFiAP(bool shutdown)
{
char buffer[33];
// Check if WiFi is currently active
if (WiFi.getMode() != WIFI_OFF)
{
@@ -588,7 +590,8 @@ void toggleWiFiAP(bool shutdown)
// Start WiFi in Access Point (AP) mode
WiFi.mode(WIFI_AP);
WiFi.softAPConfig(IPAddress(WIFI_AP_IP_GW), IPAddress(WIFI_AP_IP_GW), IPAddress(255, 255, 255, 0));
WiFi.softAP(globals.DeviceNameId, QUOTE(WIFI_AP_PASSWORD));
sanitizeWiFiString(globals.DeviceNameId, buffer, sizeof(buffer));
WiFi.softAP(buffer, QUOTE(WIFI_AP_PASSWORD));
// Stop WiFi maintenance connection ticker if enabled and display debug messages
#ifdef FEATURE_ENABLE_WIFI_CLIENT
@@ -701,7 +704,7 @@ void ProcessKeyCombos(bool *btnState)
if (keyCount_Fac2 == 2 && keyCount_Fac3 == 0)
{
Debug_pushMessage("KeyCombo: WiFi AP ON");
Debug_pushMessage("KeyCombo: WiFi AP ON\n");
OverrideDisplay(5000, "NET ", " ", " ");
toggleWiFiAP(false);
}

View File

@@ -0,0 +1,94 @@
#include "utilities.h"
/**
* @brief Validates whether a given string contains only characters allowed in WiFi SSIDs and passwords.
*
* This function checks each character in the provided string to ensure
* that it contains only characters allowed in WiFi SSIDs and passwords.
* It considers characters from 'A' to 'Z', 'a' to 'z', '0' to '9', as well as
* the following special characters: ! " # $ % & ' ( ) * + , - . / : ; < = > ? @ [ \ ] ^ _ ` { | } ~
*
* @param string Pointer to the string to be validated.
* @param size Size of the string including the null-terminator.
* @return true if the string contains only allowed characters or is NULL,
* false otherwise.
*/
bool validateWiFiString(char *string, size_t size)
{
if (string == NULL)
return false;
for (size_t i = 0; i < size; i++)
{
char c = string[i];
if (c == '\0')
{
// Reached the end of the string, all characters were valid WiFi characters.
return true;
}
if (!((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') ||
(c >= '0' && c <= '9') || c == '!' || c == '"' || c == '#' ||
c == '$' || c == '%' || c == '&' || c == '\'' || c == '(' ||
c == ')' || c == '*' || c == '+' || c == ',' || c == '-' ||
c == '.' || c == '/' || c == ':' || c == ';' || c == '<' ||
c == '=' || c == '>' || c == '?' || c == '@' || c == '[' ||
c == '\\' || c == ']' || c == '^' || c == '_' || c == '`' ||
c == '{' || c == '|' || c == '}' || c == '~'))
{
// Found a character that is not a valid WiFi character.
return false;
}
}
// If the loop completes without finding a null terminator, the string is invalid.
return false;
}
/**
* @brief Copies a string to a buffer, replacing invalid WiFi SSID characters with a placeholder.
*
* This function checks each character in the provided input string to ensure
* that it contains only characters allowed in WiFi SSIDs and passwords. If a character
* is invalid, it replaces it with a placeholder character (e.g., '_').
* It considers characters from 'A' to 'Z', 'a' to 'z', '0' to '9', as well as
* the following special characters: ! " # $ % & ' ( ) * + , - . / : ; < = > ? @ [ \ ] ^ _ ` { | } ~
*
* @param input Pointer to the input string to be validated and copied.
* @param buffer Pointer to the buffer where the output string will be copied.
* @param bufferSize Size of the buffer including the null-terminator.
*/
void sanitizeWiFiString(const char *input, char *buffer, size_t bufferSize)
{
if (input == NULL || buffer == NULL || bufferSize == 0)
return;
size_t i;
for (i = 0; i < bufferSize - 1; i++) // Leave space for null-terminator
{
char c = input[i];
if (c == '\0')
{
// Reached the end of the input string, terminate the buffer
buffer[i] = '\0';
return;
}
if (!((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') ||
(c >= '0' && c <= '9') || c == '!' || c == '"' || c == '#' ||
c == '$' || c == '%' || c == '&' || c == '\'' || c == '(' ||
c == ')' || c == '*' || c == '+' || c == ',' || c == '-' ||
c == '.' || c == '/' || c == ':' || c == ';' || c == '<' ||
c == '=' || c == '>' || c == '?' || c == '@' || c == '[' ||
c == '\\' || c == ']' || c == '^' || c == '_' || c == '`' ||
c == '{' || c == '|' || c == '}' || c == '~'))
{
// Replace invalid character with placeholder
buffer[i] = '_';
}
else
{
// Copy valid character to buffer
buffer[i] = c;
}
}
// Null-terminate the buffer
buffer[i] = '\0';
}

View File

@@ -594,44 +594,45 @@ void Websocket_RefreshClientData_DTCs(uint32_t client_id)
*/
void Websocket_RefreshClientData_Status(uint32_t client_id, bool send_mapping)
{
if (send_mapping)
{
const char mapping[] = "MAPPING_STATUS:"
"batterylevel;"
"systemstatus;"
"activefaction;"
"time_faction1;"
"time_faction2;"
"time_faction3;";
if (send_mapping)
{
const char mapping[] = "MAPPING_STATUS:"
"batterylevel;"
"systemstatus;"
"activefaction;"
"time_faction1;"
"time_faction2;"
"time_faction3;";
if (client_id > 0)
webSocket.text(client_id, mapping);
else
webSocket.textAll(mapping);
Debug_pushMessage("send MAPPING_STATUS WS-Client Data\n");
}
char dataString[200] = {0}; // Maximal 200 Zeichen für den Data-String
sprintf(dataString, "STATUS:%d;%s;%d;%ld;%ld;%ld;",
globals.battery_level,
globals.systemStatustxt,
PersistenceData.activeFaction,
PersistenceData.faction_1_timer,
PersistenceData.faction_2_timer,
PersistenceData.faction_3_timer);
if (client_id > 0)
webSocket.text(client_id, mapping);
{
webSocket.text(client_id, dataString);
}
else
webSocket.textAll(mapping);
Debug_pushMessage("send MAPPING_STATUS WS-Client Data\n");
}
String temp = "STATUS:";
temp.concat(String(globals.battery_level) + ";");
temp.concat(String(globals.systemStatustxt) + ";");
temp.concat(String(PersistenceData.activeFaction) + ";");
temp.concat(String(PersistenceData.faction_1_timer) + ";");
temp.concat(String(PersistenceData.faction_2_timer) + ";");
temp.concat(String(PersistenceData.faction_3_timer) + ";");
if (client_id > 0)
{
webSocket.text(client_id, temp);
}
else
{
webSocket.textAll(temp);
}
{
webSocket.textAll(dataString);
}
}
/**
* @brief Refreshes client data related to static configuration parameters on WebSocket clients.
*
@@ -645,6 +646,7 @@ void Websocket_RefreshClientData_Status(uint32_t client_id, bool send_mapping)
void Websocket_RefreshClientData_Static(uint32_t client_id, bool send_mapping)
{
Debug_pushMessage("send STATIC WS-Client Data\n");
if (send_mapping)
{
const char mapping[] = "MAPPING_STATIC:"
@@ -664,11 +666,11 @@ void Websocket_RefreshClientData_Static(uint32_t client_id, bool send_mapping)
webSocket.text(client_id, mapping);
else
webSocket.textAll(mapping);
Debug_pushMessage("send MAPPING_STATIC WS-Client Data\n");
}
char dataString[200]; // Maximal 200 Zeichen für den Data-String
char flash_version[6];
GetFlashVersion(flash_version, sizeof(flash_version));
char dataString[200] = {0}; // Maximal 200 Zeichen für den Data-String
sprintf(dataString, "STATIC:%s;%d;%d;%s;%s;%s;%s;%s;%d.%02d;%s;%s;",
globals.DeviceName,
@@ -681,7 +683,7 @@ void Websocket_RefreshClientData_Static(uint32_t client_id, bool send_mapping)
ConfigData.wifi_client_password,
constants.FW_Version_major,
constants.FW_Version_minor,
flash_version,
globals.FlashVersion,
constants.GitHash);
if (client_id > 0)