Files
ESPGadget/10_wifi_conf.ino

93 lines
2.8 KiB
C++

/*
* Wifi and OTA related stuff
*/
#include <time.h>
#include <ESP8266WiFi.h>
#include <WiFiClientSecure.h>
#include <WiFiManager.h>
#include <ESP8266httpUpdate.h>
WiFiManager WifiManager;
WiFiClientSecure net;
//BearSSL::WiFiClientSecure net;
unsigned long ota_lastcheck = 0;
//
// If the WifiManager configuration portal is called, we can do stuff
//
//void WifiManagerCallback(WiFiManager *myWiFiManager) {
// PRINTLN_SERIAL("Entered AP config mode");
//}
void wifi_associate() {
char apname[80];
settings.name.toCharArray(apname, 80);
WifiManager.setConfigPortalTimeout(300); // If no configuration is done in 5 mins, exit/restart quietly
if (WifiManager.autoConnect(apname)) { // @@@FIXME@@@ we should really set a PSK for the AP (but in my brief testing it crashed the ESP, so what's up with that)
settings.ip = WiFi.localIP().toString();
PRINTLN_SERIAL("Figured out my network \\O/");
//wificlient.setFingerprint(WTR_SHA1);
net.setInsecure(); // Do not check fingerprint
net.setTimeout(15000); // 15 Seconds
/* PRINT_SERIAL("Setting time using SNTP");
configTime(-5 * 3600, 0, "pool.ntp.org", "time.nist.gov");
now = time(nullptr);
while (now < 1510592825) {
delay(500);
APPEND_SERIAL(".");
now = time(nullptr);
}
APPENDLN_SERIAL(" done!");
struct tm timeinfo;
gmtime_r(&now, &timeinfo);
PRINT_SERIAL("Current time: ");
APPENDLN_SERIAL(asctime(&timeinfo)); */
}
}
void wifi_setup() {
// WifiManager.setAPCallback(WifiManagerCallback); // Enable WifiManager callback to clear the cache
wifi_associate();
}
void wifi_loop() {
if(WiFi.status() != WL_CONNECTED) {
PRINTLN_SERIAL("Wifi disconnected, trying to reconnect");
wifi_associate();
}
// OTA routine to be run once every X seconds
unsigned long ota_check = millis()/1000;
if((ota_lastcheck == 0) || ((ota_check - ota_lastcheck) > OTA_UPDATE_INTERVAL)) {
PRINTLN_SERIAL("Checking for OTA update");
// Check for firmware upgrades
String version = settings.name;
version.concat("-v");
version.concat(FW_VERSION);
t_httpUpdate_return ret = ESPhttpUpdate.update(net, OTA_SERVER, OTA_PORT, OTA_URI, version);
switch(ret) {
case HTTP_UPDATE_FAILED: // HTTP 403, 404
PRINT_SERIAL("Firmware upgrade available, but update failed ");
APPEND_SERIAL(" (ERR ");
APPEND_SERIAL(String(ESPhttpUpdate.getLastError()));
APPEND_SERIAL(") ");
APPENDLN_SERIAL(ESPhttpUpdate.getLastErrorString().c_str());
break;
case HTTP_UPDATE_NO_UPDATES: // HTTP 304
PRINTLN_SERIAL("No firmware upgrade available");
break;
case HTTP_UPDATE_OK: // HTTP 200
PRINTLN_SERIAL("Firmware upgrade available, upgraded ok."); // may not called we reboot the ESP
break;
}
ota_lastcheck = ota_check;
}
}