WebUpdate.ino 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. /*
  2. To upload through terminal you can use: curl -F "image=@firmware.bin" esp8266-webupdate.local/update
  3. */
  4. #include <ESP8266WiFi.h>
  5. #include <WiFiClient.h>
  6. #include <ESP8266WebServer.h>
  7. #include <ESP8266mDNS.h>
  8. const char* host = "esp8266-webupdate";
  9. const char* ssid = "........";
  10. const char* password = "........";
  11. ESP8266WebServer server(80);
  12. const char* serverIndex = "<form method='POST' action='/update' enctype='multipart/form-data'><input type='file' name='update'><input type='submit' value='Update'></form>";
  13. void setup(void){
  14. Serial.begin(115200);
  15. Serial.println();
  16. Serial.println("Booting Sketch...");
  17. WiFi.mode(WIFI_AP_STA);
  18. WiFi.begin(ssid, password);
  19. if(WiFi.waitForConnectResult() == WL_CONNECTED){
  20. MDNS.begin(host);
  21. server.on("/", HTTP_GET, [](){
  22. server.sendHeader("Connection", "close");
  23. server.sendHeader("Access-Control-Allow-Origin", "*");
  24. server.send(200, "text/html", serverIndex);
  25. });
  26. server.on("/update", HTTP_POST, [](){
  27. server.sendHeader("Connection", "close");
  28. server.sendHeader("Access-Control-Allow-Origin", "*");
  29. server.send(200, "text/plain", (Update.hasError())?"FAIL":"OK");
  30. ESP.restart();
  31. },[](){
  32. HTTPUpload& upload = server.upload();
  33. if(upload.status == UPLOAD_FILE_START){
  34. Serial.setDebugOutput(true);
  35. WiFiUDP::stopAll();
  36. Serial.printf("Update: %s\n", upload.filename.c_str());
  37. uint32_t maxSketchSpace = (ESP.getFreeSketchSpace() - 0x1000) & 0xFFFFF000;
  38. if(!Update.begin(maxSketchSpace)){//start with max available size
  39. Update.printError(Serial);
  40. }
  41. } else if(upload.status == UPLOAD_FILE_WRITE){
  42. if(Update.write(upload.buf, upload.currentSize) != upload.currentSize){
  43. Update.printError(Serial);
  44. }
  45. } else if(upload.status == UPLOAD_FILE_END){
  46. if(Update.end(true)){ //true to set the size to the current progress
  47. Serial.printf("Update Success: %u\nRebooting...\n", upload.totalSize);
  48. } else {
  49. Update.printError(Serial);
  50. }
  51. Serial.setDebugOutput(false);
  52. }
  53. yield();
  54. });
  55. server.begin();
  56. MDNS.addService("http", "tcp", 80);
  57. Serial.printf("Ready! Open http://%s.local in your browser\n", host);
  58. } else {
  59. Serial.println("WiFi Failed");
  60. }
  61. }
  62. void loop(void){
  63. server.handleClient();
  64. delay(1);
  65. }