simplify wifi and make it more generic

This commit is contained in:
Nicu Hodos 2024-06-01 22:14:34 +02:00
parent c9e1192804
commit 2465dbfea7

View File

@ -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() {