AsyncElegantOTA.h 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. #ifndef ElegantOTA_h
  2. #define ElegantOTA_h
  3. #include "Arduino.h"
  4. #include "stdlib_noniso.h"
  5. #if defined(ESP8266)
  6. #define HARDWARE "ESP8266"
  7. #include "ESP8266WiFi.h"
  8. #include <Hash.h>
  9. #include <ESPAsyncTCP.h>
  10. #elif defined(ESP32)
  11. #define HARDWARE "ESP32"
  12. #include "WiFi.h"
  13. #include <Hash.h>
  14. #include <AsyncTCP.h>
  15. #endif
  16. #include <ESPAsyncWebServer.h>
  17. #include "elegantWebpage.h"
  18. class AsyncElegantOtaClass{
  19. public:
  20. void begin(AsyncWebServer &server){
  21. server->on("/update", HTTP_GET, [&](AsyncWebServerRequest *request){
  22. AsyncWebServerResponse *response = request->beginResponse_P(200, "text/html", ELEGANT_HTML, ELEGANT_HTML_SIZE);
  23. response->addHeader("Content-Encoding", "gzip");
  24. request->send(response);
  25. });
  26. server.on("/update", HTTP_POST, [&](AsyncWebServerRequest *request) {
  27. // the request handler is triggered after the upload has finished...
  28. // create the response, add header, and send response
  29. AsyncWebServerResponse *response = request->beginResponse((Update.hasError())?500:200, "text/plain", (Update.hasError())?"FAIL":"OK");
  30. response->addHeader("Connection", "close");
  31. response->addHeader("Access-Control-Allow-Origin", "*");
  32. request->send(response);
  33. ESP.restart();
  34. }, [](AsyncWebServerRequest *request, String filename, size_t index, uint8_t *data, size_t len, bool final) {
  35. //Upload handler chunks in data
  36. if (!index) {
  37. #if defined(ESP8266)
  38. uint32_t maxSketchSpace = (ESP.getFreeSketchSpace() - 0x1000) & 0xFFFFF000;
  39. if (!Update.begin(maxSketchSpace)){ // Start with max available size
  40. #endif
  41. #if defined(ESP32)
  42. if (!Update.begin(UPDATE_SIZE_UNKNOWN)) { // Start with max available size
  43. #endif
  44. Update.printError(Serial);
  45. }
  46. #if defined(ESP8266)
  47. Update.runAsync(true); // Tell the updaterClass to run in async mode
  48. #endif
  49. }
  50. // Write chunked data to the free sketch space
  51. if (Update.write(data, len) != len) {
  52. Update.printError(Serial);
  53. }
  54. if (final) { // if the final flag is set then this is the last frame of data
  55. if (Update.end(true)) { //true to set the size to the current progress
  56. }
  57. }
  58. });
  59. }
  60. };
  61. AsyncElegantOtaClass AsyncElegantOTA;
  62. #endif