65 lines
1.9 KiB
C++
65 lines
1.9 KiB
C++
#include <ESP8266WiFi.h>
|
|
#include <ESP8266mDNS.h>
|
|
#include "credentials.h"
|
|
|
|
namespace Wifi {
|
|
|
|
WiFiEventHandler stationConnectedHandler;
|
|
WiFiEventHandler stationDisconnectedHandler;
|
|
|
|
void printStatus();
|
|
|
|
Task tConnect(1 * TASK_MINUTE, TASK_FOREVER,
|
|
[] {
|
|
if (WiFi.status() != WL_CONNECTED) {
|
|
Serial.println("Connecting to WiFi network...");
|
|
WiFi.forceSleepWake();
|
|
WiFi.begin(credentials.ssid, credentials.password);
|
|
}
|
|
},
|
|
&ts, true);
|
|
|
|
void setup(Scheduler& ts, void(*onConnected)() = nullptr, void(*onDisconnected)() = nullptr) {
|
|
stationConnectedHandler = WiFi.onStationModeGotIP(
|
|
[onConnected](const WiFiEventStationModeGotIP& e) {
|
|
Serial.println("Connected to network.");
|
|
printStatus();
|
|
tConnect.cancel();
|
|
if (onConnected) onConnected();
|
|
});
|
|
|
|
stationDisconnectedHandler = WiFi.onStationModeDisconnected(
|
|
[onDisconnected](const WiFiEventStationModeDisconnected& e) {
|
|
Serial.println("Disconnected from network.");
|
|
tConnect.enableIfNot();
|
|
if (onDisconnected) onDisconnected();
|
|
});
|
|
|
|
|
|
WiFi.setHostname(MAIN_DEVICE_ID);
|
|
}
|
|
|
|
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");
|
|
}
|
|
}
|