107 lines
2.7 KiB
C++
107 lines
2.7 KiB
C++
#include "wifi.h"
|
|
#include "config.h"
|
|
#include "http.h"
|
|
#include "io.h"
|
|
|
|
#define CONFIG_HOSTNAME "/wifi/hostname"
|
|
#define CONFIG_WIFI_SSID "/wifi/ssid"
|
|
#define CONFIG_WIFI_PASSWORD "/wifi/password"
|
|
|
|
#ifndef DEFAULT_HOSTNAME
|
|
#define DEFAULT_HOSTNAME "PatrixSonoff4ChPro"
|
|
#endif
|
|
#define DEFAULT_WIFI_SSID "HappyNet"
|
|
#define DEFAULT_WIFI_PASSWORD "1Grausame!Sackratte7"
|
|
|
|
#include <ArduinoOTA.h>
|
|
|
|
bool wifiConnected = false;
|
|
|
|
unsigned long wifiLast = 0;
|
|
|
|
void wifiConnect() {
|
|
WiFi.disconnect();
|
|
WiFi.enableAP(false);
|
|
WiFi.setAutoConnect(false);
|
|
WiFi.setAutoReconnect(false);
|
|
yield();
|
|
|
|
status.cycle(500, 500);
|
|
|
|
const auto hostname = configRead(CONFIG_HOSTNAME, DEFAULT_HOSTNAME);
|
|
const auto wifiSSID = configRead(CONFIG_WIFI_SSID, DEFAULT_WIFI_SSID);
|
|
const auto wifiPass = configRead(CONFIG_WIFI_PASSWORD, DEFAULT_WIFI_PASSWORD, true, true);
|
|
|
|
Serial.printf("[WiFi] Connecting: \"%s\"\n", wifiSSID.c_str());
|
|
WiFi.hostname(hostname);
|
|
WiFi.begin(wifiSSID.c_str(), wifiPass.c_str());
|
|
wifiLast = max(1UL, millis());
|
|
yield();
|
|
}
|
|
|
|
void wifiLoop() {
|
|
const auto connected = WiFi.localIP() != 0UL;
|
|
if (wifiConnected) {
|
|
if (connected) {
|
|
httpLoop();
|
|
mqttLoop();
|
|
} else {
|
|
Serial.printf("[WiFi] Disconnected!\n");
|
|
ArduinoOTA.end();
|
|
httpStop();
|
|
mqttStop();
|
|
wifiConnect();
|
|
}
|
|
} else {
|
|
if (connected) {
|
|
status.set(false);
|
|
Serial.printf("[WiFi] Connected \"%s\" as \"%s\" (%s)\n", WiFi.SSID().c_str(), WiFi.getHostname(), WiFi.localIP().toString().c_str());
|
|
ArduinoOTA.begin();
|
|
httpSetup();
|
|
mqttSetup();
|
|
} else if (wifiLast == 0 || millis() - wifiLast >= 10000) {
|
|
if (wifiLast > 0) {
|
|
Serial.printf("[WiFi] Timeout!\n");
|
|
}
|
|
wifiConnect();
|
|
}
|
|
}
|
|
wifiConnected = connected;
|
|
}
|
|
|
|
void wifiChangeHostname(const char *hostname) {
|
|
if (configWrite(CONFIG_HOSTNAME, DEFAULT_HOSTNAME, hostname)) {
|
|
WiFi.setHostname(hostname);
|
|
}
|
|
}
|
|
|
|
void wifiChangeSSID(const char *ssid) {
|
|
configWrite(CONFIG_WIFI_SSID, DEFAULT_WIFI_SSID, ssid);
|
|
}
|
|
|
|
void wifiChangePassword(const char *password) {
|
|
configWrite(CONFIG_WIFI_PASSWORD, DEFAULT_WIFI_PASSWORD, password, true);
|
|
}
|
|
|
|
void wifiSetup() {
|
|
#ifdef ESP32
|
|
esp_log_level_set("wifi", ESP_LOG_NONE);
|
|
#endif
|
|
ArduinoOTA.onStart([] {
|
|
Serial.println("[OTA] Begin!");
|
|
status.set(true);
|
|
});
|
|
ArduinoOTA.onProgress([](const unsigned progress, const unsigned total) {
|
|
Serial.printf("[OTA] %3d%%\r", 100 * progress / total);
|
|
status.toggle();
|
|
});
|
|
ArduinoOTA.onEnd([] {
|
|
Serial.println("\n[OTA] Success!");
|
|
status.set(true);
|
|
});
|
|
ArduinoOTA.onError([](const ota_error_t error) {
|
|
Serial.printf("\n[OTA] Error %u\n", error);
|
|
status.set(false);
|
|
});
|
|
}
|