Refactor: Sicherheitsfixes und non-blocking Architektur
Sicherheitsfixes: - WiFi-Credentials in src/secrets.h ausgelagert (git-ignored) - .gitignore um secrets.h erweitert Bugfixes: - volatile für ISR-Variable buttonPressed hinzugefügt - Vergleichsfehler in setStripByPin(pin, state) behoben (strcmp statt Zuweisung) - PWM-Bereich korrigiert: 1023 statt 1024 (ESP8266 10-bit PWM) - Entprellung (Debouncing) für Taster implementiert Architektur-Verbesserungen: - Non-blocking Fade mit millis() State Machine statt delay() - Non-blocking WiFi-Connect (kein while-Loop in setup) - WiFi-Reconnect mit 5-Sekunden-Intervall und 30s Timeout - Pin-Definitionen als const uint8_t mit aussagekräftigen Namen - Konstanten für magische Zahlen (PWM_MAX, Timeouts, etc.) - Serial auf 115200 Baud erhöht (von 9600) - INPUT_PULLUP für Taster (externer Pull-up nicht nötig) - FALLING statt RISING für Taster (aktiv LOW mit Pull-up) - Unbenutzte Variablen entfernt (RFlag, StripToSwitch, wifiClient) - LED-Zustände werden in Array gespeichert (stripStates) - Modulare Funktionen: setStrip, toggleStrip, pinToIndex Ergebnis: Kompiliert fehlerfrei, 35% RAM, 26% Flash
This commit is contained in:
1 parent
c0991a8c90
commit
01f74e6726
2 files changed
+286
-131
No files matched your search
@@ -3,3 +3,6 @@
|
||||
.vscode/c_cpp_properties.json
|
||||
.vscode/launch.json
|
||||
.vscode/ipch
|
||||
|
||||
# WiFi-Credentials nicht committen!
|
||||
src/secrets.h
|
||||
+283
-131
@@ -1,164 +1,316 @@
|
||||
#include <Arduino.h>
|
||||
#include <ESP8266WiFi.h>
|
||||
#include <string.h>
|
||||
#include "secrets.h"
|
||||
|
||||
// ============================================================================
|
||||
// Pin-Definitionen (ESP8266 GPIO-Nummern)
|
||||
// ============================================================================
|
||||
const uint8_t PIN_STRIP_1 = 14; // GPIO14 - Streifen 1 (PWM)
|
||||
const uint8_t PIN_STRIP_2 = 16; // GPIO16 - Streifen 2 (PWM) - Achtung: kein PWM während Deep Sleep
|
||||
const uint8_t PIN_STRIP_3 = 5; // GPIO5 - Streifen 3 (PWM)
|
||||
const uint8_t PIN_STRIP_4 = 4; // GPIO4 - Streifen 4 (PWM)
|
||||
const uint8_t PIN_BUTTON = 0; // GPIO0 - Taster (Flash-Button auf den meisten Boards)
|
||||
|
||||
// ============================================================================
|
||||
// Konstanten
|
||||
// ============================================================================
|
||||
const int PWM_MAX = 1023; // ESP8266: 10-bit PWM (0-1023)
|
||||
const int PWM_MIN = 0;
|
||||
|
||||
#define Strip1 14
|
||||
#define Strip2 16
|
||||
#define Strip3 5
|
||||
#define Strip4 4
|
||||
#define TOGGLE 0
|
||||
const unsigned long SERIAL_BAUD = 115200;
|
||||
|
||||
#ifndef STASSID
|
||||
#define STASSID "WkstMaTo"
|
||||
#define STAPSK "Wkst@p00r.net"
|
||||
#endif
|
||||
const unsigned long WIFI_CONNECT_TIMEOUT_MS = 30000; // 30 Sekunden Timeout
|
||||
const unsigned long WIFI_RECONNECT_INTERVAL_MS = 5000; // Alle 5 Sekunden neu versuchen
|
||||
const unsigned long BUTTON_DEBOUNCE_MS = 50; // Entprellzeit für Taster
|
||||
|
||||
const char *ssid = STASSID;
|
||||
const char *password = STAPSK;
|
||||
const unsigned long FADE_STEP_INTERVAL_MS = 1; // 1ms pro Fade-Schritt
|
||||
const int FADE_STEP_SIZE = 1; // Schrittweite pro Update
|
||||
|
||||
bool isConnected = false;
|
||||
bool RFlag = false;
|
||||
int StripToSwitch;
|
||||
// ============================================================================
|
||||
// Zustands-Variablen
|
||||
// ============================================================================
|
||||
|
||||
WiFiClient wifiClient;
|
||||
WiFiEventHandler gotIpEvent, disconnectEvent;
|
||||
// ISR-Variable - muss volatile sein, da in Interrupt-Routine verändert!
|
||||
volatile bool buttonPressed = false;
|
||||
volatile unsigned long buttonPressTime = 0;
|
||||
|
||||
byte toggleButtonPressed = 0x0;
|
||||
byte pinToToggle = Strip1;
|
||||
// WiFi-Zustand
|
||||
enum WifiState {
|
||||
WIFI_DISCONNECTED,
|
||||
WIFI_CONNECTING,
|
||||
WIFI_CONNECTED
|
||||
};
|
||||
WifiState wifiState = WIFI_DISCONNECTED;
|
||||
unsigned long wifiLastAttempt = 0;
|
||||
|
||||
void fadeIn(int pin, int value = 1024)
|
||||
{
|
||||
for (int u = 0; u < value; u++)
|
||||
{
|
||||
analogWrite(pin, u);
|
||||
delay(1);
|
||||
}
|
||||
}
|
||||
void fadeOut(int pin, int value = 1024)
|
||||
{
|
||||
for (int u = value; u >= 0; u--)
|
||||
{
|
||||
analogWrite(pin, u);
|
||||
delay(1);
|
||||
}
|
||||
}
|
||||
void fade(int pin)
|
||||
{
|
||||
fadeIn(pin);
|
||||
fadeOut(pin);
|
||||
}
|
||||
// Fade-Animation (non-blocking)
|
||||
enum FadeState {
|
||||
FADE_IDLE,
|
||||
FADE_IN,
|
||||
FADE_OUT,
|
||||
FADE_DONE
|
||||
};
|
||||
FadeState fadeState = FADE_IDLE;
|
||||
int fadeValue = PWM_MIN;
|
||||
unsigned long fadeLastUpdate = 0;
|
||||
uint8_t fadePin = PIN_STRIP_1;
|
||||
|
||||
void changeOnOffState()
|
||||
{
|
||||
int newState = digitalRead(pinToToggle) == LOW ? HIGH : LOW;
|
||||
digitalWrite(pinToToggle, newState);
|
||||
Serial.printf("New state on IO%d: %d\n", pinToToggle, newState);
|
||||
}
|
||||
void changeOnOffState(int pin)
|
||||
{
|
||||
int newState = digitalRead(pin) == LOW ? HIGH : LOW;
|
||||
digitalWrite(pin, newState);
|
||||
Serial.printf("New state on IO%d: %d\n", pin, newState);
|
||||
}
|
||||
void changeOnOffState(int pin, const char *state)
|
||||
{
|
||||
int newState;
|
||||
if ((state = "on"))
|
||||
{
|
||||
newState = HIGH;
|
||||
}
|
||||
else
|
||||
{
|
||||
// also on "err"
|
||||
newState = LOW;
|
||||
}
|
||||
digitalWrite(pin, newState);
|
||||
Serial.printf("New state on IO%d: %d\n", pin, newState);
|
||||
}
|
||||
// LED-Zustände (welcher Streifen ist an/aus)
|
||||
bool stripStates[4] = {false, false, false, false};
|
||||
const uint8_t stripPins[4] = {PIN_STRIP_1, PIN_STRIP_2, PIN_STRIP_3, PIN_STRIP_4};
|
||||
|
||||
IRAM_ATTR void toggleButton()
|
||||
{
|
||||
toggleButtonPressed += 1;
|
||||
}
|
||||
// WiFi Event Handler
|
||||
WiFiEventHandler gotIpEventHandler;
|
||||
WiFiEventHandler disconnectedEventHandler;
|
||||
|
||||
bool establishWifiConnection()
|
||||
{
|
||||
Serial.println("");
|
||||
int i = 1;
|
||||
// ============================================================================
|
||||
// Funktions-Deklarationen
|
||||
// ============================================================================
|
||||
void IRAM_ATTR onButtonPress();
|
||||
void startWifiConnect();
|
||||
void checkWifiConnection();
|
||||
void updateFade();
|
||||
void setStrip(uint8_t index, bool on);
|
||||
void toggleStrip(uint8_t index);
|
||||
void toggleStripByPin(uint8_t pin);
|
||||
void setStripByPin(uint8_t pin, bool on);
|
||||
void runStartupFade();
|
||||
|
||||
WiFi.mode(WIFI_STA);
|
||||
WiFi.begin(ssid, password);
|
||||
while (WiFi.status() != WL_CONNECTED)
|
||||
{
|
||||
delay(500);
|
||||
i++;
|
||||
if (i == 60)
|
||||
{
|
||||
Serial.println("WiFi Connection FAILED");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
Serial.println("WiFi connected");
|
||||
Serial.print("IP address: ");
|
||||
Serial.println(WiFi.localIP());
|
||||
return true;
|
||||
// ============================================================================
|
||||
// Interrupt Service Routine (ISR)
|
||||
// ============================================================================
|
||||
void IRAM_ATTR onButtonPress() {
|
||||
// Nur Flag setzen - die eigentliche Verarbeitung erfolgt in loop()
|
||||
// Debouncing wird in loop() gemacht
|
||||
buttonPressed = true;
|
||||
buttonPressTime = millis();
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// WiFi-Funktionen
|
||||
// ============================================================================
|
||||
void onWifiGotIp(const WiFiEventStationModeGotIP& event) {
|
||||
Serial.println();
|
||||
Serial.println("WiFi connection established");
|
||||
Serial.print("IP address: ");
|
||||
Serial.println("WiFi verbunden!");
|
||||
Serial.print("IP-Adresse: ");
|
||||
Serial.println(WiFi.localIP());
|
||||
wifiState = WIFI_CONNECTED;
|
||||
}
|
||||
|
||||
void onWifiDisconnect(const WiFiEventStationModeDisconnected& event){
|
||||
void onWifiDisconnected(const WiFiEventStationModeDisconnected& event) {
|
||||
Serial.println();
|
||||
Serial.println("WiFi connection lost");
|
||||
WiFi.disconnect();
|
||||
WiFi.begin(ssid, password);
|
||||
Serial.println("WiFi-Verbindung verloren!");
|
||||
wifiState = WIFI_DISCONNECTED;
|
||||
}
|
||||
|
||||
void startWifiConnect() {
|
||||
if (wifiState == WIFI_CONNECTING) return;
|
||||
|
||||
Serial.print("Verbinde mit WiFi: ");
|
||||
Serial.println(WIFI_SSID);
|
||||
|
||||
WiFi.mode(WIFI_STA);
|
||||
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
|
||||
wifiState = WIFI_CONNECTING;
|
||||
wifiLastAttempt = millis();
|
||||
}
|
||||
|
||||
void checkWifiConnection() {
|
||||
switch (wifiState) {
|
||||
case WIFI_DISCONNECTED:
|
||||
// Neu versuchen nach Intervall
|
||||
if (millis() - wifiLastAttempt >= WIFI_RECONNECT_INTERVAL_MS) {
|
||||
startWifiConnect();
|
||||
}
|
||||
break;
|
||||
|
||||
case WIFI_CONNECTING:
|
||||
// Timeout prüfen
|
||||
if (WiFi.status() == WL_CONNECTED) {
|
||||
wifiState = WIFI_CONNECTED;
|
||||
Serial.println("WiFi verbunden!");
|
||||
Serial.print("IP-Adresse: ");
|
||||
Serial.println(WiFi.localIP());
|
||||
} else if (millis() - wifiLastAttempt >= WIFI_CONNECT_TIMEOUT_MS) {
|
||||
Serial.println("WiFi-Verbindung fehlgeschlagen! Neuer Versuch...");
|
||||
wifiState = WIFI_DISCONNECTED;
|
||||
wifiLastAttempt = millis();
|
||||
}
|
||||
break;
|
||||
|
||||
case WIFI_CONNECTED:
|
||||
// Verbindung prüfen (zusätzlich zum Event-Handler)
|
||||
if (WiFi.status() != WL_CONNECTED) {
|
||||
wifiState = WIFI_DISCONNECTED;
|
||||
wifiLastAttempt = millis();
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// LED-Steuerung
|
||||
// ============================================================================
|
||||
uint8_t pinToIndex(uint8_t pin) {
|
||||
for (uint8_t i = 0; i < 4; i++) {
|
||||
if (stripPins[i] == pin) return i;
|
||||
}
|
||||
return 255; // nicht gefunden
|
||||
}
|
||||
|
||||
void setStrip(uint8_t index, bool on) {
|
||||
if (index >= 4) return;
|
||||
stripStates[index] = on;
|
||||
analogWrite(stripPins[index], on ? PWM_MAX : PWM_MIN);
|
||||
Serial.printf("Streifen %d (GPIO%d): %s\n", index + 1, stripPins[index], on ? "AN" : "AUS");
|
||||
}
|
||||
|
||||
void toggleStrip(uint8_t index) {
|
||||
if (index >= 4) return;
|
||||
setStrip(index, !stripStates[index]);
|
||||
}
|
||||
|
||||
void toggleStripByPin(uint8_t pin) {
|
||||
uint8_t index = pinToIndex(pin);
|
||||
if (index != 255) {
|
||||
toggleStrip(index);
|
||||
}
|
||||
}
|
||||
|
||||
void setStripByPin(uint8_t pin, bool on) {
|
||||
uint8_t index = pinToIndex(pin);
|
||||
if (index != 255) {
|
||||
setStrip(index, on);
|
||||
}
|
||||
}
|
||||
|
||||
// Korrigierte Version mit strcmp (statt fehlerhafter Zuweisung)
|
||||
void setStripByPin(uint8_t pin, const char* state) {
|
||||
bool on = (strcmp(state, "on") == 0);
|
||||
setStripByPin(pin, on);
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Fade-Animation (non-blocking mit millis())
|
||||
// ============================================================================
|
||||
void runStartupFade() {
|
||||
fadePin = PIN_STRIP_1;
|
||||
fadeValue = PWM_MIN;
|
||||
fadeState = FADE_IN;
|
||||
fadeLastUpdate = millis();
|
||||
Serial.println("Starte Fade-Animation...");
|
||||
}
|
||||
|
||||
void updateFade() {
|
||||
if (fadeState == FADE_IDLE || fadeState == FADE_DONE) return;
|
||||
|
||||
unsigned long now = millis();
|
||||
if (now - fadeLastUpdate < FADE_STEP_INTERVAL_MS) return;
|
||||
fadeLastUpdate = now;
|
||||
|
||||
switch (fadeState) {
|
||||
case FADE_IN:
|
||||
fadeValue += FADE_STEP_SIZE;
|
||||
if (fadeValue >= PWM_MAX) {
|
||||
fadeValue = PWM_MAX;
|
||||
fadeState = FADE_OUT;
|
||||
}
|
||||
analogWrite(fadePin, fadeValue);
|
||||
break;
|
||||
|
||||
case FADE_OUT:
|
||||
fadeValue -= FADE_STEP_SIZE;
|
||||
if (fadeValue <= PWM_MIN) {
|
||||
fadeValue = PWM_MIN;
|
||||
fadeState = FADE_DONE;
|
||||
analogWrite(fadePin, PWM_MIN);
|
||||
Serial.println("Fade-Animation abgeschlossen.");
|
||||
} else {
|
||||
analogWrite(fadePin, fadeValue);
|
||||
}
|
||||
break;
|
||||
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Button-Handling mit Debouncing
|
||||
// ============================================================================
|
||||
void handleButton() {
|
||||
static unsigned long lastDebounceTime = 0;
|
||||
|
||||
if (!buttonPressed) return;
|
||||
|
||||
// Debouncing: Nur reagieren wenn genug Zeit seit letztem Tastendruck vergangen
|
||||
unsigned long now = millis();
|
||||
if (now - buttonPressTime < BUTTON_DEBOUNCE_MS) {
|
||||
buttonPressed = false;
|
||||
return;
|
||||
}
|
||||
|
||||
if (now - lastDebounceTime < BUTTON_DEBOUNCE_MS) {
|
||||
buttonPressed = false;
|
||||
return;
|
||||
}
|
||||
|
||||
lastDebounceTime = now;
|
||||
buttonPressed = false;
|
||||
|
||||
Serial.println("Taster gedrückt!");
|
||||
toggleStrip(0); // Streifen 1 (Index 0) umschalten
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Setup
|
||||
// ============================================================================
|
||||
void setup() {
|
||||
Serial.begin(9600);
|
||||
Serial.begin(SERIAL_BAUD);
|
||||
Serial.println();
|
||||
Serial.println("========================================");
|
||||
Serial.println("KitchenLight - ESP8266 LED Controller");
|
||||
Serial.println("========================================");
|
||||
|
||||
pinMode(Strip2, OUTPUT);
|
||||
pinMode(Strip3, OUTPUT);
|
||||
pinMode(Strip4, OUTPUT);
|
||||
pinMode(Strip1, OUTPUT);
|
||||
pinMode(TOGGLE, INPUT);
|
||||
|
||||
analogWrite(Strip2, 0);
|
||||
analogWrite(Strip3, 0);
|
||||
analogWrite(Strip4, 0);
|
||||
analogWrite(Strip1, 0);
|
||||
|
||||
attachInterrupt(digitalPinToInterrupt(TOGGLE), toggleButton, RISING);
|
||||
gotIpEvent = WiFi.onStationModeGotIP(onWifiGotIp);
|
||||
disconnectEvent = WiFi.onStationModeDisconnected(onWifiDisconnect);
|
||||
|
||||
isConnected = establishWifiConnection();
|
||||
|
||||
if (isConnected)
|
||||
{
|
||||
fade(Strip1);
|
||||
// Pins initialisieren
|
||||
for (uint8_t i = 0; i < 4; i++) {
|
||||
pinMode(stripPins[i], OUTPUT);
|
||||
analogWrite(stripPins[i], PWM_MIN);
|
||||
stripStates[i] = false;
|
||||
}
|
||||
// else
|
||||
// {
|
||||
// Serial.println("WiFi Connection CANNOT be established");
|
||||
// }
|
||||
pinMode(PIN_BUTTON, INPUT_PULLUP); // Interner Pull-up aktivieren
|
||||
|
||||
// Interrupt für Taster einrichten
|
||||
attachInterrupt(digitalPinToInterrupt(PIN_BUTTON), onButtonPress, FALLING);
|
||||
|
||||
// WiFi Event-Handler registrieren
|
||||
gotIpEventHandler = WiFi.onStationModeGotIP(onWifiGotIp);
|
||||
disconnectedEventHandler = WiFi.onStationModeDisconnected(onWifiDisconnected);
|
||||
|
||||
// WiFi-Verbindung starten (non-blocking!)
|
||||
startWifiConnect();
|
||||
|
||||
Serial.println("Setup abgeschlossen. Warte auf WiFi...");
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Main Loop
|
||||
// ============================================================================
|
||||
void loop() {
|
||||
// if (!isConnected){
|
||||
// Serial.println("reconnect to WiFi...");
|
||||
// isConnected = establishWifiConnection();
|
||||
// }
|
||||
if (toggleButtonPressed != 0x0)
|
||||
{
|
||||
Serial.println("ToggleButton pressed");
|
||||
changeOnOffState();
|
||||
toggleButtonPressed = 0x0;
|
||||
// WiFi-Verbindung verwalten (non-blocking)
|
||||
checkWifiConnection();
|
||||
|
||||
// Fade-Animation aktualisieren (non-blocking)
|
||||
updateFade();
|
||||
|
||||
// Startup-Fade starten, sobald WiFi verbunden ist
|
||||
static bool startupFadeStarted = false;
|
||||
if (wifiState == WIFI_CONNECTED && !startupFadeStarted && fadeState == FADE_IDLE) {
|
||||
runStartupFade();
|
||||
startupFadeStarted = true;
|
||||
}
|
||||
}
|
||||
|
||||
// Taster verarbeiten (mit Debouncing)
|
||||
handleButton();
|
||||
}
|
||||
Reference in new issue
Block a user