85 lines
2.2 KiB
C++
85 lines
2.2 KiB
C++
#include "ota_update.hpp"
|
|
|
|
OtaUpdate::OtaUpdate()
|
|
: _server(80), _httpUpdater(), _configured(false), _startTime(0) {
|
|
}
|
|
|
|
bool OtaUpdate::configure(const hardware_SensorOTAEnable& config) {
|
|
_config = config;
|
|
_configured = true;
|
|
_startTime = millis();
|
|
|
|
// Disconnect if already connected
|
|
WiFi.disconnect();
|
|
delay(100);
|
|
|
|
if (_config.as_station_mode) {
|
|
// STA mode
|
|
WiFi.mode(WIFI_STA);
|
|
WiFi.begin(_config.ssid, _config.password);
|
|
|
|
Serial.print("Connecting to WiFi STA: ");
|
|
Serial.println(_config.ssid);
|
|
|
|
unsigned long startAttempt = millis();
|
|
while (WiFi.status() != WL_CONNECTED && millis() - startAttempt < 10000) {
|
|
delay(500);
|
|
Serial.print(".");
|
|
}
|
|
|
|
if (WiFi.status() != WL_CONNECTED) {
|
|
Serial.println("Failed to connect to WiFi");
|
|
_configured = false;
|
|
return false;
|
|
}
|
|
|
|
if (_config.use_static_ip) {
|
|
IPAddress ip, gateway, subnet;
|
|
ip.fromString(_config.static_ip);
|
|
gateway.fromString(_config.gateway);
|
|
subnet.fromString(_config.netmask);
|
|
WiFi.config(ip, gateway, subnet);
|
|
}
|
|
|
|
Serial.println("");
|
|
Serial.print("Connected to ");
|
|
Serial.println(_config.ssid);
|
|
Serial.print("IP address: ");
|
|
Serial.println(WiFi.localIP());
|
|
} else {
|
|
// AP mode
|
|
WiFi.mode(WIFI_AP);
|
|
WiFi.softAP(_config.ssid, _config.password);
|
|
|
|
Serial.print("Started AP: ");
|
|
Serial.println(_config.ssid);
|
|
Serial.print("IP address: ");
|
|
Serial.println(WiFi.softAPIP());
|
|
}
|
|
|
|
// Setup HTTP Update Server
|
|
_httpUpdater.setup(&_server);
|
|
_server.begin();
|
|
Serial.println("HTTP Update Server started");
|
|
|
|
return true;
|
|
}
|
|
|
|
void OtaUpdate::update() {
|
|
if (!_configured) return;
|
|
|
|
_server.handleClient();
|
|
|
|
// Check timeout
|
|
if (_config.timeout_seconds > 0 && millis() - _startTime > _config.timeout_seconds * 1000) {
|
|
Serial.println("OTA timeout, disabling WiFi");
|
|
disable();
|
|
}
|
|
}
|
|
|
|
void OtaUpdate::disable() {
|
|
_server.stop();
|
|
WiFi.disconnect();
|
|
_configured = false;
|
|
Serial.println("OTA disabled");
|
|
} |