An ESP32-based Redis-watcher and info-displayer https://rpjios.com
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

89 lines
2.4 KiB

  1. #include "zw_ota.h"
  2. #include "zw_logging.h"
  3. #include <Arduino.h>
  4. #include <HTTPClient.h>
  5. #include <Update.h>
  6. void updateProg(size_t s1, size_t s2)
  7. {
  8. static int lastUpdate = 0;
  9. auto curPercent = ((double)s1 / s2) * 100.0;
  10. if ((unsigned)curPercent >= lastUpdate + OTA_UPDATE_PRCNT_REPORT)
  11. {
  12. lastUpdate = (unsigned)curPercent;
  13. dprint("%d.. %s", lastUpdate, (lastUpdate == 100 ? "\n" : ""));
  14. zlog("OTA update progress: %0.2f%% (%d)\n", curPercent, s1);
  15. }
  16. }
  17. bool runUpdate(
  18. const char *url,
  19. const char *md5,
  20. size_t sizeInBytes,
  21. void (*preUpdateIRQDisable)(),
  22. bool (*completedCallback)())
  23. {
  24. HTTPClient http;
  25. if (http.begin(url))
  26. {
  27. auto code = http.GET();
  28. if (code > 0)
  29. {
  30. auto dataStream = http.getStream();
  31. auto avail = dataStream.available();
  32. if (avail == 0)
  33. {
  34. zlog("ERROR: no bytes available!\n");
  35. return false;
  36. }
  37. if (Update.begin(sizeInBytes))
  38. {
  39. Update.onProgress(updateProg);
  40. Update.setMD5(md5);
  41. if (preUpdateIRQDisable)
  42. preUpdateIRQDisable();
  43. dprint("OTA start szb=%d\n", sizeInBytes);
  44. auto updateTook = Update.writeStream(dataStream);
  45. if (updateTook == sizeInBytes && !Update.hasError())
  46. {
  47. if (completedCallback && !completedCallback())
  48. {
  49. zlog("WARNING: unable to delete update key!\n");
  50. }
  51. if (!Update.end())
  52. {
  53. zlog("UPDATE END FAILED!? WTF mate\n");
  54. Update.abort();
  55. return false;
  56. }
  57. return true;
  58. }
  59. else
  60. {
  61. zlog("UPDATE FAILED: %d\n", Update.getError());
  62. Update.abort();
  63. }
  64. }
  65. else
  66. {
  67. zlog("UPDATE couldn't start: %d\n", Update.getError());
  68. Update.abort();
  69. }
  70. }
  71. else
  72. {
  73. zlog("HTTPClient.get() failed: %d\n", code);
  74. }
  75. }
  76. else
  77. {
  78. zlog("HTTPClient.begin() failed\n");
  79. }
  80. return false;
  81. }