AsyncElegantOTA.h 3.0 KB

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