diff --git a/src/wifi.h b/src/wifi.h index c00d88d..f3f6361 100644 --- a/src/wifi.h +++ b/src/wifi.h @@ -7,23 +7,33 @@ namespace Wifi { WiFiEventHandler stationConnectedHandler; WiFiEventHandler stationDisconnectedHandler; - void reconnect(); - - Task tWifiReconnect(1 * TASK_MINUTE, TASK_FOREVER, reconnect, &ts); String currentSSID; String currentPsk; - void setup() { - stationConnectedHandler = WiFi.onStationModeGotIP([](const WiFiEventStationModeGotIP& e) { - Serial.println("Reconnected to network."); - tWifiConnected.restart(); - tWifiReconnect.cancel(); + void printStatus(); + + Task tReconnect(1 * TASK_MINUTE, TASK_FOREVER, []{ + if (WiFi.status() != WL_CONNECTED) { + Serial.println("Reconnecting to WiFi netowrk..."); + WiFi.forceSleepWake(); + WiFi.begin(currentSSID.c_str(), currentPsk.c_str()); + } + }); + + void setup(Scheduler& ts, void(*onConnected)() = nullptr) { + ts.addTask(tReconnect); + + stationConnectedHandler = WiFi.onStationModeGotIP([onConnected](const WiFiEventStationModeGotIP& e) { + Serial.println("Connected to network."); + printStatus(); + tReconnect.cancel(); + if (onConnected) onConnected(); }); stationDisconnectedHandler = WiFi.onStationModeDisconnected([](const WiFiEventStationModeDisconnected& e) { Serial.println("Disconnected from network."); - tWifiReconnect.restartDelayed(); + tReconnect.restartDelayed(); }); @@ -36,17 +46,11 @@ namespace Wifi { while (wifiMulti.run() != WL_CONNECTED) { delay(500); } - WiFi.setHostname("esp-clock"); + WiFi.setHostname(MAIN_DEVICE_ID); currentSSID = WiFi.SSID(); currentPsk = WiFi.psk(); - } - void reconnect() { - if (WiFi.status() != WL_CONNECTED) { - WiFi.forceSleepWake(); - WiFi.begin(currentSSID.c_str(), currentPsk.c_str()); - Serial.println("Reconnecting to WiFi netowrk..."); - } + tReconnect.enable(); } void disconnect() {