Skip to content

Instantly share code, notes, and snippets.

@JohannesBauer97
Last active February 20, 2021 12:34
Show Gist options
  • Save JohannesBauer97/d1b55f8e5187409ad84c9ab3b1dca59a to your computer and use it in GitHub Desktop.
Save JohannesBauer97/d1b55f8e5187409ad84c9ab3b1dca59a to your computer and use it in GitHub Desktop.
Base sketch for ESP8266 projects (Captive Portal, OTA Updates)
#include <ESP8266WiFi.h>
#include <DNSServer.h>
#include <ESP8266WebServer.h>
#include <WiFiManager.h> // https://github.com/tzapu/WiFiManager
#include <ESP8266HTTPClient.h>
#include <ESP8266httpUpdate.h>
const int FW_VERSION = 1;
const char* FW_VERSION_URL = "http://<domain>/<project>/version";
const char* FW_IMAGE_URL = "http://<domain>/<project>/img.bin";
void setup() {
Serial.begin(115200);
Serial.println("Setup running...");
WiFiManager wifiManager;
wifiManager.autoConnect();
checkForUpdates();
Serial.println("Setup finished...");
}
void loop() {
}
void checkForUpdates() {
HTTPClient httpClient;
httpClient.begin(FW_VERSION_URL);
int httpCode = httpClient.GET();
if(httpCode == 200) {
String newFWVersion = httpClient.getString();
Serial.print("Current firmware version: ");
Serial.println(FW_VERSION);
Serial.print("Available firmware version: ");
Serial.println(newFWVersion);
int newVersion = newFWVersion.toInt();
if(newVersion > FW_VERSION){
Serial.println("Preparing to update.");
t_httpUpdate_return ret = ESPhttpUpdate.update(FW_IMAGE_URL);
switch(ret) {
case HTTP_UPDATE_FAILED:
Serial.printf("HTTP_UPDATE_FAILED Error (%d): %s", ESPhttpUpdate.getLastError(), ESPhttpUpdate.getLastErrorString().c_str());
break;
case HTTP_UPDATE_NO_UPDATES:
Serial.println("HTTP_UPDATE_NO_UPDATES");
break;
}
} else {
Serial.println("Already on latest version");
}
} else {
Serial.print("Firmware version check failed, got HTTP response code ");
Serial.println(httpCode);
}
httpClient.end();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment