Compare commits
	
		
			97 Commits
		
	
	
		
			8eb52e286f
			...
			1.09
		
	
	| Author | SHA1 | Date | |
|---|---|---|---|
| 442fddfb7f | |||
| 558e516f7d | |||
| b024bb66a9 | |||
| 58e9a97804 | |||
| f966f2df14 | |||
| b4177c9b0f | |||
| 0763fe2181 | |||
| 024a00e1bf | |||
| 2fea8cfdd6 | |||
| 25f05ed832 | |||
| 3d090dceb1 | |||
| e4770f2fa2 | |||
| cbcdc34e6c | |||
| 48774a42f4 | |||
| 73c486be73 | |||
| 6574947a80 | |||
| 956cc49e6f | |||
| b1da9449ad | |||
| e54cadcc7c | |||
| 0b2245d7f6 | |||
| 3ceab44a96 | |||
| 91de9f0785 | |||
| 837fd7f558 | |||
| 6cacd8451f | |||
| 5ae054f314 | |||
| 3e571a515d | |||
| a2aa302121 | |||
| d04489819d | |||
| 52026296f2 | |||
| a22f71649a | |||
| ae8eef52ef | |||
| d9ee193e26 | |||
| 170c66ff49 | |||
| 2ad835966c | |||
| a20a351002 | |||
| c9fba23e70 | |||
| 9301607468 | |||
| fc592c4342 | |||
| ab2ab0e0c1 | |||
| 5ee0a23a6d | |||
| cf76ea7cc7 | |||
| 7a2e95c126 | |||
| 1cf0560957 | |||
| b66d175948 | |||
| 0967b6aa65 | |||
| 498d813624 | |||
| 268c204957 | |||
| 65d51f13aa | |||
| f727bb3247 | |||
| cd1379f90c | |||
| 0363b1eebc | |||
| e6f1283aae | |||
| a92b1edfd9 | |||
| 4cce7c1c86 | |||
| 0a1625e9b8 | |||
| c24829ed70 | |||
| a102405596 | |||
| 1b7157dbdc | |||
| cad34d6b84 | |||
| 701bf9f457 | |||
| 0a895a00b9 | |||
| 22a62e3d1e | |||
| f48b5a09ed | |||
| 7f6c486eab | |||
| 3e77f89538 | |||
| f33076a0a3 | |||
| 7e58db489d | |||
| eb771d07d3 | |||
| e2059cb587 | |||
| 6702154ef5 | |||
| a899cf4dcf | |||
| ea230bcee7 | |||
| c059d7d085 | |||
| b8c79955a8 | |||
| 44240aa7bf | |||
| 6bc523b2a8 | |||
| 97cdd7fad1 | |||
| ec62eeee1e | |||
| 7b166caf84 | |||
| 62a7cd1b9c | |||
| 7e047c0c09 | |||
| 8c2d553dfb | |||
| ca9409e328 | |||
| 5a6dc524ad | |||
| 41b27c02dd | |||
| e344977b8f | |||
| aeab80d5a8 | |||
| 4507c80eba | |||
| 427e5e5d16 | |||
| 3a0e1a931d | |||
| a960e67c7d | |||
| 9e1a4d821f | |||
| 4d0a9918ce | |||
| 53928a93b0 | |||
| 6b89ed9a8c | |||
| ae29e23812 | |||
| 8884e995ca | 
							
								
								
									
										
											BIN
										
									
								
								Documentation/Pinout_UART_LoRa.png
									
									
									
									
									
										Normal file
									
								
							
							
						
						| 
		 After Width: | Height: | Size: 53 KiB  | 
							
								
								
									
										5
									
								
								Software/.gitignore
									
									
									
									
										vendored
									
									
								
							
							
						
						@@ -1,7 +1,10 @@
 | 
			
		||||
data/
 | 
			
		||||
data_src/version
 | 
			
		||||
node_modules/
 | 
			
		||||
.pio
 | 
			
		||||
.vscode/.browse.c_cpp.db*
 | 
			
		||||
.vscode/c_cpp_properties.json
 | 
			
		||||
.vscode/launch.json
 | 
			
		||||
.vscode/ipch
 | 
			
		||||
wifi_credentials.ini
 | 
			
		||||
wifi_credentials.ini
 | 
			
		||||
__pycache__
 | 
			
		||||
							
								
								
									
										97
									
								
								Software/codegen/README_flash_esp8266.md
									
									
									
									
									
										Normal 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.
 | 
			
		||||
 | 
			
		||||
---
 | 
			
		||||
							
								
								
									
										145
									
								
								Software/codegen/dtcs.py
									
									
									
									
									
										Normal file
									
								
							
							
						
						@@ -0,0 +1,145 @@
 | 
			
		||||
import os
 | 
			
		||||
import time
 | 
			
		||||
from jinja2 import Environment, FileSystemLoader
 | 
			
		||||
import json
 | 
			
		||||
import sys
 | 
			
		||||
 | 
			
		||||
import filechecksum as fcs
 | 
			
		||||
 | 
			
		||||
def build_dtcs():
 | 
			
		||||
    # Pfad zur Eingabedatei und Ausgabedatei
 | 
			
		||||
    input_file = "src/dtc_defs.txt"
 | 
			
		||||
    output_file = "include/dtc_defs.h"
 | 
			
		||||
    json_output_file = "data_src/static/dtc_table.json"
 | 
			
		||||
    
 | 
			
		||||
    # Überprüfen, ob das Verzeichnis existiert, andernfalls erstellen
 | 
			
		||||
    json_output_dir = os.path.dirname(json_output_file)
 | 
			
		||||
    if not os.path.exists(json_output_dir):
 | 
			
		||||
        os.makedirs(json_output_dir)
 | 
			
		||||
    
 | 
			
		||||
    # Mehrdimensionales Array zum Speichern der Zeilen aus der Eingabedatei
 | 
			
		||||
    dtc_lines = []
 | 
			
		||||
    
 | 
			
		||||
    # Lesen und analysieren der Eingabedatei
 | 
			
		||||
    with open(input_file, "r", encoding="utf-8") as f:
 | 
			
		||||
        for line in f:
 | 
			
		||||
            line = line.strip()
 | 
			
		||||
            if not line or line.startswith("#"):
 | 
			
		||||
                continue
 | 
			
		||||
    
 | 
			
		||||
            parts = line.split(";")
 | 
			
		||||
            if len(parts) == 5:
 | 
			
		||||
                num, dtc_name, dtc_severity, title, description = [part.strip() for part in parts]
 | 
			
		||||
                dtc_lines.append([int(num), dtc_name, dtc_severity, title, description])
 | 
			
		||||
    
 | 
			
		||||
    # Überprüfen auf Duplikate in den DTC-Nummern und DTC-Namen
 | 
			
		||||
    num_set = set()
 | 
			
		||||
    dtc_name_set = set()
 | 
			
		||||
    duplicates = []
 | 
			
		||||
    
 | 
			
		||||
    for line in dtc_lines:
 | 
			
		||||
        num, dtc_name, _, _, _ = line
 | 
			
		||||
        if num in num_set:
 | 
			
		||||
            duplicates.append(f"DTC-Nummer {num} ist ein Duplikat.")
 | 
			
		||||
        else:
 | 
			
		||||
            num_set.add(num)
 | 
			
		||||
    
 | 
			
		||||
        if dtc_name in dtc_name_set:
 | 
			
		||||
            duplicates.append(f"DTC-Name '{dtc_name}' ist ein Duplikat.")
 | 
			
		||||
        else:
 | 
			
		||||
            dtc_name_set.add(dtc_name)
 | 
			
		||||
    
 | 
			
		||||
    if duplicates:
 | 
			
		||||
        for duplicate in duplicates:
 | 
			
		||||
            print(f"Fehler: {duplicate}")
 | 
			
		||||
        raise ValueError("Duplicate DTC Data detected")
 | 
			
		||||
    
 | 
			
		||||
    # Suchen nach DTC_NO_DTC und DTC_LAST_DTC
 | 
			
		||||
    dtc_no_dtc_added = False
 | 
			
		||||
    dtc_last_dtc_line = None
 | 
			
		||||
    
 | 
			
		||||
    for line in dtc_lines:
 | 
			
		||||
        _, dtc_name, _, _, _ = line
 | 
			
		||||
        if dtc_name == "DTC_NO_DTC":
 | 
			
		||||
            dtc_no_dtc_added = True
 | 
			
		||||
        elif dtc_name == "DTC_LAST_DTC":
 | 
			
		||||
            dtc_last_dtc_line = line
 | 
			
		||||
    
 | 
			
		||||
    # Einen DTC für DTC_NO_DTC hinzufügen (wenn nicht vorhanden)
 | 
			
		||||
    if not dtc_no_dtc_added:
 | 
			
		||||
        dtc_lines.insert(0, [0, "DTC_NO_DTC", "DTC_NONE", "No Error", "No Error"])
 | 
			
		||||
    
 | 
			
		||||
    # Falls DTC_LAST_DTC existiert, lösche es
 | 
			
		||||
    if dtc_last_dtc_line:
 | 
			
		||||
        dtc_lines.remove(dtc_last_dtc_line)
 | 
			
		||||
    
 | 
			
		||||
    # Einen DTC für DTC_LAST_DTC hinzufügen (mit der höchsten Nummer)
 | 
			
		||||
    if dtc_lines:
 | 
			
		||||
        highest_num = max([line[0] for line in dtc_lines])
 | 
			
		||||
    else:
 | 
			
		||||
        highest_num = 0
 | 
			
		||||
    
 | 
			
		||||
    dtc_lines.append([highest_num + 1, "DTC_LAST_DTC", "DTC_NONE", "Last Error", "Last Error"])
 | 
			
		||||
    
 | 
			
		||||
    # Sortieren der Zeilen nach der Nummer aufsteigend
 | 
			
		||||
    dtc_lines.sort(key=lambda x: x[0])
 | 
			
		||||
    
 | 
			
		||||
    checksum = fcs.calculate_checksum(dtc_lines)
 | 
			
		||||
    timestamp = int(time.time())
 | 
			
		||||
    
 | 
			
		||||
    if fcs.read_and_compare_checksum(output_file, checksum):
 | 
			
		||||
        print("Keine Änderungen im DTC-Headerfile erforderlich.")
 | 
			
		||||
    else:
 | 
			
		||||
        # DTC_NAME_CONSTANT-Makros initialisieren
 | 
			
		||||
        dtc_macros = []
 | 
			
		||||
        dtc_structs = []
 | 
			
		||||
    
 | 
			
		||||
        # Verarbeiten der sortierten Zeilen
 | 
			
		||||
        for i, line in enumerate(dtc_lines):
 | 
			
		||||
            num, dtc_name, dtc_severity, title, description = line
 | 
			
		||||
            dtc_macros.append(f"#define {dtc_name:<30} {num}")
 | 
			
		||||
            comma = "," if i < len(dtc_lines) - 1 else " "
 | 
			
		||||
            dtc_structs.append(f"    {{ {dtc_name:<30}, {dtc_severity:<12} }}{comma} // {description}")
 | 
			
		||||
    
 | 
			
		||||
        env = Environment(loader=FileSystemLoader('codegen/templates', encoding='utf-8'))
 | 
			
		||||
        # Lade das Jinja2-Template aus der Datei
 | 
			
		||||
        template = env.get_template('dtc_defs.h.j2')
 | 
			
		||||
    
 | 
			
		||||
        # Erstelle ein Context-Dictionary mit den erforderlichen Daten
 | 
			
		||||
        context = {
 | 
			
		||||
            'timestamp_unix': timestamp,
 | 
			
		||||
            'timestamp' : time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(timestamp)),
 | 
			
		||||
            'date' : time.strftime('%d.%m.%Y', time.localtime(timestamp)),
 | 
			
		||||
            'dtc_macros': dtc_macros,  # Übergebe die dtc_macros-Liste direkt
 | 
			
		||||
            'dtc_structs': dtc_structs,  # Übergebe die dtc_structs-Liste direkt
 | 
			
		||||
            'checksum' : checksum
 | 
			
		||||
        }
 | 
			
		||||
   
 | 
			
		||||
        # Rendere das Template mit den Werten und erhalte den Header-Text
 | 
			
		||||
        header_text = template.render(context)
 | 
			
		||||
    
 | 
			
		||||
        # Schreibe den generierten Header-Text in die Header-Datei
 | 
			
		||||
        with open(output_file, "w", encoding='utf-8') as f:
 | 
			
		||||
            f.write(header_text)
 | 
			
		||||
    
 | 
			
		||||
        print(f"Header-Datei wurde erstellt: {output_file}")
 | 
			
		||||
    
 | 
			
		||||
    if fcs.read_and_compare_json_checksum(json_output_file, checksum):
 | 
			
		||||
        print("Keine Änderungen im DTC-JSON-file erforderlich.")
 | 
			
		||||
    else:
 | 
			
		||||
        dtc_info = {
 | 
			
		||||
            "codegenerator_checksum": checksum,
 | 
			
		||||
            'timestamp' : time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(timestamp)),
 | 
			
		||||
            "dtc_table_data": []
 | 
			
		||||
        }
 | 
			
		||||
    
 | 
			
		||||
        # Verarbeiten der sortierten Zeilen
 | 
			
		||||
        for i, line in enumerate(dtc_lines):
 | 
			
		||||
            num, dtc_name, dtc_severity, title, description = line
 | 
			
		||||
            dtc_info["dtc_table_data"].append({"num": num, "title": title, "description": description})
 | 
			
		||||
 | 
			
		||||
        # JSON-Datei mit UTF-8-Zeichencodierung erstellen
 | 
			
		||||
        with open(json_output_file, 'w', encoding='utf-8') as json_f:
 | 
			
		||||
            json.dump(dtc_info, json_f, ensure_ascii=False, indent=4, separators=(',', ': '))
 | 
			
		||||
    
 | 
			
		||||
        print(f"JSON-Datei wurde erstellt: {json_output_file}")
 | 
			
		||||
							
								
								
									
										45
									
								
								Software/codegen/filechecksum.py
									
									
									
									
									
										Normal file
									
								
							
							
						
						@@ -0,0 +1,45 @@
 | 
			
		||||
 | 
			
		||||
import hashlib
 | 
			
		||||
import json
 | 
			
		||||
 | 
			
		||||
# Funktion zum Berechnen der SHA-256-Checksumme
 | 
			
		||||
def calculate_checksum(data):
 | 
			
		||||
    sha256 = hashlib.sha256()
 | 
			
		||||
    sha256.update(str(data).encode('utf-8'))
 | 
			
		||||
    return sha256.hexdigest()
 | 
			
		||||
 | 
			
		||||
# Funktion zum Lesen und Vergleichen der Checksumme in einer Datei
 | 
			
		||||
def read_and_compare_checksum(file_path, expected_checksum):
 | 
			
		||||
    try:
 | 
			
		||||
        with open(file_path, 'r') as file:
 | 
			
		||||
            content = file.read()
 | 
			
		||||
            # Suche nach der Zeile mit der Checksumme
 | 
			
		||||
            checksum_line_start = content.find("// CODEGENERATOR_CHECKSUM:")
 | 
			
		||||
            if checksum_line_start != -1:
 | 
			
		||||
                # Extrahiere die Checksumme aus der Zeile
 | 
			
		||||
                existing_checksum = content[checksum_line_start + len("// CODEGENERATOR_CHECKSUM:"):].strip()
 | 
			
		||||
                # Vergleiche die Checksummen
 | 
			
		||||
                if existing_checksum == expected_checksum:
 | 
			
		||||
                    return True
 | 
			
		||||
    except FileNotFoundError:
 | 
			
		||||
        pass  # Datei existiert nicht, was nicht schlimm ist
 | 
			
		||||
 | 
			
		||||
    return False
 | 
			
		||||
 | 
			
		||||
def read_and_compare_json_checksum(json_file_path, expected_checksum):
 | 
			
		||||
    try:
 | 
			
		||||
        with open(json_file_path, 'r') as json_file:
 | 
			
		||||
            # Lade das JSON aus der Datei
 | 
			
		||||
            data = json.load(json_file)
 | 
			
		||||
            
 | 
			
		||||
            # Überprüfe, ob "codegenerator_checksum" im JSON vorhanden ist
 | 
			
		||||
            if "codegenerator_checksum" in data:
 | 
			
		||||
                existing_checksum = data["codegenerator_checksum"]
 | 
			
		||||
                
 | 
			
		||||
                # Vergleiche die Checksummen
 | 
			
		||||
                if existing_checksum == expected_checksum:
 | 
			
		||||
                    return True
 | 
			
		||||
    except FileNotFoundError:
 | 
			
		||||
        pass  # Datei existiert nicht, was nicht schlimm ist
 | 
			
		||||
 | 
			
		||||
    return False
 | 
			
		||||
							
								
								
									
										156
									
								
								Software/codegen/flash_esp8266.py
									
									
									
									
									
										Normal 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
 | 
			
		||||
							
								
								
									
										200
									
								
								Software/codegen/prepare_littlefs.py
									
									
									
									
									
										Normal file
									
								
							
							
						
						@@ -0,0 +1,200 @@
 | 
			
		||||
import shutil
 | 
			
		||||
import gzip
 | 
			
		||||
import os
 | 
			
		||||
import subprocess
 | 
			
		||||
import platform
 | 
			
		||||
from os import popen
 | 
			
		||||
Import("env")
 | 
			
		||||
Import("projenv")
 | 
			
		||||
 | 
			
		||||
def resolve_tool(name):
 | 
			
		||||
    local_bin = os.path.join(env['PROJECT_DIR'], 'node_modules', '.bin', name)
 | 
			
		||||
    if platform.system() == "Windows":
 | 
			
		||||
        local_bin += ".cmd"
 | 
			
		||||
    if os.path.exists(local_bin):
 | 
			
		||||
        return local_bin
 | 
			
		||||
 | 
			
		||||
    found = shutil.which(name)
 | 
			
		||||
    if found:
 | 
			
		||||
        return found
 | 
			
		||||
 | 
			
		||||
    raise FileNotFoundError(f"{name} wurde nicht gefunden. Bitte `npm install` ausführen.")
 | 
			
		||||
 | 
			
		||||
def ensure_npm_dependencies():
 | 
			
		||||
    node_modules_bin = os.path.join(env['PROJECT_DIR'], 'node_modules', '.bin')
 | 
			
		||||
    required_tools = ["html-minifier", "terser", "cleancss"]
 | 
			
		||||
    missing = False
 | 
			
		||||
 | 
			
		||||
    for tool in required_tools:
 | 
			
		||||
        path = os.path.join(node_modules_bin, tool + ('.cmd' if platform.system() == "Windows" else ''))
 | 
			
		||||
        if not os.path.exists(path):
 | 
			
		||||
            missing = True
 | 
			
		||||
            break
 | 
			
		||||
 | 
			
		||||
    if missing:
 | 
			
		||||
        print("NPM-Abhängigkeiten fehlen – führe `npm install` aus...")
 | 
			
		||||
        subprocess.run(["npm", "install"], cwd=env['PROJECT_DIR'], check=True)
 | 
			
		||||
 | 
			
		||||
 | 
			
		||||
ensure_npm_dependencies()
 | 
			
		||||
 | 
			
		||||
html_minifier_path = resolve_tool("html-minifier")
 | 
			
		||||
terser_path = resolve_tool("terser")
 | 
			
		||||
cleancss_path = resolve_tool("cleancss")
 | 
			
		||||
 | 
			
		||||
def minify_html(input_path, output_path):
 | 
			
		||||
    subprocess.run([html_minifier_path, '--collapse-whitespace', '--remove-comments', input_path, '-o', output_path])
 | 
			
		||||
 | 
			
		||||
def minify_js(input_path, output_path):
 | 
			
		||||
    subprocess.run([terser_path, input_path, '-o', output_path, '-c', '-m'])
 | 
			
		||||
 | 
			
		||||
def minify_css(input_path, output_path):
 | 
			
		||||
    subprocess.run([cleancss_path, '--no-discardUnused', input_path, output_path])
 | 
			
		||||
 | 
			
		||||
def process_file(src_path, dest_path):
 | 
			
		||||
    _, file_extension = os.path.splitext(src_path)
 | 
			
		||||
 | 
			
		||||
    # Extrahiere den Ordnerpfad im Zielverzeichnis
 | 
			
		||||
    dest_dir = os.path.dirname(dest_path)
 | 
			
		||||
 | 
			
		||||
    # Erstelle den Ordner und alle dazugehörigen Unterordner, falls sie nicht existieren
 | 
			
		||||
    os.makedirs(dest_dir, exist_ok=True)
 | 
			
		||||
 | 
			
		||||
    if file_extension.lower() == '.js':
 | 
			
		||||
        minify_js(src_path, dest_path)
 | 
			
		||||
    elif file_extension.lower() == '.css':
 | 
			
		||||
        minify_css(src_path, dest_path)
 | 
			
		||||
    elif file_extension.lower() in ['.html', '.htm']:
 | 
			
		||||
        minify_html(src_path, dest_path)
 | 
			
		||||
    else:
 | 
			
		||||
        # Kopiere nicht bearbeitbare Dateien direkt in den Zielordner
 | 
			
		||||
        shutil.copy2(src_path, dest_path)
 | 
			
		||||
 | 
			
		||||
def strip_files(src_dir, dest_dir):
 | 
			
		||||
    # Erstelle den Zielordner und alle dazugehörigen Unterordner, falls sie nicht existieren
 | 
			
		||||
    os.makedirs(dest_dir, exist_ok=True)
 | 
			
		||||
 | 
			
		||||
    # Durchlaufe alle Dateien und Unterverzeichnisse im Quellordner
 | 
			
		||||
    for root, _, files in os.walk(src_dir):
 | 
			
		||||
        for filename in files:
 | 
			
		||||
            src_path = os.path.join(root, filename)
 | 
			
		||||
            dest_path = os.path.relpath(src_path, src_dir)
 | 
			
		||||
            dest_path = os.path.join(dest_dir, dest_path)
 | 
			
		||||
 | 
			
		||||
            # Verarbeite nur Dateien (keine Unterverzeichnisse)
 | 
			
		||||
            process_file(src_path, dest_path)
 | 
			
		||||
 | 
			
		||||
 | 
			
		||||
def gzip_file(src_path, dst_path):
 | 
			
		||||
 | 
			
		||||
    with open(src_path, 'rb') as src, gzip.open(dst_path, 'wb') as dst:
 | 
			
		||||
        for chunk in iter(lambda: src.read(4096), b""):
 | 
			
		||||
            dst.write(chunk)
 | 
			
		||||
 | 
			
		||||
 | 
			
		||||
def getListOfFiles(dirName):
 | 
			
		||||
    # create a list of file and sub directories
 | 
			
		||||
    # names in the given directory
 | 
			
		||||
    listOfFile = os.listdir(dirName)
 | 
			
		||||
    allFiles = list()
 | 
			
		||||
    # Iterate over all the entries
 | 
			
		||||
    for entry in listOfFile:
 | 
			
		||||
        # Create full path
 | 
			
		||||
        fullPath = os.path.join(dirName, entry)
 | 
			
		||||
        # If entry is a directory then get the list of files in this directory
 | 
			
		||||
        if os.path.isdir(fullPath):
 | 
			
		||||
            allFiles = allFiles + getListOfFiles(fullPath)
 | 
			
		||||
        else:
 | 
			
		||||
            allFiles.append(fullPath)
 | 
			
		||||
 | 
			
		||||
    return allFiles
 | 
			
		||||
 | 
			
		||||
def remove_prefix(text, prefix):
 | 
			
		||||
    if text.startswith(prefix):
 | 
			
		||||
        return text[len(prefix):]
 | 
			
		||||
    return text  # or whatever
 | 
			
		||||
 | 
			
		||||
# Compress files from 'data_src/' to 'data/'
 | 
			
		||||
 | 
			
		||||
 | 
			
		||||
def gzip_webfiles(source, target, env):
 | 
			
		||||
    # Filetypes to compress
 | 
			
		||||
    filetypes_to_gzip = ['.css', '.png', '.js', '.ico', '.woff2', '.json']
 | 
			
		||||
    print('\nGZIP: Starting gzip-Process for LittleFS-Image...\n')
 | 
			
		||||
    data_src_dir_path = os.path.join(env.get('PROJECT_DIR'), 'data_src')
 | 
			
		||||
    data_temp_dir_path = os.path.join(env.get('PROJECT_DIR'), 'data_stripped')
 | 
			
		||||
    strip_files(data_src_dir_path, data_temp_dir_path)
 | 
			
		||||
    data_dir_path = env.get('PROJECT_DATA_DIR')
 | 
			
		||||
    # check if data and datasrc exist. If the first exists and not the second, it renames it
 | 
			
		||||
    if(os.path.exists(data_dir_path) and not os.path.exists(data_temp_dir_path)):
 | 
			
		||||
        print('GZIP: Directory "'+data_dir_path +
 | 
			
		||||
              '" exists, "'+data_temp_dir_path+'" is not found.')
 | 
			
		||||
        print('GZIP: Renaming "' + data_dir_path +
 | 
			
		||||
              '" to "' + data_temp_dir_path + '"')
 | 
			
		||||
        os.rename(data_dir_path, data_temp_dir_path)
 | 
			
		||||
    # Delete the 'data' directory
 | 
			
		||||
    if(os.path.exists(data_dir_path)):
 | 
			
		||||
        print('GZIP: Deleting the "data" directory ' + data_dir_path)
 | 
			
		||||
        shutil.rmtree(data_dir_path)
 | 
			
		||||
    # Recreate empty 'data' directory
 | 
			
		||||
    print('GZIP: Re-creating an empty data directory ' + data_dir_path)
 | 
			
		||||
    os.mkdir(data_dir_path)
 | 
			
		||||
    # Determine the files to compress
 | 
			
		||||
 | 
			
		||||
    files_to_copy = []
 | 
			
		||||
    files_to_gzip = []
 | 
			
		||||
 | 
			
		||||
    all_data_src = getListOfFiles(data_temp_dir_path)
 | 
			
		||||
    for file in all_data_src:
 | 
			
		||||
        file_name, file_extension = os.path.splitext(file)
 | 
			
		||||
        print(file_name + " has filetype " + file_extension)
 | 
			
		||||
        if file_extension in filetypes_to_gzip:
 | 
			
		||||
            files_to_gzip.append(file)
 | 
			
		||||
        else:
 | 
			
		||||
            filename_subdir = remove_prefix(file, data_temp_dir_path)
 | 
			
		||||
            files_to_copy.append(filename_subdir)
 | 
			
		||||
 | 
			
		||||
    for file in files_to_copy:
 | 
			
		||||
        print('GZIP: Copying file from: ' + data_temp_dir_path + file + ' to: ' + data_dir_path + file)
 | 
			
		||||
        os.makedirs(os.path.dirname(data_dir_path + file), exist_ok=True)
 | 
			
		||||
        shutil.copy(data_temp_dir_path + file, data_dir_path + file)
 | 
			
		||||
    # Compress and move files
 | 
			
		||||
    
 | 
			
		||||
    was_error = False
 | 
			
		||||
    try:
 | 
			
		||||
        for source_file_path in files_to_gzip:
 | 
			
		||||
            print('GZIP: compressing... ' + source_file_path)
 | 
			
		||||
            filename_subdir = remove_prefix(source_file_path, data_temp_dir_path)
 | 
			
		||||
            target_file_path = data_dir_path + filename_subdir
 | 
			
		||||
            os.makedirs(os.path.dirname(target_file_path), exist_ok=True)
 | 
			
		||||
            print('GZIP: Compressed... ' + target_file_path)
 | 
			
		||||
            gzip_target_path = target_file_path + ".gz"
 | 
			
		||||
            gzip_file(source_file_path, gzip_target_path)
 | 
			
		||||
    except IOError as e:
 | 
			
		||||
        was_error = True
 | 
			
		||||
        print('GZIP: Failed to compress file: ' + source_file_path)
 | 
			
		||||
        # print( 'GZIP: EXCEPTION... {}'.format( e ) )
 | 
			
		||||
    if was_error:
 | 
			
		||||
        print('GZIP: Failure/Incomplete.\n')
 | 
			
		||||
    else:
 | 
			
		||||
        print('GZIP: Compressed correctly.\n')
 | 
			
		||||
        shutil.rmtree(data_temp_dir_path)
 | 
			
		||||
 | 
			
		||||
    return
 | 
			
		||||
 | 
			
		||||
def gzip_binffiles(source, target, env):
 | 
			
		||||
    git_revision = popen('git rev-parse --short HEAD').read().strip()
 | 
			
		||||
    custom_flash_version = env.GetProjectOption("custom_flash_version", "0.99")
 | 
			
		||||
 | 
			
		||||
    # Format the target file name
 | 
			
		||||
    target_filename = f"filesystem_{custom_flash_version}_{git_revision}.fs"
 | 
			
		||||
    littlefsbin = target[0].get_abspath()
 | 
			
		||||
    targetbin = os.path.join(os.path.dirname(littlefsbin), target_filename)
 | 
			
		||||
    shutil.copyfile(littlefsbin, targetbin)
 | 
			
		||||
    gzip_file(targetbin, os.path.join(str(targetbin) + '.gz'))
 | 
			
		||||
    os.remove(targetbin)
 | 
			
		||||
    return
 | 
			
		||||
 | 
			
		||||
# IMPORTANT, this needs to be added to call the routine
 | 
			
		||||
env.AddPreAction('$BUILD_DIR/littlefs.bin', gzip_webfiles)
 | 
			
		||||
env.AddPostAction('$BUILD_DIR/littlefs.bin', gzip_binffiles)
 | 
			
		||||
							
								
								
									
										38
									
								
								Software/codegen/run_pre.py
									
									
									
									
									
										Normal file
									
								
							
							
						
						@@ -0,0 +1,38 @@
 | 
			
		||||
Import("env")  # pylint: disable=undefined-variable
 | 
			
		||||
env.Execute("\"$PYTHONEXE\" -m pip install jinja2")
 | 
			
		||||
 | 
			
		||||
import struct2json
 | 
			
		||||
import dtcs
 | 
			
		||||
from os import popen
 | 
			
		||||
 | 
			
		||||
git_revision = popen('git rev-parse --short HEAD').read().strip()
 | 
			
		||||
 | 
			
		||||
# Versionsnummern aus platformio.ini holen
 | 
			
		||||
custom_firmware_version = env.GetProjectOption("custom_firmware_version", "0.99")
 | 
			
		||||
custom_flash_version = env.GetProjectOption("custom_flash_version", "0.99")
 | 
			
		||||
 | 
			
		||||
# Versionsnummern aufteilen in Major und Minor
 | 
			
		||||
fw_major, fw_minor = custom_firmware_version.split('.')
 | 
			
		||||
fl_major, fl_minor = custom_flash_version.split('.')
 | 
			
		||||
 | 
			
		||||
fw_major_int = int(fw_major)
 | 
			
		||||
fw_minor_int = int(fw_minor)
 | 
			
		||||
fl_major_int = int(fl_major)
 | 
			
		||||
fl_minor_int = int(fl_minor)
 | 
			
		||||
 | 
			
		||||
# Version in Datei "version" im Ordner "data_src" überschreiben
 | 
			
		||||
with open('data_src/version', 'w') as version_file:
 | 
			
		||||
    version_file.write(custom_flash_version)
 | 
			
		||||
    
 | 
			
		||||
# Build-Flags setzen
 | 
			
		||||
env.Replace(PROGNAME="firmware_%s_%s.fw" % (custom_firmware_version, git_revision))
 | 
			
		||||
env.Append(CPPDEFINES=[
 | 
			
		||||
    ('GIT_REV', '\\"{}\\"'.format(git_revision)),
 | 
			
		||||
    ('FW_MAJOR', fw_major_int),
 | 
			
		||||
    ('FW_MINOR', fw_minor_int),
 | 
			
		||||
    ('FL_MAJOR', fl_major_int),
 | 
			
		||||
    ('FL_MINOR', fl_minor_int)
 | 
			
		||||
])
 | 
			
		||||
 | 
			
		||||
struct2json.struct2json()
 | 
			
		||||
dtcs.build_dtcs()
 | 
			
		||||
							
								
								
									
										113
									
								
								Software/codegen/struct2json.py
									
									
									
									
									
										Normal file
									
								
							
							
						
						@@ -0,0 +1,113 @@
 | 
			
		||||
import os
 | 
			
		||||
import time
 | 
			
		||||
from jinja2 import Environment, FileSystemLoader
 | 
			
		||||
import re
 | 
			
		||||
 | 
			
		||||
import filechecksum as fcs
 | 
			
		||||
 | 
			
		||||
# Pfad zur Eingabedatei und Ausgabedatei
 | 
			
		||||
input_file = "include/eeprom.h"
 | 
			
		||||
output_sourcefile = "src/struct2json.cpp"
 | 
			
		||||
output_headerfile = "include/struct2json.h"
 | 
			
		||||
# Liste der zu suchenden Variablen/Structs
 | 
			
		||||
variable_names = ['ConfigData', 'PersistenceData']
 | 
			
		||||
 | 
			
		||||
def get_types(file_content, variable_names):
 | 
			
		||||
    result = {}
 | 
			
		||||
    
 | 
			
		||||
    # Entferne Kommentare, um unerwünschte Störungen zu vermeiden
 | 
			
		||||
    file_content = re.sub(r'\/\*.*?\*\/', '', file_content, flags=re.DOTALL)
 | 
			
		||||
    file_content = re.sub(r'\/\/.*', '', file_content)
 | 
			
		||||
    
 | 
			
		||||
    for var_name in variable_names:
 | 
			
		||||
        # Erstelle ein reguläres Ausdrucksmuster, um den Typ der Variable zu extrahieren
 | 
			
		||||
        pattern = re.compile(r'\b(?:extern\s+)?(\w+)\s+' + re.escape(var_name) + r'\s*;')
 | 
			
		||||
        match = pattern.search(file_content)
 | 
			
		||||
        
 | 
			
		||||
        if match:
 | 
			
		||||
            # Extrahiere den Typ aus dem Treffer
 | 
			
		||||
            type_match = match.group(1)
 | 
			
		||||
            result[var_name] = type_match
 | 
			
		||||
 | 
			
		||||
    return result
 | 
			
		||||
 | 
			
		||||
def extract_struct_fields(file_content, variable_types):
 | 
			
		||||
    result = {}
 | 
			
		||||
 | 
			
		||||
    # Entferne Kommentare, um unerwünschte Störungen zu vermeiden
 | 
			
		||||
    file_content = re.sub(r'\/\*.*?\*\/', '', file_content, flags=re.DOTALL)
 | 
			
		||||
    file_content = re.sub(r'\/\/.*', '', file_content)
 | 
			
		||||
 | 
			
		||||
    for var_name, var_type in variable_types.items():
 | 
			
		||||
        # Erstelle ein reguläres Ausdrucksmuster, um das Strukturfeld zu extrahieren
 | 
			
		||||
        pattern = re.compile(r'typedef\s+struct\s*{([^}]*)}\s*' + re.escape(var_type) + r'\s*;')
 | 
			
		||||
        match = pattern.search(file_content)
 | 
			
		||||
 | 
			
		||||
        if match:
 | 
			
		||||
            # Extrahiere die Felder aus dem Treffer
 | 
			
		||||
            fields_match = re.findall(r'\b(\w+)\s+(\w+)(?:\[(\d+)\])?\s*;', match.group(1))
 | 
			
		||||
            if fields_match:
 | 
			
		||||
                result[var_name] = {'type': var_type, 'fields': {}}
 | 
			
		||||
                for field_type, field_name, array_size in fields_match:
 | 
			
		||||
                    if array_size:
 | 
			
		||||
                        result[var_name]['fields'][field_name] = {'type': field_type, 'size': int(array_size)}
 | 
			
		||||
                    else:
 | 
			
		||||
                        result[var_name]['fields'][field_name] = {'type': field_type}
 | 
			
		||||
 | 
			
		||||
    return result
 | 
			
		||||
 | 
			
		||||
def struct2json():
 | 
			
		||||
    # Überprüfen, ob die Verzeichnisse existieren, andernfalls erstellen
 | 
			
		||||
    output_dir_source = os.path.dirname(output_sourcefile)
 | 
			
		||||
    if not os.path.exists(output_dir_source):
 | 
			
		||||
        os.makedirs(output_dir_source)
 | 
			
		||||
    output_dir_header = os.path.dirname(output_headerfile)
 | 
			
		||||
    if not os.path.exists(output_dir_header):
 | 
			
		||||
        os.makedirs(output_dir_header)
 | 
			
		||||
 | 
			
		||||
    # Unix-Zeitstempel hinzufügen
 | 
			
		||||
    timestamp = int(time.time())
 | 
			
		||||
 | 
			
		||||
    # Parse structs
 | 
			
		||||
    with open(input_file, 'r') as file:
 | 
			
		||||
        content = file.read()
 | 
			
		||||
 | 
			
		||||
    variable_types = get_types(content, variable_names)
 | 
			
		||||
    structs = extract_struct_fields(content, variable_types)
 | 
			
		||||
    checksum = fcs.calculate_checksum(structs)
 | 
			
		||||
 | 
			
		||||
    env = Environment(loader=FileSystemLoader('codegen/templates', encoding='utf-8'))
 | 
			
		||||
    # Lade das Jinja2-Template aus der Datei
 | 
			
		||||
    template_c = env.get_template('struct2json.cpp.j2')
 | 
			
		||||
    template_h = env.get_template('struct2json.h.j2')
 | 
			
		||||
 | 
			
		||||
    # Erstelle ein Context-Dictionary mit den erforderlichen Daten
 | 
			
		||||
    context = {
 | 
			
		||||
        'timestamp_unix': timestamp,
 | 
			
		||||
        'timestamp' : time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(timestamp)),
 | 
			
		||||
        'date' : time.strftime('%d.%m.%Y', time.localtime(timestamp)),
 | 
			
		||||
        'structs': structs,
 | 
			
		||||
        'checksum': checksum
 | 
			
		||||
    }
 | 
			
		||||
 | 
			
		||||
    # Überprüfe, ob die Checksummen übereinstimmen
 | 
			
		||||
    if fcs.read_and_compare_checksum(output_sourcefile, checksum):
 | 
			
		||||
        print("Keine Änderungen in der Source-Datei erforderlich.")
 | 
			
		||||
    else:
 | 
			
		||||
        # Rendere das Template mit den Werten und erhalte den Source-Text
 | 
			
		||||
        source_text = template_c.render(context)
 | 
			
		||||
        # Schreibe den generierten Source-Text in die Source-Datei
 | 
			
		||||
        with open(output_sourcefile, "w", encoding='utf-8') as f:
 | 
			
		||||
            f.write(source_text)
 | 
			
		||||
        print(f"Source-Datei wurde erstellt: {output_sourcefile}")
 | 
			
		||||
 | 
			
		||||
    # Überprüfe, ob die Checksummen übereinstimmen
 | 
			
		||||
    if fcs.read_and_compare_checksum(output_headerfile, checksum):
 | 
			
		||||
        print("Keine Änderungen in der Header-Datei erforderlich.")
 | 
			
		||||
    else:
 | 
			
		||||
        # Rendere das Template mit den Werten und erhalte den Header-Text
 | 
			
		||||
        header_text = template_h.render(context)
 | 
			
		||||
        # Schreibe den generierten Header-Text in die Header-Datei
 | 
			
		||||
        with open(output_headerfile, "w", encoding='utf-8') as f:
 | 
			
		||||
            f.write(header_text)
 | 
			
		||||
        print(f"Header-Datei wurde erstellt: {output_headerfile}")
 | 
			
		||||
							
								
								
									
										54
									
								
								Software/codegen/templates/dtc_defs.h.j2
									
									
									
									
									
										Normal file
									
								
							
							
						
						@@ -0,0 +1,54 @@
 | 
			
		||||
/**
 | 
			
		||||
 * @file dtc_defs.h
 | 
			
		||||
 *
 | 
			
		||||
 * @brief Header file for Diagnostic Trouble Code (DTC) definitions in the DE-Timer application.
 | 
			
		||||
 *
 | 
			
		||||
 * This file contains definitions for Diagnostic Trouble Codes (DTC) in the DE-Timer project.
 | 
			
		||||
 * It includes enums for DTC active status, severity levels, and specific DTC codes.
 | 
			
		||||
 * The file also defines an array of DTC definitions and a timestamp indicating the generation time.
 | 
			
		||||
 *
 | 
			
		||||
 * @note This file is auto-generated by a script on {{ timestamp }}.
 | 
			
		||||
 *
 | 
			
		||||
 * @author Marcel Peterkau
 | 
			
		||||
 * @date   {{ date }}
 | 
			
		||||
 */
 | 
			
		||||
 | 
			
		||||
#ifndef DTC_DEFS_H
 | 
			
		||||
#define DTC_DEFS_H
 | 
			
		||||
 | 
			
		||||
#include <stdint.h>
 | 
			
		||||
 | 
			
		||||
typedef uint32_t DTCNum_t;
 | 
			
		||||
 | 
			
		||||
typedef enum
 | 
			
		||||
{
 | 
			
		||||
  DTC_INACTIVE,
 | 
			
		||||
  DTC_ACTIVE,
 | 
			
		||||
  DTC_PREVIOUS
 | 
			
		||||
} DTCActive_t;
 | 
			
		||||
 | 
			
		||||
typedef enum
 | 
			
		||||
{
 | 
			
		||||
  DTC_NONE,
 | 
			
		||||
  DTC_INFO,
 | 
			
		||||
  DTC_WARN,
 | 
			
		||||
  DTC_CRITICAL
 | 
			
		||||
} DTCSeverity_t;
 | 
			
		||||
 | 
			
		||||
typedef struct {
 | 
			
		||||
  DTCNum_t code;
 | 
			
		||||
  DTCSeverity_t severity;
 | 
			
		||||
} DTC_t;
 | 
			
		||||
 | 
			
		||||
{% for dtc in dtc_macros -%}
 | 
			
		||||
{{ dtc }}
 | 
			
		||||
{% endfor %}
 | 
			
		||||
const DTC_t dtc_definitions[] = {
 | 
			
		||||
{% for struct in dtc_structs -%}
 | 
			
		||||
{{ struct }}
 | 
			
		||||
{% endfor -%}
 | 
			
		||||
};
 | 
			
		||||
 | 
			
		||||
#endif // DTC_DEFS_H
 | 
			
		||||
 | 
			
		||||
// CODEGENERATOR_CHECKSUM: {{ checksum }}
 | 
			
		||||
							
								
								
									
										25
									
								
								Software/codegen/templates/struct2json.cpp.j2
									
									
									
									
									
										Normal file
									
								
							
							
						
						@@ -0,0 +1,25 @@
 | 
			
		||||
/**
 | 
			
		||||
 * @file struct2json.cpp
 | 
			
		||||
 *
 | 
			
		||||
 * @brief Implementation file for converting structs to JSON objects.
 | 
			
		||||
 *
 | 
			
		||||
 * @note This file is auto-generated by a script on {{ timestamp }}.
 | 
			
		||||
 *
 | 
			
		||||
 * @author Marcel Peterkau
 | 
			
		||||
 * @date   {{ date }}
 | 
			
		||||
 */
 | 
			
		||||
 | 
			
		||||
 | 
			
		||||
#include "struct2json.h"
 | 
			
		||||
 | 
			
		||||
{% for var_name, var_info in structs.items() -%}
 | 
			
		||||
void generateJsonObject_{{ var_name }}(JsonObject data)
 | 
			
		||||
{
 | 
			
		||||
    {% for field_name, field_type in var_info['fields'].items() -%}
 | 
			
		||||
    data["{{ field_name }}"] = {{ var_name }}.{{ field_name }};
 | 
			
		||||
    {% endfor -%}
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
{% endfor %}
 | 
			
		||||
 | 
			
		||||
// CODEGENERATOR_CHECKSUM: {{ checksum }}
 | 
			
		||||
							
								
								
									
										26
									
								
								Software/codegen/templates/struct2json.h.j2
									
									
									
									
									
										Normal file
									
								
							
							
						
						@@ -0,0 +1,26 @@
 | 
			
		||||
/**
 | 
			
		||||
 * @file struct2json.h
 | 
			
		||||
 *
 | 
			
		||||
 * @brief Header file for converting structs to JSON objects.
 | 
			
		||||
 *
 | 
			
		||||
 * @note This file is auto-generated by a script on {{ timestamp }}.
 | 
			
		||||
 *
 | 
			
		||||
 * @author Marcel Peterkau
 | 
			
		||||
 * @date   {{ date }}
 | 
			
		||||
 */
 | 
			
		||||
 | 
			
		||||
#ifndef _STRUCT2JSON_H_
 | 
			
		||||
#define _STRUCT2JSON_H_
 | 
			
		||||
 | 
			
		||||
#include <Arduino.h>
 | 
			
		||||
#include <ArduinoJson.h>
 | 
			
		||||
 | 
			
		||||
#include "eeprom.h"
 | 
			
		||||
 | 
			
		||||
{% for var_name, var_info in structs.items() -%}
 | 
			
		||||
void generateJsonObject_{{ var_name }}(JsonObject data);
 | 
			
		||||
{% endfor %}
 | 
			
		||||
 | 
			
		||||
#endif /* _STRUCT2JSON_H_ */
 | 
			
		||||
 | 
			
		||||
// CODEGENERATOR_CHECKSUM: {{ checksum }}
 | 
			
		||||
							
								
								
									
										19
									
								
								Software/codegen/wifiAP_passcalc.py
									
									
									
									
									
										Normal file
									
								
							
							
						
						@@ -0,0 +1,19 @@
 | 
			
		||||
def djb2_hash(s):
 | 
			
		||||
    hash = 5381
 | 
			
		||||
    for c in s:
 | 
			
		||||
        hash = ((hash << 5) + hash) + ord(c)  # hash * 33 + c
 | 
			
		||||
    return hash & 0xFFFFFFFF  # Ensure it's a 32-bit unsigned integer
 | 
			
		||||
 | 
			
		||||
def generate_password(seed, chip_id):
 | 
			
		||||
    combined = (seed + chip_id)[:24]  # Ensure the combined string is up to 24 characters
 | 
			
		||||
    hash_value = djb2_hash(combined)
 | 
			
		||||
    hash_str = f"{hash_value:08X}{hash_value:08X}"  # Repeat the hash to ensure at least 16 characters
 | 
			
		||||
    return hash_str[:32]  # Ensure the password is at most 32 characters
 | 
			
		||||
 | 
			
		||||
if __name__ == "__main__":
 | 
			
		||||
    SEED = "ilikekgg"
 | 
			
		||||
    chip_id = input("Enter the Chip ID in hex (e.g., 1A2B3C4D): ").strip()
 | 
			
		||||
    chip_id = chip_id.zfill(8).upper()  # Ensure it's 8 characters, upper case
 | 
			
		||||
 | 
			
		||||
    password = generate_password(SEED, chip_id)
 | 
			
		||||
    print(f"Generated Password: {password}")
 | 
			
		||||
@@ -3,198 +3,409 @@
 | 
			
		||||
 | 
			
		||||
<head>
 | 
			
		||||
  <meta charset="utf-8" />
 | 
			
		||||
  <title>%DEVICE_NAME%</title>
 | 
			
		||||
  <meta http-equiv="content-type" content="text/html;charset=UTF-8">
 | 
			
		||||
  <meta name="viewport" content="width=device-width, initial-scale=1">
 | 
			
		||||
  <link rel="stylesheet" href="static/css/bootstrap.min.css">
 | 
			
		||||
  <link rel="stylesheet" href="static/css/custom.css">
 | 
			
		||||
  <script src="static/js/jquery-3.3.1.min.js"></script>
 | 
			
		||||
  <script src="static/js/bootstrap.bundle.min.js"></script>
 | 
			
		||||
 | 
			
		||||
  <link rel="apple-touch-icon" sizes="180x180" href="static/img/apple-touch-icon.png">
 | 
			
		||||
  <link rel="icon" type="image/png" sizes="32x32" href="static/img/favicon-32x32.png">
 | 
			
		||||
  <link rel="icon" type="image/png" sizes="16x16" href="static/img/favicon-16x16.png">
 | 
			
		||||
  <link rel="manifest" href="static/img/site.webmanifest">
 | 
			
		||||
  <link rel="mask-icon" href="static/img/safari-pinned-tab.svg" color="#111111">
 | 
			
		||||
  <link rel="shortcut icon" href="static/img/favicon.ico">
 | 
			
		||||
  <meta name="msapplication-TileColor" content="#111111">
 | 
			
		||||
  <meta name="msapplication-config" content="static/img/browserconfig.xml">
 | 
			
		||||
  <meta name="theme-color" content="#111111">
 | 
			
		||||
 | 
			
		||||
  <script type="text/javascript">
 | 
			
		||||
    var opacity = 0;
 | 
			
		||||
    var intervalID = 0;
 | 
			
		||||
    window.onload = setTimeout(() => {  fadeout(); }, 4000);
 | 
			
		||||
    function fadeout() {
 | 
			
		||||
      intervalID = setInterval(hide, 200);
 | 
			
		||||
    }
 | 
			
		||||
    function hide() {
 | 
			
		||||
      var responseMessage = document.getElementById("responseMessage");
 | 
			
		||||
      opacity =
 | 
			
		||||
        Number(window.getComputedStyle(responseMessage).getPropertyValue("opacity"))
 | 
			
		||||
      if (opacity > 0) {
 | 
			
		||||
        opacity = opacity - 0.1;
 | 
			
		||||
        responseMessage.style.opacity = opacity
 | 
			
		||||
      }
 | 
			
		||||
      else {
 | 
			
		||||
        responseMessage.remove()
 | 
			
		||||
        clearInterval(intervalID);
 | 
			
		||||
      }
 | 
			
		||||
    } 
 | 
			
		||||
  </script>
 | 
			
		||||
 | 
			
		||||
  <title>Dark Emergency Timer</title>
 | 
			
		||||
  <meta name="viewport" content="width=device-width, initial-scale=1" />
 | 
			
		||||
  <link rel="stylesheet" href="static/css/bootstrap.min.css" />
 | 
			
		||||
  <link rel="stylesheet" href="static/css/custom.css" />
 | 
			
		||||
  <link rel="stylesheet" href="static/css/tweaks.css" />
 | 
			
		||||
  <script src="static/js/jquery.min.js"></script>
 | 
			
		||||
  <script src="static/js/bootstrap.min.js"></script>
 | 
			
		||||
  <script src="static/js/websocket.js"></script>
 | 
			
		||||
  <script src="static/js/dtc_table.js"></script>
 | 
			
		||||
  <script src="static/js/script.js"></script>
 | 
			
		||||
  <link rel="apple-touch-icon" sizes="180x180" href="static/img/apple-touch-icon.png" />
 | 
			
		||||
  <link rel="icon" type="image/png" sizes="32x32" href="static/img/favicon-32x32.png" />
 | 
			
		||||
  <link rel="icon" type="image/png" sizes="16x16" href="static/img/favicon-16x16.png" />
 | 
			
		||||
  <link rel="manifest" href="static/img/site.webmanifest" />
 | 
			
		||||
</head>
 | 
			
		||||
 | 
			
		||||
<body>
 | 
			
		||||
  <header class="sticky-top">
 | 
			
		||||
    <nav class="navbar navbar-expand-sm navbar-dark bg-dark">
 | 
			
		||||
 | 
			
		||||
      <a class="navbar-brand" href="#">
 | 
			
		||||
        <img src="static/img/logo.png" width="30" height="30" class="d-inline-block align-top" alt="">
 | 
			
		||||
        %DEVICE_NAME%</a>
 | 
			
		||||
      <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavAltMarkup"
 | 
			
		||||
        aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation">
 | 
			
		||||
        <span class="navbar-toggler-icon"></span>
 | 
			
		||||
      </button>
 | 
			
		||||
 | 
			
		||||
 | 
			
		||||
      <div class="collapse navbar-collapse pr-2 mt-2 bg-secondary" id="navbarNavAltMarkup">
 | 
			
		||||
        <ul class="navbar-nav nav align-items-end">
 | 
			
		||||
          <li class="nav-item">
 | 
			
		||||
            <a class="nav-link active" href="#tab_home" data-toggle="tab">Home</a>
 | 
			
		||||
          </li>
 | 
			
		||||
          <li class="nav-item">
 | 
			
		||||
            <a class="nav-link" href="#tab_settings" data-toggle="tab">Settings</a>
 | 
			
		||||
          </li>
 | 
			
		||||
        </ul>
 | 
			
		||||
      </div>
 | 
			
		||||
    </nav>
 | 
			
		||||
  </header>
 | 
			
		||||
 | 
			
		||||
  <main class="container-fluid py-3 flex-fill">
 | 
			
		||||
  <!-- Connection-Overlay -->
 | 
			
		||||
  <div id="overlay">
 | 
			
		||||
    <div class="overlay-content">
 | 
			
		||||
      <p>Verbinde...</p>
 | 
			
		||||
      <span class="loader"></span>
 | 
			
		||||
    </div>
 | 
			
		||||
  </div>
 | 
			
		||||
  <!-- Connection-Overlay -->
 | 
			
		||||
  <!-- Notification-Container -->
 | 
			
		||||
  <div id="notification-container" class="notification-container"></div>
 | 
			
		||||
  <!-- Notification-Container -->
 | 
			
		||||
  <nav class="navbar fixed-top navbar-dark bg-primary" id="navbar1">
 | 
			
		||||
    <a class="navbar-brand" href="#">
 | 
			
		||||
      <img src="static/img/logo.png" width="30" height="30" class="d-inline-block align-top mr-1" alt="" />
 | 
			
		||||
      <span class="data-devicename">DE Airsoft Timer</span>
 | 
			
		||||
    </a>
 | 
			
		||||
    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#collapsingNavbar"
 | 
			
		||||
      aria-controls="collapsingNavbar" aria-expanded="false" aria-label="Toggle navigation">
 | 
			
		||||
      <span class="navbar-toggler-icon"></span>
 | 
			
		||||
    </button>
 | 
			
		||||
    <div class="collapse navbar-collapse" id="collapsingNavbar">
 | 
			
		||||
      <ul class="navbar-nav nav mr-auto mt-2 mt-lg-0">
 | 
			
		||||
        <li class="nav-item">
 | 
			
		||||
          <a class="nav-link active" role="tab" data-toggle="tab" href="#tab_home">Home</a>
 | 
			
		||||
        </li>
 | 
			
		||||
        <li class="nav-item">
 | 
			
		||||
          <a class="nav-link" role="tab" data-toggle="tab" href="#tab_maintenance">Wartung</a>
 | 
			
		||||
        </li>
 | 
			
		||||
        <li class="nav-item">
 | 
			
		||||
          <a class="nav-link" role="tab" data-toggle="tab" href="#tab_source">Einstellungen</a>
 | 
			
		||||
        </li>
 | 
			
		||||
        <li class="nav-item">
 | 
			
		||||
          <a class="nav-link" role="tab" data-toggle="tab" href="#tab_fwupdate">Update</a>
 | 
			
		||||
        </li>
 | 
			
		||||
      </ul>
 | 
			
		||||
    </div>
 | 
			
		||||
  </nav>
 | 
			
		||||
  <main class="container">
 | 
			
		||||
    <!-- Tabs Content -->
 | 
			
		||||
    <div class="tab-content">
 | 
			
		||||
      <!-- Div Tab Home-->
 | 
			
		||||
      <div class="tab-pane fade show active" id="tab_home" role="tabpanel">
 | 
			
		||||
        <!-- Jumbotron -->
 | 
			
		||||
        <div class="jumbotron text-center">
 | 
			
		||||
          <p class="p-4">
 | 
			
		||||
            <img src="static/img/logo.png">
 | 
			
		||||
          </p>
 | 
			
		||||
          <h3>%DEVICE_NAME%</h3>
 | 
			
		||||
      <div id="tab_home" class="tab-pane fade show active" role="tabpanel">
 | 
			
		||||
        <div class="col text-center">
 | 
			
		||||
          <div class="jumbotron">
 | 
			
		||||
            <img src="static/img/logo.png" width="120" height="120" class="img-fluid" alt="" />
 | 
			
		||||
            <h3 class="pt-3">
 | 
			
		||||
              <span class="data-devicename">DE Airsoft Timer</span>
 | 
			
		||||
            </h3>
 | 
			
		||||
          </div>
 | 
			
		||||
        </div>
 | 
			
		||||
        <!-- AlertMessageBox-->
 | 
			
		||||
        <div id="responseMessage" class="alert alert-%RESP_MESSAGE_TYPE%" %SHOW_RESP_MESSAGE%>
 | 
			
		||||
          %RESP_MESSAGE%
 | 
			
		||||
        <!-- Div Group Battery remain -->
 | 
			
		||||
        <hr />
 | 
			
		||||
        <h4>Akkuladestand</h4>
 | 
			
		||||
        <div class="progress">
 | 
			
		||||
          <div id="batterylevel" class="data-batterylevel progress-bar text-light" role="progressbar" aria-valuenow="0"
 | 
			
		||||
            aria-valuemin="0" aria-valuemax="100" style="width: 0%">
 | 
			
		||||
            0
 | 
			
		||||
          </div>
 | 
			
		||||
        </div>
 | 
			
		||||
        <div class="container-fluid pb-5">
 | 
			
		||||
          <h4>BATTERY: %BATTERY_TYPE%</h4>
 | 
			
		||||
          <div class="progress">
 | 
			
		||||
            <div class="progress-bar text-light" role="progressbar" aria-valuenow="%BAT_REMAIN_CAPACITY%"
 | 
			
		||||
              aria-valuemin="0" aria-valuemax="100" style="width: %BAT_REMAIN_CAPACITY%%">
 | 
			
		||||
              %BAT_REMAIN_CAPACITY%% / %BAT_VOLTAGE% V
 | 
			
		||||
        <!-- Div Group Battery remain -->
 | 
			
		||||
        <!-- Div Group current Mode -->
 | 
			
		||||
        <hr />
 | 
			
		||||
        <h4>aktueller Modus</h4>
 | 
			
		||||
        <input class="data-systemstatus form-control" type="text" id="sysstatus" readonly />
 | 
			
		||||
        <!-- Div Group current Mode -->
 | 
			
		||||
        <!-- Div Group Faction Points -->
 | 
			
		||||
        <hr />
 | 
			
		||||
        <h4>aktueller Punktestand</h4>
 | 
			
		||||
        <div class="container-fluid">
 | 
			
		||||
          <div class="row">
 | 
			
		||||
            <div id="header_faction1" class="col text-center data-name_faction1 text-white p-3">
 | 
			
		||||
              %NAME_FAC_1%
 | 
			
		||||
            </div>
 | 
			
		||||
            <div id="header_faction2" class="col text-center data-name_faction2 text-white p-3">
 | 
			
		||||
              %NAME_FAC_2%
 | 
			
		||||
            </div>
 | 
			
		||||
            <div id="header_faction3" class="col text-center data-name_faction3 text-white p-3">
 | 
			
		||||
              %NAME_FAC_3%
 | 
			
		||||
            </div>
 | 
			
		||||
          </div>
 | 
			
		||||
          <div class="row">
 | 
			
		||||
            <div class="col bg-dark text-white p-3 data-activefaction faction-logo faction1">
 | 
			
		||||
              <div class="glow-container">
 | 
			
		||||
                <img src="static/img/logo_fac1.png" class="rounded mx-auto img-fluid d-block" alt="..." />
 | 
			
		||||
              </div>
 | 
			
		||||
            </div>
 | 
			
		||||
            <div class="col bg-dark text-white p-3 data-activefaction faction-logo faction2 glow-active-faction">
 | 
			
		||||
              <div class="glow-container">
 | 
			
		||||
                <img src="static/img/logo_fac2.png" class="rounded mx-auto img-fluid d-block" alt="..." />
 | 
			
		||||
              </div>
 | 
			
		||||
            </div>
 | 
			
		||||
            <div class="col bg-dark text-white p-3 data-activefaction faction-logo faction3">
 | 
			
		||||
              <div class="glow-container">
 | 
			
		||||
                <img src="static/img/logo_fac3.png" class="rounded mx-auto img-fluid d-block" alt="..." />
 | 
			
		||||
              </div>
 | 
			
		||||
            </div>
 | 
			
		||||
          </div>
 | 
			
		||||
          <div class="row">
 | 
			
		||||
            <div id="time_faction1" class="data-time_faction1 col text-center bg-secondary text-white p-3 format-time">
 | 
			
		||||
              0
 | 
			
		||||
            </div>
 | 
			
		||||
            <div id="time_faction2" class="data-time_faction2 col text-center bg-secondary text-white p-3 format-time">
 | 
			
		||||
              0
 | 
			
		||||
            </div>
 | 
			
		||||
            <div id="time_faction3" class="data-time_faction3 col text-center bg-secondary text-white p-3 format-time">
 | 
			
		||||
              0
 | 
			
		||||
            </div>
 | 
			
		||||
          </div>
 | 
			
		||||
          <div class="row mt-3">
 | 
			
		||||
            <div class="col text-center">
 | 
			
		||||
              <button id="faction1" class="btn-wsevent btn btn-outline-primary">
 | 
			
		||||
                Aktivieren
 | 
			
		||||
              </button>
 | 
			
		||||
            </div>
 | 
			
		||||
            <div class="col text-center">
 | 
			
		||||
              <button id="faction2" class="btn-wsevent btn btn-outline-primary">
 | 
			
		||||
                Aktivieren
 | 
			
		||||
              </button>
 | 
			
		||||
            </div>
 | 
			
		||||
            <div class="col text-center">
 | 
			
		||||
              <button id="faction3" class="btn-wsevent btn btn-outline-primary">
 | 
			
		||||
                Aktivieren
 | 
			
		||||
              </button>
 | 
			
		||||
            </div>
 | 
			
		||||
          </div>
 | 
			
		||||
        </div>
 | 
			
		||||
        <div class="container-fluid pb-5">
 | 
			
		||||
          <h4>FACTIONS</h4>
 | 
			
		||||
          <div class="table-responsive">
 | 
			
		||||
            <table class="table text-light text-center">
 | 
			
		||||
              <thead>
 | 
			
		||||
                <tr>
 | 
			
		||||
                  <th scope="col">Faction</td>
 | 
			
		||||
                  <th scope="col">Time</td>
 | 
			
		||||
                </tr>
 | 
			
		||||
              </thead>
 | 
			
		||||
              <tbody>
 | 
			
		||||
                <tr>
 | 
			
		||||
                  <td class="align-items-center justify-content-center" scope="col">
 | 
			
		||||
                    <a href="#">
 | 
			
		||||
                      <img src="static/img/logo_fac1.png" class="img-responsive" alt="" />
 | 
			
		||||
                      <div class="desc">
 | 
			
		||||
                        <p class="desc_content">%NAME_FAC_1%</p>
 | 
			
		||||
                      </div>
 | 
			
		||||
                    </a>
 | 
			
		||||
                  </td>
 | 
			
		||||
                  <td class="align-items-center justify-content-center" scope="col">%POINTS_FAC_1%</td>
 | 
			
		||||
                </tr>
 | 
			
		||||
                <tr>
 | 
			
		||||
                  <td class="align-items-center justify-content-center" scope="col">
 | 
			
		||||
                    <a href="#">
 | 
			
		||||
                      <img src="static/img/logo_fac2.png" class="img-responsive" alt="" />
 | 
			
		||||
                      <div class="desc">
 | 
			
		||||
                        <p class="desc_content">%NAME_FAC_2%</p>
 | 
			
		||||
                      </div>
 | 
			
		||||
                    </a>
 | 
			
		||||
                  </td>
 | 
			
		||||
                  <td class="align-items-center justify-content-center" scope="col">%POINTS_FAC_2%</td>
 | 
			
		||||
                </tr>
 | 
			
		||||
                <tr>
 | 
			
		||||
                  <td class="align-items-center justify-content-center" scope="col">
 | 
			
		||||
                    <a href="#">
 | 
			
		||||
                      <img src="static/img/logo_fac3.png" class="img-responsive" alt="" />
 | 
			
		||||
                      <div class="desc">
 | 
			
		||||
                        <p class="desc_content">%NAME_FAC_3%</p>
 | 
			
		||||
                      </div>
 | 
			
		||||
                    </a>
 | 
			
		||||
                  </td>
 | 
			
		||||
                  <td class="align-items-center justify-content-center" scope="col">%POINTS_FAC_3%</td>
 | 
			
		||||
                </tr>
 | 
			
		||||
              </tbody>
 | 
			
		||||
            </table>
 | 
			
		||||
          </div>
 | 
			
		||||
        </div>
 | 
			
		||||
        <div class="container-fluid pb-5" %SHOW_DTC_TABLE%>
 | 
			
		||||
        <!-- Div GroupFaction Points -->
 | 
			
		||||
        <!-- Div Group DTC Table -->
 | 
			
		||||
        <div id="dtc_container" hidden>
 | 
			
		||||
          <hr />
 | 
			
		||||
          <h4>Fehlercodes</h4>
 | 
			
		||||
          <table class="table text-light">
 | 
			
		||||
          <table class="table" id="dtc_table">
 | 
			
		||||
            <tbody>
 | 
			
		||||
              <tr>
 | 
			
		||||
                <th class="col-md-4" scope="col">Timestamp</td>
 | 
			
		||||
                <th class="col-md-4" scope="col">DTC</td>
 | 
			
		||||
                <th class="col-md-4" scope="col">active</td>
 | 
			
		||||
                <th class="col-6" scope="col">Zeitstempel</th>
 | 
			
		||||
                <th class="col-2" scope="col">Fehlercode</th>
 | 
			
		||||
                <th class="col-2" scope="col">Schwere</th>
 | 
			
		||||
                <th class="col-2" scope="col">Aktiv</th>
 | 
			
		||||
              </tr>
 | 
			
		||||
              %DTC_TABLE%
 | 
			
		||||
            </tbody>
 | 
			
		||||
          </table>
 | 
			
		||||
        </div>
 | 
			
		||||
        <!-- Div Group DTC Table -->
 | 
			
		||||
      </div>
 | 
			
		||||
      <!-- Div Tab Home-->
 | 
			
		||||
      <!-- Div Tab Maintenance -->
 | 
			
		||||
      <div id="tab_maintenance" class="tab-pane fade" role="tabpanel">
 | 
			
		||||
        <h3>Wartung</h3>
 | 
			
		||||
        <!-- Div Group Reset Timers -->
 | 
			
		||||
        <hr />
 | 
			
		||||
        <h4>Punkte zurücksetzen</h4>
 | 
			
		||||
        <div class="form-group row">
 | 
			
		||||
          <div class="col text-center">
 | 
			
		||||
            <button id="reset-timer" class="btn-wsevent btn btn-outline-primary ml-2">
 | 
			
		||||
              Timer zurücksetzen
 | 
			
		||||
            </button>
 | 
			
		||||
          </div>
 | 
			
		||||
        </div>
 | 
			
		||||
        <!-- Div Group Reset Timers  -->
 | 
			
		||||
        <!-- Div Group LiveDebug -->
 | 
			
		||||
        <hr />
 | 
			
		||||
        <h4>Live Debug</h4>
 | 
			
		||||
        <div class="form-group row">
 | 
			
		||||
          <input id="livedebug-in" type="text" class="set-wsevent data-livedebug-in form-control" />
 | 
			
		||||
        </div>
 | 
			
		||||
        <div class="form-group row">
 | 
			
		||||
          <textarea class="form-control" spellcheck="false" id="livedebug-out" rows="3" readonly></textarea>
 | 
			
		||||
        </div>
 | 
			
		||||
        <div class="form-group row">
 | 
			
		||||
          <div class="col text-center">
 | 
			
		||||
            <button id="debugstart" class="btn-wsevent btn btn-outline-primary ml-2">
 | 
			
		||||
              Start
 | 
			
		||||
            </button>
 | 
			
		||||
            <button id="debugstop" class="btn-wsevent btn btn-outline-primary ml-2">
 | 
			
		||||
              Stop
 | 
			
		||||
            </button>
 | 
			
		||||
          </div>
 | 
			
		||||
        </div>
 | 
			
		||||
        <!-- Div Group LiveDebug -->
 | 
			
		||||
        <!-- Div Group Device Reboot -->
 | 
			
		||||
        <hr />
 | 
			
		||||
        <h4>Gerät neustarten</h4>
 | 
			
		||||
        <div class="form-group row">
 | 
			
		||||
          <div class="col text-center">
 | 
			
		||||
            <button id="reboot" class="btn-wsevent confirm btn btn-outline-primary">
 | 
			
		||||
              Reboot
 | 
			
		||||
            </button>
 | 
			
		||||
          </div>
 | 
			
		||||
        </div>
 | 
			
		||||
        <!-- Div Group Device Reboot -->
 | 
			
		||||
      </div>
 | 
			
		||||
      <!-- Div Tab Maintenance -->
 | 
			
		||||
      <!-- Div Tab Settings-->
 | 
			
		||||
      <div class="tab-pane fade" id="tab_settings" role="tabpanel">
 | 
			
		||||
        <h3>Settings</h3>
 | 
			
		||||
        <hr>
 | 
			
		||||
        <form method="POST">
 | 
			
		||||
      <div id="tab_source" class="tab-pane fade" role="tabpanel">
 | 
			
		||||
        <h3>Einstellungen</h3>
 | 
			
		||||
        <!-- Div Group Battery Type -->
 | 
			
		||||
        <hr />
 | 
			
		||||
        <h4>Akku</h4>
 | 
			
		||||
        <div class="form-group row">
 | 
			
		||||
          <label for="batterytype" class="control-label col-4">Akku-Variante</label>
 | 
			
		||||
          <div class="col-8">
 | 
			
		||||
            <select id="batterytype" class="set-wsevent data-batterytype select form-control">
 | 
			
		||||
              <option value="Undefined">Undefined</option>
 | 
			
		||||
              <option value="LiPo 3S">LiPo 3S</option>
 | 
			
		||||
              <option value="LiPo 2S">LiPo 2S</option>
 | 
			
		||||
            </select>
 | 
			
		||||
          </div>
 | 
			
		||||
        </div>
 | 
			
		||||
        <!-- Div Group Battery Type -->
 | 
			
		||||
        <!-- Div Group Timer Settings -->
 | 
			
		||||
        <hr />
 | 
			
		||||
        <h4>Timer Einstellungen</h4>
 | 
			
		||||
        <div class="form-group row">
 | 
			
		||||
          <label for="active_faction_on_reboot" class="control-label col-4">Aktive Fraktion wiederherstellen</label>
 | 
			
		||||
          <div class="col-8">
 | 
			
		||||
            <div class="form-check">
 | 
			
		||||
              <input class="set-wsevent data-active_faction_on_reboot form-check-input" type="checkbox"
 | 
			
		||||
                id="active_faction_on_reboot" />
 | 
			
		||||
              <label class="form-check-label" for="active_faction_on_reboot">
 | 
			
		||||
                aktivieren
 | 
			
		||||
              </label>
 | 
			
		||||
            </div>
 | 
			
		||||
          </div>
 | 
			
		||||
        </div>
 | 
			
		||||
        <div class="form-group row">
 | 
			
		||||
          <label for="name_faction1" class="control-label col-4">Faktion 1</label>
 | 
			
		||||
          <div class="col-8">
 | 
			
		||||
            <div class="input-group">
 | 
			
		||||
              <input id="name_faction1" type="text" class="set-wsevent data-name_faction1 form-control"
 | 
			
		||||
                required="required" />
 | 
			
		||||
              <div class="input-group-append">
 | 
			
		||||
                <span class="input-group-text">max. 32 Zeichen</span>
 | 
			
		||||
              </div>
 | 
			
		||||
            </div>
 | 
			
		||||
          </div>
 | 
			
		||||
        </div>
 | 
			
		||||
        <div class="form-group row">
 | 
			
		||||
          <label for="name_faction2" class="control-label col-4">Faktion 2</label>
 | 
			
		||||
          <div class="col-8">
 | 
			
		||||
            <div class="input-group">
 | 
			
		||||
              <input id="name_faction2" type="text" class="set-wsevent data-name_faction2 form-control"
 | 
			
		||||
                required="required" />
 | 
			
		||||
              <div class="input-group-append">
 | 
			
		||||
                <span class="input-group-text">max. 32 Zeichen</span>
 | 
			
		||||
              </div>
 | 
			
		||||
            </div>
 | 
			
		||||
          </div>
 | 
			
		||||
        </div>
 | 
			
		||||
        <div class="form-group row">
 | 
			
		||||
          <label for="name_faction3" class="control-label col-4">Faktion 3</label>
 | 
			
		||||
          <div class="col-8">
 | 
			
		||||
            <div class="input-group">
 | 
			
		||||
              <input id="name_faction3" type="text" class="set-wsevent data-name_faction3 form-control"
 | 
			
		||||
                required="required" />
 | 
			
		||||
              <div class="input-group-append">
 | 
			
		||||
                <span class="input-group-text">max. 32 Zeichen</span>
 | 
			
		||||
              </div>
 | 
			
		||||
            </div>
 | 
			
		||||
          </div>
 | 
			
		||||
        </div>
 | 
			
		||||
        <!-- Div Group Timer Settings -->
 | 
			
		||||
        <!-- Div Group Save Button-->
 | 
			
		||||
        <hr />
 | 
			
		||||
        <div class="form-group row">
 | 
			
		||||
          <div class="col text-center">
 | 
			
		||||
            <button id="settingssave" class="btn-wsevent btn btn-outline-primary">
 | 
			
		||||
              Speichern
 | 
			
		||||
            </button>
 | 
			
		||||
          </div>
 | 
			
		||||
        </div>
 | 
			
		||||
      </div>
 | 
			
		||||
      <!-- Div Tab Settings -->
 | 
			
		||||
      <!-- Div Tab Firmware Update-->
 | 
			
		||||
      <div id="tab_fwupdate" class="tab-pane fade" role="tabpanel">
 | 
			
		||||
        <h3>Firmware</h3>
 | 
			
		||||
        <!-- Div Group VersionInfo -->
 | 
			
		||||
        <hr />
 | 
			
		||||
        <h4>Version-Info</h4>
 | 
			
		||||
        <table class="table">
 | 
			
		||||
          <tbody>
 | 
			
		||||
            <tr>
 | 
			
		||||
              <th class="col-7" scope="col">Parameter</th>
 | 
			
		||||
              <th class="col-5" scope="col">Value</th>
 | 
			
		||||
            </tr>
 | 
			
		||||
            <tr>
 | 
			
		||||
              <td>Firmware Version</td>
 | 
			
		||||
              <td><span class="data-fw-version"></span></td>
 | 
			
		||||
            </tr>
 | 
			
		||||
            <tr>
 | 
			
		||||
              <td>Flash Version</td>
 | 
			
		||||
              <td><span class="data-flash-version"></span></td>
 | 
			
		||||
            </tr>
 | 
			
		||||
            <tr>
 | 
			
		||||
              <td>Git Revision</td>
 | 
			
		||||
              <td><span class="data-git-revision"></span></td>
 | 
			
		||||
            </tr>
 | 
			
		||||
          </tbody>
 | 
			
		||||
        </table>
 | 
			
		||||
        <!-- Div Group VersionInfo -->
 | 
			
		||||
        <!-- Div Group EEPROM Backup -->
 | 
			
		||||
        <hr />
 | 
			
		||||
        <h4>EEPROM-Backup</h4>
 | 
			
		||||
        <div class="form-group row">
 | 
			
		||||
          <div class="col text-center">
 | 
			
		||||
            <a class="btn btn-outline-primary" href="eejson" role="button" id="ee-backup-download">Download</a>
 | 
			
		||||
          </div>
 | 
			
		||||
        </div>
 | 
			
		||||
        <!-- Div Group EEPROM Backup -->
 | 
			
		||||
        <!-- Div Group EEPROM Restore -->
 | 
			
		||||
        <hr />
 | 
			
		||||
        <h4>EEPROM-Restore</h4>
 | 
			
		||||
        <form method="POST" action="eeRestore" enctype="multipart/form-data">
 | 
			
		||||
          <div class="form-group row">
 | 
			
		||||
            <label for="commandInput" class="col-sm-2 col-form-label">Command</label>
 | 
			
		||||
            <div class="col-sm-10">
 | 
			
		||||
              <input type="text" name="commandInput" class="form-control bg-light" id="commandInput"
 | 
			
		||||
                placeholder="type command here...">
 | 
			
		||||
            <div class="custom-file">
 | 
			
		||||
              <input type="file" name="ee-restore-file" class="custom-file-input" id="ee-restore-file" accept=".ee.json"
 | 
			
		||||
                required />
 | 
			
		||||
              <label class="custom-file-label" for="ee-restore-file">EEPROM-Backup auswählen</label>
 | 
			
		||||
            </div>
 | 
			
		||||
          </div>
 | 
			
		||||
          <div class="form-group row">
 | 
			
		||||
            <div class="col-sm-12">
 | 
			
		||||
              <button name="cmdsubmit" type="submit" class="btn btn-primary float-right">Apply</button>
 | 
			
		||||
            <div class="col text-center">
 | 
			
		||||
              <button name="submit" type="submit" class="btn btn-outline-primary">
 | 
			
		||||
                Restore starten
 | 
			
		||||
              </button>
 | 
			
		||||
            </div>
 | 
			
		||||
          </div>
 | 
			
		||||
        </form>
 | 
			
		||||
        <!-- Div Group EEPROM Restore -->
 | 
			
		||||
        <!-- Div Group Firmware Update -->
 | 
			
		||||
        <hr />
 | 
			
		||||
        <h4>Firmware-Update</h4>
 | 
			
		||||
        <form method="POST" action="doUpdate" enctype="multipart/form-data">
 | 
			
		||||
          <div class="form-group row">
 | 
			
		||||
            <div class="custom-file">
 | 
			
		||||
              <input type="file" name="fw-update-file" class="custom-file-input" id="fw-update-file"
 | 
			
		||||
                accept=".fw.bin,.fs.gz" required />
 | 
			
		||||
              <label class="custom-file-label" for="fw-update-file">Firmware-Update auswählen</label>
 | 
			
		||||
            </div>
 | 
			
		||||
          </div>
 | 
			
		||||
          <div class="form-group row">
 | 
			
		||||
            <div class="col text-center">
 | 
			
		||||
              <button name="submit" type="submit" class="btn btn-outline-primary">
 | 
			
		||||
                Update starten
 | 
			
		||||
              </button>
 | 
			
		||||
            </div>
 | 
			
		||||
          </div>
 | 
			
		||||
        </form>
 | 
			
		||||
        <!-- Div Group Firmware Update -->
 | 
			
		||||
      </div>
 | 
			
		||||
      <!-- Div Tab Settings-->
 | 
			
		||||
      <!-- Div Tab Firmware Update-->
 | 
			
		||||
    </div>
 | 
			
		||||
    <!-- Tabs Content -->
 | 
			
		||||
  </main>
 | 
			
		||||
 | 
			
		||||
  <!-- Footer -->
 | 
			
		||||
  <footer class="fixed-bottom bg-secondary font-weight-light text-light text-center py-3">
 | 
			
		||||
 | 
			
		||||
    <!-- Copyright -->
 | 
			
		||||
    <span class=" footer-copyright">
 | 
			
		||||
      © 2022 <a class="text-reset fw-bold" href="https://hiabuto.de/">Hiabuto Defence Systems</a>
 | 
			
		||||
    </span>
 | 
			
		||||
    <!-- Copyright -->
 | 
			
		||||
 | 
			
		||||
  <footer class="page-footer navbar-dark bg-primary font-small fixed-bottom">
 | 
			
		||||
    <div class="container-fluid text-center">
 | 
			
		||||
      <div class="footer-copyright text-center py-3">
 | 
			
		||||
        <span class="text-muted">© 2023 -
 | 
			
		||||
          <a class="text-reset fw-bold" href="https://eventronics.de/">Marcel Peterkau</a></span>
 | 
			
		||||
      </div>
 | 
			
		||||
    </div>
 | 
			
		||||
  </footer>
 | 
			
		||||
  <!-- Footer -->
 | 
			
		||||
 | 
			
		||||
  <!-- Modal Dialog -->
 | 
			
		||||
  <div class="modal fade" id="dtcModal" tabindex="-1" role="dialog" aria-labelledby="dtcModalLabel" aria-hidden="true">
 | 
			
		||||
    <div class="modal-dialog modal-dialog-centered" role="document">
 | 
			
		||||
      <div class="modal-content">
 | 
			
		||||
        <div class="modal-header">
 | 
			
		||||
          <h5 class="modal-title" id="dtcModalLabel">DTC-Description</h5>
 | 
			
		||||
          <button type="button" class="close" data-dismiss="modal" aria-label="Close">
 | 
			
		||||
            <span aria-hidden="true">×</span>
 | 
			
		||||
          </button>
 | 
			
		||||
        </div>
 | 
			
		||||
        <div class="modal-body">
 | 
			
		||||
          <p class="dtc-desc">DTC Description</p>
 | 
			
		||||
          <p class="dtc-debugval">DTC DebugVal</p>
 | 
			
		||||
        </div>
 | 
			
		||||
        <div class="modal-footer">
 | 
			
		||||
          <button type="button" class="btn btn-outline-secondary" data-dismiss="modal">
 | 
			
		||||
            Close
 | 
			
		||||
          </button>
 | 
			
		||||
        </div>
 | 
			
		||||
      </div>
 | 
			
		||||
    </div>
 | 
			
		||||
  </div>
 | 
			
		||||
  <!-- Modal Dialog -->
 | 
			
		||||
</body>
 | 
			
		||||
 | 
			
		||||
</html>
 | 
			
		||||
@@ -1,28 +0,0 @@
 | 
			
		||||
<!DOCTYPE html>
 | 
			
		||||
<html>
 | 
			
		||||
 | 
			
		||||
<head>
 | 
			
		||||
  <meta charset="utf-8" />
 | 
			
		||||
  <title>%DEVICE_NAME%</title>
 | 
			
		||||
  <meta http-equiv="content-type" content="text/html;charset=UTF-8">
 | 
			
		||||
  <meta name="viewport" content="width=device-width, initial-scale=1">
 | 
			
		||||
  <link rel="stylesheet" href="static/css/bootstrap.min.css">
 | 
			
		||||
  <link rel="stylesheet" href="static/css/custom.css">
 | 
			
		||||
  <script src="static/js/jquery.min.js"></script>
 | 
			
		||||
  <script src="static/js/bootstrap.min.js"></script>
 | 
			
		||||
  <link rel="apple-touch-icon" sizes="180x180" href="static/img/apple-touch-icon.png">
 | 
			
		||||
  <link rel="icon" type="image/png" sizes="32x32" href="static/img/favicon-32x32.png">
 | 
			
		||||
  <link rel="icon" type="image/png" sizes="16x16" href="static/img/favicon-16x16.png">
 | 
			
		||||
  <link rel="manifest" href="static/img/site.webmanifest">
 | 
			
		||||
  <meta http-equiv="refresh" content="3; url='/index.htm'" />
 | 
			
		||||
</head>
 | 
			
		||||
 | 
			
		||||
<body>
 | 
			
		||||
  <div class="container" style="display: flex; justify-content: center; align-items: center; height: 100vh">
 | 
			
		||||
    <div class="alert alert-success">
 | 
			
		||||
      <strong>Bitte warten!</strong> Änderungen werden übernommen.
 | 
			
		||||
    </div>
 | 
			
		||||
  </div>
 | 
			
		||||
</body>
 | 
			
		||||
 | 
			
		||||
</html>
 | 
			
		||||
							
								
								
									
										10004
									
								
								Software/data_src/static/css/bootstrap.min.css
									
									
									
									
										vendored
									
									
								
							
							
						
						
							
								
								
									
										90
									
								
								Software/data_src/static/css/tweaks.css
									
									
									
									
									
										Normal file
									
								
							
							
						
						@@ -0,0 +1,90 @@
 | 
			
		||||
@font-face {
 | 
			
		||||
    font-family: 'Comfortaa';
 | 
			
		||||
    font-style: normal;
 | 
			
		||||
    font-weight: 300;
 | 
			
		||||
    src: url(../fonts/comfortaa.woff2) format('woff2');
 | 
			
		||||
    unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
 | 
			
		||||
  }
 | 
			
		||||
 | 
			
		||||
body {
 | 
			
		||||
    padding-top: 70px;
 | 
			
		||||
    margin-bottom: 70px;
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
hr {
 | 
			
		||||
    height: 2px;
 | 
			
		||||
    border-width: 0;
 | 
			
		||||
    color: gray;
 | 
			
		||||
    background-color: gray
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
.dtc-debugval {
 | 
			
		||||
    color: #F2771A;
 | 
			
		||||
    font: 0.8rem Inconsolata, monospace;
 | 
			
		||||
    background-color: black;
 | 
			
		||||
    padding: 10px;
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
#overlay {
 | 
			
		||||
    display: none;
 | 
			
		||||
    position: fixed;
 | 
			
		||||
    top: 0;
 | 
			
		||||
    left: 0;
 | 
			
		||||
    width: 100%;
 | 
			
		||||
    height: 100%;
 | 
			
		||||
    background: rgba(0, 0, 0, 0.8); /* Dunkler Hintergrund mit Transparenz */
 | 
			
		||||
    color: white; /* Textfarbe */
 | 
			
		||||
    justify-content: center;
 | 
			
		||||
    align-items: center;
 | 
			
		||||
    z-index: 9999; /* Stellen Sie sicher, dass es über anderen Elementen liegt */
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
.overlay-content {
 | 
			
		||||
    text-align: center;
 | 
			
		||||
    font-size: 4rem;
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
.loader {
 | 
			
		||||
    width: 96px;
 | 
			
		||||
    height: 96px;
 | 
			
		||||
    border: 12px solid #FFF;
 | 
			
		||||
    border-radius: 50%;
 | 
			
		||||
    display: inline-block;
 | 
			
		||||
    position: relative;
 | 
			
		||||
    box-sizing: border-box;
 | 
			
		||||
    animation: rotation 1s linear infinite;
 | 
			
		||||
  } 
 | 
			
		||||
  .loader::after {
 | 
			
		||||
    content: '';  
 | 
			
		||||
    box-sizing: border-box;
 | 
			
		||||
    position: absolute;
 | 
			
		||||
    left: 50%;
 | 
			
		||||
    top: 50%;
 | 
			
		||||
    transform: translate(-50%, -50%);
 | 
			
		||||
    width: 120px;
 | 
			
		||||
    height: 120px;
 | 
			
		||||
    border-radius: 50%;
 | 
			
		||||
    border: 12px solid transparent;
 | 
			
		||||
    border-bottom-color: #FF3D00;
 | 
			
		||||
  }
 | 
			
		||||
  
 | 
			
		||||
  @keyframes rotation {
 | 
			
		||||
    0% {
 | 
			
		||||
      transform: rotate(0deg);
 | 
			
		||||
    }
 | 
			
		||||
    100% {
 | 
			
		||||
      transform: rotate(360deg);
 | 
			
		||||
    }
 | 
			
		||||
  } 
 | 
			
		||||
 | 
			
		||||
  .notification-container {
 | 
			
		||||
    position: fixed;
 | 
			
		||||
    top: 30%;
 | 
			
		||||
    left: 50%;
 | 
			
		||||
    transform: translateX(-50%);
 | 
			
		||||
    z-index: 1000;
 | 
			
		||||
  }
 | 
			
		||||
  
 | 
			
		||||
  .notification {
 | 
			
		||||
    margin-bottom: 20px; /* Fügen Sie bei Bedarf weitere Stile hinzu */
 | 
			
		||||
  }
 | 
			
		||||
							
								
								
									
										96
									
								
								Software/data_src/static/dtc_table.json
									
									
									
									
									
										Normal file
									
								
							
							
						
						@@ -0,0 +1,96 @@
 | 
			
		||||
{
 | 
			
		||||
    "codegenerator_checksum": "313d59949b074024df3c5d796f65e3bd518e34f0bb171185c30f008f21c19d30",
 | 
			
		||||
    "timestamp": "2024-05-30 21:56:51",
 | 
			
		||||
    "dtc_table_data": [
 | 
			
		||||
        {
 | 
			
		||||
            "num": 0,
 | 
			
		||||
            "title": "No Error",
 | 
			
		||||
            "description": "No Error"
 | 
			
		||||
        },
 | 
			
		||||
        {
 | 
			
		||||
            "num": 1,
 | 
			
		||||
            "title": "Akku leer",
 | 
			
		||||
            "description": "Akku ist komplett leer. Den Akku aufladen!"
 | 
			
		||||
        },
 | 
			
		||||
        {
 | 
			
		||||
            "num": 2,
 | 
			
		||||
            "title": "Akku niedrig",
 | 
			
		||||
            "description": "Akku ist unter der Warnschwelle. Den Akku demnächst aufladen"
 | 
			
		||||
        },
 | 
			
		||||
        {
 | 
			
		||||
            "num": 3,
 | 
			
		||||
            "title": "kein EEPROM erkannt",
 | 
			
		||||
            "description": "Es wurde kein EEPROM gefunden. Dies lässt einen Hardware-Defekt vermuten."
 | 
			
		||||
        },
 | 
			
		||||
        {
 | 
			
		||||
            "num": 4,
 | 
			
		||||
            "title": "EEPROM CFG Checksumme",
 | 
			
		||||
            "description": "Die Checksumme der Config-Partition des EEPROM ist ungültig. Setzen sie den EEPROM-Bereich 'CFG' im Menu 'Wartung' zurück"
 | 
			
		||||
        },
 | 
			
		||||
        {
 | 
			
		||||
            "num": 5,
 | 
			
		||||
            "title": "EEPROM PDS Checksumme",
 | 
			
		||||
            "description": "Die Checksumme der Betriebsdaten-Partition des EEPROM ist ungültig. Setzen sie den EEPROM-Bereich 'PDS' im Menu 'Wartung' zurück"
 | 
			
		||||
        },
 | 
			
		||||
        {
 | 
			
		||||
            "num": 6,
 | 
			
		||||
            "title": "EEPROM PDS Adresse",
 | 
			
		||||
            "description": "Die Adresse der Betriebsdaten-Partition im EEPROM ist ungültig. Setzen sie den EEPROM-Bereich 'PDS' im Menu 'Wartung' zurück"
 | 
			
		||||
        },
 | 
			
		||||
        {
 | 
			
		||||
            "num": 7,
 | 
			
		||||
            "title": "EEPROM Version falsch",
 | 
			
		||||
            "description": "Die Layout-Version des EEPROM stimmt nicht mit der Firmware-Version überein. Setzen sie den EEPROM-Bereich 'CFG' im Menu 'Wartung' zurück"
 | 
			
		||||
        },
 | 
			
		||||
        {
 | 
			
		||||
            "num": 8,
 | 
			
		||||
            "title": "Flashspeicher Fehler",
 | 
			
		||||
            "description": "Der Flashspeicher konnte nicht initialisiert werden. Aktualisieren sie Flash & Firmware"
 | 
			
		||||
        },
 | 
			
		||||
        {
 | 
			
		||||
            "num": 9,
 | 
			
		||||
            "title": "Flashversion falsch",
 | 
			
		||||
            "description": "Die Version des Flashspeicher stimmt nicht mit der Firmware-Version überein. Aktualisieren sie den Flash mit der passenden Update-Datei"
 | 
			
		||||
        },
 | 
			
		||||
        {
 | 
			
		||||
            "num": 10,
 | 
			
		||||
            "title": "Keine Akkuüberwachung",
 | 
			
		||||
            "description": "Es wurde keine Akkuüberwachung über I2C gefunden, Prüfen sie die Hardware!"
 | 
			
		||||
        },
 | 
			
		||||
        {
 | 
			
		||||
            "num": 11,
 | 
			
		||||
            "title": "LoRa-Transceiver Error",
 | 
			
		||||
            "description": "Es konnte keine Verbindung zum LoRa-Transceiver hergestellt werden. Prüfen Sie die Hardware auf Defekte"
 | 
			
		||||
        },
 | 
			
		||||
        {
 | 
			
		||||
            "num": 12,
 | 
			
		||||
            "title": "Config-Validierung",
 | 
			
		||||
            "description": "Ein oder mehrer Einstellungswerte sind ausserhalb plausibler Werte. Prüfen Sie Ihre Einstellungen"
 | 
			
		||||
        },
 | 
			
		||||
        {
 | 
			
		||||
            "num": 13,
 | 
			
		||||
            "title": "EEPROM-Migration",
 | 
			
		||||
            "description": "Es wurde ein altes EEPROm Image erkannt, konnte aber nicht migriert werden. EEPROM manuell zurück setzen und neue Einstellunge speichern."
 | 
			
		||||
        },
 | 
			
		||||
        {
 | 
			
		||||
            "num": 14,
 | 
			
		||||
            "title": "Dummy-DTC Info",
 | 
			
		||||
            "description": "Ein Dummy-DTC der Schwere \"Info\" für Debugging-Zwecke"
 | 
			
		||||
        },
 | 
			
		||||
        {
 | 
			
		||||
            "num": 15,
 | 
			
		||||
            "title": "Dummy-DTC Warnung",
 | 
			
		||||
            "description": "Ein Dummy-DTC der Schwere \"Warnung\" für Debugging-Zwecke"
 | 
			
		||||
        },
 | 
			
		||||
        {
 | 
			
		||||
            "num": 16,
 | 
			
		||||
            "title": "Dummy-DTC Kritisch",
 | 
			
		||||
            "description": "Ein Dummy-DTC der Schwere \"Kritisch\" für Debugging-Zwecke"
 | 
			
		||||
        },
 | 
			
		||||
        {
 | 
			
		||||
            "num": 17,
 | 
			
		||||
            "title": "Last Error",
 | 
			
		||||
            "description": "Last Error"
 | 
			
		||||
        }
 | 
			
		||||
    ]
 | 
			
		||||
}
 | 
			
		||||
							
								
								
									
										
											BIN
										
									
								
								Software/data_src/static/fonts/comfortaa.woff2
									
									
									
									
									
										Normal file
									
								
							
							
						
						
							
								
								
									
										
											BIN
										
									
								
								Software/data_src/static/img/critical.png
									
									
									
									
									
										Normal file
									
								
							
							
						
						| 
		 After Width: | Height: | Size: 7.9 KiB  | 
							
								
								
									
										
											BIN
										
									
								
								Software/data_src/static/img/info.png
									
									
									
									
									
										Normal file
									
								
							
							
						
						| 
		 After Width: | Height: | Size: 9.6 KiB  | 
| 
		 Before Width: | Height: | Size: 37 KiB After Width: | Height: | Size: 34 KiB  | 
| 
		 Before Width: | Height: | Size: 26 KiB After Width: | Height: | Size: 37 KiB  | 
| 
		 Before Width: | Height: | Size: 34 KiB After Width: | Height: | Size: 26 KiB  | 
							
								
								
									
										
											BIN
										
									
								
								Software/data_src/static/img/warn.png
									
									
									
									
									
										Normal file
									
								
							
							
						
						| 
		 After Width: | Height: | Size: 9.4 KiB  | 
							
								
								
									
										7
									
								
								Software/data_src/static/js/bootstrap.min.js
									
									
									
									
										vendored
									
									
										Normal file
									
								
							
							
						
						
							
								
								
									
										221
									
								
								Software/data_src/static/js/dtc_table.js
									
									
									
									
									
										Normal file
									
								
							
							
						
						@@ -0,0 +1,221 @@
 | 
			
		||||
const jsonFilePath = "static/dtc_table.json";
 | 
			
		||||
 | 
			
		||||
var dtcState = {};
 | 
			
		||||
 | 
			
		||||
async function processDTCNotifications(dtcArray) {
 | 
			
		||||
  // Entferne DTCs aus dtcState, die nicht im dtcArray enthalten sind
 | 
			
		||||
  for (var key in dtcState) {
 | 
			
		||||
    if (!dtcArray.some((dtc) => parseInt(dtc.split(",")[1]) == key)) {
 | 
			
		||||
      delete dtcState[key];
 | 
			
		||||
    }
 | 
			
		||||
  }
 | 
			
		||||
 | 
			
		||||
  if (dtcArray.length === 0 || dtcArray[0] == "0") {
 | 
			
		||||
    dtcState = {};
 | 
			
		||||
    return;
 | 
			
		||||
  }
 | 
			
		||||
 | 
			
		||||
  for (var i = 0; i < dtcArray.length; i++) {
 | 
			
		||||
    var dtcInfo = dtcArray[i].split(",");
 | 
			
		||||
    var errorCode = parseInt(dtcInfo[1]);
 | 
			
		||||
    var activity = parseInt(dtcInfo[3]);
 | 
			
		||||
    var severity = parseInt(dtcInfo[2]);
 | 
			
		||||
 | 
			
		||||
    try {
 | 
			
		||||
      var { title, description } = await getDescriptionForDTCNumber(errorCode);
 | 
			
		||||
 | 
			
		||||
      switch (severity) {
 | 
			
		||||
        case 1:
 | 
			
		||||
          severity = "info";
 | 
			
		||||
          break;
 | 
			
		||||
        case 2:
 | 
			
		||||
          severity = "warning";
 | 
			
		||||
          break;
 | 
			
		||||
        case 3:
 | 
			
		||||
          severity = "danger";
 | 
			
		||||
          break;
 | 
			
		||||
      }
 | 
			
		||||
 | 
			
		||||
      if (dtcState[errorCode]) {
 | 
			
		||||
        // Überprüfen, ob sich der Zustand von "previous" auf "active" geändert hat
 | 
			
		||||
        if (activity !== dtcState[errorCode].activity) {
 | 
			
		||||
          dtcState[errorCode].activity = activity;
 | 
			
		||||
          if (activity === 1) showNotification(description, severity);
 | 
			
		||||
        }
 | 
			
		||||
      } else {
 | 
			
		||||
        // DTC ist neu, Zustand speichern und wenn active, Benachrichtigung anzeigen
 | 
			
		||||
        dtcState[errorCode] = { activity: activity };
 | 
			
		||||
        if (activity === 1) showNotification(description, severity);
 | 
			
		||||
      }
 | 
			
		||||
    } catch (error) {
 | 
			
		||||
      console.error("Error processing DTC:", error);
 | 
			
		||||
    }
 | 
			
		||||
  }
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
function getDescriptionForDTCNumber(number) {
 | 
			
		||||
  return new Promise((resolve, reject) => {
 | 
			
		||||
    fetch(jsonFilePath)
 | 
			
		||||
      .then((response) => response.json())
 | 
			
		||||
      .then((data) => {
 | 
			
		||||
        const dtcList = data.dtc_table_data;
 | 
			
		||||
        const foundEntry = dtcList.find((entry) => entry.num === number);
 | 
			
		||||
 | 
			
		||||
        if (foundEntry) {
 | 
			
		||||
          const description = foundEntry.description;
 | 
			
		||||
          const title = foundEntry.title;
 | 
			
		||||
          resolve({ title, description });
 | 
			
		||||
        } else {
 | 
			
		||||
          // Wenn die Nummer nicht gefunden wurde, geben Sie einen Fehler zurück
 | 
			
		||||
          reject(`Beschreibung für Nummer ${number} nicht gefunden.`);
 | 
			
		||||
        }
 | 
			
		||||
      })
 | 
			
		||||
      .catch((error) => {
 | 
			
		||||
        // Im Fehlerfall geben Sie den Fehler zurück
 | 
			
		||||
        reject(error);
 | 
			
		||||
      });
 | 
			
		||||
  });
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
async function showDTCModal(event) {
 | 
			
		||||
  var dtc = parseInt(event.currentTarget.getAttribute("data-dtc"));
 | 
			
		||||
  var debugval = event.currentTarget.getAttribute("data-debugval");
 | 
			
		||||
  var modal = $("#dtcModal");
 | 
			
		||||
 | 
			
		||||
  try {
 | 
			
		||||
    var { title, description } = await getDescriptionForDTCNumber(dtc);
 | 
			
		||||
 | 
			
		||||
    modal.find(".modal-title").text(title);
 | 
			
		||||
    modal.find(".dtc-desc").text(description);
 | 
			
		||||
 | 
			
		||||
    if (debugval > 0) {
 | 
			
		||||
      modal.find(".dtc-debugval").text("Debugvalue: " + debugval);
 | 
			
		||||
    } else {
 | 
			
		||||
      modal.find(".dtc-debugval").remove();
 | 
			
		||||
    }
 | 
			
		||||
  } catch (error) {
 | 
			
		||||
    console.error("Fehler beim Abrufen der Beschreibung:", error);
 | 
			
		||||
    modal.find(".modal-title").text("Fehler");
 | 
			
		||||
    modal
 | 
			
		||||
      .find(".dtc-desc")
 | 
			
		||||
      .text("DTC-Beschreibung konnte nicht geladen werden");
 | 
			
		||||
  }
 | 
			
		||||
 | 
			
		||||
  // Modal anzeigen
 | 
			
		||||
  modal.modal("show");
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
function fillDTCTable(dtcArray) {
 | 
			
		||||
  // Referenz auf das Tabellen-Element
 | 
			
		||||
  var table = document.getElementById("dtc_table");
 | 
			
		||||
  var tablediv = document.getElementById("dtc_container");
 | 
			
		||||
 | 
			
		||||
  // Prüfen, ob DTC vorhanden sind
 | 
			
		||||
  if (dtcArray.length === 0 || dtcArray[0] == "0") {
 | 
			
		||||
    // Verstecke das Tabellen-Div, wenn keine DTC vorhanden sind
 | 
			
		||||
    tablediv.hidden = true;
 | 
			
		||||
    table.innerHTML = "";
 | 
			
		||||
    return;
 | 
			
		||||
  }
 | 
			
		||||
 | 
			
		||||
  // Prüfen, ob sich der Inhalt der Tabelle geändert hat
 | 
			
		||||
  var tableContentChanged = false;
 | 
			
		||||
  for (var i = 0; i < dtcArray.length; i++) {
 | 
			
		||||
    var dtcInfo = dtcArray[i].split(",");
 | 
			
		||||
    var errorCode = parseInt(dtcInfo[1]);
 | 
			
		||||
    var activity = parseInt(dtcInfo[3]);
 | 
			
		||||
 | 
			
		||||
    if (!dtcState[errorCode] || dtcState[errorCode].activity !== activity) {
 | 
			
		||||
      tableContentChanged = true;
 | 
			
		||||
      break;
 | 
			
		||||
    }
 | 
			
		||||
  }
 | 
			
		||||
 | 
			
		||||
  if (!tableContentChanged) {
 | 
			
		||||
    return;
 | 
			
		||||
  }
 | 
			
		||||
 | 
			
		||||
  // Zeige das Tabellen-Div, wenn DTC vorhanden sind
 | 
			
		||||
  tablediv.hidden = false;
 | 
			
		||||
 | 
			
		||||
  // Tabelle leeren, bevor sie neu gefüllt wird
 | 
			
		||||
  table.innerHTML = "";
 | 
			
		||||
 | 
			
		||||
  // Überschriften für die Tabelle erstellen
 | 
			
		||||
  var headerRow = table.insertRow(0);
 | 
			
		||||
 | 
			
		||||
  // Definition der Klassen und Scopes für die Spalten
 | 
			
		||||
  var columnDefinitions = [
 | 
			
		||||
    { class: "col-6", scope: "Zeitstempel" },
 | 
			
		||||
    { class: "col-2", scope: "Fehlercode" },
 | 
			
		||||
    { class: "col-2", scope: "Schwere" },
 | 
			
		||||
    { class: "col-2", scope: "Aktiv" },
 | 
			
		||||
  ];
 | 
			
		||||
 | 
			
		||||
  for (var i = 0; i < columnDefinitions.length; i++) {
 | 
			
		||||
    var headerCell = headerRow.insertCell(i);
 | 
			
		||||
    headerCell.className = `th ${columnDefinitions[i].class}`;
 | 
			
		||||
    headerCell.scope = columnDefinitions[i].scope;
 | 
			
		||||
    headerCell.innerHTML = columnDefinitions[i].scope;
 | 
			
		||||
  }
 | 
			
		||||
 | 
			
		||||
  // DTC-Daten in die Tabelle einfügen
 | 
			
		||||
  for (var i = 0; i < dtcArray.length; i++) {
 | 
			
		||||
    var dtcInfo = dtcArray[i].split(",");
 | 
			
		||||
 | 
			
		||||
    var row = table.insertRow(i + 1); // +1 wegen der Überschriftenzeile
 | 
			
		||||
 | 
			
		||||
    // Zeitstempel
 | 
			
		||||
    var timestampCell = row.insertCell(0);
 | 
			
		||||
    timestampCell.innerHTML = formatTimestamp(parseInt(dtcInfo[0]));
 | 
			
		||||
 | 
			
		||||
    // Fehlercode
 | 
			
		||||
    var errorCodeCell = row.insertCell(1);
 | 
			
		||||
    errorCodeCell.innerHTML = dtcInfo[1];
 | 
			
		||||
 | 
			
		||||
    // Schwere
 | 
			
		||||
    var severityCell = row.insertCell(2);
 | 
			
		||||
    var severity = parseInt(dtcInfo[2]);
 | 
			
		||||
 | 
			
		||||
    // Schwere
 | 
			
		||||
    switch (severity) {
 | 
			
		||||
      case 1:
 | 
			
		||||
        severityCell.innerHTML = '<img src="static/img/info.png" alt="Info" />';
 | 
			
		||||
        break;
 | 
			
		||||
      case 2:
 | 
			
		||||
        severityCell.innerHTML =
 | 
			
		||||
          '<img src="static/img/warn.png" alt="Warnung" />';
 | 
			
		||||
        break;
 | 
			
		||||
      case 3:
 | 
			
		||||
        severityCell.innerHTML =
 | 
			
		||||
          '<img src="static/img/critical.png" alt="Kritisch" />';
 | 
			
		||||
        break;
 | 
			
		||||
      default:
 | 
			
		||||
        severityCell.innerHTML =
 | 
			
		||||
          '<img src="static/img/none.png" alt="Unbekannt" />';
 | 
			
		||||
    }
 | 
			
		||||
 | 
			
		||||
    row.setAttribute("data-dtc", dtcInfo[1]);
 | 
			
		||||
    row.setAttribute("data-debugval", dtcInfo[4]);
 | 
			
		||||
    row.addEventListener("click", showDTCModal);
 | 
			
		||||
 | 
			
		||||
    // Aktivität
 | 
			
		||||
    var activityCell = row.insertCell(3);
 | 
			
		||||
    activityCell.innerHTML = parseInt(dtcInfo[3]) === 1 ? "active" : "previous";
 | 
			
		||||
  }
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
function formatTimestamp(milliseconds) {
 | 
			
		||||
  const date = new Date(milliseconds);
 | 
			
		||||
 | 
			
		||||
  const days = String(date.getUTCDate() - 1).padStart(2, "0");
 | 
			
		||||
  const hours = String(date.getUTCHours()).padStart(2, "0");
 | 
			
		||||
  const minutes = String(date.getUTCMinutes()).padStart(2, "0");
 | 
			
		||||
  const seconds = String(date.getUTCSeconds()).padStart(2, "0");
 | 
			
		||||
  const millisecondsFormatted = String(date.getUTCMilliseconds()).padStart(
 | 
			
		||||
    3,
 | 
			
		||||
    "0"
 | 
			
		||||
  );
 | 
			
		||||
 | 
			
		||||
  return `${days}-${hours}:${minutes}:${seconds}:${millisecondsFormatted}`;
 | 
			
		||||
}
 | 
			
		||||
							
								
								
									
										5
									
								
								Software/data_src/static/js/popper.min.js
									
									
									
									
										vendored
									
									
										Normal file
									
								
							
							
						
						
							
								
								
									
										42
									
								
								Software/data_src/static/js/script.js
									
									
									
									
									
										Normal file
									
								
							
							
						
						@@ -0,0 +1,42 @@
 | 
			
		||||
$(document).ready(function () {
 | 
			
		||||
  // Event-Listener für Navbar-Links
 | 
			
		||||
  $(".navbar-nav a").on("click", function () {
 | 
			
		||||
    $(".navbar-collapse").collapse("hide");
 | 
			
		||||
  });
 | 
			
		||||
 | 
			
		||||
  // Event-Listener für Passwort zeigen/verborgen
 | 
			
		||||
  $("#show_hide_password a").on("click", function (event) {
 | 
			
		||||
    event.preventDefault();
 | 
			
		||||
    var inputField = $("#show_hide_password input");
 | 
			
		||||
    var icon = $("#show_hide_password i");
 | 
			
		||||
    if (inputField.attr("type") == "text") {
 | 
			
		||||
      inputField.attr("type", "password");
 | 
			
		||||
      icon.addClass("fa-eye-slash");
 | 
			
		||||
      icon.removeClass("fa-eye");
 | 
			
		||||
    } else if (inputField.attr("type") == "password") {
 | 
			
		||||
      inputField.attr("type", "text");
 | 
			
		||||
      icon.removeClass("fa-eye-slash");
 | 
			
		||||
      icon.addClass("fa-eye");
 | 
			
		||||
    }
 | 
			
		||||
  });
 | 
			
		||||
 | 
			
		||||
  // Event-Listener für Datei-Upload
 | 
			
		||||
  $(".custom-file-input").on("change", function (e) {
 | 
			
		||||
    var fileName = document.getElementById("fw-update-file").files[0].name;
 | 
			
		||||
    var nextSibling = e.target.nextElementSibling;
 | 
			
		||||
    nextSibling.innerText = fileName;
 | 
			
		||||
  });
 | 
			
		||||
 | 
			
		||||
  // Event-Listener für Live-Debug-Eingabe
 | 
			
		||||
  $('#livedebug-in').on('keydown', function(event) {
 | 
			
		||||
    if (event.key === 'Enter' || event.keyCode === 13) {
 | 
			
		||||
      event.preventDefault(); // Verhindert, dass die Enter-Taste die Standardaktion ausführt (z.B. Absenden eines Formulars)
 | 
			
		||||
      
 | 
			
		||||
      const command = $('#livedebug-in').val(); // Den Befehl aus dem Eingabefeld holen
 | 
			
		||||
      websocket_sendDebugCommand(command); // Den Befehl an die Funktion übergeben
 | 
			
		||||
 | 
			
		||||
      $('#livedebug-in').val(''); // Leert das Eingabefeld
 | 
			
		||||
      $('#livedebug-in').focus(); // Setzt den Fokus zurück auf das Eingabefeld
 | 
			
		||||
    }
 | 
			
		||||
  });
 | 
			
		||||
});
 | 
			
		||||
							
								
								
									
										273
									
								
								Software/data_src/static/js/websocket.js
									
									
									
									
									
										Normal file
									
								
							
							
						
						@@ -0,0 +1,273 @@
 | 
			
		||||
var gateway = `ws://${window.location.hostname}/ws`;
 | 
			
		||||
var websocket;
 | 
			
		||||
 | 
			
		||||
var statusMapping;
 | 
			
		||||
var staticMapping;
 | 
			
		||||
var overlay;
 | 
			
		||||
 | 
			
		||||
document.addEventListener("DOMContentLoaded", function () {
 | 
			
		||||
  // Ihr JavaScript-Code hier, einschließlich der onLoad-Funktion
 | 
			
		||||
  overlay = document.getElementById("overlay");
 | 
			
		||||
  onLoad();
 | 
			
		||||
});
 | 
			
		||||
 | 
			
		||||
function initWebSocket() {
 | 
			
		||||
  console.log("Trying to open a WebSocket connection...");
 | 
			
		||||
  websocket = new WebSocket(gateway);
 | 
			
		||||
  websocket.onopen = onOpen;
 | 
			
		||||
  websocket.onclose = onClose;
 | 
			
		||||
  websocket.onmessage = onMessage; // <-- add this line
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
function initButtons() {
 | 
			
		||||
  var elements = document.getElementsByClassName("btn-wsevent");
 | 
			
		||||
 | 
			
		||||
  if (elements.length > 0) {
 | 
			
		||||
    for (var i = 0; i < elements.length; i++) {
 | 
			
		||||
      let element = elements[i];
 | 
			
		||||
      element.addEventListener("click", sendButton);
 | 
			
		||||
    }
 | 
			
		||||
  }
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
function initSettingInputs() {
 | 
			
		||||
  var elements = document.getElementsByClassName("set-wsevent");
 | 
			
		||||
 | 
			
		||||
  if (elements.length > 0) {
 | 
			
		||||
    for (var i = 0; i < elements.length; i++) {
 | 
			
		||||
      let element = elements[i];
 | 
			
		||||
      element.addEventListener("change", function () {
 | 
			
		||||
        websocket_sendevent("set-" + element.id, element.value);
 | 
			
		||||
      });
 | 
			
		||||
    }
 | 
			
		||||
  }
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
function onOpen(event) {
 | 
			
		||||
  console.log("Connection opened");
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
function onClose(event) {
 | 
			
		||||
  console.log("Connection closed");
 | 
			
		||||
  setTimeout(initWebSocket, 1000);
 | 
			
		||||
  overlay.style.display = "flex";
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
function sendButton(event) {
 | 
			
		||||
  var targetElement = event.target;
 | 
			
		||||
 | 
			
		||||
  if (
 | 
			
		||||
    targetElement.classList.contains("confirm") &&
 | 
			
		||||
    window.confirm("Sicher?") == false
 | 
			
		||||
  )
 | 
			
		||||
    return;
 | 
			
		||||
 | 
			
		||||
  websocket_sendevent("btn-" + targetElement.id, targetElement.value);
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
function onMessage(event) {
 | 
			
		||||
  var data = event.data;
 | 
			
		||||
 | 
			
		||||
  if (data.startsWith("NOTIFY:")) {
 | 
			
		||||
    var notify_data = data.slice(7).split(";")[1];
 | 
			
		||||
    var notify_type = data.slice(7).split(";")[0];
 | 
			
		||||
    showNotification(notify_data, notify_type);
 | 
			
		||||
  } else if (data.startsWith("DEBUG:")) {
 | 
			
		||||
    var addtext = data.slice(6);
 | 
			
		||||
    var livedebug_out = document.getElementById("livedebug-out");
 | 
			
		||||
    livedebug_out.value += addtext;
 | 
			
		||||
    livedebug_out.scrollTop = livedebug_out.scrollHeight;
 | 
			
		||||
    do_resize(livedebug_out);
 | 
			
		||||
  } else if (data.startsWith("DTC:")) {
 | 
			
		||||
    const dtcs = data.slice(4);
 | 
			
		||||
    const dtcArray = dtcs.trim() !== "" ? dtcs.split(";").filter(Boolean) : [];
 | 
			
		||||
 | 
			
		||||
    processDTCNotifications(dtcArray);
 | 
			
		||||
    fillDTCTable(dtcArray);
 | 
			
		||||
  } else if (data.startsWith("MAPPING_STATUS:")) {
 | 
			
		||||
    const data_sliced = data.slice(15);
 | 
			
		||||
    statusMapping = createMapping(data_sliced);
 | 
			
		||||
  } else if (data.startsWith("MAPPING_STATIC:")) {
 | 
			
		||||
    const data_sliced = data.slice(15);
 | 
			
		||||
    staticMapping = createMapping(data_sliced);
 | 
			
		||||
    console.log(staticMapping);
 | 
			
		||||
  } else if (data.startsWith("STATUS:")) {
 | 
			
		||||
    const data_sliced = data.slice(7);
 | 
			
		||||
    const result = processDataString(data_sliced, statusMapping);
 | 
			
		||||
    fillValuesToHTML(result);
 | 
			
		||||
  } else if (data.startsWith("STATIC:")) {
 | 
			
		||||
    const data_sliced = data.slice(7);
 | 
			
		||||
    const result = processDataString(data_sliced, staticMapping);
 | 
			
		||||
    fillValuesToHTML(result);
 | 
			
		||||
    console.log(result);
 | 
			
		||||
    overlay.style.display = "none";
 | 
			
		||||
  }
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
function createMapping(mappingString) {
 | 
			
		||||
  const mappingArray = mappingString.split(";");
 | 
			
		||||
  const mapping = [];
 | 
			
		||||
 | 
			
		||||
  mappingArray.forEach((variable) => {
 | 
			
		||||
    if (variable !== null) mapping.push(variable.trim());
 | 
			
		||||
  });
 | 
			
		||||
  return mapping;
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
function processDataString(dataString, mapping) {
 | 
			
		||||
  const valuesArray = dataString.split(";");
 | 
			
		||||
  const dataObject = {};
 | 
			
		||||
 | 
			
		||||
  valuesArray.forEach((value, index) => {
 | 
			
		||||
    const variable = mapping[index];
 | 
			
		||||
    if (variable) {
 | 
			
		||||
      dataObject[variable] = value.trim();
 | 
			
		||||
    }
 | 
			
		||||
  });
 | 
			
		||||
 | 
			
		||||
  return dataObject;
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
function onLoad(event) {
 | 
			
		||||
  initWebSocket();
 | 
			
		||||
  initButtons();
 | 
			
		||||
  initSettingInputs();
 | 
			
		||||
  overlay.style.display = "flex";
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
function websocket_sendevent(element_id, element_value) {
 | 
			
		||||
  websocket.send(element_id + ":" + element_value);
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
function websocket_sendDebugCommand(command) {
 | 
			
		||||
  websocket.send("debug-in:" + command);
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
function do_resize(textbox) {
 | 
			
		||||
  var maxrows = 15;
 | 
			
		||||
  var minrows = 3;
 | 
			
		||||
  var txt = textbox.value;
 | 
			
		||||
  var cols = textbox.cols;
 | 
			
		||||
 | 
			
		||||
  var arraytxt = txt.split("\n");
 | 
			
		||||
  var rows = arraytxt.length;
 | 
			
		||||
 | 
			
		||||
  for (i = 0; i < arraytxt.length; i++)
 | 
			
		||||
    rows += parseInt(arraytxt[i].length / cols);
 | 
			
		||||
 | 
			
		||||
  if (rows > maxrows) textbox.rows = maxrows;
 | 
			
		||||
  else if (rows < minrows) textbox.rows = minrows;
 | 
			
		||||
  else textbox.rows = rows;
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
function fillValuesToHTML(dataset) {
 | 
			
		||||
  for (var key in dataset) {
 | 
			
		||||
    var key_prefixed = "data-" + key;
 | 
			
		||||
    var elements = document.getElementsByClassName(key_prefixed);
 | 
			
		||||
 | 
			
		||||
    if (elements.length > 0) {
 | 
			
		||||
      for (var i = 0; i < elements.length; i++) {
 | 
			
		||||
        var element = elements[i];
 | 
			
		||||
 | 
			
		||||
        if (element.type === "checkbox") {
 | 
			
		||||
          // Wenn das Element ein Kontrollkästchen ist
 | 
			
		||||
          element.checked = dataset[key] == 1 ? true : false;
 | 
			
		||||
        } else if (element.tagName === "SELECT") {
 | 
			
		||||
          // Wenn das Element ein Dropdown ist
 | 
			
		||||
          setDropdownValue(element, dataset[key]);
 | 
			
		||||
        } else if (element.classList.contains("progress-bar")) {
 | 
			
		||||
          // Wenn das Element eine Fortschrittsleiste ist
 | 
			
		||||
          updateProgressBar(element, dataset[key]);
 | 
			
		||||
        } else if (element.classList.contains("hideable")) {
 | 
			
		||||
          // Wenn das Element ein Settingsabschnitt-div ist
 | 
			
		||||
          if (dataset[key] == 0) element.style.display = "none";
 | 
			
		||||
          else element.style.display = "";
 | 
			
		||||
        } else if (element.tagName === "DIV" || element.tagName === "SPAN") {
 | 
			
		||||
          if (element.classList.contains("format-time")) {
 | 
			
		||||
            element.innerText = formatTime(dataset[key]);
 | 
			
		||||
          } else if (element.classList.contains("faction-logo")) {
 | 
			
		||||
            // Faction-Logo-Logik
 | 
			
		||||
            updateFactionLogo(element, dataset[key]);
 | 
			
		||||
          } else {
 | 
			
		||||
            element.innerText = dataset[key];
 | 
			
		||||
          }
 | 
			
		||||
        } else {
 | 
			
		||||
          // Standardmäßig für Textfelder und andere Elemente
 | 
			
		||||
          element.value = dataset[key];
 | 
			
		||||
        }
 | 
			
		||||
      }
 | 
			
		||||
    }
 | 
			
		||||
    // Aktualisiere den <title>-Tag, wenn der Schlüssel 'devicename' im dataset vorhanden ist
 | 
			
		||||
    if (key === "devicename") {
 | 
			
		||||
      document.title = dataset[key];
 | 
			
		||||
    }
 | 
			
		||||
  }
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
function formatTime(seconds) {
 | 
			
		||||
  var hrs = Math.floor(seconds / 3600);
 | 
			
		||||
  var mins = Math.floor((seconds % 3600) / 60);
 | 
			
		||||
  var secs = seconds % 60;
 | 
			
		||||
 | 
			
		||||
  return (
 | 
			
		||||
    String(hrs).padStart(2, "0") +
 | 
			
		||||
    ":" +
 | 
			
		||||
    String(mins).padStart(2, "0") +
 | 
			
		||||
    ":" +
 | 
			
		||||
    String(secs).padStart(2, "0")
 | 
			
		||||
  );
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
function updateFactionLogo(element, faction) {
 | 
			
		||||
  const glowClass = "glow-active-faction";
 | 
			
		||||
  var factionClass = "faction" + faction;
 | 
			
		||||
  if (element.classList.contains(factionClass)) {
 | 
			
		||||
    element.classList.add(glowClass);
 | 
			
		||||
  } else {
 | 
			
		||||
    element.classList.remove(glowClass);
 | 
			
		||||
  }
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
// Funktion zum Setzen des ausgewählten Werts für Dropdowns
 | 
			
		||||
function setDropdownValue(selectElement, value) {
 | 
			
		||||
  for (var i = 0; i < selectElement.options.length; i++) {
 | 
			
		||||
    if (selectElement.options[i].value === value) {
 | 
			
		||||
      selectElement.selectedIndex = i;
 | 
			
		||||
      break;
 | 
			
		||||
    }
 | 
			
		||||
  }
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
// Funktion zum Aktualisieren der Fortschrittsleiste
 | 
			
		||||
function updateProgressBar(progressBar, value) {
 | 
			
		||||
  // Wert in das aria-valuenow-Attribut einfügen
 | 
			
		||||
  progressBar.setAttribute("aria-valuenow", value);
 | 
			
		||||
 | 
			
		||||
  // Breite des Fortschrittsbalkens und inneren Text aktualisieren
 | 
			
		||||
  progressBar.style.width = value + "%";
 | 
			
		||||
  progressBar.textContent = value + "%";
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
function showNotification(message, type) {
 | 
			
		||||
  // Erstellen Sie ein Bootstrap-Alert-Element
 | 
			
		||||
  var alertElement = $(
 | 
			
		||||
    '<div class="alert alert-' +
 | 
			
		||||
      type +
 | 
			
		||||
      ' alert-dismissible fade show notification" role="alert">' +
 | 
			
		||||
      "<strong>" +
 | 
			
		||||
      message +
 | 
			
		||||
      "</strong>" +
 | 
			
		||||
      '<button type="button" class="close" data-dismiss="alert" aria-label="Close">' +
 | 
			
		||||
      '<span aria-hidden="true">×</span>' +
 | 
			
		||||
      "</button>" +
 | 
			
		||||
      "</div>"
 | 
			
		||||
  );
 | 
			
		||||
 | 
			
		||||
  // Fügen Sie das Alert-Element dem Container hinzu
 | 
			
		||||
  $("#notification-container").append(alertElement);
 | 
			
		||||
 | 
			
		||||
  // Nach 5 Sekunden das Alert-Element ausblenden
 | 
			
		||||
  setTimeout(function () {
 | 
			
		||||
    alertElement.alert("close");
 | 
			
		||||
  }, 5000);
 | 
			
		||||
}
 | 
			
		||||
@@ -1 +0,0 @@
 | 
			
		||||
1.0
 | 
			
		||||
@@ -1,8 +0,0 @@
 | 
			
		||||
import subprocess
 | 
			
		||||
 | 
			
		||||
revision = (
 | 
			
		||||
    subprocess.check_output(["git", "rev-parse", "--short=10", "HEAD"])
 | 
			
		||||
    .strip()
 | 
			
		||||
    .decode("utf-8")
 | 
			
		||||
)
 | 
			
		||||
print("-DGIT_REV='\"%s\"'" % revision)
 | 
			
		||||
@@ -3,14 +3,23 @@
 | 
			
		||||
#define _COMMON_H_
 | 
			
		||||
 | 
			
		||||
#include <stdint.h>
 | 
			
		||||
#include <stddef.h>
 | 
			
		||||
 | 
			
		||||
#define Q(x) #x
 | 
			
		||||
#define QUOTE(x) Q(x)
 | 
			
		||||
#define SET_BIT(value, bitPosition) ((value) |= (1U << (bitPosition)))
 | 
			
		||||
 | 
			
		||||
#define TRUE 1
 | 
			
		||||
#define FALSE 0
 | 
			
		||||
 | 
			
		||||
#define HOST_NAME "AirsoftTimer_%08X"
 | 
			
		||||
#ifndef DEVICE_NAME
 | 
			
		||||
#define HOST_NAME "AirsoftTimer"
 | 
			
		||||
#else
 | 
			
		||||
#define HOST_NAME DEVICE_NAME
 | 
			
		||||
#endif
 | 
			
		||||
 | 
			
		||||
#define SHUTDOWN_DELAY_MS 5000
 | 
			
		||||
#define STARTUP_DELAY_MS 20000
 | 
			
		||||
 | 
			
		||||
#define GPIO_LORA_TX D3
 | 
			
		||||
#define GPIO_LORA_RX D4
 | 
			
		||||
@@ -41,17 +50,24 @@
 | 
			
		||||
#define OTA_DELAY 50 // ticks -> 10ms / tick
 | 
			
		||||
#endif
 | 
			
		||||
 | 
			
		||||
#ifndef ADMIN_PASSWORD
 | 
			
		||||
#error "You need to define ADMIN_PASSWORD for OTA-Update"
 | 
			
		||||
#endif
 | 
			
		||||
#ifndef WIFI_PASSWORD
 | 
			
		||||
#error "You must define an WIFI_PASSWORD for OTA-Update"
 | 
			
		||||
#endif
 | 
			
		||||
#ifndef WIFI_SSID
 | 
			
		||||
#error "You must define an WIFI_SSID for OTA-Update"
 | 
			
		||||
#endif
 | 
			
		||||
#ifndef WIFI_AP_PASSWORD
 | 
			
		||||
#error "You must define an WIFI_AP_PASSWORD for Standalone AP-Mode"
 | 
			
		||||
#endif
 | 
			
		||||
typedef enum eSystem_Status
 | 
			
		||||
{
 | 
			
		||||
  sysStat_Init,
 | 
			
		||||
  sysStat_Startup,
 | 
			
		||||
  sysStat_Normal,
 | 
			
		||||
  sysStat_Error,
 | 
			
		||||
  sysStat_Shutdown
 | 
			
		||||
} tSystem_Status;
 | 
			
		||||
 | 
			
		||||
typedef enum batteryType_e
 | 
			
		||||
{
 | 
			
		||||
  BATTERY_UNDEFINED,
 | 
			
		||||
  BATTERY_LIPO_2S,
 | 
			
		||||
  BATTERY_LIPO_3S
 | 
			
		||||
} batteryType_t;
 | 
			
		||||
 | 
			
		||||
// String representation of SpeedSource enum
 | 
			
		||||
extern const char *BatteryString[];
 | 
			
		||||
extern const size_t BatteryString_Elements;
 | 
			
		||||
 | 
			
		||||
#endif
 | 
			
		||||
							
								
								
									
										51
									
								
								Software/include/debugger.h
									
									
									
									
									
										Normal file
									
								
							
							
						
						@@ -0,0 +1,51 @@
 | 
			
		||||
/**
 | 
			
		||||
 * @file debugger.h
 | 
			
		||||
 *
 | 
			
		||||
 * @brief Header file for debugging functions and status in the ChainLube application.
 | 
			
		||||
 *
 | 
			
		||||
 * This file declares functions and status definitions for debugging purposes in the ChainLube project.
 | 
			
		||||
 * It includes functions to print system information, WiFi information, format EEPROM data,
 | 
			
		||||
 * handle debug messages, and manage the status of different debug ports.
 | 
			
		||||
 *
 | 
			
		||||
 * @author Marcel Peterkau
 | 
			
		||||
 * @date   09.01.2024
 | 
			
		||||
 */
 | 
			
		||||
 | 
			
		||||
#ifndef _DEBUGGER_H_
 | 
			
		||||
#define _DEBUGGER_H_
 | 
			
		||||
 | 
			
		||||
#include <Arduino.h>
 | 
			
		||||
#include "webui.h"
 | 
			
		||||
 | 
			
		||||
typedef enum DebugStatus_e
 | 
			
		||||
{
 | 
			
		||||
    disabled,
 | 
			
		||||
    enabled
 | 
			
		||||
} DebugStatus_t;
 | 
			
		||||
 | 
			
		||||
typedef enum DebugPorts_e
 | 
			
		||||
{
 | 
			
		||||
    dbg_Serial,
 | 
			
		||||
    dbg_Webui,
 | 
			
		||||
    dbg_cntElements
 | 
			
		||||
} DebugPorts_t;
 | 
			
		||||
 | 
			
		||||
const char sDebugPorts[dbg_cntElements][7] = {
 | 
			
		||||
    "Serial",
 | 
			
		||||
    "WebUI"};
 | 
			
		||||
 | 
			
		||||
extern DebugStatus_t DebuggerStatus[dbg_cntElements];
 | 
			
		||||
 | 
			
		||||
enum LogLevel
 | 
			
		||||
{
 | 
			
		||||
    LOG_INFO,
 | 
			
		||||
    LOG_WARN,
 | 
			
		||||
    LOG_ERROR
 | 
			
		||||
};
 | 
			
		||||
 | 
			
		||||
void initDebugger();
 | 
			
		||||
void Debug_pushMessage(const char *format, ...);
 | 
			
		||||
void SetDebugportStatus(DebugPorts_t port, DebugStatus_t status);
 | 
			
		||||
void Debug_Process();
 | 
			
		||||
void Debug_ProcessCommand(uint8_t *command);
 | 
			
		||||
#endif
 | 
			
		||||
							
								
								
									
										39
									
								
								Software/include/dtc.h
									
									
									
									
									
										Normal file
									
								
							
							
						
						@@ -0,0 +1,39 @@
 | 
			
		||||
/**
 | 
			
		||||
 * @file dtc.h
 | 
			
		||||
 *
 | 
			
		||||
 * @brief Header file for handling Diagnostic Trouble Codes (DTC) in the DE-Timer application.
 | 
			
		||||
 *
 | 
			
		||||
 * This file provides definitions and functions for handling Diagnostic Trouble Codes (DTC)
 | 
			
		||||
 * in the DE-Timer project. It includes structures for DTC entries, severity levels,
 | 
			
		||||
 * and functions for DTC maintenance and processing. DTCs are used to track system errors and issues.
 | 
			
		||||
 *
 | 
			
		||||
 * @author Marcel Peterkau
 | 
			
		||||
 * @date   09.01.2024
 | 
			
		||||
 */
 | 
			
		||||
 | 
			
		||||
#ifndef _DTC_H_
 | 
			
		||||
#define _DTC_H_
 | 
			
		||||
 | 
			
		||||
#include <Arduino.h>
 | 
			
		||||
#include "dtc_defs.h"
 | 
			
		||||
 | 
			
		||||
#define MAX_DTC_STORAGE 12
 | 
			
		||||
 | 
			
		||||
typedef struct
 | 
			
		||||
{
 | 
			
		||||
  DTCNum_t Number;
 | 
			
		||||
  uint32_t timestamp;
 | 
			
		||||
  DTCActive_t active;
 | 
			
		||||
  uint32_t debugVal;
 | 
			
		||||
} DTCEntry_t;
 | 
			
		||||
 | 
			
		||||
void MaintainDTC(DTCNum_t DTC_no, boolean active, uint32_t DebugValue = 0);
 | 
			
		||||
void ClearDTC(DTCNum_t DTC_no);
 | 
			
		||||
void ClearAllDTC();
 | 
			
		||||
DTCNum_t getlastDTC(boolean only_active);
 | 
			
		||||
DTCNum_t ActiveDTCseverity(DTCSeverity_t severity);
 | 
			
		||||
DTCSeverity_t getSeverityForDTC(DTCNum_t targetCode);
 | 
			
		||||
void DTC_Process();
 | 
			
		||||
 | 
			
		||||
extern DTCEntry_t DTCStorage[MAX_DTC_STORAGE];
 | 
			
		||||
#endif
 | 
			
		||||
							
								
								
									
										85
									
								
								Software/include/dtc_defs.h
									
									
									
									
									
										Normal file
									
								
							
							
						
						@@ -0,0 +1,85 @@
 | 
			
		||||
/**
 | 
			
		||||
 * @file dtc_defs.h
 | 
			
		||||
 *
 | 
			
		||||
 * @brief Header file for Diagnostic Trouble Code (DTC) definitions in the DE-Timer application.
 | 
			
		||||
 *
 | 
			
		||||
 * This file contains definitions for Diagnostic Trouble Codes (DTC) in the DE-Timer project.
 | 
			
		||||
 * It includes enums for DTC active status, severity levels, and specific DTC codes.
 | 
			
		||||
 * The file also defines an array of DTC definitions and a timestamp indicating the generation time.
 | 
			
		||||
 *
 | 
			
		||||
 * @note This file is auto-generated by a script on 2024-05-30 21:56:51.
 | 
			
		||||
 *
 | 
			
		||||
 * @author Marcel Peterkau
 | 
			
		||||
 * @date   30.05.2024
 | 
			
		||||
 */
 | 
			
		||||
 | 
			
		||||
#ifndef DTC_DEFS_H
 | 
			
		||||
#define DTC_DEFS_H
 | 
			
		||||
 | 
			
		||||
#include <stdint.h>
 | 
			
		||||
 | 
			
		||||
typedef uint32_t DTCNum_t;
 | 
			
		||||
 | 
			
		||||
typedef enum
 | 
			
		||||
{
 | 
			
		||||
  DTC_INACTIVE,
 | 
			
		||||
  DTC_ACTIVE,
 | 
			
		||||
  DTC_PREVIOUS
 | 
			
		||||
} DTCActive_t;
 | 
			
		||||
 | 
			
		||||
typedef enum
 | 
			
		||||
{
 | 
			
		||||
  DTC_NONE,
 | 
			
		||||
  DTC_INFO,
 | 
			
		||||
  DTC_WARN,
 | 
			
		||||
  DTC_CRITICAL
 | 
			
		||||
} DTCSeverity_t;
 | 
			
		||||
 | 
			
		||||
typedef struct {
 | 
			
		||||
  DTCNum_t code;
 | 
			
		||||
  DTCSeverity_t severity;
 | 
			
		||||
} DTC_t;
 | 
			
		||||
 | 
			
		||||
#define DTC_NO_DTC                     0
 | 
			
		||||
#define DTC_BAT_CRITICAL               1
 | 
			
		||||
#define DTC_BAT_LOW                    2
 | 
			
		||||
#define DTC_NO_EEPROM_FOUND            3
 | 
			
		||||
#define DTC_EEPROM_CFG_BAD             4
 | 
			
		||||
#define DTC_EEPROM_PDS_BAD             5
 | 
			
		||||
#define DTC_EEPROM_PDSADRESS_BAD       6
 | 
			
		||||
#define DTC_EEPROM_VERSION_BAD         7
 | 
			
		||||
#define DTC_FLASHFS_ERROR              8
 | 
			
		||||
#define DTC_FLASHFS_VERSION_ERROR      9
 | 
			
		||||
#define DTC_NO_BATMNON_FOUND           10
 | 
			
		||||
#define DTC_NO_LORA_FOUND              11
 | 
			
		||||
#define DTC_EEPROM_CFG_SANITY          12
 | 
			
		||||
#define DTC_EEPROM_MIGRATE_FAILED      13
 | 
			
		||||
#define DTC_FAKE_DTC_INFO              14
 | 
			
		||||
#define DTC_FAKE_DTC_WARN              15
 | 
			
		||||
#define DTC_FAKE_DTC_CRIT              16
 | 
			
		||||
#define DTC_LAST_DTC                   17
 | 
			
		||||
 | 
			
		||||
const DTC_t dtc_definitions[] = {
 | 
			
		||||
    { DTC_NO_DTC                    , DTC_NONE     }, // No Error
 | 
			
		||||
    { DTC_BAT_CRITICAL              , DTC_CRITICAL }, // Akku ist komplett leer. Den Akku aufladen!
 | 
			
		||||
    { DTC_BAT_LOW                   , DTC_WARN     }, // Akku ist unter der Warnschwelle. Den Akku demnächst aufladen
 | 
			
		||||
    { DTC_NO_EEPROM_FOUND           , DTC_CRITICAL }, // Es wurde kein EEPROM gefunden. Dies lässt einen Hardware-Defekt vermuten.
 | 
			
		||||
    { DTC_EEPROM_CFG_BAD            , DTC_CRITICAL }, // Die Checksumme der Config-Partition des EEPROM ist ungültig. Setzen sie den EEPROM-Bereich 'CFG' im Menu 'Wartung' zurück
 | 
			
		||||
    { DTC_EEPROM_PDS_BAD            , DTC_CRITICAL }, // Die Checksumme der Betriebsdaten-Partition des EEPROM ist ungültig. Setzen sie den EEPROM-Bereich 'PDS' im Menu 'Wartung' zurück
 | 
			
		||||
    { DTC_EEPROM_PDSADRESS_BAD      , DTC_CRITICAL }, // Die Adresse der Betriebsdaten-Partition im EEPROM ist ungültig. Setzen sie den EEPROM-Bereich 'PDS' im Menu 'Wartung' zurück
 | 
			
		||||
    { DTC_EEPROM_VERSION_BAD        , DTC_CRITICAL }, // Die Layout-Version des EEPROM stimmt nicht mit der Firmware-Version überein. Setzen sie den EEPROM-Bereich 'CFG' im Menu 'Wartung' zurück
 | 
			
		||||
    { DTC_FLASHFS_ERROR             , DTC_CRITICAL }, // Der Flashspeicher konnte nicht initialisiert werden. Aktualisieren sie Flash & Firmware
 | 
			
		||||
    { DTC_FLASHFS_VERSION_ERROR     , DTC_CRITICAL }, // Die Version des Flashspeicher stimmt nicht mit der Firmware-Version überein. Aktualisieren sie den Flash mit der passenden Update-Datei
 | 
			
		||||
    { DTC_NO_BATMNON_FOUND          , DTC_CRITICAL }, // Es wurde keine Akkuüberwachung über I2C gefunden, Prüfen sie die Hardware!
 | 
			
		||||
    { DTC_NO_LORA_FOUND             , DTC_CRITICAL }, // Es konnte keine Verbindung zum LoRa-Transceiver hergestellt werden. Prüfen Sie die Hardware auf Defekte
 | 
			
		||||
    { DTC_EEPROM_CFG_SANITY         , DTC_WARN     }, // Ein oder mehrer Einstellungswerte sind ausserhalb plausibler Werte. Prüfen Sie Ihre Einstellungen
 | 
			
		||||
    { DTC_EEPROM_MIGRATE_FAILED     , DTC_CRITICAL }, // Es wurde ein altes EEPROm Image erkannt, konnte aber nicht migriert werden. EEPROM manuell zurück setzen und neue Einstellunge speichern.
 | 
			
		||||
    { DTC_FAKE_DTC_INFO             , DTC_INFO     }, // Ein Dummy-DTC der Schwere "Info" für Debugging-Zwecke
 | 
			
		||||
    { DTC_FAKE_DTC_WARN             , DTC_WARN     }, // Ein Dummy-DTC der Schwere "Warnung" für Debugging-Zwecke
 | 
			
		||||
    { DTC_FAKE_DTC_CRIT             , DTC_CRITICAL }, // Ein Dummy-DTC der Schwere "Kritisch" für Debugging-Zwecke
 | 
			
		||||
    { DTC_LAST_DTC                  , DTC_NONE     }  // Last Error
 | 
			
		||||
};
 | 
			
		||||
 | 
			
		||||
#endif // DTC_DEFS_H
 | 
			
		||||
 | 
			
		||||
// CODEGENERATOR_CHECKSUM: 313d59949b074024df3c5d796f65e3bd518e34f0bb171185c30f008f21c19d30
 | 
			
		||||
							
								
								
									
										107
									
								
								Software/include/eeprom.h
									
									
									
									
									
										Normal file
									
								
							
							
						
						@@ -0,0 +1,107 @@
 | 
			
		||||
/**
 | 
			
		||||
 * @file eeprom.h
 | 
			
		||||
 *
 | 
			
		||||
 * @brief Header file for configuration settings and EEPROM operations in the DE-Timer application.
 | 
			
		||||
 *
 | 
			
		||||
 * This file defines configuration settings for the DE-Timer project, including default values,
 | 
			
		||||
 * EEPROM structures, and functions for EEPROM operations. It also defines enums for different Battery Types.
 | 
			
		||||
 * Additionally, it includes functions for EEPROM handling such as storing, retrieving, and formatting configuration data.
 | 
			
		||||
 *
 | 
			
		||||
 * @author Marcel Peterkau
 | 
			
		||||
 * @date   09.01.2024
 | 
			
		||||
 */
 | 
			
		||||
 | 
			
		||||
#ifndef _EEPROM_H_
 | 
			
		||||
#define _EEPROM_H_
 | 
			
		||||
 | 
			
		||||
#include <Arduino.h>
 | 
			
		||||
#include <Wire.h>
 | 
			
		||||
#include <I2C_eeprom.h>
 | 
			
		||||
#include "dtc.h"
 | 
			
		||||
#include "common.h"
 | 
			
		||||
 | 
			
		||||
#define I2C_EE_ADDRESS 0x50
 | 
			
		||||
#define EEPROM_STRUCTURE_REVISION 4 // Increment this version when changing EEPROM structures
 | 
			
		||||
#define EEPROM_SIZE_BYTES I2C_DEVICESIZE_24LC256
 | 
			
		||||
 | 
			
		||||
typedef enum Factions_e
 | 
			
		||||
{
 | 
			
		||||
  NONE,
 | 
			
		||||
  FACTION_1,
 | 
			
		||||
  FACTION_2,
 | 
			
		||||
  FACTION_3
 | 
			
		||||
} Factions_t;
 | 
			
		||||
 | 
			
		||||
typedef enum EERequest_e
 | 
			
		||||
{
 | 
			
		||||
  EE_IDLE,
 | 
			
		||||
  EE_CFG_SAVE,
 | 
			
		||||
  EE_CFG_LOAD,
 | 
			
		||||
  EE_CFG_FORMAT,
 | 
			
		||||
  EE_PDS_SAVE,
 | 
			
		||||
  EE_PDS_LOAD,
 | 
			
		||||
  EE_PDS_FORMAT,
 | 
			
		||||
  EE_FORMAT_ALL,
 | 
			
		||||
  EE_ALL_SAVE
 | 
			
		||||
 | 
			
		||||
} EERequest_t;
 | 
			
		||||
 | 
			
		||||
// Structure for persistence data stored in EEPROM
 | 
			
		||||
typedef struct
 | 
			
		||||
{
 | 
			
		||||
  uint32_t writeCycleCounter;
 | 
			
		||||
  uint32_t faction_1_timer;
 | 
			
		||||
  uint32_t faction_2_timer;
 | 
			
		||||
  uint32_t faction_3_timer;
 | 
			
		||||
  Factions_t activeFaction;
 | 
			
		||||
  uint32_t checksum;
 | 
			
		||||
} persistenceData_t;
 | 
			
		||||
 | 
			
		||||
// Structure for configuration settings stored in EEPROM
 | 
			
		||||
typedef struct
 | 
			
		||||
{
 | 
			
		||||
  uint8_t EEPROM_Version;
 | 
			
		||||
  batteryType_t batteryType;
 | 
			
		||||
  bool active_faction_on_reboot;
 | 
			
		||||
  char Faction_1_Name[33];
 | 
			
		||||
  char Faction_2_Name[33];
 | 
			
		||||
  char Faction_3_Name[33];
 | 
			
		||||
  char wifi_client_ssid[33];
 | 
			
		||||
  char wifi_client_password[64];
 | 
			
		||||
  bool wifi_autoconnect;
 | 
			
		||||
  uint32_t checksum;
 | 
			
		||||
} configData_t;
 | 
			
		||||
 | 
			
		||||
// Default configuration settings
 | 
			
		||||
const configData_t ConfigData_defaults = {
 | 
			
		||||
    2,               // EEPROM_Version (incerease this if anything on Layout changes!)
 | 
			
		||||
    BATTERY_LIPO_3S, // batteryType
 | 
			
		||||
    false,           // active_faction_on_reboot
 | 
			
		||||
    "FACTION 1",     // Faction_1_Name
 | 
			
		||||
    "FACTION 2",     // Faction_2_Name
 | 
			
		||||
    "FACTION 3",     // Faction_3_Name
 | 
			
		||||
    QUOTE(WIFI_SSID_CLIENT),
 | 
			
		||||
    QUOTE(WIFI_PASSWORD_CLIENT),
 | 
			
		||||
    true,
 | 
			
		||||
    0 // checksum
 | 
			
		||||
};
 | 
			
		||||
 | 
			
		||||
boolean InitEEPROM();
 | 
			
		||||
void EEPROM_Process();
 | 
			
		||||
void StoreConfig_EEPROM();
 | 
			
		||||
void GetConfig_EEPROM();
 | 
			
		||||
void StorePersistence_EEPROM();
 | 
			
		||||
void GetPersistence_EEPROM();
 | 
			
		||||
void FormatConfig_EEPROM();
 | 
			
		||||
void FormatPersistence_EEPROM();
 | 
			
		||||
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);
 | 
			
		||||
void writeSequentialToEEPROM(uint16_t memoryAddress, uint16_t length);
 | 
			
		||||
void writeZeroToEEPROM(uint16_t memoryAddress, uint16_t length);
 | 
			
		||||
 | 
			
		||||
extern configData_t ConfigData;
 | 
			
		||||
extern persistenceData_t PersistenceData;
 | 
			
		||||
extern uint16_t eePersistenceMarker;
 | 
			
		||||
#endif // _CONFIG_H_
 | 
			
		||||
							
								
								
									
										46
									
								
								Software/include/globals.h
									
									
									
									
									
										Normal file
									
								
							
							
						
						@@ -0,0 +1,46 @@
 | 
			
		||||
#ifndef _GLOBALS_H_
 | 
			
		||||
#define _GLOBALS_H_
 | 
			
		||||
 | 
			
		||||
#include <Arduino.h>
 | 
			
		||||
#include "eeprom.h"
 | 
			
		||||
#include "common.h"
 | 
			
		||||
typedef struct Globals_s
 | 
			
		||||
{
 | 
			
		||||
  tSystem_Status systemStatus = sysStat_Startup; /**< Current system status */
 | 
			
		||||
  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[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 */
 | 
			
		||||
  bool hasDTC;
 | 
			
		||||
  int loadvoltage_mV = 0;
 | 
			
		||||
  int battery_level = 0;
 | 
			
		||||
  bool timer_disabled = false;
 | 
			
		||||
  bool toggle_wifi = false;
 | 
			
		||||
} Globals_t;
 | 
			
		||||
 | 
			
		||||
extern Globals_t globals; /**< Global variable struct */
 | 
			
		||||
 | 
			
		||||
typedef struct Constants_s
 | 
			
		||||
{
 | 
			
		||||
  uint8_t FW_Version_major;             /**< Firmware version major number */
 | 
			
		||||
  uint8_t FW_Version_minor;             /**< Firmware version minor number */
 | 
			
		||||
  uint8_t Required_Flash_Version_major; /**< Required flash version major number */
 | 
			
		||||
  uint8_t Required_Flash_Version_minor; /**< Required flash version minor number */
 | 
			
		||||
  char GitHash[11];                     /**< Git hash string */
 | 
			
		||||
} Constants_t;
 | 
			
		||||
 | 
			
		||||
const Constants_t constants PROGMEM = {
 | 
			
		||||
    FW_MAJOR, FW_MINOR,   // Firmware_Version
 | 
			
		||||
    FL_MAJOR, FL_MINOR,   // Required Flash Version
 | 
			
		||||
    GIT_REV // Git-Hash-String
 | 
			
		||||
};
 | 
			
		||||
 | 
			
		||||
/**
 | 
			
		||||
 * @brief Initializes global variables.
 | 
			
		||||
 */
 | 
			
		||||
void initGlobals();
 | 
			
		||||
 | 
			
		||||
#endif // _GLOBALS_H_
 | 
			
		||||
							
								
								
									
										27
									
								
								Software/include/lora_net.h
									
									
									
									
									
										Normal file
									
								
							
							
						
						@@ -0,0 +1,27 @@
 | 
			
		||||
#ifndef _LORA_NET_H_
 | 
			
		||||
#define _LORA_NET_H_
 | 
			
		||||
 | 
			
		||||
#include <Arduino.h>
 | 
			
		||||
 | 
			
		||||
#ifdef LORA_FEATURE_ENABLED
 | 
			
		||||
#include <LoRa_E220.h>
 | 
			
		||||
#elif defined(FEATURE_ENABLE_UARTLORA)
 | 
			
		||||
#include <SoftwareSerial.h>
 | 
			
		||||
#endif
 | 
			
		||||
 | 
			
		||||
// local includes
 | 
			
		||||
#include "lora_messages.h"
 | 
			
		||||
#include "debugger.h"
 | 
			
		||||
#include "defaults.h"
 | 
			
		||||
#include "config.h"
 | 
			
		||||
#include "globals.h"
 | 
			
		||||
#include "dtc.h"
 | 
			
		||||
#include "common.h"
 | 
			
		||||
 | 
			
		||||
#define FREQUENCY_868
 | 
			
		||||
 | 
			
		||||
bool InitLoRa(void (*MPinHelper)(int, int));
 | 
			
		||||
void LoRa_Process();
 | 
			
		||||
void sendStatus_LoRa();
 | 
			
		||||
 | 
			
		||||
#endif
 | 
			
		||||
							
								
								
									
										75
									
								
								Software/include/sanitycheck.h
									
									
									
									
									
										Normal file
									
								
							
							
						
						@@ -0,0 +1,75 @@
 | 
			
		||||
#ifndef _SANITYCHECK_H_
 | 
			
		||||
#define _SANITYCHECK_H_
 | 
			
		||||
 | 
			
		||||
// Utility macros for handling quotes
 | 
			
		||||
#define Q(x) #x
 | 
			
		||||
#define QUOTE(x) Q(x)
 | 
			
		||||
 | 
			
		||||
// Utility macros for checking string lengths
 | 
			
		||||
#define STRING_LENGTH_CHECK(str, max_length) (sizeof(str) <= (max_length) + 1)
 | 
			
		||||
#define IS_ALPHANUMERIC(c) ((((c) >= '0') && ((c) <= '9')) || (((c) >= 'A') && ((c) <= 'Z')) || (((c) >= 'a') && ((c) <= 'z')))
 | 
			
		||||
#define IS_PRINTABLE_ASCII(c) ((c) >= 32 && (c) <= 126)
 | 
			
		||||
#define IS_VALID_WIFI_CHAR(c) (IS_PRINTABLE_ASCII(c))
 | 
			
		||||
#define IS_ALPHANUMERIC_HELPER(str, i) (i >= sizeof(str) - 1 || IS_ALPHANUMERIC(str[i]))
 | 
			
		||||
#define IS_PRINTABLE_ASCII_HELPER(str, i) (i >= sizeof(str) - 1 || IS_PRINTABLE_ASCII(str[i]))
 | 
			
		||||
#define IS_VALID_WIFI_CHAR_HELPER(str, i) (i >= sizeof(str) - 1 || IS_VALID_WIFI_CHAR(str[i]))
 | 
			
		||||
#define IS_ALPHANUMERIC_IMPL(str, i) (IS_ALPHANUMERIC_HELPER(str, i) && IS_ALPHANUMERIC_HELPER(str, i+1) && IS_ALPHANUMERIC_HELPER(str, i+2) && IS_ALPHANUMERIC_HELPER(str, i+3) && IS_ALPHANUMERIC_HELPER(str, i+4) && IS_ALPHANUMERIC_HELPER(str, i+5) && IS_ALPHANUMERIC_HELPER(str, i+6) && IS_ALPHANUMERIC_HELPER(str, i+7) && IS_ALPHANUMERIC_HELPER(str, i+8) && IS_ALPHANUMERIC_HELPER(str, i+9) && IS_ALPHANUMERIC_HELPER(str, i+10) && IS_ALPHANUMERIC_HELPER(str, i+11) && IS_ALPHANUMERIC_HELPER(str, i+12) && IS_ALPHANUMERIC_HELPER(str, i+13) && IS_ALPHANUMERIC_HELPER(str, i+14) && IS_ALPHANUMERIC_HELPER(str, i+15) && IS_ALPHANUMERIC_HELPER(str, i+16))
 | 
			
		||||
#define IS_PRINTABLE_ASCII_IMPL(str, i) (IS_PRINTABLE_ASCII_HELPER(str, i) && IS_PRINTABLE_ASCII_HELPER(str, i+1) && IS_PRINTABLE_ASCII_HELPER(str, i+2) && IS_PRINTABLE_ASCII_HELPER(str, i+3) && IS_PRINTABLE_ASCII_HELPER(str, i+4) && IS_PRINTABLE_ASCII_HELPER(str, i+5) && IS_PRINTABLE_ASCII_HELPER(str, i+6) && IS_PRINTABLE_ASCII_HELPER(str, i+7) && IS_PRINTABLE_ASCII_HELPER(str, i+8) && IS_PRINTABLE_ASCII_HELPER(str, i+9) && IS_PRINTABLE_ASCII_HELPER(str, i+10) && IS_PRINTABLE_ASCII_HELPER(str, i+11) && IS_PRINTABLE_ASCII_HELPER(str, i+12) && IS_PRINTABLE_ASCII_HELPER(str, i+13) && IS_PRINTABLE_ASCII_HELPER(str, i+14) && IS_PRINTABLE_ASCII_HELPER(str, i+15) && IS_PRINTABLE_ASCII_HELPER(str, i+16) && IS_PRINTABLE_ASCII_HELPER(str, i+17) && IS_PRINTABLE_ASCII_HELPER(str, i+18) && IS_PRINTABLE_ASCII_HELPER(str, i+19) && IS_PRINTABLE_ASCII_HELPER(str, i+20) && IS_PRINTABLE_ASCII_HELPER(str, i+21) && IS_PRINTABLE_ASCII_HELPER(str, i+22) && IS_PRINTABLE_ASCII_HELPER(str, i+23) && IS_PRINTABLE_ASCII_HELPER(str, i+24))
 | 
			
		||||
#define IS_ALPHANUMERIC_STRING(str) (IS_ALPHANUMERIC_IMPL(str, 0))
 | 
			
		||||
#define IS_PRINTABLE_ASCII_STRING(str) (IS_PRINTABLE_ASCII_IMPL(str, 0))
 | 
			
		||||
#define IS_VALID_WIFI_STRING(str) (IS_VALID_WIFI_CHAR_HELPER(str, 0) && IS_VALID_WIFI_CHAR_HELPER(str, 1) && IS_VALID_WIFI_CHAR_HELPER(str, 2) && IS_VALID_WIFI_CHAR_HELPER(str, 3) && IS_VALID_WIFI_CHAR_HELPER(str, 4) && IS_VALID_WIFI_CHAR_HELPER(str, 5) && IS_VALID_WIFI_CHAR_HELPER(str, 6) && IS_VALID_WIFI_CHAR_HELPER(str, 7) && IS_VALID_WIFI_CHAR_HELPER(str, 8) && IS_VALID_WIFI_CHAR_HELPER(str, 9) && IS_VALID_WIFI_CHAR_HELPER(str, 10) && IS_VALID_WIFI_CHAR_HELPER(str, 11) && IS_VALID_WIFI_CHAR_HELPER(str, 12) && IS_VALID_WIFI_CHAR_HELPER(str, 13) && IS_VALID_WIFI_CHAR_HELPER(str, 14) && IS_VALID_WIFI_CHAR_HELPER(str, 15) && IS_VALID_WIFI_CHAR_HELPER(str, 16) && IS_VALID_WIFI_CHAR_HELPER(str, 17) && IS_VALID_WIFI_CHAR_HELPER(str, 18) && IS_VALID_WIFI_CHAR_HELPER(str, 19) && IS_VALID_WIFI_CHAR_HELPER(str, 20) && IS_VALID_WIFI_CHAR_HELPER(str, 21) && IS_VALID_WIFI_CHAR_HELPER(str, 22) && IS_VALID_WIFI_CHAR_HELPER(str, 23) && IS_VALID_WIFI_CHAR_HELPER(str, 24) && IS_VALID_WIFI_CHAR_HELPER(str, 25) && IS_VALID_WIFI_CHAR_HELPER(str, 26) && IS_VALID_WIFI_CHAR_HELPER(str, 27) && IS_VALID_WIFI_CHAR_HELPER(str, 28) && IS_VALID_WIFI_CHAR_HELPER(str, 29) && IS_VALID_WIFI_CHAR_HELPER(str, 30) && IS_VALID_WIFI_CHAR_HELPER(str, 31) && IS_VALID_WIFI_CHAR_HELPER(str, 32))
 | 
			
		||||
 | 
			
		||||
// ADMIN_PASSWORD check
 | 
			
		||||
#ifndef ADMIN_PASSWORD
 | 
			
		||||
    #error "You need to define ADMIN_PASSWORD for OTA-Update"
 | 
			
		||||
#else
 | 
			
		||||
    _Static_assert(STRING_LENGTH_CHECK(QUOTE(ADMIN_PASSWORD), 16), "ADMIN_PASSWORD must be at most 16 characters long");
 | 
			
		||||
#endif
 | 
			
		||||
 | 
			
		||||
// WIFI_AP_SSID check
 | 
			
		||||
#ifndef WIFI_AP_SSID
 | 
			
		||||
    #warning "No WIFI_AP_SSID defined. Using DeviceName"
 | 
			
		||||
    #define WIFI_AP_SSID DEVICE_NAME
 | 
			
		||||
#else
 | 
			
		||||
    _Static_assert(STRING_LENGTH_CHECK(QUOTE(WIFI_AP_SSID), 32), "WIFI_AP_SSID must be at most 32 characters long");
 | 
			
		||||
    _Static_assert(IS_VALID_WIFI_STRING(QUOTE(WIFI_AP_SSID)), "WIFI_AP_SSID must contain only valid WiFi characters");
 | 
			
		||||
#endif
 | 
			
		||||
 | 
			
		||||
// WIFI_PASS_SEED check
 | 
			
		||||
#ifndef WIFI_PASS_SEED
 | 
			
		||||
    #error "You must define an WIFI_PASS_SEED for Standalone AP-Mode"
 | 
			
		||||
#else
 | 
			
		||||
    _Static_assert(STRING_LENGTH_CHECK(QUOTE(WIFI_PASS_SEED), 16), "WIFI_PASS_SEED must be at most 16 characters long");
 | 
			
		||||
    _Static_assert(IS_ALPHANUMERIC_STRING(QUOTE(WIFI_PASS_SEED)), "WIFI_PASS_SEED must contain only alphanumeric characters (a-z, A-Z, 0-9)");
 | 
			
		||||
#endif
 | 
			
		||||
 | 
			
		||||
// DEVICE_NAME check
 | 
			
		||||
#ifndef DEVICE_NAME
 | 
			
		||||
    #error "You must define DEVICE_NAME"
 | 
			
		||||
#else
 | 
			
		||||
    _Static_assert(STRING_LENGTH_CHECK(QUOTE(DEVICE_NAME), 24), "DEVICE_NAME must be at most 24 characters long");
 | 
			
		||||
    _Static_assert(IS_VALID_WIFI_STRING(QUOTE(DEVICE_NAME)), "DEVICE_NAME must contain only valid WiFi characters");
 | 
			
		||||
#endif
 | 
			
		||||
 | 
			
		||||
// Mutual exclusion check for LoRa features
 | 
			
		||||
#if defined(FEATURE_ENABLE_UARTLORA) && defined(FEATURE_ENABLE_LORA)
 | 
			
		||||
    #error "You cannot enable LoRa and UART-Protocol at the same time!"
 | 
			
		||||
#endif
 | 
			
		||||
 | 
			
		||||
// WIFI_CLIENT checks
 | 
			
		||||
#ifdef FEATURE_ENABLE_WIFI_CLIENT
 | 
			
		||||
    #ifndef WIFI_PASSWORD_CLIENT
 | 
			
		||||
        #error "You must define an WIFI_PASSWORD_CLIENT for OTA-Update"
 | 
			
		||||
    #else
 | 
			
		||||
        _Static_assert(STRING_LENGTH_CHECK(QUOTE(WIFI_PASSWORD_CLIENT), 63), "WIFI_PASSWORD_CLIENT must be at most 63 characters long");
 | 
			
		||||
    #endif
 | 
			
		||||
 | 
			
		||||
    #ifndef WIFI_SSID_CLIENT
 | 
			
		||||
        #error "You must define an WIFI_SSID_CLIENT for OTA-Update"
 | 
			
		||||
    #else
 | 
			
		||||
        _Static_assert(STRING_LENGTH_CHECK(QUOTE(WIFI_SSID_CLIENT), 32), "WIFI_SSID_CLIENT must be at most 32 characters long");
 | 
			
		||||
        _Static_assert(IS_VALID_WIFI_STRING(QUOTE(WIFI_SSID_CLIENT)), "WIFI_SSID_CLIENT must contain only valid WiFi characters");
 | 
			
		||||
    #endif
 | 
			
		||||
#endif
 | 
			
		||||
 | 
			
		||||
#endif // _SANITYCHECK_H_
 | 
			
		||||
							
								
								
									
										26
									
								
								Software/include/struct2json.h
									
									
									
									
									
										Normal file
									
								
							
							
						
						@@ -0,0 +1,26 @@
 | 
			
		||||
/**
 | 
			
		||||
 * @file struct2json.h
 | 
			
		||||
 *
 | 
			
		||||
 * @brief Header file for converting structs to JSON objects.
 | 
			
		||||
 *
 | 
			
		||||
 * @note This file is auto-generated by a script on 2024-06-06 18:52:33.
 | 
			
		||||
 *
 | 
			
		||||
 * @author Marcel Peterkau
 | 
			
		||||
 * @date   06.06.2024
 | 
			
		||||
 */
 | 
			
		||||
 | 
			
		||||
#ifndef _STRUCT2JSON_H_
 | 
			
		||||
#define _STRUCT2JSON_H_
 | 
			
		||||
 | 
			
		||||
#include <Arduino.h>
 | 
			
		||||
#include <ArduinoJson.h>
 | 
			
		||||
 | 
			
		||||
#include "eeprom.h"
 | 
			
		||||
 | 
			
		||||
void generateJsonObject_ConfigData(JsonObject data);
 | 
			
		||||
void generateJsonObject_PersistenceData(JsonObject data);
 | 
			
		||||
 | 
			
		||||
 | 
			
		||||
#endif /* _STRUCT2JSON_H_ */
 | 
			
		||||
 | 
			
		||||
// CODEGENERATOR_CHECKSUM: 3a3fd3024dd9dd769ff5d62f61b3ba1b781b7d06e7568a1ddac56d193dba9ee5
 | 
			
		||||
							
								
								
									
										48
									
								
								Software/include/utilities.h
									
									
									
									
									
										Normal file
									
								
							
							
						
						@@ -0,0 +1,48 @@
 | 
			
		||||
#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);
 | 
			
		||||
 | 
			
		||||
/**
 | 
			
		||||
 * @brief Generates a device-specific password based on a seed and the ESP8266 Chip ID.
 | 
			
		||||
 *
 | 
			
		||||
 * This function combines a given seed with the unique Chip ID of the ESP8266 device to create a device-specific password.
 | 
			
		||||
 * The resulting password is stored in the provided character buffer.
 | 
			
		||||
 *
 | 
			
		||||
 * @param seed The seed string used for password generation. Should be up to 16 characters long.
 | 
			
		||||
 * @param passwordBuffer The character buffer where the generated password will be stored.
 | 
			
		||||
 * @param bufferLength The length of the password buffer. Should be large enough to hold the generated password and null terminator.
 | 
			
		||||
 */
 | 
			
		||||
void GenerateDeviceSpecificPassword(const char* seed, char* passwordBuffer, size_t bufferLength);
 | 
			
		||||
 | 
			
		||||
#endif // UTILITIES_H
 | 
			
		||||
							
								
								
									
										49
									
								
								Software/include/webui.h
									
									
									
									
									
										Normal file
									
								
							
							
						
						@@ -0,0 +1,49 @@
 | 
			
		||||
/**
 | 
			
		||||
 * @file webui.h
 | 
			
		||||
 *
 | 
			
		||||
 * @brief Header file for the web-based user interface (WebUI) in the DE-Timer application.
 | 
			
		||||
 *
 | 
			
		||||
 * This file contains declarations for functions related to the initialization and processing of the
 | 
			
		||||
 * web-based user interface (WebUI). It includes the necessary libraries and dependencies for handling
 | 
			
		||||
 * web server functionality, asynchronous JSON operations, and live debugging through WebSockets.
 | 
			
		||||
 *
 | 
			
		||||
 * @author Marcel Peterkau
 | 
			
		||||
 * @date   09.01.2024
 | 
			
		||||
 */
 | 
			
		||||
 | 
			
		||||
#ifndef _WEBUI_H_
 | 
			
		||||
#define _WEBUI_H_
 | 
			
		||||
 | 
			
		||||
#include <Arduino.h>
 | 
			
		||||
#include <FS.h>
 | 
			
		||||
#include <LittleFS.h>
 | 
			
		||||
#include <ESPAsyncTCP.h>
 | 
			
		||||
#include <ESPAsyncWebServer.h>
 | 
			
		||||
#include <Updater.h>
 | 
			
		||||
#include <ESP8266mDNS.h>
 | 
			
		||||
#include <AsyncJson.h>
 | 
			
		||||
#include <ArduinoJson.h>
 | 
			
		||||
 | 
			
		||||
#include "config.h"
 | 
			
		||||
#include "globals.h"
 | 
			
		||||
#include "dtc.h"
 | 
			
		||||
#include "common.h"
 | 
			
		||||
#include "debugger.h"
 | 
			
		||||
#include "struct2json.h"
 | 
			
		||||
 | 
			
		||||
typedef enum
 | 
			
		||||
{
 | 
			
		||||
    info,
 | 
			
		||||
    success,
 | 
			
		||||
    warning,
 | 
			
		||||
    error
 | 
			
		||||
} NotificationType_t;
 | 
			
		||||
 | 
			
		||||
void initWebUI();
 | 
			
		||||
void Webserver_Process();
 | 
			
		||||
void Webserver_Shutdown();
 | 
			
		||||
 | 
			
		||||
void Websocket_PushLiveDebug(String Message);
 | 
			
		||||
void Websocket_PushNotification(String Message, NotificationType_t type);
 | 
			
		||||
 | 
			
		||||
#endif // _WEBUI_H_
 | 
			
		||||
@@ -274,7 +274,7 @@ bool LoRa_E220::begin(){
 | 
			
		||||
 | 
			
		||||
    this->serialDef.stream->setTimeout(100);
 | 
			
		||||
    Status status = setMode(MODE_0_NORMAL);
 | 
			
		||||
    return status==E220_SUCCESS;
 | 
			
		||||
    return status;
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
/*
 | 
			
		||||
 
 | 
			
		||||
							
								
								
									
										9
									
								
								Software/package.json
									
									
									
									
									
										Normal file
									
								
							
							
						
						@@ -0,0 +1,9 @@
 | 
			
		||||
{
 | 
			
		||||
  "name": "pio-build-tools",
 | 
			
		||||
  "private": true,
 | 
			
		||||
  "devDependencies": {
 | 
			
		||||
    "html-minifier": "^4.0.0",
 | 
			
		||||
    "terser": "^5.0.0",
 | 
			
		||||
    "clean-css-cli": "^5.0.0"
 | 
			
		||||
  }
 | 
			
		||||
}
 | 
			
		||||
@@ -17,45 +17,48 @@ platform = espressif8266
 | 
			
		||||
framework = arduino
 | 
			
		||||
board = d1_mini
 | 
			
		||||
 | 
			
		||||
custom_firmware_version = 1.09
 | 
			
		||||
custom_flash_version = 1.09
 | 
			
		||||
 | 
			
		||||
upload_protocol = esptool
 | 
			
		||||
upload_speed = 921600
 | 
			
		||||
;upload_port = 10.0.1.48
 | 
			
		||||
;upload_protocol = espota
 | 
			
		||||
;upload_flags =  
 | 
			
		||||
;   --auth=${wifi_cred.admin_password}
 | 
			
		||||
;upload_port = 10.0.0.1
 | 
			
		||||
;upload_flags =
 | 
			
		||||
;  --port=8266
 | 
			
		||||
;  --auth=${wifi_cred.admin_password}
 | 
			
		||||
 | 
			
		||||
build_flags=
 | 
			
		||||
  !python git_rev_macro.py
 | 
			
		||||
  ;-DSERIAL_DEBUG
 | 
			
		||||
  ;-DWIFI_CLIENT
 | 
			
		||||
  ;-DCAPTIVE
 | 
			
		||||
  -DWIFI_AP_IP_GW=10,0,1,1
 | 
			
		||||
  -DATOMIC_FS_UPDATE
 | 
			
		||||
  ;-DFEATURE_ENABLE_WIFI_CLIENT
 | 
			
		||||
  ;-DFEATURE_ENABLE_LORA
 | 
			
		||||
  -DFEATURE_ENABLE_UARTLORA
 | 
			
		||||
  -DWIFI_AP_IP_GW=10,0,0,1
 | 
			
		||||
  -DADMIN_PASSWORD=${wifi_cred.admin_password}
 | 
			
		||||
  -DWIFI_SSID=${wifi_cred.wifi_ssid}
 | 
			
		||||
  -DWIFI_PASSWORD=${wifi_cred.wifi_password}
 | 
			
		||||
  -DWIFI_AP_PASSWORD=${wifi_cred.wifi_ap_password}
 | 
			
		||||
  -DWIFI_SSID_CLIENT=${wifi_cred.wifi_ssid_client}
 | 
			
		||||
  -DWIFI_PASSWORD_CLIENT=${wifi_cred.wifi_password_client}
 | 
			
		||||
  -DWIFI_PASS_SEED=${wifi_cred.wifi_pass_seed}
 | 
			
		||||
  -DDEVICE_NAME='"Dark Emergency Timer"'
 | 
			
		||||
  -DFACTION_1_NAME='"GOF"'
 | 
			
		||||
  -DFACTION_2_NAME='"MILIZ"'
 | 
			
		||||
  -DFACTION_3_NAME='"KGG"'
 | 
			
		||||
 | 
			
		||||
;build_type = debug
 | 
			
		||||
 | 
			
		||||
board_build.filesystem = littlefs
 | 
			
		||||
board_build.ldscript = eagle.flash.4m1m.ld
 | 
			
		||||
extra_scripts = post:prepare_littlefs.py
 | 
			
		||||
extra_scripts = 
 | 
			
		||||
  post:codegen/prepare_littlefs.py
 | 
			
		||||
  pre:codegen/run_pre.py
 | 
			
		||||
 | 
			
		||||
monitor_filters = esp8266_exception_decoder
 | 
			
		||||
monitor_speed = 115200
 | 
			
		||||
 | 
			
		||||
lib_ldf_mode = deep
 | 
			
		||||
lib_deps = 
 | 
			
		||||
	;xreef/EByte LoRa E220 library@^1.0.6   ; made Lib local, due to changes for I2C-controller M0,M1-Pins
 | 
			
		||||
	sstaub/Ticker@^4.4.0
 | 
			
		||||
  robtillaart/PCF8574 @ ^0.3.7
 | 
			
		||||
	adafruit/Adafruit INA219 @ ^1.1.1
 | 
			
		||||
  plerup/EspSoftwareSerial @ 6.8.5        ; needed exactly this Version as newer ones have Problems with compiling
 | 
			
		||||
  akj7/TM1637 Driver @ ^2.1.2
 | 
			
		||||
  me-no-dev/ESPAsyncTCP @ ^1.2.2
 | 
			
		||||
  robtillaart/I2C_EEPROM @ ^1.5.2
 | 
			
		||||
  sstaub/Ticker @ ^4.4.0
 | 
			
		||||
  robtillaart/I2C_EEPROM @ ^1.8.2
 | 
			
		||||
  esphome/ESPAsyncWebServer-esphome @ ^3.2.2
 | 
			
		||||
  sandeepmistry/LoRa @ ^0.8.0
 | 
			
		||||
  bblanchon/ArduinoJson @ ^6.19.4
 | 
			
		||||
  bblanchon/ArduinoJson @ ^7.0.4
 | 
			
		||||
@@ -1,116 +0,0 @@
 | 
			
		||||
# SCRIPT TO GZIP CRITICAL FILES FOR ACCELERATED WEBSERVING
 | 
			
		||||
# see also https://community.platformio.org/t/question-esp32-compress-files-in-data-to-gzip-before-upload-possible-to-spiffs/6274/10
 | 
			
		||||
 | 
			
		||||
 | 
			
		||||
import glob
 | 
			
		||||
import shutil
 | 
			
		||||
import gzip
 | 
			
		||||
import os
 | 
			
		||||
Import("env")
 | 
			
		||||
Import("projenv")
 | 
			
		||||
 | 
			
		||||
 | 
			
		||||
def gzip_file(src_path, dst_path):
 | 
			
		||||
 | 
			
		||||
    with open(src_path, 'rb') as src, gzip.open(dst_path, 'wb') as dst:
 | 
			
		||||
        for chunk in iter(lambda: src.read(4096), b""):
 | 
			
		||||
            dst.write(chunk)
 | 
			
		||||
 | 
			
		||||
 | 
			
		||||
def getListOfFiles(dirName):
 | 
			
		||||
    # create a list of file and sub directories
 | 
			
		||||
    # names in the given directory
 | 
			
		||||
    listOfFile = os.listdir(dirName)
 | 
			
		||||
    allFiles = list()
 | 
			
		||||
    # Iterate over all the entries
 | 
			
		||||
    for entry in listOfFile:
 | 
			
		||||
        # Create full path
 | 
			
		||||
        fullPath = os.path.join(dirName, entry)
 | 
			
		||||
        # If entry is a directory then get the list of files in this directory
 | 
			
		||||
        if os.path.isdir(fullPath):
 | 
			
		||||
            allFiles = allFiles + getListOfFiles(fullPath)
 | 
			
		||||
        else:
 | 
			
		||||
            allFiles.append(fullPath)
 | 
			
		||||
 | 
			
		||||
    return allFiles
 | 
			
		||||
 | 
			
		||||
def remove_prefix(text, prefix):
 | 
			
		||||
    if text.startswith(prefix):
 | 
			
		||||
        return text[len(prefix):]
 | 
			
		||||
    return text  # or whatever
 | 
			
		||||
 | 
			
		||||
# Compress files from 'data_src/' to 'data/'
 | 
			
		||||
 | 
			
		||||
 | 
			
		||||
def gzip_webfiles(source, target, env):
 | 
			
		||||
    # Filetypes to compress
 | 
			
		||||
    filetypes_to_gzip = ['.css', '.png', '.js', '.ico', '.woff2', '.json']
 | 
			
		||||
    print('\nGZIP: Starting gzip-Process for LittleFS-Image...\n')
 | 
			
		||||
    data_src_dir_path = os.path.join(env.get('PROJECT_DIR'), 'data_src')
 | 
			
		||||
    data_dir_path = env.get('PROJECT_DATA_DIR')
 | 
			
		||||
    # check if data and datasrc exist. If the first exists and not the second, it renames it
 | 
			
		||||
    if(os.path.exists(data_dir_path) and not os.path.exists(data_src_dir_path)):
 | 
			
		||||
        print('GZIP: Directory "'+data_dir_path +
 | 
			
		||||
              '" exists, "'+data_src_dir_path+'" is not found.')
 | 
			
		||||
        print('GZIP: Renaming "' + data_dir_path +
 | 
			
		||||
              '" to "' + data_src_dir_path + '"')
 | 
			
		||||
        os.rename(data_dir_path, data_src_dir_path)
 | 
			
		||||
    # Delete the 'data' directory
 | 
			
		||||
    if(os.path.exists(data_dir_path)):
 | 
			
		||||
        print('GZIP: Deleting the "data" directory ' + data_dir_path)
 | 
			
		||||
        shutil.rmtree(data_dir_path)
 | 
			
		||||
    # Recreate empty 'data' directory
 | 
			
		||||
    print('GZIP: Re-creating an empty data directory ' + data_dir_path)
 | 
			
		||||
    os.mkdir(data_dir_path)
 | 
			
		||||
    # Determine the files to compress
 | 
			
		||||
 | 
			
		||||
    files_to_copy = []
 | 
			
		||||
    files_to_gzip = []
 | 
			
		||||
 | 
			
		||||
    all_data_src = getListOfFiles(data_src_dir_path)
 | 
			
		||||
    for file in all_data_src:
 | 
			
		||||
        file_name, file_extension = os.path.splitext(file)
 | 
			
		||||
        print(file_name + " has filetype " + file_extension)
 | 
			
		||||
        if file_extension in filetypes_to_gzip:
 | 
			
		||||
            files_to_gzip.append(file)
 | 
			
		||||
        else:
 | 
			
		||||
            filename_subdir = remove_prefix(file, data_src_dir_path)
 | 
			
		||||
            files_to_copy.append(filename_subdir)
 | 
			
		||||
 | 
			
		||||
    for file in files_to_copy:
 | 
			
		||||
        print('GZIP: Copying file from: ' + data_src_dir_path + file + ' to: ' + data_dir_path + file)
 | 
			
		||||
        os.makedirs(os.path.dirname(data_dir_path + file), exist_ok=True)
 | 
			
		||||
        shutil.copy(data_src_dir_path + file, data_dir_path + file)
 | 
			
		||||
    # Compress and move files
 | 
			
		||||
    
 | 
			
		||||
    was_error = False
 | 
			
		||||
    try:
 | 
			
		||||
        for source_file_path in files_to_gzip:
 | 
			
		||||
            print('GZIP: compressing... ' + source_file_path)
 | 
			
		||||
            filename_subdir = remove_prefix(source_file_path, data_src_dir_path)
 | 
			
		||||
            target_file_path = data_dir_path + filename_subdir
 | 
			
		||||
            os.makedirs(os.path.dirname(target_file_path), exist_ok=True)
 | 
			
		||||
            print('GZIP: Compressed... ' + target_file_path)
 | 
			
		||||
            gzip_file(source_file_path, target_file_path + ".gz")
 | 
			
		||||
    except IOError as e:
 | 
			
		||||
        was_error = True
 | 
			
		||||
        print('GZIP: Failed to compress file: ' + source_file_path)
 | 
			
		||||
        # print( 'GZIP: EXCEPTION... {}'.format( e ) )
 | 
			
		||||
    if was_error:
 | 
			
		||||
        print('GZIP: Failure/Incomplete.\n')
 | 
			
		||||
    else:
 | 
			
		||||
        print('GZIP: Compressed correctly.\n')
 | 
			
		||||
 | 
			
		||||
    return
 | 
			
		||||
 
 | 
			
		||||
def gzip_binffiles(source, target, env):
 | 
			
		||||
    littlefsbin = target[0].get_abspath()
 | 
			
		||||
    targetbin = os.path.join(os.path.dirname(littlefsbin), 'filesystem.fs')
 | 
			
		||||
    shutil.copyfile(littlefsbin, targetbin)
 | 
			
		||||
    gzip_file(targetbin, os.path.join(str(targetbin) + '.gz'))
 | 
			
		||||
    os.remove(targetbin)
 | 
			
		||||
    return
 | 
			
		||||
 | 
			
		||||
# IMPORTANT, this needs to be added to call the routine
 | 
			
		||||
env.AddPreAction('$BUILD_DIR/littlefs.bin', gzip_webfiles)
 | 
			
		||||
env.AddPostAction('$BUILD_DIR/littlefs.bin', gzip_binffiles)
 | 
			
		||||
							
								
								
									
										9
									
								
								Software/src/common.cpp
									
									
									
									
									
										Normal file
									
								
							
							
						
						@@ -0,0 +1,9 @@
 | 
			
		||||
#include "common.h"
 | 
			
		||||
 | 
			
		||||
const char *BatteryString[] = {
 | 
			
		||||
    "Undefined",
 | 
			
		||||
    "LiPo 2S",
 | 
			
		||||
    "LiPo 3S"
 | 
			
		||||
    };
 | 
			
		||||
 | 
			
		||||
const size_t BatteryString_Elements = sizeof(BatteryString) / sizeof(BatteryString[0]);
 | 
			
		||||
@@ -1,261 +0,0 @@
 | 
			
		||||
#include "config.h"
 | 
			
		||||
 | 
			
		||||
I2C_eeprom ee(0x50, EEPROM_SIZE_BYTES);
 | 
			
		||||
 | 
			
		||||
configData_t ConfigData;
 | 
			
		||||
persistenceData_t PersistenceData;
 | 
			
		||||
const uint16_t eeVersion = 1; // inc
 | 
			
		||||
boolean eeAvailable = false;
 | 
			
		||||
 | 
			
		||||
const uint16_t persistencemarker_Adress = 0; // sizeof 4
 | 
			
		||||
const uint16_t startofConfig_Adress = 16;
 | 
			
		||||
const uint16_t startofPersistence_Adress = startofConfig_Adress + sizeof(ConfigData) + (sizeof(ConfigData) % 16);
 | 
			
		||||
 | 
			
		||||
boolean checkEEPROMavailable();
 | 
			
		||||
 | 
			
		||||
void InitEEPROM()
 | 
			
		||||
{
 | 
			
		||||
  ee.begin();
 | 
			
		||||
  if (!checkEEPROMavailable())
 | 
			
		||||
  {
 | 
			
		||||
    globals.systemStatus = sysStat_Error;
 | 
			
		||||
    MaintainDTC(DTC_NO_EEPROM_FOUND, true);
 | 
			
		||||
    return;
 | 
			
		||||
  }
 | 
			
		||||
  GetConfig_EEPROM();
 | 
			
		||||
 | 
			
		||||
  if (ConfigData.EEPROM_Version != eeVersion)
 | 
			
		||||
  {
 | 
			
		||||
    FormatConfig_EEPROM();
 | 
			
		||||
    globals.systemStatus = sysStat_Error;
 | 
			
		||||
    MaintainDTC(DTC_EEPROM_VERSION_BAD, true);
 | 
			
		||||
    return;
 | 
			
		||||
  }
 | 
			
		||||
 | 
			
		||||
  if (getPersistanceAddress() > ee.getDeviceSize())
 | 
			
		||||
  {
 | 
			
		||||
    FormatPersistence_EEPROM();
 | 
			
		||||
    globals.systemStatus = sysStat_Error;
 | 
			
		||||
    MaintainDTC(DTC_EEPROM_PDS_MARKER_INVALID, true);
 | 
			
		||||
    return;
 | 
			
		||||
  }
 | 
			
		||||
  GetPersistence_EEPROM();
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
void EEPROM_Process()
 | 
			
		||||
{
 | 
			
		||||
 | 
			
		||||
  switch (globals.requestEEAction)
 | 
			
		||||
  {
 | 
			
		||||
  case EE_CFG_SAVE:
 | 
			
		||||
    StoreConfig_EEPROM();
 | 
			
		||||
    globals.requestEEAction = EE_IDLE;
 | 
			
		||||
    break;
 | 
			
		||||
  case EE_CFG_LOAD:
 | 
			
		||||
    GetConfig_EEPROM();
 | 
			
		||||
    globals.requestEEAction = EE_IDLE;
 | 
			
		||||
    break;
 | 
			
		||||
  case EE_PDS_SAVE:
 | 
			
		||||
    StorePersistence_EEPROM();
 | 
			
		||||
    globals.requestEEAction = EE_IDLE;
 | 
			
		||||
    break;
 | 
			
		||||
  case EE_PDS_LOAD:
 | 
			
		||||
    GetPersistence_EEPROM();
 | 
			
		||||
    globals.requestEEAction = EE_IDLE;
 | 
			
		||||
    break;
 | 
			
		||||
  case EE_IDLE:
 | 
			
		||||
  default:
 | 
			
		||||
    globals.requestEEAction = EE_IDLE;
 | 
			
		||||
  }
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
void StoreConfig_EEPROM()
 | 
			
		||||
{
 | 
			
		||||
  ConfigData.checksum = 0;
 | 
			
		||||
  ConfigData.checksum = Checksum_EEPROM((uint8_t *)&ConfigData, sizeof(ConfigData));
 | 
			
		||||
  if (!checkEEPROMavailable())
 | 
			
		||||
    return;
 | 
			
		||||
 | 
			
		||||
  ee.updateBlock(startofConfig_Adress, (uint8_t *)&ConfigData, sizeof(ConfigData));
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
void GetConfig_EEPROM()
 | 
			
		||||
{
 | 
			
		||||
  if (!checkEEPROMavailable())
 | 
			
		||||
    return;
 | 
			
		||||
 | 
			
		||||
  ee.readBlock(startofConfig_Adress, (uint8_t *)&ConfigData, sizeof(ConfigData));
 | 
			
		||||
 | 
			
		||||
  uint32_t checksum = ConfigData.checksum;
 | 
			
		||||
  ConfigData.checksum = 0;
 | 
			
		||||
 | 
			
		||||
  if (Checksum_EEPROM((uint8_t *)&ConfigData, sizeof(ConfigData)) != checksum)
 | 
			
		||||
  {
 | 
			
		||||
    MaintainDTC(DTC_EEPROM_CFG_BAD, true);
 | 
			
		||||
    FormatConfig_EEPROM();
 | 
			
		||||
  }
 | 
			
		||||
  ConfigData.checksum = checksum;
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
uint32_t getPersistanceAddress()
 | 
			
		||||
{
 | 
			
		||||
  uint32_t eePersistenceMarker;
 | 
			
		||||
  ee.readBlock(persistencemarker_Adress, (uint8_t *)&eePersistenceMarker, sizeof(eePersistenceMarker));
 | 
			
		||||
  return eePersistenceMarker;
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
void updatePersistanceAddress(uint32_t adress)
 | 
			
		||||
{
 | 
			
		||||
  ee.updateBlock(persistencemarker_Adress, (uint8_t *)&adress, sizeof(adress));
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
void StorePersistence_EEPROM()
 | 
			
		||||
{
 | 
			
		||||
  if (PersistenceData.writeCycleCounter >= EEPROM_ENDURANCE)
 | 
			
		||||
    MovePersistencePage_EEPROM(false);
 | 
			
		||||
  else
 | 
			
		||||
    PersistenceData.writeCycleCounter++;
 | 
			
		||||
 | 
			
		||||
  PersistenceData.checksum = 0;
 | 
			
		||||
  PersistenceData.checksum = Checksum_EEPROM((uint8_t *)&PersistenceData, sizeof(PersistenceData));
 | 
			
		||||
 | 
			
		||||
  if (!checkEEPROMavailable())
 | 
			
		||||
    return;
 | 
			
		||||
 | 
			
		||||
  ee.updateBlock(getPersistanceAddress(), (uint8_t *)&PersistenceData, sizeof(PersistenceData));
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
void GetPersistence_EEPROM()
 | 
			
		||||
{
 | 
			
		||||
  if (!checkEEPROMavailable())
 | 
			
		||||
    return;
 | 
			
		||||
 | 
			
		||||
  ee.readBlock(getPersistanceAddress(), (uint8_t *)&PersistenceData, sizeof(PersistenceData));
 | 
			
		||||
 | 
			
		||||
  uint32_t checksum = PersistenceData.checksum;
 | 
			
		||||
  PersistenceData.checksum = 0;
 | 
			
		||||
 | 
			
		||||
  if (Checksum_EEPROM((uint8_t *)&PersistenceData, sizeof(PersistenceData)) != checksum)
 | 
			
		||||
  {
 | 
			
		||||
    MaintainDTC(DTC_EEPROM_PDS_BAD, true);
 | 
			
		||||
    FormatPersistence_EEPROM();
 | 
			
		||||
  }
 | 
			
		||||
  PersistenceData.checksum = checksum;
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
void FormatConfig_EEPROM()
 | 
			
		||||
{
 | 
			
		||||
  configData_t defaults;
 | 
			
		||||
  ConfigData = defaults;
 | 
			
		||||
  ConfigData.EEPROM_Version = eeVersion;
 | 
			
		||||
  StoreConfig_EEPROM();
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
void FormatPersistence_EEPROM()
 | 
			
		||||
{
 | 
			
		||||
  persistenceData_t defaults;
 | 
			
		||||
  PersistenceData = defaults;
 | 
			
		||||
  updatePersistanceAddress(startofPersistence_Adress);
 | 
			
		||||
  StorePersistence_EEPROM();
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
void MovePersistencePage_EEPROM(boolean reset)
 | 
			
		||||
{
 | 
			
		||||
  if (!checkEEPROMavailable())
 | 
			
		||||
    return;
 | 
			
		||||
 | 
			
		||||
  if (reset)
 | 
			
		||||
  {
 | 
			
		||||
    updatePersistanceAddress(startofPersistence_Adress);
 | 
			
		||||
  }
 | 
			
		||||
  else
 | 
			
		||||
  {
 | 
			
		||||
    uint32_t newPersistenceMarker = getPersistanceAddress() + sizeof(PersistenceData);
 | 
			
		||||
 | 
			
		||||
    // check if we reached the End of the EEPROM and Startover at the beginning
 | 
			
		||||
    if ((newPersistenceMarker + sizeof(PersistenceData)) > ee.getDeviceSize())
 | 
			
		||||
    {
 | 
			
		||||
      MaintainDTC(DTC_EEPROM_WORNOUT, true);
 | 
			
		||||
      return;
 | 
			
		||||
    }
 | 
			
		||||
    else
 | 
			
		||||
    {
 | 
			
		||||
      updatePersistanceAddress(newPersistenceMarker);
 | 
			
		||||
      PersistenceData.writeCycleCounter = 0;
 | 
			
		||||
    }
 | 
			
		||||
  }
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
uint32_t GetEESize()
 | 
			
		||||
{
 | 
			
		||||
  return ee.getDeviceSize();
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
uint32_t Checksum_EEPROM(uint8_t const *data, size_t len)
 | 
			
		||||
{
 | 
			
		||||
  if (data == NULL)
 | 
			
		||||
    return 0;
 | 
			
		||||
  uint32_t crc, mask;
 | 
			
		||||
  crc = 0xFFFFFFFF;
 | 
			
		||||
 | 
			
		||||
  while (len--)
 | 
			
		||||
  {
 | 
			
		||||
    crc ^= *data++;
 | 
			
		||||
    for (uint8_t k = 0; k < 8; k++)
 | 
			
		||||
    {
 | 
			
		||||
      mask = -(crc & 1);
 | 
			
		||||
      crc = (crc >> 1) ^ (0xEDB88320 & mask);
 | 
			
		||||
    }
 | 
			
		||||
  }
 | 
			
		||||
  return ~crc;
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
void dumpEEPROM(uint16_t memoryAddress, uint16_t length)
 | 
			
		||||
{
 | 
			
		||||
#define BLOCK_TO_LENGTH 16
 | 
			
		||||
 | 
			
		||||
  if (length > ee.getDeviceSize())
 | 
			
		||||
    length = ee.getDeviceSize();
 | 
			
		||||
 | 
			
		||||
  if (memoryAddress + length > ee.getDeviceSize())
 | 
			
		||||
    return;
 | 
			
		||||
 | 
			
		||||
  if (!checkEEPROMavailable())
 | 
			
		||||
    return;
 | 
			
		||||
 | 
			
		||||
  char ascii_buf[BLOCK_TO_LENGTH + 1];
 | 
			
		||||
  sprintf(ascii_buf, "%*s", BLOCK_TO_LENGTH, "ASCII");
 | 
			
		||||
  Serial.print(PSTR("\nAddress "));
 | 
			
		||||
  for (int x = 0; x < BLOCK_TO_LENGTH; x++)
 | 
			
		||||
    Serial.printf("%3d", x);
 | 
			
		||||
 | 
			
		||||
  memoryAddress = memoryAddress / BLOCK_TO_LENGTH * BLOCK_TO_LENGTH;
 | 
			
		||||
  length = (length + BLOCK_TO_LENGTH - 1) / BLOCK_TO_LENGTH * BLOCK_TO_LENGTH;
 | 
			
		||||
 | 
			
		||||
  for (unsigned int i = 0; i < length; i++)
 | 
			
		||||
  {
 | 
			
		||||
    int blockpoint = memoryAddress % BLOCK_TO_LENGTH;
 | 
			
		||||
    if (blockpoint == 0)
 | 
			
		||||
    {
 | 
			
		||||
      ascii_buf[BLOCK_TO_LENGTH] = 0;
 | 
			
		||||
      Serial.printf("  %s", ascii_buf);
 | 
			
		||||
      Serial.printf("\n0x%05X:", memoryAddress);
 | 
			
		||||
    }
 | 
			
		||||
    ascii_buf[blockpoint] = ee.readByte(memoryAddress);
 | 
			
		||||
    Serial.printf(" %02X", ascii_buf[blockpoint]);
 | 
			
		||||
    if (ascii_buf[blockpoint] < 0x20 || ascii_buf[blockpoint] > 0x7E)
 | 
			
		||||
      ascii_buf[blockpoint] = '.';
 | 
			
		||||
    memoryAddress++;
 | 
			
		||||
  }
 | 
			
		||||
  Serial.println();
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
boolean checkEEPROMavailable()
 | 
			
		||||
{
 | 
			
		||||
  if (!ee.isConnected())
 | 
			
		||||
  {
 | 
			
		||||
    MaintainDTC(DTC_NO_EEPROM_FOUND, true);
 | 
			
		||||
    return false;
 | 
			
		||||
  }
 | 
			
		||||
  return true;
 | 
			
		||||
}
 | 
			
		||||
@@ -1,69 +0,0 @@
 | 
			
		||||
#ifndef _CONFIG_H_
 | 
			
		||||
#define _CONFIG_H_
 | 
			
		||||
 | 
			
		||||
#include <Arduino.h>
 | 
			
		||||
#include <Wire.h>
 | 
			
		||||
#include <I2C_eeprom.h>
 | 
			
		||||
 | 
			
		||||
#include "globals.h"
 | 
			
		||||
#include "dtc.h"
 | 
			
		||||
 | 
			
		||||
#define EEPROM_SIZE_BYTES I2C_DEVICESIZE_24LC01
 | 
			
		||||
#define EEPROM_ENDURANCE 1000000
 | 
			
		||||
 | 
			
		||||
typedef enum
 | 
			
		||||
{
 | 
			
		||||
  NONE,
 | 
			
		||||
  FACTION_1,
 | 
			
		||||
  FACTION_2,
 | 
			
		||||
  FACTION_3
 | 
			
		||||
} factions_t;
 | 
			
		||||
 | 
			
		||||
typedef struct
 | 
			
		||||
{
 | 
			
		||||
  uint32_t writeCycleCounter = 0;
 | 
			
		||||
  uint32_t faction_1_timer = 0;
 | 
			
		||||
  uint32_t faction_2_timer = 0;
 | 
			
		||||
  uint32_t faction_3_timer = 0;
 | 
			
		||||
  factions_t activeFaction = NONE;
 | 
			
		||||
  uint32_t checksum = 0;
 | 
			
		||||
} persistenceData_t;
 | 
			
		||||
 | 
			
		||||
typedef enum
 | 
			
		||||
{
 | 
			
		||||
  BATTERY_UNDEFINED,
 | 
			
		||||
  BATTERY_LIPO_2S,
 | 
			
		||||
  BATTERY_LIPO_3S
 | 
			
		||||
} batteryType_t;
 | 
			
		||||
 | 
			
		||||
const char BatteryString[][10]{
 | 
			
		||||
  "Undefined",
 | 
			
		||||
  "LiPo 2S",
 | 
			
		||||
  "LiPo 3S"
 | 
			
		||||
};
 | 
			
		||||
 | 
			
		||||
typedef struct
 | 
			
		||||
{
 | 
			
		||||
  uint8_t EEPROM_Version = 1;
 | 
			
		||||
  batteryType_t batteryType = BATTERY_UNDEFINED;
 | 
			
		||||
  uint32_t checksum = 0;
 | 
			
		||||
} configData_t;
 | 
			
		||||
 | 
			
		||||
void InitEEPROM();
 | 
			
		||||
void EEPROM_Process();
 | 
			
		||||
void StoreConfig_EEPROM();
 | 
			
		||||
void GetConfig_EEPROM();
 | 
			
		||||
void StorePersistence_EEPROM();
 | 
			
		||||
void GetPersistence_EEPROM();
 | 
			
		||||
void FormatConfig_EEPROM();
 | 
			
		||||
void FormatPersistence_EEPROM();
 | 
			
		||||
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 getPersistanceAddress();
 | 
			
		||||
void updatePersistanceAddress(uint32_t adress);
 | 
			
		||||
uint32_t GetEESize();
 | 
			
		||||
 | 
			
		||||
extern configData_t ConfigData;
 | 
			
		||||
extern persistenceData_t PersistenceData;
 | 
			
		||||
#endif // _CONFIG_H_
 | 
			
		||||
							
								
								
									
										612
									
								
								Software/src/debugger.cpp
									
									
									
									
									
										Normal file
									
								
							
							
						
						@@ -0,0 +1,612 @@
 | 
			
		||||
/**
 | 
			
		||||
 * @file debugger.cpp
 | 
			
		||||
 * @brief Implementation of debugging functions for monitoring and diagnostics.
 | 
			
		||||
 *
 | 
			
		||||
 * This file contains the implementation of various debugging functions to monitor
 | 
			
		||||
 * and diagnose the system. It includes functions to print system information, WiFi
 | 
			
		||||
 * details, EEPROM status, dump configuration settings, dump persistence data, show
 | 
			
		||||
 * Diagnostic Trouble Codes (DTCs), and more.
 | 
			
		||||
 *
 | 
			
		||||
 * @author Marcel Peterkau
 | 
			
		||||
 * @date 09.04.2024
 | 
			
		||||
 */
 | 
			
		||||
 | 
			
		||||
#include "debugger.h"
 | 
			
		||||
#include <map>
 | 
			
		||||
#include <functional>
 | 
			
		||||
#include <vector>
 | 
			
		||||
#include "utilities.h"
 | 
			
		||||
#include <pgmspace.h>
 | 
			
		||||
 | 
			
		||||
DebugStatus_t DebuggerStatus[dbg_cntElements];
 | 
			
		||||
 | 
			
		||||
void processCmdDebug(String command);
 | 
			
		||||
void Debug_formatCFG();
 | 
			
		||||
void Debug_formatPersistence();
 | 
			
		||||
void Debug_printSystemInfo();
 | 
			
		||||
void Debug_printWifiInfo();
 | 
			
		||||
void Debug_CheckEEPOM(bool autocorrect);
 | 
			
		||||
void Debug_dumpConfig();
 | 
			
		||||
void Debug_dumpPersistance();
 | 
			
		||||
void Debug_ShowDTCs();
 | 
			
		||||
void Debug_dumpGlobals();
 | 
			
		||||
void Debug_printHelp();
 | 
			
		||||
void Debug_Reboot();
 | 
			
		||||
void Debug_setBatteryType(int batterytype);
 | 
			
		||||
const char *uint32_to_binary_string(uint32_t num);
 | 
			
		||||
 | 
			
		||||
/**
 | 
			
		||||
 * @brief Initializes the debugger by setting the initial status for different debug ports.
 | 
			
		||||
 *        Serial debug output is turned off.
 | 
			
		||||
 */
 | 
			
		||||
void initDebugger()
 | 
			
		||||
{
 | 
			
		||||
    // Set the initial status of debug ports
 | 
			
		||||
    DebuggerStatus[dbg_Serial] = disabled;
 | 
			
		||||
    DebuggerStatus[dbg_Webui] = disabled;
 | 
			
		||||
 | 
			
		||||
    // Disable serial debug output
 | 
			
		||||
    Serial.setDebugOutput(false);
 | 
			
		||||
}
 | 
			
		||||
/**
 | 
			
		||||
 * @brief Processes incoming debug commands from the Serial interface.
 | 
			
		||||
 *        It reads characters from Serial and interprets them as commands.
 | 
			
		||||
 *        The recognized commands are processed accordingly.
 | 
			
		||||
 */
 | 
			
		||||
void Debug_Process()
 | 
			
		||||
{
 | 
			
		||||
    // Enumeration for tracking the state of input processing
 | 
			
		||||
    typedef enum InputProcessed_e
 | 
			
		||||
    {
 | 
			
		||||
        IDLE,         ///< No command processing is in progress
 | 
			
		||||
        CMD_COMPLETE, ///< Received a complete command
 | 
			
		||||
        CMD_ABORT,    ///< Received an abort command (Esc)
 | 
			
		||||
        CMD_OVERFLOW  ///< Input buffer overflow occurred
 | 
			
		||||
    } InputProcessed_t;
 | 
			
		||||
 | 
			
		||||
    static unsigned int inputCnt = 0;       ///< Counter for characters in the input buffer
 | 
			
		||||
    static char inputBuffer[32];            ///< Buffer to store the received characters
 | 
			
		||||
    InputProcessed_t InputProcessed = IDLE; ///< State variable for input processing
 | 
			
		||||
 | 
			
		||||
    // Check if there are characters available in the Serial input buffer
 | 
			
		||||
    if (Serial.available())
 | 
			
		||||
    {
 | 
			
		||||
        char inputChar = Serial.read();
 | 
			
		||||
 | 
			
		||||
        // Process the received character based on its value
 | 
			
		||||
        switch (inputChar)
 | 
			
		||||
        {
 | 
			
		||||
        case '\n':
 | 
			
		||||
            inputBuffer[inputCnt] = 0; // terminate the String
 | 
			
		||||
            inputCnt = 0;
 | 
			
		||||
            InputProcessed = CMD_COMPLETE;
 | 
			
		||||
            Serial.write(inputChar);
 | 
			
		||||
            break;
 | 
			
		||||
 | 
			
		||||
        case 0x1B: // Esc
 | 
			
		||||
            inputBuffer[0] = 0;
 | 
			
		||||
            inputCnt = 0;
 | 
			
		||||
            InputProcessed = CMD_ABORT;
 | 
			
		||||
            break;
 | 
			
		||||
 | 
			
		||||
        case 0x20 ... 0x7E: // it's a real letter or sign and not some control-chars
 | 
			
		||||
            inputBuffer[inputCnt] = inputChar;
 | 
			
		||||
            inputCnt++;
 | 
			
		||||
            Serial.write(inputChar);
 | 
			
		||||
            break;
 | 
			
		||||
 | 
			
		||||
        default:
 | 
			
		||||
            break;
 | 
			
		||||
        }
 | 
			
		||||
 | 
			
		||||
        // Check for input buffer overflow
 | 
			
		||||
        if (inputCnt >= sizeof(inputBuffer) - 1)
 | 
			
		||||
        {
 | 
			
		||||
            inputBuffer[sizeof(inputBuffer) - 1] = '\0';
 | 
			
		||||
            inputCnt = 0;
 | 
			
		||||
            InputProcessed = CMD_OVERFLOW;
 | 
			
		||||
        }
 | 
			
		||||
    }
 | 
			
		||||
 | 
			
		||||
    // Process the command based on the detected state of input processing
 | 
			
		||||
    switch (InputProcessed)
 | 
			
		||||
    {
 | 
			
		||||
    case CMD_ABORT:
 | 
			
		||||
        Debug_pushMessage("Abort\n");
 | 
			
		||||
        break;
 | 
			
		||||
 | 
			
		||||
    case CMD_COMPLETE:
 | 
			
		||||
        processCmdDebug(String(inputBuffer));
 | 
			
		||||
        break;
 | 
			
		||||
 | 
			
		||||
    case CMD_OVERFLOW:
 | 
			
		||||
        Debug_pushMessage("Input buffer overflow\n");
 | 
			
		||||
        break;
 | 
			
		||||
 | 
			
		||||
    default:
 | 
			
		||||
        break;
 | 
			
		||||
    }
 | 
			
		||||
 | 
			
		||||
    if (InputProcessed != IDLE)
 | 
			
		||||
        Serial.print(">");
 | 
			
		||||
 | 
			
		||||
    InputProcessed = IDLE;
 | 
			
		||||
}
 | 
			
		||||
/**
 | 
			
		||||
 * @brief Sets the status of a specific debug port (Serial or WebUI).
 | 
			
		||||
 *        Updates the status in the DebuggerStatus array and provides debug messages.
 | 
			
		||||
 *
 | 
			
		||||
 * @param port   The debug port to set the status for (dbg_Serial or dbg_Webui).
 | 
			
		||||
 * @param status The status to set (enabled or disabled).
 | 
			
		||||
 */
 | 
			
		||||
void SetDebugportStatus(DebugPorts_t port, DebugStatus_t status)
 | 
			
		||||
{
 | 
			
		||||
    // Display a debug message based on the provided status
 | 
			
		||||
    if (status == disabled)
 | 
			
		||||
        Debug_pushMessage("Disable DebugPort %s\n", sDebugPorts[port]);
 | 
			
		||||
 | 
			
		||||
    // Update the status in the DebuggerStatus array
 | 
			
		||||
    DebuggerStatus[port] = status;
 | 
			
		||||
 | 
			
		||||
    // Display a debug message based on the updated status
 | 
			
		||||
    if (status == enabled)
 | 
			
		||||
        Debug_pushMessage("Enabled DebugPort %s\n", sDebugPorts[port]);
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
void Debug_log(LogLevel level, const char *format, ...)
 | 
			
		||||
{
 | 
			
		||||
    if ((DebuggerStatus[dbg_Serial] == enabled) || (DebuggerStatus[dbg_Webui] == enabled))
 | 
			
		||||
    {
 | 
			
		||||
        char buff[128];
 | 
			
		||||
        va_list arg;
 | 
			
		||||
        va_start(arg, format);
 | 
			
		||||
        vsnprintf(buff, sizeof(buff), format, arg);
 | 
			
		||||
        va_end(arg);
 | 
			
		||||
 | 
			
		||||
        if (DebuggerStatus[dbg_Serial] == enabled)
 | 
			
		||||
        {
 | 
			
		||||
            Serial.print(buff);
 | 
			
		||||
        }
 | 
			
		||||
        if (DebuggerStatus[dbg_Webui] == enabled)
 | 
			
		||||
        {
 | 
			
		||||
            Websocket_PushLiveDebug(String(buff));
 | 
			
		||||
        }
 | 
			
		||||
    }
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
/**
 | 
			
		||||
 * @brief Pushes a formatted debug message to the enabled debug ports (Serial or WebUI).
 | 
			
		||||
 *
 | 
			
		||||
 * @param format The format string for the debug message.
 | 
			
		||||
 * @param ...    Additional arguments for formatting the message.
 | 
			
		||||
 */
 | 
			
		||||
void Debug_pushMessage(const char *format, ...)
 | 
			
		||||
{
 | 
			
		||||
    // Check if either the Serial or WebUI debug port is enabled
 | 
			
		||||
    if ((DebuggerStatus[dbg_Serial] == enabled) || (DebuggerStatus[dbg_Webui] == enabled))
 | 
			
		||||
    {
 | 
			
		||||
        char buff[128]; // Buffer to hold the formatted message
 | 
			
		||||
        va_list arg;    // Variable argument list for vsnprintf
 | 
			
		||||
        va_start(arg, format);
 | 
			
		||||
 | 
			
		||||
        // Format the message and store it in the buffer
 | 
			
		||||
        vsnprintf(buff, sizeof(buff), format, arg);
 | 
			
		||||
        va_end(arg);
 | 
			
		||||
 | 
			
		||||
        // Send the message to the Serial debug port if enabled
 | 
			
		||||
        if (DebuggerStatus[dbg_Serial] == enabled)
 | 
			
		||||
        {
 | 
			
		||||
            Serial.print(buff);
 | 
			
		||||
        }
 | 
			
		||||
 | 
			
		||||
        // Push the message to the WebUI debug port if enabled
 | 
			
		||||
        if (DebuggerStatus[dbg_Webui] == enabled)
 | 
			
		||||
        {
 | 
			
		||||
            Websocket_PushLiveDebug(String(buff));
 | 
			
		||||
        }
 | 
			
		||||
    }
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
// === splitArgs Helper ===
 | 
			
		||||
std::vector<String> splitArgs(const String &input)
 | 
			
		||||
{
 | 
			
		||||
    std::vector<String> tokens;
 | 
			
		||||
    int start = 0, end = 0;
 | 
			
		||||
    while ((end = input.indexOf(' ', start)) != -1)
 | 
			
		||||
    {
 | 
			
		||||
        tokens.push_back(input.substring(start, end));
 | 
			
		||||
        start = end + 1;
 | 
			
		||||
    }
 | 
			
		||||
    if (start < input.length())
 | 
			
		||||
        tokens.push_back(input.substring(start));
 | 
			
		||||
    return tokens;
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
// === getArg helper ===
 | 
			
		||||
String getArg(const std::vector<String> &args, size_t index, const String &defaultVal = "")
 | 
			
		||||
{
 | 
			
		||||
    if (index < args.size())
 | 
			
		||||
        return args[index];
 | 
			
		||||
    return defaultVal;
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
// === Command Handler Map ===
 | 
			
		||||
typedef std::function<void(const String &args)> DebugCmdHandler;
 | 
			
		||||
 | 
			
		||||
static const std::map<String, DebugCmdHandler> &getCmdMap()
 | 
			
		||||
{
 | 
			
		||||
    static const std::map<String, DebugCmdHandler> cmdMap = {
 | 
			
		||||
        {"help", [](const String &)
 | 
			
		||||
         {
 | 
			
		||||
             Debug_log(LOG_INFO, "Available commands:\n");
 | 
			
		||||
             for (const auto &entry : getCmdMap())
 | 
			
		||||
                 Debug_log(LOG_INFO, " - %s\n", entry.first.c_str());
 | 
			
		||||
         }},
 | 
			
		||||
        {"sysinfo", [](const String &)
 | 
			
		||||
         { Debug_printSystemInfo(); }},
 | 
			
		||||
        {"netinfo", [](const String &)
 | 
			
		||||
         { Debug_printWifiInfo(); }},
 | 
			
		||||
        {"formatCFG", [](const String &)
 | 
			
		||||
         { Debug_formatCFG(); }},
 | 
			
		||||
        {"formatPDS", [](const String &)
 | 
			
		||||
         { Debug_formatPersistence(); }},
 | 
			
		||||
        {"checkEE", [](const String &)
 | 
			
		||||
         { Debug_CheckEEPOM(false); }},
 | 
			
		||||
        {"checkEEfix", [](const String &)
 | 
			
		||||
         { Debug_CheckEEPOM(true); }},
 | 
			
		||||
        {"dumpEE1k", [](const String &)
 | 
			
		||||
         { dumpEEPROM(0, 1024); }},
 | 
			
		||||
        {"dumpEE", [](const String &args)
 | 
			
		||||
         {
 | 
			
		||||
             int start = 0, len = EEPROM_SIZE_BYTES;
 | 
			
		||||
             auto tokens = splitArgs(args);
 | 
			
		||||
             if (tokens.size() >= 2)
 | 
			
		||||
             {
 | 
			
		||||
                 start = tokens[0].toInt();
 | 
			
		||||
                 len = tokens[1].toInt();
 | 
			
		||||
             }
 | 
			
		||||
             dumpEEPROM(start, len);
 | 
			
		||||
         }},
 | 
			
		||||
        {"resetPageEE", [](const String &)
 | 
			
		||||
         { MovePersistencePage_EEPROM(true); }},
 | 
			
		||||
        {"dumpCFG", [](const String &)
 | 
			
		||||
         { Debug_dumpConfig(); }},
 | 
			
		||||
        {"dumpPDS", [](const String &)
 | 
			
		||||
         { Debug_dumpPersistance(); }},
 | 
			
		||||
        {"saveEE", [](const String &)
 | 
			
		||||
         { globals.requestEEAction = EE_ALL_SAVE; }},
 | 
			
		||||
        {"dumpGlobals", [](const String &)
 | 
			
		||||
         { Debug_dumpGlobals(); }},
 | 
			
		||||
        {"sdbg", [](const String &)
 | 
			
		||||
         { SetDebugportStatus(dbg_Serial, enabled); }},
 | 
			
		||||
        {"dtc_show", [](const String &)
 | 
			
		||||
         { Debug_ShowDTCs(); }},
 | 
			
		||||
        {"dtc_clear", [](const String &)
 | 
			
		||||
         { ClearAllDTC(); }},
 | 
			
		||||
        {"dtc_crit", [](const String &)
 | 
			
		||||
         { MaintainDTC(DTC_FAKE_DTC_CRIT, true, millis()); }},
 | 
			
		||||
        {"dtc_warn", [](const String &)
 | 
			
		||||
         { MaintainDTC(DTC_FAKE_DTC_WARN, true, millis()); }},
 | 
			
		||||
        {"dtc_info", [](const String &)
 | 
			
		||||
         { MaintainDTC(DTC_FAKE_DTC_INFO, true, millis()); }},
 | 
			
		||||
        {"notify_error", [](const String &)
 | 
			
		||||
         { Websocket_PushNotification("Debug Error Notification", error); }},
 | 
			
		||||
        {"notify_warning", [](const String &)
 | 
			
		||||
         { Websocket_PushNotification("Debug Warning Notification", warning); }},
 | 
			
		||||
        {"notify_success", [](const String &)
 | 
			
		||||
         { Websocket_PushNotification("Debug Success Notification", success); }},
 | 
			
		||||
        {"notify_info", [](const String &)
 | 
			
		||||
         { Websocket_PushNotification("Debug Info Notification", info); }},
 | 
			
		||||
        {"reboot", [](const String &)
 | 
			
		||||
         { Debug_Reboot(); }},
 | 
			
		||||
        {"toggle_wifi", [](const String &)
 | 
			
		||||
         { globals.toggle_wifi = true; }},
 | 
			
		||||
        {"dtc_add", [](const String &args)
 | 
			
		||||
         {
 | 
			
		||||
             auto tokens = splitArgs(args);
 | 
			
		||||
             if (!tokens.empty())
 | 
			
		||||
             {
 | 
			
		||||
                 int code = tokens[0].toInt();
 | 
			
		||||
                 MaintainDTC((DTCNum_t)code, true, millis());
 | 
			
		||||
             }
 | 
			
		||||
         }},
 | 
			
		||||
        {"set_battery", [](const String &args)
 | 
			
		||||
         {
 | 
			
		||||
             auto tokens = splitArgs(args);
 | 
			
		||||
             if (!tokens.empty())
 | 
			
		||||
             {
 | 
			
		||||
                 int batteryType = tokens[0].toInt();
 | 
			
		||||
                 Debug_setBatteryType(batteryType);
 | 
			
		||||
             }
 | 
			
		||||
         }}};
 | 
			
		||||
    return cmdMap;
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
void processCmdDebug(String input)
 | 
			
		||||
{
 | 
			
		||||
    input.trim();
 | 
			
		||||
    int splitIndex = input.indexOf(' ');
 | 
			
		||||
    String command = splitIndex == -1 ? input : input.substring(0, splitIndex);
 | 
			
		||||
    String args = splitIndex == -1 ? "" : input.substring(splitIndex + 1);
 | 
			
		||||
 | 
			
		||||
    auto &cmdMap = getCmdMap();
 | 
			
		||||
    auto it = cmdMap.find(command);
 | 
			
		||||
    if (it != cmdMap.end())
 | 
			
		||||
        it->second(args);
 | 
			
		||||
    else
 | 
			
		||||
        Debug_log(LOG_WARN, "Unknown command: '%s'\n", command.c_str());
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
/**
 | 
			
		||||
 * @brief Formats the Config-EEPROM and resets it to default values.
 | 
			
		||||
 *        Prints a debug message after formatting.
 | 
			
		||||
 */
 | 
			
		||||
void Debug_formatCFG()
 | 
			
		||||
{
 | 
			
		||||
    Debug_pushMessage("Formatting Config-EEPROM and resetting to default\n");
 | 
			
		||||
    FormatConfig_EEPROM();
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
/**
 | 
			
		||||
 * @brief Formats the Persistence-EEPROM and resets it to default values.
 | 
			
		||||
 *        Prints a debug message after formatting.
 | 
			
		||||
 */
 | 
			
		||||
void Debug_formatPersistence()
 | 
			
		||||
{
 | 
			
		||||
    Debug_pushMessage("Formatting Persistence-EEPROM and resetting to default\n");
 | 
			
		||||
    FormatPersistence_EEPROM();
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
/**
 | 
			
		||||
 * @brief Prints system information and status to the debug output.
 | 
			
		||||
 */
 | 
			
		||||
void Debug_printSystemInfo()
 | 
			
		||||
{
 | 
			
		||||
    Debug_pushMessage("Hostname: %s\n", globals.DeviceNameId);
 | 
			
		||||
 | 
			
		||||
    FlashMode_t ideMode = ESP.getFlashChipMode();
 | 
			
		||||
    Debug_pushMessage("Sdk version: %s\n", ESP.getSdkVersion());
 | 
			
		||||
    Debug_pushMessage("Core Version: %s\n", ESP.getCoreVersion().c_str());
 | 
			
		||||
    Debug_pushMessage("Boot Version: %u\n", ESP.getBootVersion());
 | 
			
		||||
    Debug_pushMessage("Boot Mode: %u\n", ESP.getBootMode());
 | 
			
		||||
    Debug_pushMessage("CPU Frequency: %u MHz\n", ESP.getCpuFreqMHz());
 | 
			
		||||
    Debug_pushMessage("Reset reason: %s\n", ESP.getResetReason().c_str());
 | 
			
		||||
    Debug_pushMessage("Flash Size: %d\n", ESP.getFlashChipRealSize());
 | 
			
		||||
    Debug_pushMessage("Flash Size IDE: %d\n", ESP.getFlashChipSize());
 | 
			
		||||
    Debug_pushMessage("Flash ide mode:  %s\n", (ideMode == FM_QIO ? "QIO" : ideMode == FM_QOUT ? "QOUT"
 | 
			
		||||
                                                                        : ideMode == FM_DIO    ? "DIO"
 | 
			
		||||
                                                                        : ideMode == FM_DOUT   ? "DOUT"
 | 
			
		||||
                                                                                               : "UNKNOWN"));
 | 
			
		||||
    Debug_pushMessage("OTA-Pass: %s\n", QUOTE(ADMIN_PASSWORD));
 | 
			
		||||
    Debug_pushMessage("Git-Revision: %s\n", constants.GitHash);
 | 
			
		||||
    Debug_pushMessage("Sw-Version: %d.%02d\n", constants.FW_Version_major, constants.FW_Version_minor);
 | 
			
		||||
 | 
			
		||||
    Debug_pushMessage("globals.systemStatus: %d\n", globals.systemStatus);
 | 
			
		||||
    Debug_pushMessage("globals.resumeStatus: %d\n", globals.resumeStatus);
 | 
			
		||||
    Debug_pushMessage("globals.systemStatustxt: %s\n", globals.systemStatustxt);
 | 
			
		||||
    Debug_pushMessage("globals.requestEEAction: %d\n", globals.requestEEAction);
 | 
			
		||||
    Debug_pushMessage("globals.DeviceName: %s\n", globals.DeviceName);
 | 
			
		||||
    Debug_pushMessage("globals.FlashVersion: %s\n", globals.FlashVersion);
 | 
			
		||||
    Debug_pushMessage("globals.eePersistanceAdress: %u\n", globals.eePersistanceAdress);
 | 
			
		||||
    Debug_pushMessage("globals.hasDTC: %d\n", globals.hasDTC);
 | 
			
		||||
    Debug_pushMessage("globals.loadvoltage_mV: %d\n", globals.loadvoltage_mV);
 | 
			
		||||
    Debug_pushMessage("globals.battery_level: %d\n", globals.battery_level);
 | 
			
		||||
    Debug_pushMessage("globals.timer_disabled: %d\n", globals.timer_disabled);
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
/**
 | 
			
		||||
 * @brief Dumps the current configuration parameters to the debug output.
 | 
			
		||||
 */
 | 
			
		||||
void Debug_dumpConfig()
 | 
			
		||||
{
 | 
			
		||||
    Debug_pushMessage("batteryType: %d\n", ConfigData.batteryType);
 | 
			
		||||
    Debug_pushMessage("Faction_1_Name: %s\n", ConfigData.Faction_1_Name);
 | 
			
		||||
    Debug_pushMessage("Faction_1_Name: %s\n", ConfigData.Faction_2_Name);
 | 
			
		||||
    Debug_pushMessage("Faction_1_Name: %s\n", ConfigData.Faction_3_Name);
 | 
			
		||||
    Debug_pushMessage("active_faction_on_reboot: %d\n", ConfigData.active_faction_on_reboot);
 | 
			
		||||
    Debug_pushMessage("wifi_autoconnect: %d\n", ConfigData.wifi_autoconnect);
 | 
			
		||||
    Debug_pushMessage("wifi_client_ssid: %s\n", ConfigData.wifi_client_ssid);
 | 
			
		||||
    Debug_pushMessage("wifi_client_password: %s\n", ConfigData.wifi_client_password);
 | 
			
		||||
    Debug_pushMessage("EEPROM_Version: %d\n", ConfigData.EEPROM_Version);
 | 
			
		||||
    Debug_pushMessage("checksum: 0x%08X\n", ConfigData.checksum);
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
/**
 | 
			
		||||
 * @brief Dumps the global variables and their values to the debug output.
 | 
			
		||||
 */
 | 
			
		||||
void Debug_dumpGlobals()
 | 
			
		||||
{
 | 
			
		||||
    Debug_pushMessage("systemStatus: %d\n", globals.systemStatus);
 | 
			
		||||
    Debug_pushMessage("battery_level: %d\n", globals.battery_level);
 | 
			
		||||
    Debug_pushMessage("loadvoltage_mV: %d\n", globals.loadvoltage_mV);
 | 
			
		||||
    Debug_pushMessage("requestEEAction: %d\n", globals.requestEEAction);
 | 
			
		||||
    Debug_pushMessage("DeviceName: %s\n", globals.DeviceName);
 | 
			
		||||
    Debug_pushMessage("FlashVersion: %s\n", globals.FlashVersion);
 | 
			
		||||
    Debug_pushMessage("eePersistanceAdress: %d\n", globals.eePersistanceAdress);
 | 
			
		||||
    Debug_pushMessage("hasDTC: %d\n", globals.hasDTC);
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
/**
 | 
			
		||||
 * @brief Dumps the persistence data variables and their values to the debug output.
 | 
			
		||||
 */
 | 
			
		||||
void Debug_dumpPersistance()
 | 
			
		||||
{
 | 
			
		||||
    Debug_pushMessage("writeCycleCounter: %d\n", PersistenceData.writeCycleCounter);
 | 
			
		||||
    Debug_pushMessage("activeFaction: %d\n", PersistenceData.activeFaction);
 | 
			
		||||
    Debug_pushMessage("faction_1_timer: %d\n", PersistenceData.faction_1_timer);
 | 
			
		||||
    Debug_pushMessage("faction_2_timer: %d\n", PersistenceData.faction_2_timer);
 | 
			
		||||
    Debug_pushMessage("faction_3_timer: %d\n", PersistenceData.faction_3_timer);
 | 
			
		||||
    Debug_pushMessage("checksum: %d\n", PersistenceData.checksum);
 | 
			
		||||
    Debug_pushMessage("PSD Adress: 0x%04X\n", globals.eePersistanceAdress);
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
/**
 | 
			
		||||
 * @brief Prints information related to WiFi to the debug output.
 | 
			
		||||
 */
 | 
			
		||||
void Debug_printWifiInfo()
 | 
			
		||||
{
 | 
			
		||||
    char buffer[33];
 | 
			
		||||
    GenerateDeviceSpecificPassword(QUOTE(WIFI_PASS_SEED), buffer, sizeof(buffer));
 | 
			
		||||
    Debug_pushMessage("IP Adress: %s\n", WiFi.localIP().toString().c_str());
 | 
			
		||||
    Debug_pushMessage("WiFi AP Pw: %s\n", buffer);
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
void Debug_setBatteryType(int batterytype)
 | 
			
		||||
{
 | 
			
		||||
 | 
			
		||||
    switch (batterytype)
 | 
			
		||||
    {
 | 
			
		||||
    case 2:
 | 
			
		||||
        ConfigData.batteryType = BATTERY_LIPO_2S;
 | 
			
		||||
        break;
 | 
			
		||||
    case 3:
 | 
			
		||||
        ConfigData.batteryType = BATTERY_LIPO_3S;
 | 
			
		||||
        break;
 | 
			
		||||
    default:
 | 
			
		||||
        ConfigData.batteryType = BATTERY_UNDEFINED;
 | 
			
		||||
        break;
 | 
			
		||||
    }
 | 
			
		||||
 | 
			
		||||
    Debug_pushMessage("Set BatteryType to : %d\n", batterytype);
 | 
			
		||||
    globals.requestEEAction = EE_CFG_SAVE;
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
/**
 | 
			
		||||
 * @brief Checks the EEPROM data integrity by calculating and comparing checksums.
 | 
			
		||||
 *        Prints the result to the debug output.
 | 
			
		||||
 */
 | 
			
		||||
void Debug_CheckEEPOM(bool autocorrect)
 | 
			
		||||
{
 | 
			
		||||
    // Check PersistenceData EEPROM checksum
 | 
			
		||||
    uint32_t checksum = PersistenceData.checksum;
 | 
			
		||||
    PersistenceData.checksum = 0;
 | 
			
		||||
 | 
			
		||||
    if (Checksum_EEPROM((uint8_t *)&PersistenceData, sizeof(PersistenceData)) == checksum)
 | 
			
		||||
    {
 | 
			
		||||
        Debug_pushMessage("PersistenceData EEPROM Checksum OK\n");
 | 
			
		||||
    }
 | 
			
		||||
    else
 | 
			
		||||
    {
 | 
			
		||||
        Debug_pushMessage("PersistenceData EEPROM Checksum BAD\n");
 | 
			
		||||
    }
 | 
			
		||||
 | 
			
		||||
    PersistenceData.checksum = checksum;
 | 
			
		||||
 | 
			
		||||
    // Check ConfigData EEPROM checksum
 | 
			
		||||
    checksum = ConfigData.checksum;
 | 
			
		||||
    ConfigData.checksum = 0;
 | 
			
		||||
 | 
			
		||||
    if (Checksum_EEPROM((uint8_t *)&ConfigData, sizeof(ConfigData)) == checksum)
 | 
			
		||||
    {
 | 
			
		||||
        Debug_pushMessage("ConfigData EEPROM Checksum OK\n");
 | 
			
		||||
    }
 | 
			
		||||
    else
 | 
			
		||||
    {
 | 
			
		||||
        Debug_pushMessage("ConfigData EEPROM Checksum BAD\n");
 | 
			
		||||
    }
 | 
			
		||||
    ConfigData.checksum = checksum;
 | 
			
		||||
 | 
			
		||||
    uint32_t sanitycheck = ConfigSanityCheck(autocorrect);
 | 
			
		||||
 | 
			
		||||
    if (sanitycheck == 0)
 | 
			
		||||
    {
 | 
			
		||||
        Debug_pushMessage("ConfigData Sanity Check OK\n");
 | 
			
		||||
    }
 | 
			
		||||
    else
 | 
			
		||||
    {
 | 
			
		||||
        Debug_pushMessage("ConfigData Sanity Check BAD: %s\n", uint32_to_binary_string(sanitycheck));
 | 
			
		||||
    }
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
/**
 | 
			
		||||
 * @brief Displays Diagnostic Trouble Codes (DTCs) along with their timestamps,
 | 
			
		||||
 *        status, and severity in a formatted manner.
 | 
			
		||||
 */
 | 
			
		||||
void Debug_ShowDTCs()
 | 
			
		||||
{
 | 
			
		||||
    char buff_timestamp[16]; // Format: DD-hh:mm:ss:xxx
 | 
			
		||||
    char buff_active[9];
 | 
			
		||||
 | 
			
		||||
    // Header for the DTC display
 | 
			
		||||
    Debug_pushMessage("\n      timestamp | DTC-Nr. |   status | severity\n");
 | 
			
		||||
 | 
			
		||||
    // Iterate through DTCStorage and display each entry
 | 
			
		||||
    for (uint32_t i = 0; i < MAX_DTC_STORAGE; i++)
 | 
			
		||||
    {
 | 
			
		||||
        if (DTCStorage[i].Number < DTC_LAST_DTC)
 | 
			
		||||
        {
 | 
			
		||||
            // Format timestamp
 | 
			
		||||
            sprintf(buff_timestamp, "%02d-%02d:%02d:%02d:%03d",
 | 
			
		||||
                    DTCStorage[i].timestamp / 86400000,    // Days
 | 
			
		||||
                    DTCStorage[i].timestamp / 360000 % 24, // Hours
 | 
			
		||||
                    DTCStorage[i].timestamp / 60000 % 60,  // Minutes
 | 
			
		||||
                    DTCStorage[i].timestamp / 1000 % 60,   // Seconds
 | 
			
		||||
                    DTCStorage[i].timestamp % 1000);       // Milliseconds
 | 
			
		||||
 | 
			
		||||
            // Determine DTC status
 | 
			
		||||
            if (DTCStorage[i].active == DTC_ACTIVE)
 | 
			
		||||
                strcpy(buff_active, "active");
 | 
			
		||||
            else if (DTCStorage[i].active == DTC_PREVIOUS)
 | 
			
		||||
                strcpy(buff_active, "previous");
 | 
			
		||||
            else
 | 
			
		||||
                strcpy(buff_active, "none");
 | 
			
		||||
 | 
			
		||||
            // Display DTC information
 | 
			
		||||
            Debug_pushMessage("%s   %7d   %8s   %8d\n", buff_timestamp, DTCStorage[i].Number, buff_active);
 | 
			
		||||
        }
 | 
			
		||||
    }
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
/**
 | 
			
		||||
 * @brief Initiates a system reboot by setting the system status to shutdown.
 | 
			
		||||
 *
 | 
			
		||||
 * This function sets the global system status to `sysStat_Shutdown`,
 | 
			
		||||
 * which will trigger a system reboot sequence.
 | 
			
		||||
 */
 | 
			
		||||
void Debug_Reboot()
 | 
			
		||||
{
 | 
			
		||||
    globals.systemStatus = sysStat_Shutdown;
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
/**
 | 
			
		||||
 * @brief Processes a debug command.
 | 
			
		||||
 *
 | 
			
		||||
 * This function takes a pointer to a debug command and processes it by
 | 
			
		||||
 * passing it to the `processCmdDebug` function. The command is expected
 | 
			
		||||
 * to be a string, so it is cast to `const char *` before being processed.
 | 
			
		||||
 *
 | 
			
		||||
 * @param command Pointer to the debug command, expected to be a null-terminated string.
 | 
			
		||||
 */
 | 
			
		||||
void Debug_ProcessCommand(uint8_t *command)
 | 
			
		||||
{
 | 
			
		||||
    processCmdDebug((const char *)command);
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
/**
 | 
			
		||||
 * @brief Convert a uint32_t value to a binary string with nibbles separated by a space.
 | 
			
		||||
 *
 | 
			
		||||
 * This function takes a uint32_t value and converts it to a binary string
 | 
			
		||||
 * representation. The binary string is stored in a static buffer and returned
 | 
			
		||||
 * as a const char pointer. Each nibble (4 bits) in the binary representation
 | 
			
		||||
 * is separated by a space. The buffer is overwritten on subsequent calls to
 | 
			
		||||
 * this function.
 | 
			
		||||
 *
 | 
			
		||||
 * @param num The uint32_t value to convert.
 | 
			
		||||
 * @return A pointer to a const char string containing the binary representation
 | 
			
		||||
 * of the input number with nibbles separated by a space.
 | 
			
		||||
 */
 | 
			
		||||
const char *uint32_to_binary_string(uint32_t num)
 | 
			
		||||
{
 | 
			
		||||
    static char binary_str[65]; // 32 bits + 31 spaces + null terminator
 | 
			
		||||
    int i, j;
 | 
			
		||||
    for (i = 31, j = 0; i >= 0; i--, j++)
 | 
			
		||||
    {
 | 
			
		||||
        binary_str[j] = ((num >> i) & 1) ? '1' : '0';
 | 
			
		||||
        if (i % 4 == 0 && i != 0)
 | 
			
		||||
        {
 | 
			
		||||
            binary_str[++j] = ' '; // Insert space after every nibble
 | 
			
		||||
        }
 | 
			
		||||
    }
 | 
			
		||||
    binary_str[j] = '\0'; // Null terminator
 | 
			
		||||
    return binary_str;
 | 
			
		||||
}
 | 
			
		||||
@@ -1,70 +1,121 @@
 | 
			
		||||
/**
 | 
			
		||||
 * @file dtc.cpp
 | 
			
		||||
 * @brief Implementation of functions related to Diagnostic Trouble Codes (DTCs).
 | 
			
		||||
 *
 | 
			
		||||
 * This file contains the implementation of functions that manage the status
 | 
			
		||||
 * and registration of Diagnostic Trouble Codes in the system.
 | 
			
		||||
 *
 | 
			
		||||
 * @author Marcel Peterkau
 | 
			
		||||
 * @date 09.01.2024
 | 
			
		||||
 */
 | 
			
		||||
#include "dtc.h"
 | 
			
		||||
#include "debugger.h"
 | 
			
		||||
 | 
			
		||||
DTCEntry_s DTCStorage[MAX_DTC_STORAGE];
 | 
			
		||||
DTCEntry_t DTCStorage[MAX_DTC_STORAGE];
 | 
			
		||||
 | 
			
		||||
void MaintainDTC(DTCNums_t DTC_no, boolean active)
 | 
			
		||||
// Function implementations...
 | 
			
		||||
 | 
			
		||||
/**
 | 
			
		||||
 * @brief Maintains the status of Diagnostic Trouble Codes (DTCs) in the DTCStorage array.
 | 
			
		||||
 *        Updates the status of existing DTCs or adds new ones based on their activity.
 | 
			
		||||
 *
 | 
			
		||||
 * @param DTC_no      The number of the Diagnostic Trouble Code.
 | 
			
		||||
 * @param active      Indicates whether the DTC is active (true) or inactive (false).
 | 
			
		||||
 * @param DebugValue  Additional debugging information associated with the DTC.
 | 
			
		||||
 */
 | 
			
		||||
void MaintainDTC(DTCNum_t DTC_no, boolean active, uint32_t DebugValue)
 | 
			
		||||
{
 | 
			
		||||
    // Iterate through the existing DTCs in the storage
 | 
			
		||||
    for (int i = 0; i < MAX_DTC_STORAGE; i++)
 | 
			
		||||
    {
 | 
			
		||||
        // Check if the DTC with the specified number exists
 | 
			
		||||
        if (DTCStorage[i].Number == DTC_no)
 | 
			
		||||
        {
 | 
			
		||||
            // If the DTC is active and was not active before, update its status
 | 
			
		||||
            if (active && DTCStorage[i].active != DTC_ACTIVE)
 | 
			
		||||
            {
 | 
			
		||||
                Serial.printf("DTC gone active: %d", DTC_no);
 | 
			
		||||
                Debug_pushMessage("DTC gone active: %d, DebugVal: %d\n", DTC_no, DebugValue);
 | 
			
		||||
                DTCStorage[i].timestamp = millis();
 | 
			
		||||
                DTCStorage[i].active = DTC_ACTIVE;
 | 
			
		||||
                DTCStorage[i].debugVal = DebugValue;
 | 
			
		||||
            }
 | 
			
		||||
            // If the DTC is not active anymore, update its status to previous
 | 
			
		||||
            if (!active && DTCStorage[i].active == DTC_ACTIVE)
 | 
			
		||||
            {
 | 
			
		||||
                Serial.printf("DTC gone previous: %d", DTC_no);
 | 
			
		||||
                Debug_pushMessage("DTC gone previous: %d\n", DTC_no);
 | 
			
		||||
                DTCStorage[i].active = DTC_PREVIOUS;
 | 
			
		||||
            }
 | 
			
		||||
            return;
 | 
			
		||||
            return; // DTC found and processed, exit the function
 | 
			
		||||
        }
 | 
			
		||||
    }
 | 
			
		||||
 | 
			
		||||
    // DTC was not found with upper iteration, but is active
 | 
			
		||||
    // so we need to look for free space to store DTC
 | 
			
		||||
    // DTC was not found in the existing storage, but it is active,
 | 
			
		||||
    // so look for free space to store the new DTC
 | 
			
		||||
    if (active == true)
 | 
			
		||||
    {
 | 
			
		||||
        for (int i = 0; i < MAX_DTC_STORAGE; i++)
 | 
			
		||||
        {
 | 
			
		||||
            // Check for an empty slot in the storage
 | 
			
		||||
            if (DTCStorage[i].Number == DTC_LAST_DTC)
 | 
			
		||||
            {
 | 
			
		||||
                Serial.printf("new DTC registered: %d", DTC_no);
 | 
			
		||||
                Debug_pushMessage("new DTC registered: %d, DebugVal: %d\n", DTC_no, DebugValue);
 | 
			
		||||
                DTCStorage[i].Number = DTC_no;
 | 
			
		||||
                DTCStorage[i].timestamp = millis();
 | 
			
		||||
                DTCStorage[i].active = DTC_ACTIVE;
 | 
			
		||||
                return;
 | 
			
		||||
                DTCStorage[i].debugVal = DebugValue;
 | 
			
		||||
                return; // New DTC registered, exit the function
 | 
			
		||||
            }
 | 
			
		||||
        }
 | 
			
		||||
    }
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
void ClearDTC(DTCNums_t DTC_no)
 | 
			
		||||
/**
 | 
			
		||||
 * @brief Clears a specific Diagnostic Trouble Code (DTC) entry.
 | 
			
		||||
 *
 | 
			
		||||
 * This function clears the information related to a specific DTC entry,
 | 
			
		||||
 * setting its status to inactive and timestamp to zero.
 | 
			
		||||
 *
 | 
			
		||||
 * @param DTC_no The Diagnostic Trouble Code number to be cleared.
 | 
			
		||||
 */
 | 
			
		||||
void ClearDTC(DTCNum_t DTC_no)
 | 
			
		||||
{
 | 
			
		||||
    for (int i = 0; i < MAX_DTC_STORAGE; i++)
 | 
			
		||||
    {
 | 
			
		||||
        if (DTCStorage[i].Number == DTC_no)
 | 
			
		||||
        {
 | 
			
		||||
            DTCStorage[i].Number = DTC_LAST_DTC;
 | 
			
		||||
            DTCStorage[i].active = DTC_NONE;
 | 
			
		||||
            DTCStorage[i].active = DTC_INACTIVE;
 | 
			
		||||
            DTCStorage[i].timestamp = 0;
 | 
			
		||||
        }
 | 
			
		||||
    }
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
/**
 | 
			
		||||
 * @brief Clears all Diagnostic Trouble Code (DTC) entries.
 | 
			
		||||
 *
 | 
			
		||||
 * This function clears all DTC entries, setting their status to inactive and
 | 
			
		||||
 * timestamps to zero.
 | 
			
		||||
 */
 | 
			
		||||
void ClearAllDTC()
 | 
			
		||||
{
 | 
			
		||||
    for (int i = 0; i < MAX_DTC_STORAGE; i++)
 | 
			
		||||
    {
 | 
			
		||||
        DTCStorage[i].Number = DTC_LAST_DTC;
 | 
			
		||||
        DTCStorage[i].active = DTC_NONE;
 | 
			
		||||
        DTCStorage[i].active = DTC_INACTIVE;
 | 
			
		||||
        DTCStorage[i].timestamp = 0;
 | 
			
		||||
    }
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
DTCNums_t getlastDTC(boolean only_active)
 | 
			
		||||
/**
 | 
			
		||||
 * @brief Gets the last recorded Diagnostic Trouble Code (DTC) number.
 | 
			
		||||
 *
 | 
			
		||||
 * This function retrieves the DTC number of the last recorded DTC based on the
 | 
			
		||||
 * timestamp. Optionally, it can filter only active DTCs.
 | 
			
		||||
 *
 | 
			
		||||
 * @param only_active If true, considers only active DTCs; otherwise, considers all.
 | 
			
		||||
 * @return The DTC number of the last recorded DTC or DTC_LAST_DTC if none found.
 | 
			
		||||
 */
 | 
			
		||||
DTCNum_t getlastDTC(boolean only_active)
 | 
			
		||||
{
 | 
			
		||||
    int8_t pointer = -1;
 | 
			
		||||
    uint32_t lasttimestamp = 0;
 | 
			
		||||
@@ -82,4 +133,64 @@ DTCNums_t getlastDTC(boolean only_active)
 | 
			
		||||
    }
 | 
			
		||||
 | 
			
		||||
    return pointer >= 0 ? DTCStorage[pointer].Number : DTC_LAST_DTC;
 | 
			
		||||
}
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
/**
 | 
			
		||||
 * @brief Gets the severity level for a specific Diagnostic Trouble Code (DTC).
 | 
			
		||||
 *
 | 
			
		||||
 * This function looks up the severity level associated with the provided DTC code
 | 
			
		||||
 * from the predefined list of DTC definitions.
 | 
			
		||||
 *
 | 
			
		||||
 * @param targetCode The DTC code for which to retrieve the severity.
 | 
			
		||||
 * @return The severity level of the specified DTC or DTC_NONE if not found.
 | 
			
		||||
 */
 | 
			
		||||
DTCSeverity_t getSeverityForDTC(DTCNum_t targetCode)
 | 
			
		||||
{
 | 
			
		||||
    for (int i = 0; i < DTC_LAST_DTC; i++)
 | 
			
		||||
    {
 | 
			
		||||
        if (dtc_definitions[i].code == targetCode)
 | 
			
		||||
        {
 | 
			
		||||
            return dtc_definitions[i].severity;
 | 
			
		||||
        }
 | 
			
		||||
    }
 | 
			
		||||
    return DTC_NONE;
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
/**
 | 
			
		||||
 * @brief Processes Diagnostic Trouble Codes (DTCs) and updates system status accordingly.
 | 
			
		||||
 *
 | 
			
		||||
 * This function checks for the presence of active DTCs and adjusts the system status
 | 
			
		||||
 * based on the severity of the most critical DTC. If a critical DTC is detected,
 | 
			
		||||
 * the system status is set to sysStat_Error, potentially triggering a system shutdown.
 | 
			
		||||
 *
 | 
			
		||||
 * @note The function also preserves the original system status when transitioning to an error state
 | 
			
		||||
 *       and restores it when all DTCs are cleared.
 | 
			
		||||
 */
 | 
			
		||||
void DTC_Process()
 | 
			
		||||
{
 | 
			
		||||
    static tSystem_Status preserverSysStatusError;
 | 
			
		||||
    DTCNum_t lastDTC = getlastDTC(true);
 | 
			
		||||
 | 
			
		||||
    if (lastDTC < DTC_LAST_DTC)
 | 
			
		||||
    {
 | 
			
		||||
        globals.hasDTC = true;
 | 
			
		||||
 | 
			
		||||
        if (getSeverityForDTC(lastDTC) == DTC_CRITICAL && globals.systemStatus != sysStat_Shutdown)
 | 
			
		||||
        {
 | 
			
		||||
            if (globals.systemStatus != sysStat_Error)
 | 
			
		||||
            {
 | 
			
		||||
                preserverSysStatusError = globals.systemStatus;
 | 
			
		||||
            }
 | 
			
		||||
            globals.systemStatus = sysStat_Error;
 | 
			
		||||
        }
 | 
			
		||||
    }
 | 
			
		||||
    else
 | 
			
		||||
    {
 | 
			
		||||
        globals.hasDTC = false;
 | 
			
		||||
 | 
			
		||||
        if (globals.systemStatus == sysStat_Error)
 | 
			
		||||
        {
 | 
			
		||||
            globals.systemStatus = preserverSysStatusError;
 | 
			
		||||
        }
 | 
			
		||||
    }
 | 
			
		||||
}
 | 
			
		||||
 
 | 
			
		||||
@@ -1,39 +0,0 @@
 | 
			
		||||
#ifndef _DTC_H_
 | 
			
		||||
#define _DTC_H_
 | 
			
		||||
 | 
			
		||||
#include <Arduino.h>
 | 
			
		||||
 | 
			
		||||
#define MAX_DTC_STORAGE 6
 | 
			
		||||
 | 
			
		||||
typedef enum DTCNums_e
 | 
			
		||||
{
 | 
			
		||||
  DTC_NO_EEPROM_FOUND,
 | 
			
		||||
  DTC_EEPROM_CFG_BAD,
 | 
			
		||||
  DTC_EEPROM_PDS_BAD,
 | 
			
		||||
  DTC_EEPROM_VERSION_BAD,
 | 
			
		||||
  DTC_EEPROM_WORNOUT,                 // this will happen if the EEPROM-cells are all overwritten 1 million times!
 | 
			
		||||
  DTC_EEPROM_PDS_MARKER_INVALID,      // This happens if the Marker of the PersistanceData was pointing to an EE-Adress bigger than the used EEPROM-IC
 | 
			
		||||
  DTC_LAST_DTC
 | 
			
		||||
} DTCNums_t;
 | 
			
		||||
 | 
			
		||||
typedef enum DTCActive_e
 | 
			
		||||
{
 | 
			
		||||
  DTC_ACTIVE,
 | 
			
		||||
  DTC_PREVIOUS,
 | 
			
		||||
  DTC_NONE
 | 
			
		||||
} DTCActive_t;
 | 
			
		||||
 | 
			
		||||
typedef struct DTCEntry_s
 | 
			
		||||
{
 | 
			
		||||
  DTCNums_t Number;
 | 
			
		||||
  uint32_t timestamp;
 | 
			
		||||
  DTCActive_t active;
 | 
			
		||||
} DTCEntry_t;
 | 
			
		||||
 | 
			
		||||
void MaintainDTC(DTCNums_t DTC_no, boolean active);
 | 
			
		||||
void ClearDTC(DTCNums_t DTC_no);
 | 
			
		||||
void ClearAllDTC();
 | 
			
		||||
DTCNums_t getlastDTC(boolean only_active);
 | 
			
		||||
 | 
			
		||||
extern DTCEntry_s DTCStorage[MAX_DTC_STORAGE];
 | 
			
		||||
#endif
 | 
			
		||||
							
								
								
									
										18
									
								
								Software/src/dtc_defs.txt
									
									
									
									
									
										Normal file
									
								
							
							
						
						@@ -0,0 +1,18 @@
 | 
			
		||||
# No. |                 DTC-Constant |      Severity |                 Title | Description     
 | 
			
		||||
#-----|------------------------------|---------------|-----------------------|----------------------------------------------------------------------------------------------------------------------------------------------------
 | 
			
		||||
    1;              DTC_BAT_CRITICAL;   DTC_CRITICAL;              Akku leer;  Akku ist komplett leer. Den Akku aufladen!
 | 
			
		||||
    2;                   DTC_BAT_LOW;       DTC_WARN;           Akku niedrig;  Akku ist unter der Warnschwelle. Den Akku demnächst aufladen
 | 
			
		||||
    3;           DTC_NO_EEPROM_FOUND;   DTC_CRITICAL;    kein EEPROM erkannt;  Es wurde kein EEPROM gefunden. Dies lässt einen Hardware-Defekt vermuten.
 | 
			
		||||
    4;            DTC_EEPROM_CFG_BAD;   DTC_CRITICAL;  EEPROM CFG Checksumme;  Die Checksumme der Config-Partition des EEPROM ist ungültig. Setzen sie den EEPROM-Bereich 'CFG' im Menu 'Wartung' zurück
 | 
			
		||||
    5;            DTC_EEPROM_PDS_BAD;   DTC_CRITICAL;  EEPROM PDS Checksumme;  Die Checksumme der Betriebsdaten-Partition des EEPROM ist ungültig. Setzen sie den EEPROM-Bereich 'PDS' im Menu 'Wartung' zurück
 | 
			
		||||
    6;      DTC_EEPROM_PDSADRESS_BAD;   DTC_CRITICAL;     EEPROM PDS Adresse;  Die Adresse der Betriebsdaten-Partition im EEPROM ist ungültig. Setzen sie den EEPROM-Bereich 'PDS' im Menu 'Wartung' zurück
 | 
			
		||||
    7;        DTC_EEPROM_VERSION_BAD;   DTC_CRITICAL;  EEPROM Version falsch;  Die Layout-Version des EEPROM stimmt nicht mit der Firmware-Version überein. Setzen sie den EEPROM-Bereich 'CFG' im Menu 'Wartung' zurück
 | 
			
		||||
    8;             DTC_FLASHFS_ERROR;   DTC_CRITICAL;   Flashspeicher Fehler;  Der Flashspeicher konnte nicht initialisiert werden. Aktualisieren sie Flash & Firmware
 | 
			
		||||
    9;     DTC_FLASHFS_VERSION_ERROR;   DTC_CRITICAL;    Flashversion falsch;  Die Version des Flashspeicher stimmt nicht mit der Firmware-Version überein. Aktualisieren sie den Flash mit der passenden Update-Datei
 | 
			
		||||
   10;          DTC_NO_BATMNON_FOUND;   DTC_CRITICAL;  Keine Akkuüberwachung;  Es wurde keine Akkuüberwachung über I2C gefunden, Prüfen sie die Hardware!
 | 
			
		||||
   11;             DTC_NO_LORA_FOUND;   DTC_CRITICAL; LoRa-Transceiver Error;  Es konnte keine Verbindung zum LoRa-Transceiver hergestellt werden. Prüfen Sie die Hardware auf Defekte
 | 
			
		||||
   12;         DTC_EEPROM_CFG_SANITY;       DTC_WARN;     Config-Validierung;  Ein oder mehrer Einstellungswerte sind ausserhalb plausibler Werte. Prüfen Sie Ihre Einstellungen
 | 
			
		||||
   13;     DTC_EEPROM_MIGRATE_FAILED;   DTC_CRITICAL;       EEPROM-Migration;  Es wurde ein altes EEPROm Image erkannt, konnte aber nicht migriert werden. EEPROM manuell zurück setzen und neue Einstellunge speichern.
 | 
			
		||||
   14;             DTC_FAKE_DTC_INFO;       DTC_INFO;         Dummy-DTC Info;  Ein Dummy-DTC der Schwere "Info" für Debugging-Zwecke
 | 
			
		||||
   15;             DTC_FAKE_DTC_WARN;       DTC_WARN;      Dummy-DTC Warnung;  Ein Dummy-DTC der Schwere "Warnung" für Debugging-Zwecke
 | 
			
		||||
   16;             DTC_FAKE_DTC_CRIT;   DTC_CRITICAL;     Dummy-DTC Kritisch;  Ein Dummy-DTC der Schwere "Kritisch" für Debugging-Zwecke
 | 
			
		||||
							
								
								
									
										460
									
								
								Software/src/eeprom.cpp
									
									
									
									
									
										Normal file
									
								
							
							
						
						@@ -0,0 +1,460 @@
 | 
			
		||||
/**
 | 
			
		||||
 * @file config.cpp
 | 
			
		||||
 * @brief Implementation of EEPROM and configuration-related functions.
 | 
			
		||||
 *
 | 
			
		||||
 * This file contains functions for managing EEPROM storage and handling configuration data.
 | 
			
		||||
 * It includes the definitions of configuration structures, EEPROM access, and utility functions.
 | 
			
		||||
 */
 | 
			
		||||
 | 
			
		||||
#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);
 | 
			
		||||
 | 
			
		||||
// Configuration and persistence data structures
 | 
			
		||||
configData_t ConfigData;
 | 
			
		||||
persistenceData_t PersistenceData;
 | 
			
		||||
 | 
			
		||||
// EEPROM version identifier
 | 
			
		||||
const uint16_t eeVersion = EEPROM_STRUCTURE_REVISION;
 | 
			
		||||
 | 
			
		||||
// Flag indicating whether EEPROM is available
 | 
			
		||||
boolean eeAvailable = false;
 | 
			
		||||
 | 
			
		||||
// Offsets within EEPROM for ConfigData and PersistenceData
 | 
			
		||||
const uint16_t startofConfigData = 16;
 | 
			
		||||
const uint16_t startofPersistence = 16 + sizeof(ConfigData) + (sizeof(ConfigData) % 16);
 | 
			
		||||
 | 
			
		||||
// Function prototype to check EEPROM availability
 | 
			
		||||
boolean checkEEPROMavailable();
 | 
			
		||||
 | 
			
		||||
/**
 | 
			
		||||
 * @brief Initializes EEPROM and checks its availability.
 | 
			
		||||
 *
 | 
			
		||||
 * This function initializes the EEPROM using the I2C_eeprom instance and checks if it's available.
 | 
			
		||||
 */
 | 
			
		||||
boolean InitEEPROM()
 | 
			
		||||
{
 | 
			
		||||
  Wire.begin();
 | 
			
		||||
  ConfigData = ConfigData_defaults;
 | 
			
		||||
  PersistenceData = {0};
 | 
			
		||||
  ee.begin();
 | 
			
		||||
  return checkEEPROMavailable();
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
/**
 | 
			
		||||
 * @brief Processes EEPROM actions based on the request from the global state.
 | 
			
		||||
 *
 | 
			
		||||
 * This function processes EEPROM actions based on the request from the global state.
 | 
			
		||||
 * It performs actions such as saving, loading, and formatting EEPROM data for both configuration and persistence.
 | 
			
		||||
 */
 | 
			
		||||
void EEPROM_Process()
 | 
			
		||||
{
 | 
			
		||||
  switch (globals.requestEEAction)
 | 
			
		||||
  {
 | 
			
		||||
  case EE_CFG_SAVE:
 | 
			
		||||
    StoreConfig_EEPROM();
 | 
			
		||||
    globals.requestEEAction = EE_IDLE;
 | 
			
		||||
    Debug_pushMessage("Stored EEPROM CFG\n");
 | 
			
		||||
    break;
 | 
			
		||||
  case EE_CFG_LOAD:
 | 
			
		||||
    GetConfig_EEPROM();
 | 
			
		||||
    globals.requestEEAction = EE_IDLE;
 | 
			
		||||
    Debug_pushMessage("Loaded EEPROM CFG\n");
 | 
			
		||||
    break;
 | 
			
		||||
  case EE_CFG_FORMAT:
 | 
			
		||||
    FormatConfig_EEPROM();
 | 
			
		||||
    globals.requestEEAction = EE_IDLE;
 | 
			
		||||
    GetConfig_EEPROM();
 | 
			
		||||
    Debug_pushMessage("Formatted EEPROM CFG\n");
 | 
			
		||||
    break;
 | 
			
		||||
  case EE_PDS_SAVE:
 | 
			
		||||
    StorePersistence_EEPROM();
 | 
			
		||||
    globals.requestEEAction = EE_IDLE;
 | 
			
		||||
    Debug_pushMessage("Stored EEPROM PDS\n");
 | 
			
		||||
    break;
 | 
			
		||||
  case EE_PDS_LOAD:
 | 
			
		||||
    GetPersistence_EEPROM();
 | 
			
		||||
    globals.requestEEAction = EE_IDLE;
 | 
			
		||||
    Debug_pushMessage("Loaded EEPROM PDS\n");
 | 
			
		||||
    break;
 | 
			
		||||
  case EE_PDS_FORMAT:
 | 
			
		||||
    FormatPersistence_EEPROM();
 | 
			
		||||
    globals.requestEEAction = EE_IDLE;
 | 
			
		||||
    GetPersistence_EEPROM();
 | 
			
		||||
    Debug_pushMessage("Formatted EEPROM PDS\n");
 | 
			
		||||
    break;
 | 
			
		||||
  case EE_FORMAT_ALL:
 | 
			
		||||
    FormatConfig_EEPROM();
 | 
			
		||||
    FormatPersistence_EEPROM();
 | 
			
		||||
    GetConfig_EEPROM();
 | 
			
		||||
    GetPersistence_EEPROM();
 | 
			
		||||
    globals.requestEEAction = EE_IDLE;
 | 
			
		||||
    Debug_pushMessage("Formatted EEPROM ALL\n");
 | 
			
		||||
    break;
 | 
			
		||||
  case EE_ALL_SAVE:
 | 
			
		||||
    StorePersistence_EEPROM();
 | 
			
		||||
    StoreConfig_EEPROM();
 | 
			
		||||
    globals.requestEEAction = EE_IDLE;
 | 
			
		||||
    Debug_pushMessage("Stored EEPROM ALL\n");
 | 
			
		||||
    break;
 | 
			
		||||
  case EE_IDLE:
 | 
			
		||||
  default:
 | 
			
		||||
    globals.requestEEAction = EE_IDLE;
 | 
			
		||||
  }
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
/**
 | 
			
		||||
 * @brief Stores the configuration data in EEPROM.
 | 
			
		||||
 *
 | 
			
		||||
 * This function calculates the checksum for the configuration data, updates it, and stores it in EEPROM.
 | 
			
		||||
 * It also performs a sanity check on the configuration and raises a diagnostic trouble code (DTC) if needed.
 | 
			
		||||
 */
 | 
			
		||||
void StoreConfig_EEPROM()
 | 
			
		||||
{
 | 
			
		||||
  // Berechnung der Prüfsumme
 | 
			
		||||
  ConfigData.checksum = 0;
 | 
			
		||||
  ConfigData.checksum = Checksum_EEPROM((uint8_t *)&ConfigData, sizeof(ConfigData));
 | 
			
		||||
 | 
			
		||||
  // Überprüfung, ob der EEPROM verfügbar ist
 | 
			
		||||
  if (!checkEEPROMavailable())
 | 
			
		||||
    return;
 | 
			
		||||
 | 
			
		||||
  // Byteweise in den EEPROM schreiben
 | 
			
		||||
  uint8_t *dataPtr = (uint8_t *)&ConfigData;
 | 
			
		||||
  for (uint16_t i = 0; i < sizeof(ConfigData); i++)
 | 
			
		||||
  {
 | 
			
		||||
    ee.writeByte(startofConfigData + i, dataPtr[i]);
 | 
			
		||||
  }
 | 
			
		||||
 | 
			
		||||
  // Sanity Check der Konfiguration
 | 
			
		||||
  uint32_t ConfigSanityCheckResult = ConfigSanityCheck(false);
 | 
			
		||||
  if (ConfigSanityCheckResult > 0)
 | 
			
		||||
  {
 | 
			
		||||
    MaintainDTC(DTC_EEPROM_CFG_SANITY, true, ConfigSanityCheckResult);
 | 
			
		||||
  }
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
/**
 | 
			
		||||
 * @brief Retrieves the configuration data from EEPROM.
 | 
			
		||||
 *
 | 
			
		||||
 * This function reads the configuration data from EEPROM, performs a checksum validation,
 | 
			
		||||
 * and conducts a sanity check on the configuration. It raises a diagnostic trouble code (DTC) if needed.
 | 
			
		||||
 */
 | 
			
		||||
void GetConfig_EEPROM()
 | 
			
		||||
{
 | 
			
		||||
  if (!checkEEPROMavailable())
 | 
			
		||||
    return;
 | 
			
		||||
 | 
			
		||||
  ee.readBlock(startofConfigData, (uint8_t *)&ConfigData, sizeof(ConfigData));
 | 
			
		||||
 | 
			
		||||
  uint32_t checksum = ConfigData.checksum;
 | 
			
		||||
  ConfigData.checksum = 0;
 | 
			
		||||
 | 
			
		||||
  MaintainDTC(DTC_EEPROM_CFG_BAD, (Checksum_EEPROM((uint8_t *)&ConfigData, sizeof(ConfigData)) != checksum));
 | 
			
		||||
 | 
			
		||||
  ConfigData.checksum = checksum;
 | 
			
		||||
 | 
			
		||||
  uint32_t ConfigSanityCheckResult = ConfigSanityCheck(true);
 | 
			
		||||
 | 
			
		||||
  MaintainDTC(DTC_EEPROM_CFG_SANITY, (ConfigSanityCheckResult > 0), ConfigSanityCheckResult);
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
/**
 | 
			
		||||
 * @brief Stores the persistence data in EEPROM.
 | 
			
		||||
 *
 | 
			
		||||
 * This function increments the write cycle counter, performs a checksum calculation on the persistence data,
 | 
			
		||||
 * and stores it in EEPROM. It also handles EEPROM page movement when needed.
 | 
			
		||||
 */
 | 
			
		||||
void StorePersistence_EEPROM()
 | 
			
		||||
{
 | 
			
		||||
  if (PersistenceData.writeCycleCounter >= 0xFFF0)
 | 
			
		||||
    MovePersistencePage_EEPROM(false);
 | 
			
		||||
  else
 | 
			
		||||
    PersistenceData.writeCycleCounter++;
 | 
			
		||||
 | 
			
		||||
  PersistenceData.checksum = 0;
 | 
			
		||||
  PersistenceData.checksum = Checksum_EEPROM((uint8_t *)&PersistenceData, sizeof(PersistenceData));
 | 
			
		||||
 | 
			
		||||
  if (!checkEEPROMavailable())
 | 
			
		||||
    return;
 | 
			
		||||
 | 
			
		||||
  // Byteweise in den EEPROM schreiben
 | 
			
		||||
  uint8_t *dataPtr = (uint8_t *)&PersistenceData;
 | 
			
		||||
  for (uint16_t i = 0; i < sizeof(PersistenceData); i++)
 | 
			
		||||
  {
 | 
			
		||||
    ee.writeByte(globals.eePersistanceAdress + i, dataPtr[i]);
 | 
			
		||||
  }
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
/**
 | 
			
		||||
 * @brief Retrieves the persistence data from EEPROM.
 | 
			
		||||
 *
 | 
			
		||||
 * This function reads the EEPROM to get the start address of the persistence data.
 | 
			
		||||
 * If the start address is out of range, it resets and stores defaults. Otherwise,
 | 
			
		||||
 * it reads from EEPROM and checks if the data is correct.
 | 
			
		||||
 */
 | 
			
		||||
void GetPersistence_EEPROM()
 | 
			
		||||
{
 | 
			
		||||
  if (!checkEEPROMavailable())
 | 
			
		||||
    return;
 | 
			
		||||
 | 
			
		||||
  ee.readBlock(0, (uint8_t *)&globals.eePersistanceAdress, sizeof(globals.eePersistanceAdress));
 | 
			
		||||
  // if we got the StartAdress of Persistance and it's out of Range - we Reset it and store defaults
 | 
			
		||||
  // otherwise we Read from eeprom and check if everything is correct
 | 
			
		||||
  if (globals.eePersistanceAdress < startofPersistence || globals.eePersistanceAdress > ee.getDeviceSize())
 | 
			
		||||
  {
 | 
			
		||||
    MovePersistencePage_EEPROM(true);
 | 
			
		||||
    FormatPersistence_EEPROM();
 | 
			
		||||
    MaintainDTC(DTC_EEPROM_PDSADRESS_BAD, true);
 | 
			
		||||
  }
 | 
			
		||||
  else
 | 
			
		||||
  {
 | 
			
		||||
    ee.readBlock(globals.eePersistanceAdress, (uint8_t *)&PersistenceData, sizeof(PersistenceData));
 | 
			
		||||
 | 
			
		||||
    uint32_t checksum = PersistenceData.checksum;
 | 
			
		||||
    PersistenceData.checksum = 0;
 | 
			
		||||
 | 
			
		||||
    MaintainDTC(DTC_EEPROM_PDS_BAD, (Checksum_EEPROM((uint8_t *)&PersistenceData, sizeof(PersistenceData)) != checksum));
 | 
			
		||||
 | 
			
		||||
    PersistenceData.checksum = checksum;
 | 
			
		||||
  }
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
/**
 | 
			
		||||
 * @brief Formats the configuration partition in EEPROM.
 | 
			
		||||
 *
 | 
			
		||||
 * This function resets the configuration data to defaults and stores it in EEPROM.
 | 
			
		||||
 */
 | 
			
		||||
void FormatConfig_EEPROM()
 | 
			
		||||
{
 | 
			
		||||
  Debug_pushMessage("Formatting Config-Partition\n");
 | 
			
		||||
  ConfigData = ConfigData_defaults;
 | 
			
		||||
  ConfigData.EEPROM_Version = eeVersion;
 | 
			
		||||
  StoreConfig_EEPROM();
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
/**
 | 
			
		||||
 * @brief Formats the persistence partition in EEPROM.
 | 
			
		||||
 *
 | 
			
		||||
 * This function resets the persistence data to defaults and stores it in EEPROM.
 | 
			
		||||
 */
 | 
			
		||||
void FormatPersistence_EEPROM()
 | 
			
		||||
{
 | 
			
		||||
  Debug_pushMessage("Formatting Persistance-Partition\n");
 | 
			
		||||
  PersistenceData = {0};
 | 
			
		||||
  // memset(&PersistenceData, 0, sizeof(PersistenceData));
 | 
			
		||||
  StorePersistence_EEPROM();
 | 
			
		||||
}
 | 
			
		||||
/**
 | 
			
		||||
 * @brief Moves the persistence page in EEPROM.
 | 
			
		||||
 *
 | 
			
		||||
 * This function adjusts the persistence page address and resets the write cycle counter.
 | 
			
		||||
 *
 | 
			
		||||
 * @param reset If true, the function resets the persistence page address to the start of the partition.
 | 
			
		||||
 */
 | 
			
		||||
void MovePersistencePage_EEPROM(boolean reset)
 | 
			
		||||
{
 | 
			
		||||
  if (!checkEEPROMavailable())
 | 
			
		||||
    return;
 | 
			
		||||
 | 
			
		||||
  globals.eePersistanceAdress += sizeof(PersistenceData);
 | 
			
		||||
  PersistenceData.writeCycleCounter = 0;
 | 
			
		||||
 | 
			
		||||
  // Check if we reached the end of the EEPROM and start over at the beginning
 | 
			
		||||
  if ((globals.eePersistanceAdress + sizeof(PersistenceData)) > ee.getDeviceSize() || reset)
 | 
			
		||||
  {
 | 
			
		||||
    globals.eePersistanceAdress = startofPersistence;
 | 
			
		||||
  }
 | 
			
		||||
 | 
			
		||||
  ee.updateBlock(0, (uint8_t *)&globals.eePersistanceAdress, sizeof(globals.eePersistanceAdress));
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
/**
 | 
			
		||||
 * @brief Calculate CRC-32 checksum for a block of data.
 | 
			
		||||
 *
 | 
			
		||||
 * This function implements the CRC-32 algorithm.
 | 
			
		||||
 *
 | 
			
		||||
 * @param data Pointer to the data block.
 | 
			
		||||
 * @param len Length of the data block in bytes.
 | 
			
		||||
 * @return CRC-32 checksum.
 | 
			
		||||
 */
 | 
			
		||||
uint32_t Checksum_EEPROM(uint8_t const *data, size_t len)
 | 
			
		||||
{
 | 
			
		||||
  if (data == NULL)
 | 
			
		||||
    return 0;
 | 
			
		||||
 | 
			
		||||
  uint32_t crc = 0xFFFFFFFF;
 | 
			
		||||
  uint32_t mask;
 | 
			
		||||
 | 
			
		||||
  while (len--)
 | 
			
		||||
  {
 | 
			
		||||
    crc ^= *data++;
 | 
			
		||||
 | 
			
		||||
    for (uint8_t k = 0; k < 8; k++)
 | 
			
		||||
    {
 | 
			
		||||
      mask = -(crc & 1);
 | 
			
		||||
      crc = (crc >> 1) ^ (0xEDB88320 & mask);
 | 
			
		||||
    }
 | 
			
		||||
  }
 | 
			
		||||
 | 
			
		||||
  return ~crc;
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
/**
 | 
			
		||||
 * @brief Dump a portion of EEPROM contents for debugging.
 | 
			
		||||
 *
 | 
			
		||||
 * This function prints the contents of a specified portion of EEPROM in a formatted way.
 | 
			
		||||
 *
 | 
			
		||||
 * @param memoryAddress Starting address in EEPROM.
 | 
			
		||||
 * @param length Number of bytes to dump.
 | 
			
		||||
 */
 | 
			
		||||
void dumpEEPROM(uint16_t memoryAddress, uint16_t length)
 | 
			
		||||
{
 | 
			
		||||
#define BLOCK_TO_LENGTH 16
 | 
			
		||||
 | 
			
		||||
  if (!checkEEPROMavailable())
 | 
			
		||||
    return;
 | 
			
		||||
 | 
			
		||||
  char ascii_buf[BLOCK_TO_LENGTH + 1] = {0};
 | 
			
		||||
  sprintf(ascii_buf, "%*s", BLOCK_TO_LENGTH, "ASCII");
 | 
			
		||||
 | 
			
		||||
  // Print column headers
 | 
			
		||||
  Debug_pushMessage(PSTR("\nAddress "));
 | 
			
		||||
  for (int x = 0; x < BLOCK_TO_LENGTH; x++)
 | 
			
		||||
    Debug_pushMessage("%3d", x);
 | 
			
		||||
 | 
			
		||||
  // Align address and length to BLOCK_TO_LENGTH boundaries
 | 
			
		||||
  memoryAddress = memoryAddress / BLOCK_TO_LENGTH * BLOCK_TO_LENGTH;
 | 
			
		||||
  length = (length + BLOCK_TO_LENGTH - 1) / BLOCK_TO_LENGTH * BLOCK_TO_LENGTH;
 | 
			
		||||
 | 
			
		||||
  // Iterate through the specified portion of EEPROM
 | 
			
		||||
  for (unsigned int i = 0; i < length; i++)
 | 
			
		||||
  {
 | 
			
		||||
    int blockpoint = memoryAddress % BLOCK_TO_LENGTH;
 | 
			
		||||
 | 
			
		||||
    // Print ASCII representation header for each block
 | 
			
		||||
    if (blockpoint == 0)
 | 
			
		||||
    {
 | 
			
		||||
      if (i > 0) // Ensure we don't print an empty ASCII buffer on the first iteration
 | 
			
		||||
      {
 | 
			
		||||
        ascii_buf[BLOCK_TO_LENGTH] = 0;
 | 
			
		||||
        Debug_pushMessage("  %s", ascii_buf);
 | 
			
		||||
      }
 | 
			
		||||
      Debug_pushMessage("\n0x%05X:", memoryAddress);
 | 
			
		||||
      memset(ascii_buf, ' ', BLOCK_TO_LENGTH); // Clear the ASCII buffer with spaces
 | 
			
		||||
    }
 | 
			
		||||
 | 
			
		||||
    // Read and print each byte
 | 
			
		||||
    uint8_t byte = ee.readByte(memoryAddress);
 | 
			
		||||
    ascii_buf[blockpoint] = (byte >= 0x20 && byte <= 0x7E) ? byte : '.';
 | 
			
		||||
    Debug_pushMessage(" %02X", byte);
 | 
			
		||||
 | 
			
		||||
    memoryAddress++;
 | 
			
		||||
  }
 | 
			
		||||
 | 
			
		||||
  // Print remaining ASCII buffer
 | 
			
		||||
  ascii_buf[BLOCK_TO_LENGTH] = 0;
 | 
			
		||||
  Debug_pushMessage("  %s\n", ascii_buf); // Final ASCII line
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
/**
 | 
			
		||||
 * @brief Check if EEPROM is available and connected.
 | 
			
		||||
 *
 | 
			
		||||
 * This function checks if the EEPROM is available and connected. If not, it triggers
 | 
			
		||||
 * a diagnostic trouble code (DTC) indicating the absence of EEPROM.
 | 
			
		||||
 *
 | 
			
		||||
 * @return true if EEPROM is available, false otherwise.
 | 
			
		||||
 */
 | 
			
		||||
boolean checkEEPROMavailable()
 | 
			
		||||
{
 | 
			
		||||
  // Check if EEPROM is connected
 | 
			
		||||
  if (!ee.isConnected())
 | 
			
		||||
  {
 | 
			
		||||
    // Trigger DTC for no EEPROM found
 | 
			
		||||
    MaintainDTC(DTC_NO_EEPROM_FOUND, true);
 | 
			
		||||
    return false;
 | 
			
		||||
  }
 | 
			
		||||
 | 
			
		||||
  // Clear DTC for no EEPROM found since it's available now
 | 
			
		||||
  MaintainDTC(DTC_NO_EEPROM_FOUND, false);
 | 
			
		||||
 | 
			
		||||
  // EEPROM is available
 | 
			
		||||
  return true;
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
/**
 | 
			
		||||
 * @brief Perform sanity check on configuration settings.
 | 
			
		||||
 *
 | 
			
		||||
 * This function checks the validity of various configuration settings and returns a bitmask
 | 
			
		||||
 * indicating which settings need to be reset. If autocorrect is enabled, it resets the settings
 | 
			
		||||
 * to their default values.
 | 
			
		||||
 *
 | 
			
		||||
 * @param autocorrect If true, automatically correct invalid settings by resetting to defaults.
 | 
			
		||||
 * @return A bitmask indicating which settings need to be reset.
 | 
			
		||||
 */
 | 
			
		||||
uint32_t ConfigSanityCheck(bool autocorrect)
 | 
			
		||||
{
 | 
			
		||||
  uint32_t setting_reset_bits = 0;
 | 
			
		||||
 | 
			
		||||
  if (!validateWiFiString(ConfigData.wifi_client_ssid, sizeof(ConfigData.wifi_client_ssid)))
 | 
			
		||||
  {
 | 
			
		||||
    SET_BIT(setting_reset_bits, 0);
 | 
			
		||||
    if (autocorrect)
 | 
			
		||||
      strncpy(ConfigData.wifi_client_ssid, ConfigData_defaults.wifi_client_ssid, sizeof(ConfigData.wifi_client_ssid));
 | 
			
		||||
  }
 | 
			
		||||
 | 
			
		||||
  if (!validateWiFiString(ConfigData.wifi_client_password, sizeof(ConfigData.wifi_client_password)))
 | 
			
		||||
  {
 | 
			
		||||
    SET_BIT(setting_reset_bits, 1);
 | 
			
		||||
    if (autocorrect)
 | 
			
		||||
      strncpy(ConfigData.wifi_client_password, ConfigData_defaults.wifi_client_password, sizeof(ConfigData.wifi_client_password));
 | 
			
		||||
  }
 | 
			
		||||
  // Return the bitmask indicating which settings need to be reset
 | 
			
		||||
  return setting_reset_bits;
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
 | 
			
		||||
/**
 | 
			
		||||
 * @brief Write sequential numbers to a portion of EEPROM.
 | 
			
		||||
 *
 | 
			
		||||
 * This function writes sequential numbers starting from 0 to a specified portion of EEPROM.
 | 
			
		||||
 * If the number reaches 255, it wraps around and starts again from 1.
 | 
			
		||||
 *
 | 
			
		||||
 * @param memoryAddress Starting address in EEPROM.
 | 
			
		||||
 * @param length Number of bytes to write.
 | 
			
		||||
 */
 | 
			
		||||
void writeSequentialToEEPROM(uint16_t memoryAddress, uint16_t length)
 | 
			
		||||
{
 | 
			
		||||
  if (!checkEEPROMavailable())
 | 
			
		||||
    return;
 | 
			
		||||
 | 
			
		||||
  uint8_t value = 0;
 | 
			
		||||
  for (uint16_t i = 0; i < length; i++)
 | 
			
		||||
  {
 | 
			
		||||
    ee.writeByte(memoryAddress + i, value);
 | 
			
		||||
    value = (value == 255) ? 1 : value + 1;
 | 
			
		||||
  }
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
/**
 | 
			
		||||
 * @brief Write 0 to a portion of EEPROM.
 | 
			
		||||
 *
 | 
			
		||||
 * This function writes 0 to a specified portion of EEPROM.
 | 
			
		||||
 *
 | 
			
		||||
 * @param memoryAddress Starting address in EEPROM.
 | 
			
		||||
 * @param length Number of bytes to write.
 | 
			
		||||
 */
 | 
			
		||||
void writeZeroToEEPROM(uint16_t memoryAddress, uint16_t length)
 | 
			
		||||
{
 | 
			
		||||
  if (!checkEEPROMavailable())
 | 
			
		||||
    return;
 | 
			
		||||
 | 
			
		||||
  for (uint16_t i = 0; i < length; i++)
 | 
			
		||||
  {
 | 
			
		||||
    ee.writeByte(memoryAddress + i, 0);
 | 
			
		||||
  }
 | 
			
		||||
}
 | 
			
		||||
							
								
								
									
										11
									
								
								Software/src/globals.cpp
									
									
									
									
									
										Normal file
									
								
							
							
						
						@@ -0,0 +1,11 @@
 | 
			
		||||
#include "globals.h"
 | 
			
		||||
 | 
			
		||||
Globals_t globals;
 | 
			
		||||
 | 
			
		||||
void initGlobals()
 | 
			
		||||
{
 | 
			
		||||
  globals.systemStatus = sysStat_Startup;
 | 
			
		||||
  globals.requestEEAction = EE_IDLE;
 | 
			
		||||
  globals.systemStatustxt[0] = 0;
 | 
			
		||||
  globals.toggle_wifi = false;
 | 
			
		||||
}
 | 
			
		||||
@@ -1,36 +0,0 @@
 | 
			
		||||
#ifndef _GLOBALS_H_
 | 
			
		||||
#define _GLOBALS_H_
 | 
			
		||||
 | 
			
		||||
#include <Arduino.h>
 | 
			
		||||
 | 
			
		||||
typedef enum eSystem_Status
 | 
			
		||||
{
 | 
			
		||||
  sysStat_Startup,
 | 
			
		||||
  sysStat_Normal,
 | 
			
		||||
  sysStat_Error,
 | 
			
		||||
  sysStat_Shutdown
 | 
			
		||||
} tSystem_Status;
 | 
			
		||||
 | 
			
		||||
typedef enum eEERequest
 | 
			
		||||
{
 | 
			
		||||
  EE_IDLE,
 | 
			
		||||
  EE_CFG_SAVE,
 | 
			
		||||
  EE_CFG_LOAD,
 | 
			
		||||
  EE_PDS_SAVE,
 | 
			
		||||
  EE_PDS_LOAD
 | 
			
		||||
} tEERequest;
 | 
			
		||||
 | 
			
		||||
typedef struct Globals_s
 | 
			
		||||
{
 | 
			
		||||
  char DeviceName[33];
 | 
			
		||||
  char DeviceName_ID[43];
 | 
			
		||||
  tSystem_Status systemStatus = sysStat_Startup;
 | 
			
		||||
  tSystem_Status resumeStatus = sysStat_Startup;
 | 
			
		||||
  eEERequest requestEEAction = EE_IDLE;
 | 
			
		||||
  float loadvoltage = 0;
 | 
			
		||||
  int battery_level = 0;
 | 
			
		||||
} Globals_t;
 | 
			
		||||
 | 
			
		||||
extern Globals_t globals;
 | 
			
		||||
 | 
			
		||||
#endif
 | 
			
		||||
							
								
								
									
										373
									
								
								Software/src/lora_net.cpp
									
									
									
									
									
										Normal file
									
								
							
							
						
						@@ -0,0 +1,373 @@
 | 
			
		||||
#include "lora_net.h"
 | 
			
		||||
 | 
			
		||||
#ifdef FEATURE_ENABLE_LORA
 | 
			
		||||
LoRa_E220 e220ttl(GPIO_LORA_TX, GPIO_LORA_RX, GPIO_LORA_AUX, 3, 4); // Arduino RX <-- e220 TX, Arduino TX --> e220 RX AUX M0 M1
 | 
			
		||||
void printParameters(struct Configuration configuration);
 | 
			
		||||
void printModuleInformation(struct ModuleInformation moduleInformation);
 | 
			
		||||
#elif defined(FEATURE_ENABLE_UARTLORA)
 | 
			
		||||
SoftwareSerial SerialLoRa(GPIO_LORA_RX, GPIO_LORA_TX); // RX, TX
 | 
			
		||||
void Parse_LoRa_UartCommand(char input[], int size);
 | 
			
		||||
#endif
 | 
			
		||||
 | 
			
		||||
bool InitLoRa(void (*MPinHelper)(int, int))
 | 
			
		||||
{
 | 
			
		||||
    bool returnval = false;
 | 
			
		||||
 | 
			
		||||
#ifdef FEATURE_ENABLE_LORA
 | 
			
		||||
 | 
			
		||||
    e220ttl.setMPins = MPinHelper;
 | 
			
		||||
    returnval = e220ttl.begin();
 | 
			
		||||
 | 
			
		||||
    if (returnval == true)
 | 
			
		||||
    {
 | 
			
		||||
        ResponseStructContainer c;
 | 
			
		||||
        c = e220ttl.getConfiguration();
 | 
			
		||||
        // It's important get configuration pointer before all other operation
 | 
			
		||||
        Configuration configuration = *(Configuration *)c.data;
 | 
			
		||||
        Serial.println(c.status.getResponseDescription());
 | 
			
		||||
        Serial.println(c.status.code);
 | 
			
		||||
 | 
			
		||||
        ResponseStructContainer cMi;
 | 
			
		||||
        cMi = e220ttl.getModuleInformation();
 | 
			
		||||
        // It's important get information pointer before all other operation
 | 
			
		||||
        // ModuleInformation mi = *(ModuleInformation *)cMi.data;
 | 
			
		||||
 | 
			
		||||
        Serial.println(cMi.status.getResponseDescription());
 | 
			
		||||
        Serial.println(cMi.status.code);
 | 
			
		||||
 | 
			
		||||
        //	----------------------- DEFAULT TRANSPARENT WITH RSSI -----------------------
 | 
			
		||||
        configuration.ADDL = 0x02;
 | 
			
		||||
        configuration.ADDH = 0x00;
 | 
			
		||||
 | 
			
		||||
        configuration.CHAN = 23;
 | 
			
		||||
 | 
			
		||||
        configuration.SPED.uartBaudRate = UART_BPS_9600;
 | 
			
		||||
        configuration.SPED.airDataRate = AIR_DATA_RATE_010_24;
 | 
			
		||||
        configuration.SPED.uartParity = MODE_00_8N1;
 | 
			
		||||
 | 
			
		||||
        configuration.OPTION.subPacketSetting = SPS_200_00;
 | 
			
		||||
        configuration.OPTION.RSSIAmbientNoise = RSSI_AMBIENT_NOISE_ENABLED;
 | 
			
		||||
        configuration.OPTION.transmissionPower = POWER_22;
 | 
			
		||||
 | 
			
		||||
        configuration.TRANSMISSION_MODE.enableRSSI = RSSI_ENABLED;
 | 
			
		||||
        configuration.TRANSMISSION_MODE.fixedTransmission = FT_FIXED_TRANSMISSION;
 | 
			
		||||
        configuration.TRANSMISSION_MODE.enableLBT = LBT_ENABLED;
 | 
			
		||||
        configuration.TRANSMISSION_MODE.WORPeriod = WOR_2000_011;
 | 
			
		||||
 | 
			
		||||
        // Set configuration changed and set to not hold the configuration
 | 
			
		||||
        ResponseStatus rs = e220ttl.setConfiguration(configuration, WRITE_CFG_PWR_DWN_LOSE);
 | 
			
		||||
        Serial.println(rs.getResponseDescription());
 | 
			
		||||
        Serial.println(rs.code);
 | 
			
		||||
        c.close();
 | 
			
		||||
 | 
			
		||||
        printParameters(configuration);
 | 
			
		||||
    }
 | 
			
		||||
    else
 | 
			
		||||
    {
 | 
			
		||||
        MaintainDTC(DTC_NO_LORA_FOUND, DTC_WARN, true);
 | 
			
		||||
    }
 | 
			
		||||
#elif defined(FEATURE_ENABLE_UARTLORA)
 | 
			
		||||
    SerialLoRa.begin(9600);
 | 
			
		||||
    returnval = true;
 | 
			
		||||
#endif
 | 
			
		||||
    return returnval;
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
void LoRa_Process()
 | 
			
		||||
{
 | 
			
		||||
#ifdef FEATURE_ENABLE_LORA
 | 
			
		||||
    if (e220ttl.available() > 1)
 | 
			
		||||
    {
 | 
			
		||||
        ResponseContainer rc = e220ttl.receiveMessageRSSI();
 | 
			
		||||
        // If something goes wrong, print error
 | 
			
		||||
        if (rc.status.code != 1)
 | 
			
		||||
        {
 | 
			
		||||
            Serial.println(rc.status.getResponseDescription());
 | 
			
		||||
        }
 | 
			
		||||
        else
 | 
			
		||||
        {
 | 
			
		||||
            // Print the data received
 | 
			
		||||
            Serial.println(rc.status.getResponseDescription());
 | 
			
		||||
            Serial.println(rc.data);
 | 
			
		||||
            Serial.print("RSSI: ");
 | 
			
		||||
            Serial.println(rc.rssi, DEC);
 | 
			
		||||
        }
 | 
			
		||||
    }
 | 
			
		||||
#elif defined(FEATURE_ENABLE_UARTLORA)
 | 
			
		||||
 | 
			
		||||
    static char packageInput[32];
 | 
			
		||||
    static bool packageReceived = false;
 | 
			
		||||
    static unsigned int bufferPtr = 0;
 | 
			
		||||
    int receivedSize = 0;
 | 
			
		||||
 | 
			
		||||
    while (SerialLoRa.available() && !packageReceived)
 | 
			
		||||
    {
 | 
			
		||||
        char c = SerialLoRa.read();
 | 
			
		||||
 | 
			
		||||
        // CR ignorieren (falls CRLF)
 | 
			
		||||
        if (c == '\r')
 | 
			
		||||
        {
 | 
			
		||||
            continue;
 | 
			
		||||
        }
 | 
			
		||||
 | 
			
		||||
        if (c == '\n')
 | 
			
		||||
        {
 | 
			
		||||
            // Zeilenende: String sauber terminieren, Größe setzen
 | 
			
		||||
            packageInput[bufferPtr] = '\0';
 | 
			
		||||
            receivedSize = bufferPtr;
 | 
			
		||||
            bufferPtr = 0;
 | 
			
		||||
            packageReceived = true;
 | 
			
		||||
            Debug_pushMessage("Got LoRa UART: %s\n", packageInput);
 | 
			
		||||
            break;
 | 
			
		||||
        }
 | 
			
		||||
 | 
			
		||||
        // Optional: in Uppercase wandeln (macht Kommandos robust)
 | 
			
		||||
        if (c >= 'a' && c <= 'z')
 | 
			
		||||
            c = (char)(c - 'a' + 'A');
 | 
			
		||||
 | 
			
		||||
        // Erlaubte Zeichen (Ziffern, Großbuchstaben, Space, Komma, Punkt, Semikolon)
 | 
			
		||||
        bool allowed =
 | 
			
		||||
            (c >= '0' && c <= '9') ||
 | 
			
		||||
            (c >= 'A' && c <= 'Z') ||
 | 
			
		||||
            (c == ' ' || c == ',' || c == '.' || c == ';');
 | 
			
		||||
 | 
			
		||||
        if (allowed)
 | 
			
		||||
        {
 | 
			
		||||
            if (bufferPtr < sizeof(packageInput) - 1)
 | 
			
		||||
            {
 | 
			
		||||
                packageInput[bufferPtr++] = c;
 | 
			
		||||
                packageInput[bufferPtr] = '\0'; // immer NUL-terminiert halten
 | 
			
		||||
            }
 | 
			
		||||
            else
 | 
			
		||||
            {
 | 
			
		||||
                Debug_pushMessage("Buffer overflow. Resetting buffer.\n");
 | 
			
		||||
                bufferPtr = 0;
 | 
			
		||||
            }
 | 
			
		||||
        }
 | 
			
		||||
        else
 | 
			
		||||
        {
 | 
			
		||||
            Debug_pushMessage("Invalid character received: %c\n", c);
 | 
			
		||||
        }
 | 
			
		||||
    }
 | 
			
		||||
 | 
			
		||||
    if (packageReceived)
 | 
			
		||||
    {
 | 
			
		||||
        // Hinweis: receivedSize ist jetzt strlen(packageInput), ohne \n/\r
 | 
			
		||||
        Parse_LoRa_UartCommand(packageInput, receivedSize);
 | 
			
		||||
        packageReceived = false;
 | 
			
		||||
    }
 | 
			
		||||
 | 
			
		||||
#endif
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
void sendStatus_LoRa()
 | 
			
		||||
{
 | 
			
		||||
#ifdef FEATURE_ENABLE_LORA
 | 
			
		||||
    struct
 | 
			
		||||
    {
 | 
			
		||||
        MessageType_t type = "STATUS";
 | 
			
		||||
        MessageStatus_t status;
 | 
			
		||||
    } __attribute__((packed)) sendStatus;
 | 
			
		||||
 | 
			
		||||
    sendStatus.status.nodeid = 0x0002;
 | 
			
		||||
    sendStatus.status.millis = millis();
 | 
			
		||||
    sendStatus.status.faction_active = 1;
 | 
			
		||||
    sendStatus.status.faction_1_timer = 0xBBBBBBBB;
 | 
			
		||||
    sendStatus.status.faction_2_timer = 0xCCCCCCCC;
 | 
			
		||||
    sendStatus.status.faction_3_timer = 0xDDDDDDDD;
 | 
			
		||||
 | 
			
		||||
    ResponseStatus rs = e220ttl.sendFixedMessage(0xFF, 0xFF, 23, (byte *)&sendStatus, sizeof(sendStatus));
 | 
			
		||||
    Serial.println(rs.getResponseDescription());
 | 
			
		||||
 | 
			
		||||
#elif defined(FEATURE_ENABLE_UARTLORA)
 | 
			
		||||
 | 
			
		||||
    SerialLoRa.print(PersistenceData.faction_1_timer);
 | 
			
		||||
    SerialLoRa.write(";");
 | 
			
		||||
    SerialLoRa.print(PersistenceData.faction_2_timer);
 | 
			
		||||
    SerialLoRa.write(";");
 | 
			
		||||
    SerialLoRa.print(PersistenceData.faction_3_timer);
 | 
			
		||||
    SerialLoRa.write(";");
 | 
			
		||||
    SerialLoRa.print(PersistenceData.activeFaction);
 | 
			
		||||
    SerialLoRa.write(";");
 | 
			
		||||
    SerialLoRa.print(globals.battery_level);
 | 
			
		||||
    SerialLoRa.write('\n');
 | 
			
		||||
 | 
			
		||||
#endif
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
#ifdef FEATURE_ENABLE_LORA
 | 
			
		||||
 | 
			
		||||
void printParameters(struct Configuration configuration)
 | 
			
		||||
{
 | 
			
		||||
    Serial.println("----------------------------------------");
 | 
			
		||||
 | 
			
		||||
    Serial.print(F("HEAD : "));
 | 
			
		||||
    Serial.print(configuration.COMMAND, HEX);
 | 
			
		||||
    Serial.print(" ");
 | 
			
		||||
    Serial.print(configuration.STARTING_ADDRESS, HEX);
 | 
			
		||||
    Serial.print(" ");
 | 
			
		||||
    Serial.println(configuration.LENGHT, HEX);
 | 
			
		||||
    Serial.println(F(" "));
 | 
			
		||||
    Serial.print(F("AddH : "));
 | 
			
		||||
    Serial.println(configuration.ADDH, HEX);
 | 
			
		||||
    Serial.print(F("AddL : "));
 | 
			
		||||
    Serial.println(configuration.ADDL, HEX);
 | 
			
		||||
    Serial.println(F(" "));
 | 
			
		||||
    Serial.print(F("Chan : "));
 | 
			
		||||
    Serial.print(configuration.CHAN, DEC);
 | 
			
		||||
    Serial.print(" -> ");
 | 
			
		||||
    Serial.println(configuration.getChannelDescription());
 | 
			
		||||
    Serial.println(F(" "));
 | 
			
		||||
    Serial.print(F("SpeedParityBit     : "));
 | 
			
		||||
    Serial.print(configuration.SPED.uartParity, BIN);
 | 
			
		||||
    Serial.print(" -> ");
 | 
			
		||||
    Serial.println(configuration.SPED.getUARTParityDescription());
 | 
			
		||||
    Serial.print(F("SpeedUARTDatte     : "));
 | 
			
		||||
    Serial.print(configuration.SPED.uartBaudRate, BIN);
 | 
			
		||||
    Serial.print(" -> ");
 | 
			
		||||
    Serial.println(configuration.SPED.getUARTBaudRateDescription());
 | 
			
		||||
    Serial.print(F("SpeedAirDataRate   : "));
 | 
			
		||||
    Serial.print(configuration.SPED.airDataRate, BIN);
 | 
			
		||||
    Serial.print(" -> ");
 | 
			
		||||
    Serial.println(configuration.SPED.getAirDataRateDescription());
 | 
			
		||||
    Serial.println(F(" "));
 | 
			
		||||
    Serial.print(F("OptionSubPacketSett: "));
 | 
			
		||||
    Serial.print(configuration.OPTION.subPacketSetting, BIN);
 | 
			
		||||
    Serial.print(" -> ");
 | 
			
		||||
    Serial.println(configuration.OPTION.getSubPacketSetting());
 | 
			
		||||
    Serial.print(F("OptionTranPower    : "));
 | 
			
		||||
    Serial.print(configuration.OPTION.transmissionPower, BIN);
 | 
			
		||||
    Serial.print(" -> ");
 | 
			
		||||
    Serial.println(configuration.OPTION.getTransmissionPowerDescription());
 | 
			
		||||
    Serial.print(F("OptionRSSIAmbientNo: "));
 | 
			
		||||
    Serial.print(configuration.OPTION.RSSIAmbientNoise, BIN);
 | 
			
		||||
    Serial.print(" -> ");
 | 
			
		||||
    Serial.println(configuration.OPTION.getRSSIAmbientNoiseEnable());
 | 
			
		||||
    Serial.println(F(" "));
 | 
			
		||||
    Serial.print(F("TransModeWORPeriod : "));
 | 
			
		||||
    Serial.print(configuration.TRANSMISSION_MODE.WORPeriod, BIN);
 | 
			
		||||
    Serial.print(" -> ");
 | 
			
		||||
    Serial.println(configuration.TRANSMISSION_MODE.getWORPeriodByParamsDescription());
 | 
			
		||||
    Serial.print(F("TransModeEnableLBT : "));
 | 
			
		||||
    Serial.print(configuration.TRANSMISSION_MODE.enableLBT, BIN);
 | 
			
		||||
    Serial.print(" -> ");
 | 
			
		||||
    Serial.println(configuration.TRANSMISSION_MODE.getLBTEnableByteDescription());
 | 
			
		||||
    Serial.print(F("TransModeEnableRSSI: "));
 | 
			
		||||
    Serial.print(configuration.TRANSMISSION_MODE.enableRSSI, BIN);
 | 
			
		||||
    Serial.print(" -> ");
 | 
			
		||||
    Serial.println(configuration.TRANSMISSION_MODE.getRSSIEnableByteDescription());
 | 
			
		||||
    Serial.print(F("TransModeFixedTrans: "));
 | 
			
		||||
    Serial.print(configuration.TRANSMISSION_MODE.fixedTransmission, BIN);
 | 
			
		||||
    Serial.print(" -> ");
 | 
			
		||||
    Serial.println(configuration.TRANSMISSION_MODE.getFixedTransmissionDescription());
 | 
			
		||||
 | 
			
		||||
    Serial.println("----------------------------------------");
 | 
			
		||||
}
 | 
			
		||||
#endif
 | 
			
		||||
#ifdef FEATURE_ENABLE_UARTLORA
 | 
			
		||||
#include <ctype.h>
 | 
			
		||||
 | 
			
		||||
static void rstrip(char *s)
 | 
			
		||||
{
 | 
			
		||||
    size_t n = strlen(s);
 | 
			
		||||
    while (n && (s[n - 1] == '\r' || s[n - 1] == '\n' || isspace((unsigned char)s[n - 1])))
 | 
			
		||||
    {
 | 
			
		||||
        s[--n] = '\0';
 | 
			
		||||
    }
 | 
			
		||||
}
 | 
			
		||||
static void lstrip(char *s)
 | 
			
		||||
{
 | 
			
		||||
    size_t i = 0, n = strlen(s);
 | 
			
		||||
    while (i < n && isspace((unsigned char)s[i]))
 | 
			
		||||
        i++;
 | 
			
		||||
    if (i)
 | 
			
		||||
        memmove(s, s + i, n - i + 1);
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
void Parse_LoRa_UartCommand(char input[], int size)
 | 
			
		||||
{
 | 
			
		||||
    Debug_pushMessage("Start parsing, size: %d\n", size);
 | 
			
		||||
 | 
			
		||||
    // Auf mehreren Delimitern splitten: ;, CR, LF, Tabs/Spaces
 | 
			
		||||
    const char *delims = ";\r\n\t ";
 | 
			
		||||
    char *ptr;
 | 
			
		||||
 | 
			
		||||
    // erstes Token (Kommando)
 | 
			
		||||
    ptr = strtok(input, delims);
 | 
			
		||||
    if (!ptr)
 | 
			
		||||
    {
 | 
			
		||||
        Debug_pushMessage("No command token\n");
 | 
			
		||||
        return;
 | 
			
		||||
    }
 | 
			
		||||
 | 
			
		||||
    char command[16];
 | 
			
		||||
    strncpy(command, ptr, sizeof(command) - 1);
 | 
			
		||||
    command[sizeof(command) - 1] = '\0';
 | 
			
		||||
    lstrip(command);
 | 
			
		||||
    rstrip(command);
 | 
			
		||||
 | 
			
		||||
    // zweites Token (optional: Wert)
 | 
			
		||||
    ptr = strtok(NULL, delims);
 | 
			
		||||
    char value[16] = {0};
 | 
			
		||||
    if (ptr)
 | 
			
		||||
    {
 | 
			
		||||
        strncpy(value, ptr, sizeof(value) - 1);
 | 
			
		||||
        value[sizeof(value) - 1] = '\0';
 | 
			
		||||
        lstrip(value);
 | 
			
		||||
        rstrip(value);
 | 
			
		||||
    }
 | 
			
		||||
 | 
			
		||||
    Debug_pushMessage("Parsed LoRa UART Command: %s  Value: %s\n", command, value);
 | 
			
		||||
 | 
			
		||||
    if (!strcmp(command, "ENABLE"))
 | 
			
		||||
    {
 | 
			
		||||
        globals.timer_disabled = false;
 | 
			
		||||
        Debug_pushMessage("Enabled by LoRa\n");
 | 
			
		||||
    }
 | 
			
		||||
    else if (!strcmp(command, "DISABLE"))
 | 
			
		||||
    {
 | 
			
		||||
        globals.timer_disabled = true;
 | 
			
		||||
        Debug_pushMessage("Disabled by LoRa\n");
 | 
			
		||||
    }
 | 
			
		||||
    else if (!strcmp(command, "RESET"))
 | 
			
		||||
    {
 | 
			
		||||
        PersistenceData.activeFaction = NONE;
 | 
			
		||||
        PersistenceData.faction_1_timer = 0;
 | 
			
		||||
        PersistenceData.faction_2_timer = 0;
 | 
			
		||||
        PersistenceData.faction_3_timer = 0;
 | 
			
		||||
        Debug_pushMessage("Reset by LoRa\n");
 | 
			
		||||
    }
 | 
			
		||||
    else if (!strcmp(command, "TMRSTP"))
 | 
			
		||||
    {
 | 
			
		||||
        PersistenceData.activeFaction = NONE;
 | 
			
		||||
    }
 | 
			
		||||
    else if (!strcmp(command, "TMR1"))
 | 
			
		||||
    {
 | 
			
		||||
        PersistenceData.faction_1_timer = atol(value);
 | 
			
		||||
    }
 | 
			
		||||
    else if (!strcmp(command, "TMR2"))
 | 
			
		||||
    {
 | 
			
		||||
        PersistenceData.faction_2_timer = atol(value);
 | 
			
		||||
    }
 | 
			
		||||
    else if (!strcmp(command, "TMR3"))
 | 
			
		||||
    {
 | 
			
		||||
        PersistenceData.faction_3_timer = atol(value);
 | 
			
		||||
    }
 | 
			
		||||
    else if (!strcmp(command, "EFAC1"))
 | 
			
		||||
    {
 | 
			
		||||
        PersistenceData.activeFaction = FACTION_1;
 | 
			
		||||
    }
 | 
			
		||||
    else if (!strcmp(command, "EFAC2"))
 | 
			
		||||
    {
 | 
			
		||||
        PersistenceData.activeFaction = FACTION_2;
 | 
			
		||||
    }
 | 
			
		||||
    else if (!strcmp(command, "EFAC3"))
 | 
			
		||||
    {
 | 
			
		||||
        PersistenceData.activeFaction = FACTION_3;
 | 
			
		||||
    }
 | 
			
		||||
    else
 | 
			
		||||
    {
 | 
			
		||||
        Debug_pushMessage("Unknown command: %s\n", command);
 | 
			
		||||
    }
 | 
			
		||||
}
 | 
			
		||||
#endif
 | 
			
		||||
@@ -1,106 +1,129 @@
 | 
			
		||||
#define FREQUENCY_868
 | 
			
		||||
 | 
			
		||||
#include <Arduino.h>
 | 
			
		||||
#include <TM1637.h>
 | 
			
		||||
#include <Ticker.h>
 | 
			
		||||
#include <DNSServer.h>
 | 
			
		||||
#include <ESP8266WiFi.h>
 | 
			
		||||
#include <ESPAsyncTCP.h>
 | 
			
		||||
#include <ESP8266mDNS.h>
 | 
			
		||||
#include <ArduinoOTA.h>
 | 
			
		||||
#include <ESPAsyncWebServer.h>
 | 
			
		||||
#include <LittleFS.h>
 | 
			
		||||
#include <PCF8574.h>
 | 
			
		||||
#include <Wire.h>
 | 
			
		||||
#include <Adafruit_INA219.h>
 | 
			
		||||
#include <ArduinoJson.h>
 | 
			
		||||
#include <LoRa_E220.h>
 | 
			
		||||
 | 
			
		||||
// local includes
 | 
			
		||||
#include "lora_messages.h"
 | 
			
		||||
#include "common.h"
 | 
			
		||||
#include "sanitycheck.h"
 | 
			
		||||
#include "defaults.h"
 | 
			
		||||
#include "webui.h"
 | 
			
		||||
#include "config.h"
 | 
			
		||||
#include "globals.h"
 | 
			
		||||
#include "dtc.h"
 | 
			
		||||
#include "common.h"
 | 
			
		||||
#include "debugger.h"
 | 
			
		||||
#include "utilities.h"
 | 
			
		||||
#if defined(FEATURE_ENABLE_LORA) || defined(FEATURE_ENABLE_UARTLORA)
 | 
			
		||||
#include "lora_net.h"
 | 
			
		||||
#endif
 | 
			
		||||
 | 
			
		||||
#ifdef WIFI_CLIENT
 | 
			
		||||
#include <WiFiMulti.h>
 | 
			
		||||
#ifdef FEATURE_ENABLE_WIFI_CLIENT
 | 
			
		||||
#include <ESP8266WiFiMulti.h>
 | 
			
		||||
 | 
			
		||||
const char *ssid = QUOTE(WIFI_SSID);
 | 
			
		||||
const char *password = QUOTE(WIFI_PASSWORD);
 | 
			
		||||
const char *ssid = QUOTE(WIFI_SSID_CLIENT);
 | 
			
		||||
const char *password = QUOTE(WIFI_PASSWORD_CLIENT);
 | 
			
		||||
const uint32_t connectTimeoutMs = 5000;
 | 
			
		||||
 | 
			
		||||
WiFiMulti wifiMulti;
 | 
			
		||||
ESP8266WiFiMulti wifiMulti;
 | 
			
		||||
#endif
 | 
			
		||||
 | 
			
		||||
PCF8574 i2c_io(I2C_IO_ADDRESS);
 | 
			
		||||
Adafruit_INA219 ina219;
 | 
			
		||||
LoRa_E220 e220ttl(GPIO_LORA_TX, GPIO_LORA_RX, GPIO_LORA_AUX, 3, 4); // Arduino RX <-- e220 TX, Arduino TX --> e220 RX AUX M0 M1
 | 
			
		||||
 | 
			
		||||
TM1637 disp_FAC_1(GPIO_7SEG_CLK, GPIO_7SEG_EN_FAC1);
 | 
			
		||||
TM1637 disp_FAC_2(GPIO_7SEG_CLK, GPIO_7SEG_EN_FAC2);
 | 
			
		||||
TM1637 disp_FAC_3(GPIO_7SEG_CLK, GPIO_7SEG_EN_FAC3);
 | 
			
		||||
 | 
			
		||||
#ifdef CAPTIVE
 | 
			
		||||
DNSServer dnsServer;
 | 
			
		||||
#endif
 | 
			
		||||
AsyncWebServer server(80);
 | 
			
		||||
 | 
			
		||||
void printParameters(struct Configuration configuration);
 | 
			
		||||
void printModuleInformation(struct ModuleInformation moduleInformation);
 | 
			
		||||
void displayInfo();
 | 
			
		||||
void SevenSeg_Output();
 | 
			
		||||
void toggleWiFiAP(boolean shutdown = false);
 | 
			
		||||
void SystemShutdown();
 | 
			
		||||
void SystemShutdown(bool restart = false);
 | 
			
		||||
void SetBatteryType(batteryType_t type);
 | 
			
		||||
void ProcessKeyCombos(bool *btnState);
 | 
			
		||||
void OverrideDisplay(const uint8_t *message, uint32_t time);
 | 
			
		||||
uint32_t getESPChipID();
 | 
			
		||||
void OverrideDisplay(uint32_t time, const char *message1, const char *message2, const char *message3);
 | 
			
		||||
void EEPROMCyclicPDS_callback();
 | 
			
		||||
 | 
			
		||||
#if defined(FEATURE_ENABLE_UARTLORA) || defined(FEATURE_ENABLE_LORA)
 | 
			
		||||
void setMPins_Helper(int pin, int status);
 | 
			
		||||
void tmrCallback_StatusSender();
 | 
			
		||||
Ticker tmrStatusSender(tmrCallback_StatusSender, 30000, 0, MILLIS);
 | 
			
		||||
#endif
 | 
			
		||||
 | 
			
		||||
void tmrCallback_PowerMonitor();
 | 
			
		||||
Ticker tmrPowerMonitor(tmrCallback_PowerMonitor, 10000, 0, MILLIS);
 | 
			
		||||
void tmrCallback_FactionTicker();
 | 
			
		||||
Ticker tmrFactionTicker(tmrCallback_FactionTicker, 1000, 0, MILLIS);
 | 
			
		||||
void tmrCallback_InputGetter();
 | 
			
		||||
Ticker tmrInputGetter(tmrCallback_InputGetter, 250, 0, MILLIS);
 | 
			
		||||
void tmrCallback_EEPROMCyclicPDS();
 | 
			
		||||
Ticker tmrEEPROMCyclicPDS(tmrCallback_EEPROMCyclicPDS, 60000, 0, MILLIS);
 | 
			
		||||
void EEPROMCyclicPDS_callback();
 | 
			
		||||
Ticker tmrEEPROMCyclicPDS(EEPROMCyclicPDS_callback, 60000, 0, MILLIS);
 | 
			
		||||
 | 
			
		||||
#ifdef WIFI_CLIENT
 | 
			
		||||
void tmrCallback_WiFiMaintainConnection();
 | 
			
		||||
Ticker tmrWiFiMaintainConnection(tmrCallback_WiFiMaintainConnection, 1000, 0, MILLIS);
 | 
			
		||||
#ifdef FEATURE_ENABLE_WIFI_CLIENT
 | 
			
		||||
void wifiMaintainConnectionTicker_callback();
 | 
			
		||||
Ticker tmrWiFiMaintainConnection(wifiMaintainConnectionTicker_callback, 1000, 0, MILLIS);
 | 
			
		||||
#endif
 | 
			
		||||
 | 
			
		||||
uint32_t DisplayOverrideFlag = 0;
 | 
			
		||||
char DisplayOverrideValue[5] = {0};
 | 
			
		||||
 | 
			
		||||
Globals_t globals;
 | 
			
		||||
char DisplayOverrideValue[3][5] = {0};
 | 
			
		||||
 | 
			
		||||
#if defined(FEATURE_ENABLE_UARTLORA) || defined(FEATURE_ENABLE_LORA)
 | 
			
		||||
void setMPins_Helper(int pin, int status)
 | 
			
		||||
{
 | 
			
		||||
	i2c_io.write(pin, status);
 | 
			
		||||
}
 | 
			
		||||
#endif
 | 
			
		||||
 | 
			
		||||
void setup()
 | 
			
		||||
{
 | 
			
		||||
	// Set CPU frequency to 80MHz
 | 
			
		||||
	system_update_cpu_freq(SYS_CPU_80MHZ);
 | 
			
		||||
 | 
			
		||||
	Serial.begin(115200);
 | 
			
		||||
	Serial.print("\n\n\n");
 | 
			
		||||
	// Generate a unique device name based on ESP chip ID
 | 
			
		||||
	strncpy(globals.DeviceName, HOST_NAME, sizeof(globals.DeviceName));
 | 
			
		||||
	snprintf(globals.DeviceNameId, sizeof(globals.DeviceNameId), "%s_%08X", globals.DeviceName, ESP.getChipId());
 | 
			
		||||
 | 
			
		||||
#ifdef SERIAL_DEBUG
 | 
			
		||||
	Serial.setDebugOutput(true);
 | 
			
		||||
	// Disable WiFi persistent storage
 | 
			
		||||
	WiFi.persistent(false);
 | 
			
		||||
 | 
			
		||||
	// Initialize and clear Diagnostic Trouble Code (DTC) storage
 | 
			
		||||
	ClearAllDTC();
 | 
			
		||||
 | 
			
		||||
#ifdef FEATURE_ENABLE_WIFI_CLIENT
 | 
			
		||||
	// Configure WiFi settings for client mode if enabled
 | 
			
		||||
	WiFi.mode(WIFI_STA);
 | 
			
		||||
	WiFi.setHostname(globals.DeviceNameId);
 | 
			
		||||
	wifiMulti.addAP(QUOTE(WIFI_SSID_CLIENT), QUOTE(WIFI_PASSWORD_CLIENT));
 | 
			
		||||
	tmrWiFiMaintainConnection.start();
 | 
			
		||||
#else
 | 
			
		||||
	// Disable WiFi if WiFi client feature is not enabled
 | 
			
		||||
	WiFi.mode(WIFI_OFF);
 | 
			
		||||
#endif
 | 
			
		||||
 | 
			
		||||
	WiFi.persistent(false);
 | 
			
		||||
	WiFi.disconnect();
 | 
			
		||||
	// Initialize Serial communication
 | 
			
		||||
	Serial.begin(115200);
 | 
			
		||||
	Serial.setDebugOutput(false);
 | 
			
		||||
 | 
			
		||||
	strcpy(globals.DeviceName, DEVICE_NAME);
 | 
			
		||||
	snprintf(globals.DeviceName_ID, 42, "%s_%08X", globals.DeviceName, getESPChipID());
 | 
			
		||||
	Serial.print("\n\n-------------------START-------------------\n");
 | 
			
		||||
	Serial.print(globals.DeviceNameId);
 | 
			
		||||
	Serial.print("\nby Hiabuto Defense\n\n");
 | 
			
		||||
 | 
			
		||||
	// Initialize EEPROM, load configuration, and persistence data from EEPROM
 | 
			
		||||
	if (InitEEPROM())
 | 
			
		||||
	{
 | 
			
		||||
		GetConfig_EEPROM();
 | 
			
		||||
		GetPersistence_EEPROM();
 | 
			
		||||
		Serial.printf("Initialized EEPROM at Address 0x%02X\n", I2C_EE_ADDRESS);
 | 
			
		||||
	}
 | 
			
		||||
	else
 | 
			
		||||
	{
 | 
			
		||||
		Serial.print("EEPROM not Initialized\n");
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	if (i2c_io.begin())
 | 
			
		||||
	{
 | 
			
		||||
@@ -121,72 +144,21 @@ void setup()
 | 
			
		||||
		Serial.print("INA219 not Initialized\n");
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	e220ttl.setMPins = &setMPins_Helper;
 | 
			
		||||
	e220ttl.begin();
 | 
			
		||||
 | 
			
		||||
	ResponseStructContainer c;
 | 
			
		||||
	c = e220ttl.getConfiguration();
 | 
			
		||||
	// It's important get configuration pointer before all other operation
 | 
			
		||||
	Configuration configuration = *(Configuration *)c.data;
 | 
			
		||||
	Serial.println(c.status.getResponseDescription());
 | 
			
		||||
	Serial.println(c.status.code);
 | 
			
		||||
 | 
			
		||||
	ResponseStructContainer cMi;
 | 
			
		||||
	cMi = e220ttl.getModuleInformation();
 | 
			
		||||
	// It's important get information pointer before all other operation
 | 
			
		||||
	// ModuleInformation mi = *(ModuleInformation *)cMi.data;
 | 
			
		||||
 | 
			
		||||
	Serial.println(cMi.status.getResponseDescription());
 | 
			
		||||
	Serial.println(cMi.status.code);
 | 
			
		||||
 | 
			
		||||
	//	----------------------- DEFAULT TRANSPARENT WITH RSSI -----------------------
 | 
			
		||||
	configuration.ADDL = 0x02;
 | 
			
		||||
	configuration.ADDH = 0x00;
 | 
			
		||||
 | 
			
		||||
	configuration.CHAN = 23;
 | 
			
		||||
 | 
			
		||||
	configuration.SPED.uartBaudRate = UART_BPS_9600;
 | 
			
		||||
	configuration.SPED.airDataRate = AIR_DATA_RATE_010_24;
 | 
			
		||||
	configuration.SPED.uartParity = MODE_00_8N1;
 | 
			
		||||
 | 
			
		||||
	configuration.OPTION.subPacketSetting = SPS_200_00;
 | 
			
		||||
	configuration.OPTION.RSSIAmbientNoise = RSSI_AMBIENT_NOISE_ENABLED;
 | 
			
		||||
	configuration.OPTION.transmissionPower = POWER_22;
 | 
			
		||||
 | 
			
		||||
	configuration.TRANSMISSION_MODE.enableRSSI = RSSI_ENABLED;
 | 
			
		||||
	configuration.TRANSMISSION_MODE.fixedTransmission = FT_FIXED_TRANSMISSION;
 | 
			
		||||
	configuration.TRANSMISSION_MODE.enableLBT = LBT_ENABLED;
 | 
			
		||||
	configuration.TRANSMISSION_MODE.WORPeriod = WOR_2000_011;
 | 
			
		||||
 | 
			
		||||
	// Set configuration changed and set to not hold the configuration
 | 
			
		||||
	ResponseStatus rs = e220ttl.setConfiguration(configuration, WRITE_CFG_PWR_DWN_LOSE);
 | 
			
		||||
	Serial.println(rs.getResponseDescription());
 | 
			
		||||
	Serial.println(rs.code);
 | 
			
		||||
	c.close();
 | 
			
		||||
 | 
			
		||||
	printParameters(configuration);
 | 
			
		||||
	tmrStatusSender.start();
 | 
			
		||||
 | 
			
		||||
	LittleFS.begin();
 | 
			
		||||
 | 
			
		||||
#ifdef WIFI_CLIENT
 | 
			
		||||
	WiFi.mode(WIFI_STA);
 | 
			
		||||
	WiFi.setHostname(globals.DeviceName_ID);
 | 
			
		||||
	wifiMulti.addAP(QUOTE(WIFI_SSID), QUOTE(WIFI_PASSWORD));
 | 
			
		||||
	tmrWiFiMaintainConnection.start();
 | 
			
		||||
#else
 | 
			
		||||
	WiFi.mode(WIFI_AP);
 | 
			
		||||
	WiFi.begin(QUOTE(DEVICE_NAME), QUOTE(WIFI_AP_PASSWORD));
 | 
			
		||||
#if defined(ESP32)
 | 
			
		||||
	WiFi.sleep(true);
 | 
			
		||||
#endif
 | 
			
		||||
	WiFi.mode(WIFI_OFF);
 | 
			
		||||
#if defined(FEATURE_ENABLE_UARTLORA) || defined(FEATURE_ENABLE_LORA)
 | 
			
		||||
	if (InitLoRa(&setMPins_Helper))
 | 
			
		||||
	{
 | 
			
		||||
		Serial.print("Initialized LoRa_Transceiver\n");
 | 
			
		||||
		tmrStatusSender.start();
 | 
			
		||||
	}
 | 
			
		||||
	else
 | 
			
		||||
	{
 | 
			
		||||
		Serial.print("LoRa not Initialized\n");
 | 
			
		||||
	}
 | 
			
		||||
#endif
 | 
			
		||||
 | 
			
		||||
	InitEEPROM();
 | 
			
		||||
 | 
			
		||||
	// Set up OTA updates
 | 
			
		||||
	ArduinoOTA.setPort(8266);
 | 
			
		||||
	ArduinoOTA.setHostname(globals.DeviceName_ID);
 | 
			
		||||
	ArduinoOTA.setHostname(globals.DeviceNameId);
 | 
			
		||||
	ArduinoOTA.setPassword(QUOTE(ADMIN_PASSWORD));
 | 
			
		||||
 | 
			
		||||
	ArduinoOTA.onStart([]()
 | 
			
		||||
@@ -229,13 +201,21 @@ void setup()
 | 
			
		||||
                         Serial.println("Receive Failed");
 | 
			
		||||
                       else if (error == OTA_END_ERROR)
 | 
			
		||||
                         Serial.println("End Failed"); });
 | 
			
		||||
 | 
			
		||||
	// Begin OTA updates
 | 
			
		||||
	ArduinoOTA.begin();
 | 
			
		||||
	Serial.print("\nOTA-Init done");
 | 
			
		||||
 | 
			
		||||
#ifdef CAPTIVE
 | 
			
		||||
	dnsServer.start(53, "*", WiFi.softAPIP());
 | 
			
		||||
#endif
 | 
			
		||||
 | 
			
		||||
	// Initialize the web user interface
 | 
			
		||||
	initWebUI();
 | 
			
		||||
	Serial.print("\nWebUI-Init done");
 | 
			
		||||
 | 
			
		||||
	// Initialize global variables
 | 
			
		||||
	initGlobals();
 | 
			
		||||
	Serial.print("\nglobals-Init done");
 | 
			
		||||
 | 
			
		||||
	// Start cyclic EEPROM updates for Persistence Data Structure (PDS)
 | 
			
		||||
	tmrEEPROMCyclicPDS.start();
 | 
			
		||||
 | 
			
		||||
	disp_FAC_1.init();
 | 
			
		||||
	disp_FAC_1.setBrightness(5);
 | 
			
		||||
@@ -244,52 +224,100 @@ void setup()
 | 
			
		||||
	disp_FAC_3.init();
 | 
			
		||||
	disp_FAC_3.setBrightness(5);
 | 
			
		||||
 | 
			
		||||
	tmrEEPROMCyclicPDS.start();
 | 
			
		||||
	tmrFactionTicker.start();
 | 
			
		||||
	tmrInputGetter.start();
 | 
			
		||||
	Serial.println("Setup Done");
 | 
			
		||||
 | 
			
		||||
	if (ConfigData.active_faction_on_reboot == false)
 | 
			
		||||
		PersistenceData.activeFaction = NONE;
 | 
			
		||||
 | 
			
		||||
	Serial.print("\nSetup Done\n");
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
void loop()
 | 
			
		||||
{
 | 
			
		||||
 | 
			
		||||
	if (e220ttl.available() > 1)
 | 
			
		||||
	{
 | 
			
		||||
		ResponseContainer rc = e220ttl.receiveMessageRSSI();
 | 
			
		||||
		// Is something goes wrong print error
 | 
			
		||||
		if (rc.status.code != 1)
 | 
			
		||||
		{
 | 
			
		||||
			Serial.println(rc.status.getResponseDescription());
 | 
			
		||||
		}
 | 
			
		||||
		else
 | 
			
		||||
		{
 | 
			
		||||
			// Print the data received
 | 
			
		||||
			Serial.println(rc.status.getResponseDescription());
 | 
			
		||||
			Serial.println(rc.data);
 | 
			
		||||
			Serial.print("RSSI: ");
 | 
			
		||||
			Serial.println(rc.rssi, DEC);
 | 
			
		||||
		}
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	tmrEEPROMCyclicPDS.update();
 | 
			
		||||
	tmrFactionTicker.update();
 | 
			
		||||
	tmrInputGetter.update();
 | 
			
		||||
	tmrStatusSender.update();
 | 
			
		||||
	tmrPowerMonitor.update();
 | 
			
		||||
 | 
			
		||||
	ArduinoOTA.handle();
 | 
			
		||||
	SevenSeg_Output();
 | 
			
		||||
	EEPROM_Process();
 | 
			
		||||
	Webserver_Process();
 | 
			
		||||
	DTC_Process();
 | 
			
		||||
	Debug_Process();
 | 
			
		||||
 | 
			
		||||
#ifdef CAPTIVE
 | 
			
		||||
	dnsServer.processNextRequest();
 | 
			
		||||
	if (globals.toggle_wifi == true)
 | 
			
		||||
	{
 | 
			
		||||
 | 
			
		||||
		globals.toggle_wifi = false;
 | 
			
		||||
		toggleWiFiAP();
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
#if defined(FEATURE_ENABLE_LORA) || defined(FEATURE_ENABLE_UARTLORA)
 | 
			
		||||
	LoRa_Process();
 | 
			
		||||
	tmrStatusSender.update();
 | 
			
		||||
#endif
 | 
			
		||||
#ifdef WIFI_CLIENT
 | 
			
		||||
 | 
			
		||||
#ifdef FEATURE_ENABLE_WIFI_CLIENT
 | 
			
		||||
	// Update WiFi connection maintenance ticker if WiFi client feature is enabled
 | 
			
		||||
	tmrWiFiMaintainConnection.update();
 | 
			
		||||
#endif
 | 
			
		||||
	if (globals.systemStatus == sysStat_Shutdown)
 | 
			
		||||
		SystemShutdown();
 | 
			
		||||
 | 
			
		||||
	static tSystem_Status lastStatus = sysStat_Init;
 | 
			
		||||
 | 
			
		||||
	// Handle different system statuses
 | 
			
		||||
	switch (globals.systemStatus)
 | 
			
		||||
	{
 | 
			
		||||
	case sysStat_Startup:
 | 
			
		||||
		if (lastStatus != globals.systemStatus)
 | 
			
		||||
		{
 | 
			
		||||
			strcpy_P(globals.systemStatustxt, PSTR("Startup"));
 | 
			
		||||
			lastStatus = globals.systemStatus;
 | 
			
		||||
		}
 | 
			
		||||
		// Transition to Normal status after startup delay
 | 
			
		||||
		if (millis() > STARTUP_DELAY_MS)
 | 
			
		||||
		{
 | 
			
		||||
			globals.systemStatus = sysStat_Normal;
 | 
			
		||||
			globals.resumeStatus = sysStat_Normal;
 | 
			
		||||
			Debug_pushMessage("sysstat = Normal");
 | 
			
		||||
		}
 | 
			
		||||
		break;
 | 
			
		||||
 | 
			
		||||
	case sysStat_Normal:
 | 
			
		||||
		if (lastStatus != globals.systemStatus)
 | 
			
		||||
		{
 | 
			
		||||
			strcpy_P(globals.systemStatustxt, PSTR("Normal"));
 | 
			
		||||
			lastStatus = globals.systemStatus;
 | 
			
		||||
		}
 | 
			
		||||
		break;
 | 
			
		||||
 | 
			
		||||
		if (lastStatus != globals.systemStatus)
 | 
			
		||||
		{
 | 
			
		||||
			strcpy_P(globals.systemStatustxt, PSTR("Error"));
 | 
			
		||||
			lastStatus = globals.systemStatus;
 | 
			
		||||
		}
 | 
			
		||||
		break;
 | 
			
		||||
 | 
			
		||||
	case sysStat_Shutdown:
 | 
			
		||||
		if (lastStatus != globals.systemStatus)
 | 
			
		||||
		{
 | 
			
		||||
			strcpy_P(globals.systemStatustxt, PSTR("Shutdown"));
 | 
			
		||||
			lastStatus = globals.systemStatus;
 | 
			
		||||
		}
 | 
			
		||||
		SystemShutdown(false);
 | 
			
		||||
		break;
 | 
			
		||||
	case sysStat_Error:
 | 
			
		||||
		if (lastStatus != globals.systemStatus)
 | 
			
		||||
		{
 | 
			
		||||
			strcpy_P(globals.systemStatustxt, PSTR("Error"));
 | 
			
		||||
			lastStatus = globals.systemStatus;
 | 
			
		||||
		}
 | 
			
		||||
	default:
 | 
			
		||||
		break;
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	// Yield to allow other tasks to run
 | 
			
		||||
	yield();
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
@@ -303,31 +331,33 @@ String macToString(const unsigned char *mac)
 | 
			
		||||
 | 
			
		||||
void SevenSeg_Output()
 | 
			
		||||
{
 | 
			
		||||
	char sevenSegBuff[5] = "";
 | 
			
		||||
	char sevenSegBuff[9] = "";
 | 
			
		||||
 | 
			
		||||
	if (DisplayOverrideFlag > millis())
 | 
			
		||||
	{
 | 
			
		||||
		disp_FAC_1.setBrightness(5);
 | 
			
		||||
		disp_FAC_2.setBrightness(5);
 | 
			
		||||
		disp_FAC_3.setBrightness(5);
 | 
			
		||||
		disp_FAC_1.display(String(DisplayOverrideValue));
 | 
			
		||||
		disp_FAC_2.clearScreen();
 | 
			
		||||
		disp_FAC_3.clearScreen();
 | 
			
		||||
		disp_FAC_1.display(String(DisplayOverrideValue[0]));
 | 
			
		||||
		disp_FAC_2.display(String(DisplayOverrideValue[1]));
 | 
			
		||||
		disp_FAC_3.display(String(DisplayOverrideValue[2]));
 | 
			
		||||
	}
 | 
			
		||||
	else
 | 
			
		||||
	{
 | 
			
		||||
		if (globals.battery_level < BAT_LOW_PERCENT && millis() % 10000 > 7000)
 | 
			
		||||
		{
 | 
			
		||||
			if (millis() % 3000 < 1500)
 | 
			
		||||
				snprintf(sevenSegBuff, sizeof(sevenSegBuff), "%4d", globals.battery_level);
 | 
			
		||||
				snprintf(sevenSegBuff, sizeof(sevenSegBuff), "%4u", globals.battery_level);
 | 
			
		||||
			else
 | 
			
		||||
				snprintf(sevenSegBuff, sizeof(sevenSegBuff), "%4s", String(globals.loadvoltage, 1).c_str());
 | 
			
		||||
				snprintf(sevenSegBuff, sizeof(sevenSegBuff), "%3u.%1u", (globals.loadvoltage_mV / 1000), ((globals.loadvoltage_mV % 1000) / 100));
 | 
			
		||||
 | 
			
		||||
			sevenSegBuff[5] = '\0'; // truncate here if for any reason something bigger is in buffer than ecpected
 | 
			
		||||
 | 
			
		||||
			disp_FAC_1.setBrightness(1);
 | 
			
		||||
			disp_FAC_1.display(" BAT");
 | 
			
		||||
			disp_FAC_1.display(" Bat");
 | 
			
		||||
 | 
			
		||||
			disp_FAC_2.setBrightness(1);
 | 
			
		||||
			disp_FAC_2.display("LOW ");
 | 
			
		||||
			disp_FAC_2.display("low ");
 | 
			
		||||
 | 
			
		||||
			disp_FAC_3.setBrightness(1);
 | 
			
		||||
			disp_FAC_3.display(String(sevenSegBuff));
 | 
			
		||||
@@ -337,23 +367,32 @@ void SevenSeg_Output()
 | 
			
		||||
			disp_FAC_1.setBrightness(PersistenceData.activeFaction == FACTION_1 ? 5 : 1);
 | 
			
		||||
			disp_FAC_1.refresh();
 | 
			
		||||
			snprintf(sevenSegBuff, sizeof(sevenSegBuff), "%4d", PersistenceData.faction_1_timer / 60);
 | 
			
		||||
			sevenSegBuff[5] = '\0'; // truncate here if for any reason something bigger is in buffer than ecpected
 | 
			
		||||
			disp_FAC_1.display(String(sevenSegBuff), false, false);
 | 
			
		||||
			disp_FAC_1.setDp((PersistenceData.activeFaction == FACTION_1) && (millis() % 1000 > 500) ? 0x08 : 0x00);
 | 
			
		||||
 | 
			
		||||
			disp_FAC_2.setBrightness(PersistenceData.activeFaction == FACTION_2 ? 5 : 1);
 | 
			
		||||
			disp_FAC_2.refresh();
 | 
			
		||||
			snprintf(sevenSegBuff, sizeof(sevenSegBuff), "%4d", PersistenceData.faction_2_timer / 60);
 | 
			
		||||
			sevenSegBuff[5] = '\0'; // truncate here if for any reason something bigger is in buffer than ecpected
 | 
			
		||||
			disp_FAC_2.display(String(sevenSegBuff), false, false);
 | 
			
		||||
			disp_FAC_2.setDp((PersistenceData.activeFaction == FACTION_2) && (millis() % 1000 > 500) ? 0x08 : 0x00);
 | 
			
		||||
 | 
			
		||||
			disp_FAC_3.setBrightness(PersistenceData.activeFaction == FACTION_3 ? 5 : 1);
 | 
			
		||||
			disp_FAC_3.refresh();
 | 
			
		||||
			snprintf(sevenSegBuff, sizeof(sevenSegBuff), "%4d", PersistenceData.faction_3_timer / 60);
 | 
			
		||||
			sevenSegBuff[5] = '\0'; // truncate here if for any reason something bigger is in buffer than ecpected
 | 
			
		||||
			disp_FAC_3.display(String(sevenSegBuff), false, false);
 | 
			
		||||
			disp_FAC_3.setDp((PersistenceData.activeFaction == FACTION_3) && (millis() % 1000 > 500) ? 0x08 : 0x00);
 | 
			
		||||
		}
 | 
			
		||||
	}
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
void tmrCallback_FactionTicker()
 | 
			
		||||
{
 | 
			
		||||
	if (globals.timer_disabled == true)
 | 
			
		||||
		PersistenceData.activeFaction = NONE;
 | 
			
		||||
 | 
			
		||||
	switch (PersistenceData.activeFaction)
 | 
			
		||||
	{
 | 
			
		||||
	case FACTION_1:
 | 
			
		||||
@@ -390,124 +429,48 @@ void tmrCallback_InputGetter()
 | 
			
		||||
 | 
			
		||||
	if (keysPressed > 1)
 | 
			
		||||
	{
 | 
			
		||||
		Serial.println("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;
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	if (btnState[0] == FAC_1_TRG_PRESSED)
 | 
			
		||||
	if (btnState[0] == FAC_1_TRG_PRESSED && globals.timer_disabled != true)
 | 
			
		||||
	{
 | 
			
		||||
		if (PersistenceData.activeFaction != FACTION_1)
 | 
			
		||||
		{
 | 
			
		||||
			Serial.println("Faction 1 captured !");
 | 
			
		||||
			Debug_pushMessage("Faction 1 captured !\n");
 | 
			
		||||
			globals.requestEEAction = EE_PDS_SAVE;
 | 
			
		||||
		}
 | 
			
		||||
		PersistenceData.activeFaction = FACTION_1;
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	if (btnState[1] == FAC_2_TRG_PRESSED)
 | 
			
		||||
	if (btnState[1] == FAC_2_TRG_PRESSED && globals.timer_disabled != true)
 | 
			
		||||
	{
 | 
			
		||||
		if (PersistenceData.activeFaction != FACTION_2)
 | 
			
		||||
		{
 | 
			
		||||
			Serial.println("Faction 2 captured !");
 | 
			
		||||
			Debug_pushMessage("Faction 2 captured !\n");
 | 
			
		||||
			globals.requestEEAction = EE_PDS_SAVE;
 | 
			
		||||
		}
 | 
			
		||||
		PersistenceData.activeFaction = FACTION_2;
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	if (btnState[2] == FAC_3_TRG_PRESSED)
 | 
			
		||||
	if (btnState[2] == FAC_3_TRG_PRESSED && globals.timer_disabled != true)
 | 
			
		||||
	{
 | 
			
		||||
		if (PersistenceData.activeFaction != FACTION_3)
 | 
			
		||||
		{
 | 
			
		||||
			Serial.println("Faction 3 captured !");
 | 
			
		||||
			Debug_pushMessage("Faction 3 captured !\n");
 | 
			
		||||
			globals.requestEEAction = EE_PDS_SAVE;
 | 
			
		||||
		}
 | 
			
		||||
		PersistenceData.activeFaction = FACTION_3;
 | 
			
		||||
	}
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
void printParameters(struct Configuration configuration)
 | 
			
		||||
{
 | 
			
		||||
	Serial.println("----------------------------------------");
 | 
			
		||||
 | 
			
		||||
	Serial.print(F("HEAD : "));
 | 
			
		||||
	Serial.print(configuration.COMMAND, HEX);
 | 
			
		||||
	Serial.print(" ");
 | 
			
		||||
	Serial.print(configuration.STARTING_ADDRESS, HEX);
 | 
			
		||||
	Serial.print(" ");
 | 
			
		||||
	Serial.println(configuration.LENGHT, HEX);
 | 
			
		||||
	Serial.println(F(" "));
 | 
			
		||||
	Serial.print(F("AddH : "));
 | 
			
		||||
	Serial.println(configuration.ADDH, HEX);
 | 
			
		||||
	Serial.print(F("AddL : "));
 | 
			
		||||
	Serial.println(configuration.ADDL, HEX);
 | 
			
		||||
	Serial.println(F(" "));
 | 
			
		||||
	Serial.print(F("Chan : "));
 | 
			
		||||
	Serial.print(configuration.CHAN, DEC);
 | 
			
		||||
	Serial.print(" -> ");
 | 
			
		||||
	Serial.println(configuration.getChannelDescription());
 | 
			
		||||
	Serial.println(F(" "));
 | 
			
		||||
	Serial.print(F("SpeedParityBit     : "));
 | 
			
		||||
	Serial.print(configuration.SPED.uartParity, BIN);
 | 
			
		||||
	Serial.print(" -> ");
 | 
			
		||||
	Serial.println(configuration.SPED.getUARTParityDescription());
 | 
			
		||||
	Serial.print(F("SpeedUARTDatte     : "));
 | 
			
		||||
	Serial.print(configuration.SPED.uartBaudRate, BIN);
 | 
			
		||||
	Serial.print(" -> ");
 | 
			
		||||
	Serial.println(configuration.SPED.getUARTBaudRateDescription());
 | 
			
		||||
	Serial.print(F("SpeedAirDataRate   : "));
 | 
			
		||||
	Serial.print(configuration.SPED.airDataRate, BIN);
 | 
			
		||||
	Serial.print(" -> ");
 | 
			
		||||
	Serial.println(configuration.SPED.getAirDataRateDescription());
 | 
			
		||||
	Serial.println(F(" "));
 | 
			
		||||
	Serial.print(F("OptionSubPacketSett: "));
 | 
			
		||||
	Serial.print(configuration.OPTION.subPacketSetting, BIN);
 | 
			
		||||
	Serial.print(" -> ");
 | 
			
		||||
	Serial.println(configuration.OPTION.getSubPacketSetting());
 | 
			
		||||
	Serial.print(F("OptionTranPower    : "));
 | 
			
		||||
	Serial.print(configuration.OPTION.transmissionPower, BIN);
 | 
			
		||||
	Serial.print(" -> ");
 | 
			
		||||
	Serial.println(configuration.OPTION.getTransmissionPowerDescription());
 | 
			
		||||
	Serial.print(F("OptionRSSIAmbientNo: "));
 | 
			
		||||
	Serial.print(configuration.OPTION.RSSIAmbientNoise, BIN);
 | 
			
		||||
	Serial.print(" -> ");
 | 
			
		||||
	Serial.println(configuration.OPTION.getRSSIAmbientNoiseEnable());
 | 
			
		||||
	Serial.println(F(" "));
 | 
			
		||||
	Serial.print(F("TransModeWORPeriod : "));
 | 
			
		||||
	Serial.print(configuration.TRANSMISSION_MODE.WORPeriod, BIN);
 | 
			
		||||
	Serial.print(" -> ");
 | 
			
		||||
	Serial.println(configuration.TRANSMISSION_MODE.getWORPeriodByParamsDescription());
 | 
			
		||||
	Serial.print(F("TransModeEnableLBT : "));
 | 
			
		||||
	Serial.print(configuration.TRANSMISSION_MODE.enableLBT, BIN);
 | 
			
		||||
	Serial.print(" -> ");
 | 
			
		||||
	Serial.println(configuration.TRANSMISSION_MODE.getLBTEnableByteDescription());
 | 
			
		||||
	Serial.print(F("TransModeEnableRSSI: "));
 | 
			
		||||
	Serial.print(configuration.TRANSMISSION_MODE.enableRSSI, BIN);
 | 
			
		||||
	Serial.print(" -> ");
 | 
			
		||||
	Serial.println(configuration.TRANSMISSION_MODE.getRSSIEnableByteDescription());
 | 
			
		||||
	Serial.print(F("TransModeFixedTrans: "));
 | 
			
		||||
	Serial.print(configuration.TRANSMISSION_MODE.fixedTransmission, BIN);
 | 
			
		||||
	Serial.print(" -> ");
 | 
			
		||||
	Serial.println(configuration.TRANSMISSION_MODE.getFixedTransmissionDescription());
 | 
			
		||||
 | 
			
		||||
	Serial.println("----------------------------------------");
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
#if defined(FEATURE_ENABLE_LORA) || defined(FEATURE_ENABLE_UARTLORA)
 | 
			
		||||
void tmrCallback_StatusSender()
 | 
			
		||||
{
 | 
			
		||||
	struct
 | 
			
		||||
	{
 | 
			
		||||
		MessageType_t type = "STATUS";
 | 
			
		||||
		MessageStatus_t status;
 | 
			
		||||
	} __attribute__((packed)) sendStatus;
 | 
			
		||||
 | 
			
		||||
	sendStatus.status.nodeid = 0x0002;
 | 
			
		||||
	sendStatus.status.millis = millis();
 | 
			
		||||
	sendStatus.status.faction_active = 1;
 | 
			
		||||
	sendStatus.status.faction_1_timer = 0xBBBBBBBB;
 | 
			
		||||
	sendStatus.status.faction_2_timer = 0xCCCCCCCC;
 | 
			
		||||
	sendStatus.status.faction_3_timer = 0xDDDDDDDD;
 | 
			
		||||
 | 
			
		||||
	ResponseStatus rs = e220ttl.sendFixedMessage(0xFF, 0xFF, 23, (byte *)&sendStatus, sizeof(sendStatus));
 | 
			
		||||
	Serial.println(rs.getResponseDescription());
 | 
			
		||||
	sendStatus_LoRa();
 | 
			
		||||
}
 | 
			
		||||
#endif
 | 
			
		||||
 | 
			
		||||
void tmrCallback_PowerMonitor()
 | 
			
		||||
{
 | 
			
		||||
@@ -528,15 +491,15 @@ void tmrCallback_PowerMonitor()
 | 
			
		||||
	busvoltage = ina219.getBusVoltage_V();
 | 
			
		||||
	// current_mA = ina219.getCurrent_mA();
 | 
			
		||||
	// power_mW = ina219.getPower_mW();
 | 
			
		||||
	globals.loadvoltage = busvoltage + (shuntvoltage / 1000);
 | 
			
		||||
	globals.loadvoltage_mV = (busvoltage * 1000) + shuntvoltage;
 | 
			
		||||
	switch (ConfigData.batteryType)
 | 
			
		||||
	{
 | 
			
		||||
	case BATTERY_LIPO_2S:
 | 
			
		||||
		battery_level = map(globals.loadvoltage * 100, bat_min_2s, bat_max_2s, 0, 100);
 | 
			
		||||
		battery_level = map(globals.loadvoltage_mV / 10, bat_min_2s, bat_max_2s, 0, 100);
 | 
			
		||||
		globals.battery_level = battery_level < 0 ? 0 : battery_level;
 | 
			
		||||
		break;
 | 
			
		||||
	case BATTERY_LIPO_3S:
 | 
			
		||||
		battery_level = map(globals.loadvoltage * 100, bat_min_3s, bat_max_3s, 0, 100);
 | 
			
		||||
		battery_level = map(globals.loadvoltage_mV / 10, bat_min_3s, bat_max_3s, 0, 100);
 | 
			
		||||
		globals.battery_level = battery_level < 0 ? 0 : battery_level;
 | 
			
		||||
		break;
 | 
			
		||||
	default:
 | 
			
		||||
@@ -544,63 +507,147 @@ void tmrCallback_PowerMonitor()
 | 
			
		||||
		break;
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	MaintainDTC(DTC_BAT_LOW, (battery_level < 15 ? true : false), battery_level);
 | 
			
		||||
	MaintainDTC(DTC_BAT_CRITICAL, (battery_level < 5 ? true : false), battery_level);
 | 
			
		||||
 | 
			
		||||
	// Serial.printf("Battery Level: %d %%\n", globals.battery_level);
 | 
			
		||||
	// Serial.printf("Bus Voltage: %f V\n", busvoltage);
 | 
			
		||||
	// Serial.printf("Shunt Voltage: %f mV\n", shuntvoltage);
 | 
			
		||||
	// Serial.printf("Load Voltage: %f V\n", globals.loadvoltage);
 | 
			
		||||
	// Serial.printf("Load Voltage: %d mV\n", globals.loadvoltage_mV;
 | 
			
		||||
	// Serial.printf("Current: %f mA\n", current_mA);
 | 
			
		||||
	// Serial.printf("Power: %f mW\n", power_mW);
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
void tmrCallback_EEPROMCyclicPDS()
 | 
			
		||||
/**
 | 
			
		||||
 * @brief Callback function for cyclically storing Persistence Data Structure (PDS) to EEPROM.
 | 
			
		||||
 *
 | 
			
		||||
 * This callback function is invoked periodically to store the Persistence Data Structure (PDS)
 | 
			
		||||
 * to the EEPROM. It ensures that essential data is saved persistently, allowing the system to
 | 
			
		||||
 * recover its state after power cycles or resets.
 | 
			
		||||
 */
 | 
			
		||||
void EEPROMCyclicPDS_callback()
 | 
			
		||||
{
 | 
			
		||||
	StorePersistence_EEPROM();
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
#ifdef WIFI_CLIENT
 | 
			
		||||
void tmrCallback_WiFiMaintainConnection()
 | 
			
		||||
#ifdef FEATURE_ENABLE_WIFI_CLIENT
 | 
			
		||||
/**
 | 
			
		||||
 * @brief Callback function for maintaining WiFi connection and handling connection failures.
 | 
			
		||||
 *
 | 
			
		||||
 * This callback function is used by a ticker to periodically check the WiFi connection status.
 | 
			
		||||
 * If the device is not connected to WiFi, it counts connection failures. If the number of failures
 | 
			
		||||
 * exceeds a defined threshold, the function triggers the initiation of an Access Point (AP) mode
 | 
			
		||||
 * using the `toggleWiFiAP` function.
 | 
			
		||||
 */
 | 
			
		||||
void wifiMaintainConnectionTicker_callback()
 | 
			
		||||
{
 | 
			
		||||
	// Static variables to track WiFi connection failure count and maximum allowed failures
 | 
			
		||||
	static uint32_t WiFiFailCount = 0;
 | 
			
		||||
	const uint32_t WiFiFailMax = 20;
 | 
			
		||||
 | 
			
		||||
	// Check if the device is connected to WiFi
 | 
			
		||||
	if (wifiMulti.run(connectTimeoutMs) == WL_CONNECTED)
 | 
			
		||||
	{
 | 
			
		||||
		return;
 | 
			
		||||
		return; // Exit if connected
 | 
			
		||||
	}
 | 
			
		||||
	else
 | 
			
		||||
	{
 | 
			
		||||
		// Increment WiFi connection failure count
 | 
			
		||||
		if (WiFiFailCount < WiFiFailMax)
 | 
			
		||||
		{
 | 
			
		||||
			WiFiFailCount++;
 | 
			
		||||
		}
 | 
			
		||||
		else
 | 
			
		||||
			toggleWiFiAP(false);
 | 
			
		||||
		{
 | 
			
		||||
			// Trigger AP mode if the maximum failures are reached
 | 
			
		||||
			Debug_pushMessage("WiFi not connected! - Start AP\n");
 | 
			
		||||
			toggleWiFiAP();
 | 
			
		||||
		}
 | 
			
		||||
	}
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
#endif
 | 
			
		||||
 | 
			
		||||
void toggleWiFiAP(boolean shutdown)
 | 
			
		||||
/**
 | 
			
		||||
 * @brief Toggles the WiFi functionality based on the current status.
 | 
			
		||||
 *
 | 
			
		||||
 * This function manages the WiFi state, either turning it off or starting it as an Access Point (AP),
 | 
			
		||||
 * depending on the current mode. If the WiFi is turned off, it can be started in AP mode with the
 | 
			
		||||
 * device name and password configured. Additionally, it may stop certain operations related to WiFi
 | 
			
		||||
 * maintenance or display debug messages based on the defined features.
 | 
			
		||||
 *
 | 
			
		||||
 * @param shutdown Flag indicating whether the system is in a shutdown state.
 | 
			
		||||
 */
 | 
			
		||||
void toggleWiFiAP(bool shutdown)
 | 
			
		||||
{
 | 
			
		||||
	if (WiFi.getMode() != WIFI_OFF && shutdown == true)
 | 
			
		||||
	char buffer[33];
 | 
			
		||||
	char buffer_pass[33];
 | 
			
		||||
	// Check if WiFi is currently active
 | 
			
		||||
	if (WiFi.getMode() != WIFI_OFF)
 | 
			
		||||
	{
 | 
			
		||||
		// Turn off WiFi
 | 
			
		||||
		WiFi.mode(WIFI_OFF);
 | 
			
		||||
#ifdef WIFI_CLIENT
 | 
			
		||||
		Debug_pushMessage("WiFi turned off\n");
 | 
			
		||||
 | 
			
		||||
		// Stop WiFi maintenance connection ticker if enabled
 | 
			
		||||
#ifdef FEATURE_ENABLE_WIFI_CLIENT
 | 
			
		||||
		tmrWiFiMaintainConnection.stop();
 | 
			
		||||
#endif
 | 
			
		||||
	}
 | 
			
		||||
	else if (shutdown == false)
 | 
			
		||||
	else
 | 
			
		||||
	{
 | 
			
		||||
		// 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.DeviceName_ID, QUOTE(WIFI_AP_PASSWORD));
 | 
			
		||||
#ifdef WIFI_CLIENT
 | 
			
		||||
		sanitizeWiFiString(globals.DeviceNameId, buffer, sizeof(buffer));
 | 
			
		||||
		GenerateDeviceSpecificPassword(QUOTE(WIFI_PASS_SEED), buffer_pass, sizeof(buffer_pass));
 | 
			
		||||
		WiFi.softAP(buffer, buffer_pass);
 | 
			
		||||
 | 
			
		||||
		// Stop WiFi maintenance connection ticker if enabled and display debug messages
 | 
			
		||||
#ifdef FEATURE_ENABLE_WIFI_CLIENT
 | 
			
		||||
		tmrWiFiMaintainConnection.stop();
 | 
			
		||||
		Debug_pushMessage("WiFi AP started, stopped Maintain-Timer\n");
 | 
			
		||||
#else
 | 
			
		||||
		Debug_pushMessage("WiFi AP started\n");
 | 
			
		||||
#endif
 | 
			
		||||
	}
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
void SystemShutdown()
 | 
			
		||||
/**
 | 
			
		||||
 * @brief Performs necessary tasks before shutting down and optionally restarts the ESP.
 | 
			
		||||
 *
 | 
			
		||||
 * This function initiates a system shutdown, performing tasks such as storing configuration
 | 
			
		||||
 * and persistence data to EEPROM before shutting down. If a restart is requested, the ESP
 | 
			
		||||
 * will be restarted; otherwise, the system will enter an indefinite loop.
 | 
			
		||||
 *
 | 
			
		||||
 * @param restart Flag indicating whether to restart the ESP after shutdown (default: false).
 | 
			
		||||
 */
 | 
			
		||||
void SystemShutdown(bool restart)
 | 
			
		||||
{
 | 
			
		||||
	StoreConfig_EEPROM();
 | 
			
		||||
	ESP.restart();
 | 
			
		||||
	static uint32_t shutdown_delay = 0;
 | 
			
		||||
 | 
			
		||||
	// Initialize shutdown delay on the first call
 | 
			
		||||
	if (shutdown_delay == 0)
 | 
			
		||||
	{
 | 
			
		||||
		shutdown_delay = millis() + SHUTDOWN_DELAY_MS;
 | 
			
		||||
		Serial.printf("Shutdown requested - Restarting in %d seconds\n", SHUTDOWN_DELAY_MS / 1000);
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	// Check if the shutdown delay has elapsed
 | 
			
		||||
	if (shutdown_delay < millis())
 | 
			
		||||
	{
 | 
			
		||||
		Webserver_Shutdown();
 | 
			
		||||
 | 
			
		||||
		// Store persistence data to EEPROM
 | 
			
		||||
		StorePersistence_EEPROM();
 | 
			
		||||
 | 
			
		||||
		// Perform restart if requested, otherwise enter an indefinite loop
 | 
			
		||||
		if (restart)
 | 
			
		||||
			ESP.restart();
 | 
			
		||||
		else
 | 
			
		||||
			while (1)
 | 
			
		||||
				;
 | 
			
		||||
	}
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
void SetBatteryType(batteryType_t type)
 | 
			
		||||
@@ -613,24 +660,12 @@ void SetBatteryType(batteryType_t type)
 | 
			
		||||
	}
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
void OverrideDisplay(const char *message, uint32_t time)
 | 
			
		||||
void OverrideDisplay(uint32_t time, const char *message1, const char *message2, const char *message3)
 | 
			
		||||
{
 | 
			
		||||
	DisplayOverrideFlag = millis() + time;
 | 
			
		||||
	strcpy(DisplayOverrideValue, message);
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
uint32_t getESPChipID()
 | 
			
		||||
{
 | 
			
		||||
#if defined(ESP8266)
 | 
			
		||||
	return ESP.getChipId();
 | 
			
		||||
#elif defined(ESP32)
 | 
			
		||||
	uint32_t chipId;
 | 
			
		||||
	for (int i = 0; i < 17; i = i + 8)
 | 
			
		||||
	{
 | 
			
		||||
		chipId |= ((ESP.getEfuseMac() >> (40 - i)) & 0xff) << i;
 | 
			
		||||
	}
 | 
			
		||||
	return chipId;
 | 
			
		||||
#endif
 | 
			
		||||
	strcpy(DisplayOverrideValue[0], message1);
 | 
			
		||||
	strcpy(DisplayOverrideValue[1], message2);
 | 
			
		||||
	strcpy(DisplayOverrideValue[2], message3);
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
void ProcessKeyCombos(bool *btnState)
 | 
			
		||||
@@ -642,24 +677,14 @@ void ProcessKeyCombos(bool *btnState)
 | 
			
		||||
	} keyStatus_t;
 | 
			
		||||
 | 
			
		||||
	static keyStatus_t keyStatus_Fac1 = KEY_RELEASED;
 | 
			
		||||
	static uint8_t keyCount_Fac1 = 0;
 | 
			
		||||
	static keyStatus_t keyStatus_Fac2 = KEY_RELEASED;
 | 
			
		||||
	static uint8_t keyCount_Fac2 = 0;
 | 
			
		||||
	static keyStatus_t keyStatus_Fac3 = KEY_RELEASED;
 | 
			
		||||
	static uint8_t keyCount_Fac3 = 0;
 | 
			
		||||
 | 
			
		||||
	if (btnState[2] == FAC_3_TRG_PRESSED)
 | 
			
		||||
	if (btnState[0] == FAC_1_TRG_PRESSED)
 | 
			
		||||
	{
 | 
			
		||||
		keyStatus_Fac3 = KEY_PRESSED;
 | 
			
		||||
 | 
			
		||||
		// Process FactionKey 1 ComboCounter
 | 
			
		||||
		if (btnState[0] == FAC_1_TRG_PRESSED && keyStatus_Fac1 == KEY_RELEASED)
 | 
			
		||||
		{
 | 
			
		||||
			keyStatus_Fac1 = KEY_PRESSED;
 | 
			
		||||
			keyCount_Fac1++;
 | 
			
		||||
		}
 | 
			
		||||
 | 
			
		||||
		if (btnState[0] != FAC_1_TRG_PRESSED)
 | 
			
		||||
			keyStatus_Fac1 = KEY_RELEASED;
 | 
			
		||||
		keyStatus_Fac1 = KEY_PRESSED;
 | 
			
		||||
 | 
			
		||||
		// Process FactionKey 2 ComboCounter
 | 
			
		||||
		if (btnState[1] == FAC_2_TRG_PRESSED && keyStatus_Fac2 == KEY_RELEASED)
 | 
			
		||||
@@ -670,24 +695,98 @@ void ProcessKeyCombos(bool *btnState)
 | 
			
		||||
 | 
			
		||||
		if (btnState[1] != FAC_2_TRG_PRESSED)
 | 
			
		||||
			keyStatus_Fac2 = KEY_RELEASED;
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	if (btnState[2] != FAC_3_TRG_PRESSED && keyStatus_Fac3 == KEY_PRESSED)
 | 
			
		||||
	{
 | 
			
		||||
		if (keyCount_Fac1 > 0 || keyCount_Fac2 > 0)
 | 
			
		||||
			Serial.printf("KeyCombo 1: %d | 2: %d\n", keyCount_Fac1, keyCount_Fac2);
 | 
			
		||||
 | 
			
		||||
		if (keyCount_Fac1 == 2 && keyCount_Fac2 == 2)
 | 
			
		||||
		// Process FactionKey 3 ComboCounter
 | 
			
		||||
		if (btnState[2] == FAC_3_TRG_PRESSED && keyStatus_Fac3 == KEY_RELEASED)
 | 
			
		||||
		{
 | 
			
		||||
			Serial.println("KeyCombo: WiFi AP ON");
 | 
			
		||||
			OverrideDisplay("NET ", 5000);
 | 
			
		||||
			toggleWiFiAP(false);
 | 
			
		||||
			keyStatus_Fac3 = KEY_PRESSED;
 | 
			
		||||
			keyCount_Fac3++;
 | 
			
		||||
		}
 | 
			
		||||
 | 
			
		||||
		if (btnState[2] != FAC_3_TRG_PRESSED)
 | 
			
		||||
			keyStatus_Fac3 = KEY_RELEASED;
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	if (btnState[0] != FAC_1_TRG_PRESSED && keyStatus_Fac1 == KEY_PRESSED)
 | 
			
		||||
	{
 | 
			
		||||
		if (keyCount_Fac2 > 0 || keyCount_Fac3 > 0)
 | 
			
		||||
			Debug_pushMessage("KeyCombo 2: %d | 3: %d\n", keyCount_Fac2, keyCount_Fac3);
 | 
			
		||||
 | 
			
		||||
		if (keyCount_Fac2 == 2 && keyCount_Fac3 == 0)
 | 
			
		||||
		{
 | 
			
		||||
			Debug_pushMessage("KeyCombo: WiFi AP ON\n");
 | 
			
		||||
			OverrideDisplay(5000, "NET ", "    ", "    ");
 | 
			
		||||
			toggleWiFiAP(false);
 | 
			
		||||
		}
 | 
			
		||||
		else if (keyCount_Fac2 == 4 && keyCount_Fac3 == 0)
 | 
			
		||||
		{
 | 
			
		||||
			Debug_pushMessage("KeyCombo: Reset Timer\n");
 | 
			
		||||
			if (millis() < STARTUP_DELAY_MS)
 | 
			
		||||
			{
 | 
			
		||||
				OverrideDisplay(5000, "RST ", "    ", "    ");
 | 
			
		||||
				PersistenceData.faction_1_timer = 0;
 | 
			
		||||
				PersistenceData.faction_2_timer = 0;
 | 
			
		||||
				PersistenceData.faction_3_timer = 0;
 | 
			
		||||
				PersistenceData.activeFaction = NONE;
 | 
			
		||||
				globals.requestEEAction = EE_PDS_SAVE;
 | 
			
		||||
			}
 | 
			
		||||
			else
 | 
			
		||||
			{
 | 
			
		||||
				OverrideDisplay(5000, "ERR ", "    ", "    ");
 | 
			
		||||
				Debug_pushMessage("ERROR: only %d seconds after Startup!\n", STARTUP_DELAY_MS / 1000);
 | 
			
		||||
			}
 | 
			
		||||
		}
 | 
			
		||||
 | 
			
		||||
		keyCount_Fac1 = 0;
 | 
			
		||||
		keyCount_Fac2 = 0;
 | 
			
		||||
		keyCount_Fac3 = 0;
 | 
			
		||||
		keyStatus_Fac1 = KEY_RELEASED;
 | 
			
		||||
		keyStatus_Fac2 = KEY_RELEASED;
 | 
			
		||||
		keyStatus_Fac3 = KEY_RELEASED;
 | 
			
		||||
	}
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
void maintainSysStat()
 | 
			
		||||
{
 | 
			
		||||
 | 
			
		||||
	static tSystem_Status lastStat = sysStat_Startup;
 | 
			
		||||
 | 
			
		||||
	// system Status Transistions
 | 
			
		||||
	switch (globals.systemStatus)
 | 
			
		||||
	{
 | 
			
		||||
	case sysStat_Shutdown:
 | 
			
		||||
		SystemShutdown();
 | 
			
		||||
		break;
 | 
			
		||||
 | 
			
		||||
	case sysStat_Startup:
 | 
			
		||||
		if (millis() > STARTUP_DELAY_MS)
 | 
			
		||||
			globals.systemStatus = sysStat_Normal;
 | 
			
		||||
		break;
 | 
			
		||||
 | 
			
		||||
	case sysStat_Error:
 | 
			
		||||
	case sysStat_Normal:
 | 
			
		||||
	default:
 | 
			
		||||
		break;
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	// system Status Changed Actions
 | 
			
		||||
	if (lastStat != globals.systemStatus)
 | 
			
		||||
	{
 | 
			
		||||
		switch (globals.systemStatus)
 | 
			
		||||
		{
 | 
			
		||||
		case sysStat_Shutdown:
 | 
			
		||||
			OverrideDisplay(SHUTDOWN_DELAY_MS, "  re", "boot", "    ");
 | 
			
		||||
			break;
 | 
			
		||||
 | 
			
		||||
		case sysStat_Startup:
 | 
			
		||||
			OverrideDisplay(STARTUP_DELAY_MS, "star", "t up", "    ");
 | 
			
		||||
			break;
 | 
			
		||||
 | 
			
		||||
		case sysStat_Error:
 | 
			
		||||
		case sysStat_Normal:
 | 
			
		||||
		default:
 | 
			
		||||
			break;
 | 
			
		||||
		}
 | 
			
		||||
 | 
			
		||||
		lastStat = globals.systemStatus;
 | 
			
		||||
	}
 | 
			
		||||
}
 | 
			
		||||
@@ -1,42 +0,0 @@
 | 
			
		||||
#include "oled_display.h"
 | 
			
		||||
 | 
			
		||||
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RST);
 | 
			
		||||
 | 
			
		||||
void OLED_Init()
 | 
			
		||||
{
 | 
			
		||||
 | 
			
		||||
    // reset OLED display via software
 | 
			
		||||
    pinMode(OLED_RST, OUTPUT);
 | 
			
		||||
    digitalWrite(OLED_RST, LOW);
 | 
			
		||||
    delay(20);
 | 
			
		||||
    digitalWrite(OLED_RST, HIGH);
 | 
			
		||||
 | 
			
		||||
    // initialize OLED
 | 
			
		||||
    Wire.begin(OLED_SDA, OLED_SCL);
 | 
			
		||||
    if (!display.begin(SSD1306_SWITCHCAPVCC, 0x3c, false, false))
 | 
			
		||||
    { // Address 0x3C for 128x32
 | 
			
		||||
        Serial.println(F("SSD1306 allocation failed"));
 | 
			
		||||
    }
 | 
			
		||||
 | 
			
		||||
    display.clearDisplay();
 | 
			
		||||
    display.setTextColor(WHITE);
 | 
			
		||||
    display.setTextSize(1);
 | 
			
		||||
    display.setCursor(0, 0);
 | 
			
		||||
    display.print("DISPLAY INIT");
 | 
			
		||||
    display.display();
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
void OLED_Process()
 | 
			
		||||
{
 | 
			
		||||
 | 
			
		||||
    display.clearDisplay();
 | 
			
		||||
    display.setCursor(0, 0);
 | 
			
		||||
    display.printf("LiPo: %d%%\n", globals.battery_level);
 | 
			
		||||
    display.print(PersistenceData.activeFaction == FACTION_1 ? "> " : "  ");
 | 
			
		||||
    display.printf("%-5s: %02d:%02d:%02d\n", FACTION_1_NAME, PersistenceData.faction_1_timer / 3600, (PersistenceData.faction_1_timer / 60) % 60, PersistenceData.faction_1_timer % 60);
 | 
			
		||||
    display.print(PersistenceData.activeFaction == FACTION_2 ? "> " : "  ");
 | 
			
		||||
    display.printf("%-5s: %02d:%02d:%02d\n", FACTION_2_NAME, PersistenceData.faction_2_timer / 3600, (PersistenceData.faction_2_timer / 60) % 60, PersistenceData.faction_2_timer % 60);
 | 
			
		||||
    display.print(PersistenceData.activeFaction == FACTION_3 ? "> " : "  ");
 | 
			
		||||
    display.printf("%-5s: %02d:%02d:%02d\n", FACTION_3_NAME, PersistenceData.faction_3_timer / 3600, (PersistenceData.faction_3_timer / 60) % 60, PersistenceData.faction_3_timer % 60);
 | 
			
		||||
    display.display();
 | 
			
		||||
}
 | 
			
		||||
@@ -1,20 +0,0 @@
 | 
			
		||||
#ifndef _OLED_DISPLAY_H_
 | 
			
		||||
#define _OLED_DISPLAY_H_
 | 
			
		||||
 | 
			
		||||
#include <Arduino.h>
 | 
			
		||||
#include <Wire.h>
 | 
			
		||||
#include <Adafruit_GFX.h>
 | 
			
		||||
#include <Adafruit_SSD1306.h>
 | 
			
		||||
#include "globals.h"
 | 
			
		||||
#include "config.h"
 | 
			
		||||
 | 
			
		||||
#define OLED_SDA 4
 | 
			
		||||
#define OLED_SCL 15
 | 
			
		||||
#define OLED_RST 16
 | 
			
		||||
#define SCREEN_WIDTH 128 // OLED display width, in pixels
 | 
			
		||||
#define SCREEN_HEIGHT 64 // OLED display height, in pixels
 | 
			
		||||
 | 
			
		||||
void OLED_Init();
 | 
			
		||||
void OLED_Process();
 | 
			
		||||
 | 
			
		||||
#endif
 | 
			
		||||
							
								
								
									
										41
									
								
								Software/src/struct2json.cpp
									
									
									
									
									
										Normal file
									
								
							
							
						
						@@ -0,0 +1,41 @@
 | 
			
		||||
/**
 | 
			
		||||
 * @file struct2json.cpp
 | 
			
		||||
 *
 | 
			
		||||
 * @brief Implementation file for converting structs to JSON objects.
 | 
			
		||||
 *
 | 
			
		||||
 * @note This file is auto-generated by a script on 2024-06-06 18:52:33.
 | 
			
		||||
 *
 | 
			
		||||
 * @author Marcel Peterkau
 | 
			
		||||
 * @date   06.06.2024
 | 
			
		||||
 */
 | 
			
		||||
 | 
			
		||||
 | 
			
		||||
#include "struct2json.h"
 | 
			
		||||
 | 
			
		||||
void generateJsonObject_ConfigData(JsonObject data)
 | 
			
		||||
{
 | 
			
		||||
    data["EEPROM_Version"] = ConfigData.EEPROM_Version;
 | 
			
		||||
    data["batteryType"] = ConfigData.batteryType;
 | 
			
		||||
    data["active_faction_on_reboot"] = ConfigData.active_faction_on_reboot;
 | 
			
		||||
    data["Faction_1_Name"] = ConfigData.Faction_1_Name;
 | 
			
		||||
    data["Faction_2_Name"] = ConfigData.Faction_2_Name;
 | 
			
		||||
    data["Faction_3_Name"] = ConfigData.Faction_3_Name;
 | 
			
		||||
    data["wifi_client_ssid"] = ConfigData.wifi_client_ssid;
 | 
			
		||||
    data["wifi_client_password"] = ConfigData.wifi_client_password;
 | 
			
		||||
    data["wifi_autoconnect"] = ConfigData.wifi_autoconnect;
 | 
			
		||||
    data["checksum"] = ConfigData.checksum;
 | 
			
		||||
    }
 | 
			
		||||
 | 
			
		||||
void generateJsonObject_PersistenceData(JsonObject data)
 | 
			
		||||
{
 | 
			
		||||
    data["writeCycleCounter"] = PersistenceData.writeCycleCounter;
 | 
			
		||||
    data["faction_1_timer"] = PersistenceData.faction_1_timer;
 | 
			
		||||
    data["faction_2_timer"] = PersistenceData.faction_2_timer;
 | 
			
		||||
    data["faction_3_timer"] = PersistenceData.faction_3_timer;
 | 
			
		||||
    data["activeFaction"] = PersistenceData.activeFaction;
 | 
			
		||||
    data["checksum"] = PersistenceData.checksum;
 | 
			
		||||
    }
 | 
			
		||||
 | 
			
		||||
 | 
			
		||||
 | 
			
		||||
// CODEGENERATOR_CHECKSUM: 3a3fd3024dd9dd769ff5d62f61b3ba1b781b7d06e7568a1ddac56d193dba9ee5
 | 
			
		||||
							
								
								
									
										126
									
								
								Software/src/utilities.cpp
									
									
									
									
									
										Normal file
									
								
							
							
						
						@@ -0,0 +1,126 @@
 | 
			
		||||
#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 == '~' || 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 == '~' || c == ' '))
 | 
			
		||||
        {
 | 
			
		||||
            // Replace invalid character with placeholder
 | 
			
		||||
            buffer[i] = '_';
 | 
			
		||||
        }
 | 
			
		||||
        else
 | 
			
		||||
        {
 | 
			
		||||
            // Copy valid character to buffer
 | 
			
		||||
            buffer[i] = c;
 | 
			
		||||
        }
 | 
			
		||||
    }
 | 
			
		||||
    // Null-terminate the buffer
 | 
			
		||||
    buffer[i] = '\0';
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
/**
 | 
			
		||||
 * @brief Generates a device-specific password based on a seed and the ESP8266 Chip ID.
 | 
			
		||||
 *
 | 
			
		||||
 * This function combines a given seed with the unique Chip ID of the ESP8266 device to create a device-specific password.
 | 
			
		||||
 * The resulting password is stored in the provided character buffer.
 | 
			
		||||
 *
 | 
			
		||||
 * @param seed The seed string used for password generation. Should be up to 16 characters long.
 | 
			
		||||
 * @param passwordBuffer The character buffer where the generated password will be stored.
 | 
			
		||||
 * @param bufferLength The length of the password buffer. Should be large enough to hold the generated password and null terminator.
 | 
			
		||||
 */
 | 
			
		||||
void GenerateDeviceSpecificPassword(const char* seed, char* passwordBuffer, size_t bufferLength) {
 | 
			
		||||
    uint32_t chipId = ESP.getChipId();
 | 
			
		||||
    char chipIdStr[9]; // 8 characters + null terminator
 | 
			
		||||
    snprintf(chipIdStr, sizeof(chipIdStr), "%08X", chipId);
 | 
			
		||||
 | 
			
		||||
    char combined[33]; // seed (16) + chipId (8) + null terminator (1)
 | 
			
		||||
    strncpy(combined, seed, 16);
 | 
			
		||||
    strncat(combined, chipIdStr, 8);
 | 
			
		||||
 | 
			
		||||
    // Simple hash function for demonstration
 | 
			
		||||
    unsigned long hash = 5381;
 | 
			
		||||
    int c;
 | 
			
		||||
    char *str = combined;
 | 
			
		||||
 | 
			
		||||
    while ((c = *str++)) {
 | 
			
		||||
        hash = ((hash << 5) + hash) + c; // hash * 33 + c
 | 
			
		||||
    }
 | 
			
		||||
 | 
			
		||||
    snprintf(passwordBuffer, bufferLength, "%08X%08X", hash, hash);
 | 
			
		||||
    passwordBuffer[bufferLength - 1] = '\0'; // Ensure null termination
 | 
			
		||||
}
 | 
			
		||||
@@ -1,16 +0,0 @@
 | 
			
		||||
#ifndef _WEBUI_H_
 | 
			
		||||
#define _WEBUI_H_
 | 
			
		||||
 | 
			
		||||
#include <Arduino.h>
 | 
			
		||||
#include <FS.h>
 | 
			
		||||
#include <LittleFS.h>
 | 
			
		||||
#include <ESPAsyncTCP.h>
 | 
			
		||||
#include <ESPAsyncWebServer.h>
 | 
			
		||||
#include "config.h"
 | 
			
		||||
#include "globals.h"
 | 
			
		||||
#include "dtc.h"
 | 
			
		||||
#include "defaults.h"
 | 
			
		||||
 | 
			
		||||
void initWebUI();
 | 
			
		||||
 | 
			
		||||
#endif
 | 
			
		||||
@@ -1,5 +1,5 @@
 | 
			
		||||
[wifi_cred]
 | 
			
		||||
wifi_ap_password = wifiappass
 | 
			
		||||
wifi_ssid = wifi-ssid
 | 
			
		||||
wifi_password = wifi-pass
 | 
			
		||||
admin_password = ota-password
 | 
			
		||||
admin_password = chainlube
 | 
			
		||||
wifi_pass_seed = wifiapseed
 | 
			
		||||
wifi_ssid_client = wifi-ssid
 | 
			
		||||
wifi_password_client = ota-password
 | 
			
		||||