Files
nanopsx_sen66/firmware/src/wifi_mgr.c
T

382 lines
12 KiB
C
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// File: src/wifi_mgr.c
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <inttypes.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/event_groups.h"
#include "esp_event.h"
#include "esp_log.h"
#include "esp_system.h"
#include "esp_wifi.h"
#include "esp_netif.h"
#include "esp_timer.h"
#include "lwip/netdb.h"
#include "http_portal.h"
#include "wifi_mgr.h"
#include "storage.h" // NVS-Zugriffe
#include "net_mdns.h"
#include "sys_status.h"
// Captive-DNS ist in http_portal.c implementiert:
void dns_captive_start(void);
void dns_captive_stop(void);
// ---------- Konfig ----------
#define SOFTAP_SSID "nanoPSX"
#define SOFTAP_PASS "" // leer => offenes WLAN
#define SOFTAP_CHANNEL 1
#define SOFTAP_MAX_CONN 4
static const char *TAG = "wifi_mgr";
// ---------- Globals ----------
static esp_netif_t *netif_ap = NULL, *netif_sta = NULL;
static EventGroupHandle_t wifi_events;
#define EVT_STA_GOTIP BIT0
#define EVT_STA_FAIL BIT1
#define EVT_STA_DISCONNECTED BIT2
// AP-Auto-Off / DNS start/stop
static bool ap_is_on = true;
// AP-Auto-Off Timer
static esp_timer_handle_t ap_off_timer = NULL;
// ---------- Vorwärtsdeklarationen ----------
static void ap_enable(void);
static void ap_disable(void);
static void ap_set_dhcp_dns_to_self(void);
static void mdns_discover_task(void *arg);
// Wi-Fi
static void wifi_event_handler(void* arg, esp_event_base_t base, int32_t id, void* data);
static void wifi_start_ap_sta(void);
// Timer Callback
static void ap_off_timer_cb(void *arg);
// ---------- Öffentliche Helfer (Wrapper um storage) ----------
bool wifi_mgr_load_sta_creds(char **out_ssid, char **out_pass) {
return storage_load_wifi_creds(out_ssid, out_pass);
}
void wifi_mgr_save_sta_creds_and_reconnect(const char* ssid, const char* pass) {
if (!ssid || !pass) return;
(void)storage_save_wifi_creds(ssid, pass);
// Status zurücksetzen
xEventGroupClearBits(wifi_events, EVT_STA_GOTIP | EVT_STA_FAIL | EVT_STA_DISCONNECTED);
// 1) sauber trennen (asynchron)
esp_err_t err = esp_wifi_disconnect();
if (err != ESP_OK && err != ESP_ERR_WIFI_NOT_CONNECT) {
ESP_LOGW(TAG, "esp_wifi_disconnect: %s", esp_err_to_name(err));
}
// 2) auf "disconnected" warten (kurz)
(void)xEventGroupWaitBits(
wifi_events,
EVT_STA_DISCONNECTED,
pdTRUE, // beim Eintreffen löschen
pdFALSE,
pdMS_TO_TICKS(1500) // 1.5 s Timeout – gern anpassen
);
// (Optionaler Fallback falls Timeout: Treiber kurz stoppen/neu starten)
// Das vermeidet 0x3006 bei hartnäckigen Races.
wifi_mode_t mode = WIFI_MODE_APSTA;
if (esp_wifi_set_mode(mode) != ESP_OK) {
ESP_LOGW(TAG, "set_mode(APSTA) failed pre-config");
}
// 3) neue Creds setzen (MIT sicherer Kopie + Terminierung!)
char *s = NULL, *pw = NULL;
bool have = storage_load_wifi_creds(&s, &pw);
if (have) {
wifi_config_t sta = {0};
// WICHTIG: KEIN strncpy-Fallstrick → immer nullterminieren!
strlcpy((char*)sta.sta.ssid, s, sizeof(sta.sta.ssid));
strlcpy((char*)sta.sta.password, pw, sizeof(sta.sta.password));
#ifdef WPA3_SAE_PWE_BOTH
sta.sta.pmf_cfg.required = true;
sta.sta.sae_pwe_h2e = WPA3_SAE_PWE_BOTH;
sta.sta.threshold.authmode = WIFI_AUTH_WPA2_WPA3_PSK;
#else
sta.sta.threshold.authmode = WIFI_AUTH_WPA2_PSK;
#endif
err = esp_wifi_set_config(WIFI_IF_STA, &sta);
if (err == ESP_ERR_WIFI_STATE) {
// Harter Fallback: kurz stoppen, dann setzen.
ESP_LOGW(TAG, "set_config: WIFI_STATE – stop/start fallback");
ESP_ERROR_CHECK(esp_wifi_stop());
ESP_ERROR_CHECK(esp_wifi_start());
ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_APSTA));
ESP_ERROR_CHECK(esp_wifi_set_config(WIFI_IF_STA, &sta));
} else {
ESP_ERROR_CHECK(err);
}
ESP_ERROR_CHECK(esp_wifi_connect());
}
if (s) free(s);
if (pw) free(pw);
}
void wifi_mgr_save_device_info(const char* devicename,
const char* token,
const char* bucket,
const char* org) {
// 1) Devicename separat handhaben (NULL=kein Update, ""=löschen)
(void)storage_save_device_name(devicename);
// 2) Influx-Teil mit SoftAP-Semantik (NULL=keep, ""=löschen, sonst setzen)
(void)storage_save_influx_softap(org, bucket, token);
// 3) Debug: alles nochmal ausgeben
storage_debug_dump();
}
// ---------- AP Toggle ----------
static void ap_enable(void) {
if (ap_is_on) return;
wifi_config_t ap = (wifi_config_t){0};
strncpy((char*)ap.ap.ssid, SOFTAP_SSID, sizeof(ap.ap.ssid));
ap.ap.ssid_len = strlen(SOFTAP_SSID);
ap.ap.channel = SOFTAP_CHANNEL;
ap.ap.max_connection = SOFTAP_MAX_CONN;
if (strlen(SOFTAP_PASS) == 0) {
ap.ap.authmode = WIFI_AUTH_OPEN;
} else {
strncpy((char*)ap.ap.password, SOFTAP_PASS, sizeof(ap.ap.password));
ap.ap.authmode = WIFI_AUTH_WPA_WPA2_PSK;
}
ap.ap.pmf_cfg.required = false;
esp_wifi_set_mode(WIFI_MODE_APSTA);
esp_wifi_set_config(WIFI_IF_AP, &ap);
ap_is_on = true;
// DNS/Captive einschalten
(void)dns_captive_start();
// DHCP-DNS Option auf AP-IP setzen
ap_set_dhcp_dns_to_self();
if (netif_ap) {
esp_netif_ip_info_t ip;
if (esp_netif_get_ip_info(netif_ap, &ip) == ESP_OK) {
ESP_LOGI(TAG, "AP reaktiviert. IP " IPSTR, IP2STR(&ip.ip));
} else {
ESP_LOGI(TAG, "AP reaktiviert.");
}
}
}
static void ap_disable(void) {
if (!ap_is_on) return;
// DNS/Captive aus
dns_captive_stop();
esp_wifi_set_mode(WIFI_MODE_STA); // nur STA aktiv
ap_is_on = false;
ESP_LOGI(TAG, "AP/DNS deaktiviert (nur STA aktiv).");
// (Optional) Portal mit abschalten, damit es nicht auf STA erreichbar bleibt:
// portal_http_stop();
}
// ---------- Timer Callback ----------
static void ap_off_timer_cb(void *arg) {
(void)arg;
EventBits_t bits = xEventGroupGetBits(wifi_events);
if (bits & EVT_STA_GOTIP) {
ap_disable();
} else {
ESP_LOGW(TAG, "AP-Auto-Off abgebrochen (keine STA-IP mehr).");
}
}
// ---------- Wi-Fi ----------
static void wifi_event_handler(void* arg, esp_event_base_t base, int32_t id, void* data) {
(void)arg;
if (base == WIFI_EVENT && id == WIFI_EVENT_STA_START) {
sys_status_set_wifi_ok(false);
ESP_LOGI(TAG, "STA start");
} else if (base == WIFI_EVENT && id == WIFI_EVENT_STA_DISCONNECTED) {
sys_status_set_wifi_ok(false);
ESP_LOGW(TAG, "STA disconnected");
xEventGroupClearBits(wifi_events, EVT_STA_GOTIP);
xEventGroupSetBits(wifi_events, EVT_STA_FAIL | EVT_STA_DISCONNECTED);
if (ap_off_timer && esp_timer_is_active(ap_off_timer)) {
esp_timer_stop(ap_off_timer);
}
ap_enable();
esp_wifi_connect();
} else if (base == IP_EVENT && id == IP_EVENT_STA_GOT_IP) {
sys_status_set_wifi_ok(true);
ip_event_got_ip_t *e = (ip_event_got_ip_t*)data;
ESP_LOGI(TAG, "STA got IP: " IPSTR, IP2STR(&e->ip_info.ip));
xEventGroupSetBits(wifi_events, EVT_STA_GOTIP);
xTaskCreate(mdns_discover_task, "mdns_discover", 3072, NULL, 4, NULL);
if (ap_off_timer) {
if (esp_timer_is_active(ap_off_timer)) esp_timer_stop(ap_off_timer);
ESP_ERROR_CHECK(esp_timer_start_once(ap_off_timer, 10 * 1000 * 1000)); // 10 s
ESP_LOGI(TAG, "AP-Auto-Off in 10s geplant…");
}
}
}
static void wifi_start_ap_sta(void) {
netif_ap = esp_netif_create_default_wifi_ap();
netif_sta = esp_netif_create_default_wifi_sta();
ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_APSTA));
wifi_config_t ap = (wifi_config_t){0};
strncpy((char*)ap.ap.ssid, SOFTAP_SSID, sizeof(ap.ap.ssid));
ap.ap.ssid_len = strlen(SOFTAP_SSID);
ap.ap.channel = SOFTAP_CHANNEL;
ap.ap.max_connection = SOFTAP_MAX_CONN;
if (strlen(SOFTAP_PASS) == 0) {
ap.ap.authmode = WIFI_AUTH_OPEN;
} else {
strncpy((char*)ap.ap.password, SOFTAP_PASS, sizeof(ap.ap.password));
ap.ap.authmode = WIFI_AUTH_WPA_WPA2_PSK;
}
ap.ap.pmf_cfg.required = false;
ESP_ERROR_CHECK(esp_wifi_set_config(WIFI_IF_AP, &ap));
char *ssid = NULL, *pass = NULL;
bool have = storage_load_wifi_creds(&ssid, &pass);
if (have) {
wifi_config_t sta = (wifi_config_t){0};
strncpy((char*)sta.sta.ssid, ssid, sizeof(sta.sta.ssid));
strncpy((char*)sta.sta.password, pass, sizeof(sta.sta.password));
#ifdef WPA3_SAE_PWE_BOTH
sta.sta.pmf_cfg.required = true;
sta.sta.sae_pwe_h2e = WPA3_SAE_PWE_BOTH;
sta.sta.threshold.authmode = WIFI_AUTH_WPA2_WPA3_PSK;
#else
sta.sta.threshold.authmode = WIFI_AUTH_WPA2_PSK;
#endif
ESP_ERROR_CHECK(esp_wifi_set_config(WIFI_IF_STA, &sta));
}
ESP_ERROR_CHECK(esp_wifi_start());
// DHCP-DNS auf AP-IP setzen (erhöht Captive-Trefferquote)
ap_set_dhcp_dns_to_self();
if (netif_ap) {
esp_netif_ip_info_t ip;
if (esp_netif_get_ip_info(netif_ap, &ip) == ESP_OK) {
ESP_LOGI(TAG, "AP %s gestartet. IP " IPSTR, SOFTAP_SSID, IP2STR(&ip.ip));
}
}
if (have) {
ESP_LOGI(TAG, "Versuche STA zu verbinden zu '%s' ...", ssid);
esp_wifi_connect();
}
if (ssid) free(ssid);
if (pass) free(pass);
}
// ---------- Öffentliche API ----------
void wifi_mgr_init(void) {
// NVS (neu über storage)
ESP_ERROR_CHECK(storage_init());
ESP_ERROR_CHECK(esp_netif_init());
ESP_ERROR_CHECK(esp_event_loop_create_default());
wifi_events = xEventGroupCreate();
wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
ESP_ERROR_CHECK(esp_wifi_init(&cfg));
ESP_ERROR_CHECK(esp_event_handler_register(WIFI_EVENT, ESP_EVENT_ANY_ID, &wifi_event_handler, NULL));
ESP_ERROR_CHECK(esp_event_handler_register(IP_EVENT, IP_EVENT_STA_GOT_IP, &wifi_event_handler, NULL));
const esp_timer_create_args_t targs = {
.callback = ap_off_timer_cb,
.arg = NULL,
.dispatch_method = ESP_TIMER_TASK,
.name = "ap_off_timer"
};
ESP_ERROR_CHECK(esp_timer_create(&targs, &ap_off_timer));
}
void wifi_mgr_start(void) {
// AP+STA hochfahren
wifi_start_ap_sta();
// HTTP-Portal starten (erzwingt Captive bis Save, s. http_portal.c)
ESP_ERROR_CHECK(portal_http_start(wifi_events, EVT_STA_GOTIP, EVT_STA_FAIL, SOFTAP_SSID));
// DNS/Captive starten
(void)dns_captive_start();
ESP_LOGI(TAG, "Bereit. Verbinde dich mit '%s' und öffne beliebige Seite – das Portal erscheint.", SOFTAP_SSID);
}
// ---------- Hilfsfunktionen ----------
static void ap_set_dhcp_dns_to_self(void) {
if (!netif_ap) return;
esp_netif_ip_info_t ip;
if (esp_netif_get_ip_info(netif_ap, &ip) != ESP_OK) return;
// DHCP-Server neu konfigurieren: als DNS-Server die eigene AP-IP anbieten
esp_netif_dhcps_stop(netif_ap);
esp_netif_dhcps_option(netif_ap, ESP_NETIF_OP_SET,
ESP_NETIF_DOMAIN_NAME_SERVER,
&ip.ip, sizeof(ip.ip));
esp_netif_dhcps_start(netif_ap);
}
// Task für mDNS-Discover ---
static void mdns_discover_task(void *arg) {
// Start/ensure mDNS läuft
(void)net_mdns_autostart_init(NULL, NULL);
const TickType_t kDelay = pdMS_TO_TICKS(60000); // 60 s
for (;;) {
// Erst offizieller Service, dann Fallback auf HTTP:8086
esp_err_t err = net_mdns_autodiscover_and_store("_myapp", "_tcp", -1,
NULL, NULL, 2000);
if (err != ESP_OK) {
err = net_mdns_autodiscover_and_store("_http", "_tcp", 8086,
NULL, NULL, 2000);
}
if (err == ESP_OK) {
sys_status_set_mdns_ok(true);
ESP_LOGI(TAG, "mDNS: Service gefunden und gespeichert. Beende Re-Try-Task.");
vTaskDelete(NULL); // fertig, keine weiteren Versuche
} else {
sys_status_set_mdns_ok(false);
ESP_LOGW(TAG, "mDNS: nichts gefunden – neuer Versuch in 60 s");
vTaskDelay(kDelay);
}
}
}