ota.c 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  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. static int esp_err_to_fwupdate(int err)
  8. {
  9. switch (err) {
  10. case ESP_OK:
  11. return Z_OK;
  12. case ESP_ERR_NO_MEM:
  13. return Z_MEM_ERROR;
  14. case ESP_ERR_NOT_FOUND:
  15. return FWUPDATE_ERR_ESP_NO_PARTITION;
  16. case ESP_ERR_INVALID_ARG:
  17. case ESP_ERR_OTA_PARTITION_CONFLICT:
  18. case ESP_ERR_OTA_SELECT_INFO_INVALID:
  19. case ESP_ERR_OTA_ROLLBACK_INVALID_STATE:
  20. return FWUPDATE_ERR_ESP_BAD_OTA;
  21. case ESP_ERR_FLASH_OP_TIMEOUT:
  22. case ESP_ERR_FLASH_OP_FAIL:
  23. return FWUPDATE_ERR_ESP_FLASH_FAILED;
  24. case ESP_ERR_OTA_VALIDATE_FAILED:
  25. return FWUPDATE_ERR_ESP_BAD_DATA;
  26. default:
  27. return FWUPDATE_ERR_UNKNOWN;
  28. }
  29. }
  30. int esp_update(read_func_t read_func, token_t token, size_t size)
  31. {
  32. const esp_partition_t *partition;
  33. int err = ESP_FAIL;
  34. esp_ota_handle_t handle;
  35. bool ota_started = false;
  36. int len;
  37. char *buf = xmalloc_dma(BUFFER_SIZE);
  38. partition = esp_ota_get_next_update_partition(NULL);
  39. if (!partition) {
  40. err = ESP_ERR_NOT_FOUND;
  41. goto fail;
  42. }
  43. MSG("starting ESP OTA update, total %zu bytes\n", size);
  44. err = esp_ota_begin(partition, size, &handle);
  45. if (err)
  46. goto fail;
  47. ota_started = true;
  48. size_t left = size;
  49. while (left) {
  50. size_t chunk = left;
  51. if (chunk > BUFFER_SIZE)
  52. chunk = BUFFER_SIZE;
  53. len = read_func(token, buf, chunk);
  54. if (len <= 0)
  55. break;
  56. left -= len;
  57. MSG("writing %d bytes, %zu left\r", len, left);
  58. err = esp_ota_write(handle, buf, len);
  59. CMSG("\n");
  60. if (err)
  61. goto fail;
  62. }
  63. if (left) {
  64. MSG("short input data, aborting update\n");
  65. err = ESP_ERR_OTA_VALIDATE_FAILED;
  66. goto fail;
  67. }
  68. MSG("finalizing flash update\n");
  69. err = esp_ota_end(handle);
  70. if (err)
  71. goto fail;
  72. free(buf);
  73. buf = NULL;
  74. MSG("setting boot partition\n");
  75. err = esp_ota_set_boot_partition(partition);
  76. fail:
  77. err = esp_err_to_fwupdate(err);
  78. if (err) {
  79. MSG("failure: error %d\n", err);
  80. if (ota_started)
  81. esp_ota_abort(handle);
  82. }
  83. if (buf)
  84. free(buf);
  85. return err;
  86. }