ota.c 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. #define MODULE "ota"
  2. #define DEBUG 1
  3. #include "common.h"
  4. #include "fw.h"
  5. #include <esp_ota_ops.h>
  6. #define BUFFER_SIZE 4096
  7. esp_err_t esp_update(read_func_t read_func, token_t token, size_t size)
  8. {
  9. const esp_partition_t *partition;
  10. esp_err_t err = ESP_ERR_INVALID_ARG;
  11. esp_ota_handle_t handle;
  12. bool ota_started = false;
  13. int len;
  14. char *buf = NULL;
  15. buf = malloc(BUFFER_SIZE);
  16. if (!buf) {
  17. err = ESP_ERR_NO_MEM;
  18. goto fail;
  19. }
  20. partition = esp_ota_get_next_update_partition(NULL);
  21. if (!partition) {
  22. err = ESP_ERR_NOT_FOUND;
  23. goto fail;
  24. }
  25. MSG("starting ESP OTA update, total %zu bytes\n", size);
  26. err = esp_ota_begin(partition, size, &handle);
  27. if (err)
  28. goto fail;
  29. ota_started = true;
  30. size_t left = size;
  31. while (left) {
  32. size_t chunk = left;
  33. if (chunk > BUFFER_SIZE)
  34. chunk = BUFFER_SIZE;
  35. len = read_func(token, buf, chunk);
  36. if (len <= 0)
  37. break;
  38. left -= len;
  39. MSG("writing %d bytes, %zu left\n", len, left);
  40. err = esp_ota_write(handle, buf, len);
  41. if (err)
  42. goto fail;
  43. }
  44. if (left) {
  45. MSG("short input data, aborting update\n");
  46. err = ESP_ERR_OTA_VALIDATE_FAILED;
  47. goto fail;
  48. }
  49. MSG("finalizing flash update\n");
  50. err = esp_ota_end(handle);
  51. if (err)
  52. goto fail;
  53. free(buf);
  54. MSG("setting boot partition\n");
  55. return esp_ota_set_boot_partition(partition);
  56. fail:
  57. MSG("failure: error 0x%x\n", err);
  58. if (ota_started)
  59. esp_ota_abort(handle);
  60. if (buf)
  61. free(buf);
  62. return err;
  63. }