75 lines
2.0 KiB
C++
75 lines
2.0 KiB
C++
#include <ESP8266WiFi.h>
|
|
#include <ESP8266WiFiMulti.h>
|
|
#include <ESP8266mDNS.h>
|
|
#include "credentials.h"
|
|
|
|
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();
|
|
});
|
|
|
|
stationDisconnectedHandler = WiFi.onStationModeDisconnected([](const WiFiEventStationModeDisconnected& e) {
|
|
Serial.println("Disconnected from network.");
|
|
tWifiReconnect.restartDelayed();
|
|
});
|
|
|
|
|
|
ESP8266WiFiMulti wifiMulti;
|
|
for (uint32_t i = 0; i < sizeof(credentials) / sizeof(WifiCredentials); i++) {
|
|
wifiMulti.addAP(credentials[i].ssid, credentials[i].password);
|
|
}
|
|
|
|
Serial.println("Connecting to WiFi netowrk.");
|
|
while (wifiMulti.run() != WL_CONNECTED) {
|
|
delay(500);
|
|
}
|
|
WiFi.setHostname("esp-clock");
|
|
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...");
|
|
}
|
|
}
|
|
|
|
void disconnect() {
|
|
Serial.println("Disconnecting WiFi");
|
|
WiFi.disconnect();
|
|
WiFi.forceSleepBegin();
|
|
}
|
|
|
|
void printStatus() {
|
|
// print the SSID of the network you're attached to:
|
|
Serial.print("SSID: ");
|
|
Serial.println(WiFi.SSID());
|
|
|
|
// print your WiFi shield's IP address:
|
|
IPAddress ip = WiFi.localIP();
|
|
Serial.print("IP Address: ");
|
|
Serial.println(ip);
|
|
|
|
// print the received signal strength:
|
|
long rssi = WiFi.RSSI();
|
|
Serial.print("signal strength (RSSI):");
|
|
Serial.print(rssi);
|
|
Serial.println(" dBm");
|
|
}
|
|
}
|