squeezelite-ota.c 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614
  1. /* OTA example
  2. This example code is in the Public Domain (or CC0 licensed, at your option.)
  3. Unless required by applicable law or agreed to in writing, this
  4. software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
  5. CONDITIONS OF ANY KIND, either express or implied.
  6. */
  7. #ifndef LOG_LOCAL_LEVEL
  8. #define LOG_LOCAL_LEVEL ESP_LOG_INFO
  9. #endif
  10. #include "freertos/FreeRTOS.h"
  11. #include "freertos/task.h"
  12. #include "esp_system.h"
  13. #include "esp_event.h"
  14. #include "esp_log.h"
  15. #include "esp_https_ota.h"
  16. #include "string.h"
  17. #include <stdbool.h>
  18. #include "nvs.h"
  19. #include "nvs_flash.h"
  20. #include "cmd_system.h"
  21. #include "esp_err.h"
  22. #include "tcpip_adapter.h"
  23. #include "squeezelite-ota.h"
  24. #include "config.h"
  25. #include <time.h>
  26. #include <sys/time.h>
  27. #include <stdarg.h>
  28. #include "esp_secure_boot.h"
  29. #include "esp_flash_encrypt.h"
  30. #include "esp_spi_flash.h"
  31. #include "sdkconfig.h"
  32. #include "esp_ota_ops.h"
  33. extern const char * get_certificate();
  34. static const char *TAG = "squeezelite-ota";
  35. char * ota_write_data = NULL;
  36. esp_http_client_handle_t ota_http_client = NULL;
  37. #define IMAGE_HEADER_SIZE sizeof(esp_image_header_t) + sizeof(esp_image_segment_header_t) + sizeof(esp_app_desc_t) + 1
  38. #define BUFFSIZE 4096
  39. #define HASH_LEN 32 /* SHA-256 digest length */
  40. static struct {
  41. char status_text[81];
  42. uint32_t ota_actual_len;
  43. uint32_t ota_total_len;
  44. char * redirected_url;
  45. char * current_url;
  46. bool bOTAStarted;
  47. bool bInitialized;
  48. uint8_t lastpct;
  49. uint8_t newpct;
  50. struct timeval OTA_start;
  51. bool bOTAThreadStarted;
  52. } ota_status;
  53. struct timeval tv;
  54. static esp_http_client_config_t ota_config;
  55. extern void wifi_manager_refresh_ota_json();
  56. void _printMemStats(){
  57. ESP_LOGD(TAG,"Heap internal:%zu (min:%zu) external:%zu (min:%zu)",
  58. heap_caps_get_free_size(MALLOC_CAP_INTERNAL),
  59. heap_caps_get_minimum_free_size(MALLOC_CAP_INTERNAL),
  60. heap_caps_get_free_size(MALLOC_CAP_SPIRAM),
  61. heap_caps_get_minimum_free_size(MALLOC_CAP_SPIRAM));
  62. }
  63. void triggerStatusJsonRefresh(bool bDelay,const char * status, ...){
  64. va_list args;
  65. va_start(args, status);
  66. vsnprintf(ota_status.status_text,sizeof(ota_status.status_text)-1,status, args);
  67. va_end(args);
  68. _printMemStats();
  69. wifi_manager_refresh_ota_json();
  70. if(bDelay){
  71. ESP_LOGD(TAG,"Holding task...");
  72. vTaskDelay(200 / portTICK_PERIOD_MS); // wait here for a short amount of time. This will help with refreshing the UI status
  73. ESP_LOGD(TAG,"Done holding task...");
  74. }
  75. else {
  76. ESP_LOGI(TAG,"%s",ota_status.status_text);
  77. taskYIELD();
  78. }
  79. }
  80. const char * ota_get_status(){
  81. if(!ota_status.bInitialized)
  82. {
  83. memset(ota_status.status_text, 0x00,sizeof(ota_status.status_text));
  84. ota_status.bInitialized = true;
  85. }
  86. return ota_status.status_text;
  87. }
  88. uint8_t ota_get_pct_complete(){
  89. return ota_status.ota_total_len==0?0:
  90. (uint8_t)((float)ota_status.ota_actual_len/(float)ota_status.ota_total_len*100.0f);
  91. }
  92. static void __attribute__((noreturn)) task_fatal_error(void)
  93. {
  94. ESP_LOGE(TAG, "Exiting task due to fatal error...");
  95. (void)vTaskDelete(NULL);
  96. while (1) {
  97. ;
  98. }
  99. }
  100. #define FREE_RESET(p) if(p!=NULL) { free(p); p=NULL; }
  101. esp_err_t _http_event_handler(esp_http_client_event_t *evt)
  102. {
  103. // --------------
  104. // Received parameters
  105. //
  106. // esp_http_client_event_id_tevent_id event_id, to know the cause of the event
  107. // esp_http_client_handle_t client
  108. // esp_http_client_handle_t context
  109. // void *data data of the event
  110. // int data_len - data length of data
  111. // void *user_data -- user_data context, from esp_http_client_config_t user_data
  112. // char *header_key For HTTP_EVENT_ON_HEADER event_id, it’s store current http header key
  113. // char *header_value For HTTP_EVENT_ON_HEADER event_id, it’s store current http header value
  114. // --------------
  115. switch (evt->event_id) {
  116. case HTTP_EVENT_ERROR:
  117. ESP_LOGD(TAG, "HTTP_EVENT_ERROR");
  118. _printMemStats();
  119. //strncpy(ota_status,"HTTP_EVENT_ERROR",sizeof(ota_status)-1);
  120. break;
  121. case HTTP_EVENT_ON_CONNECTED:
  122. ESP_LOGD(TAG, "HTTP_EVENT_ON_CONNECTED");
  123. if(ota_status.bOTAStarted) triggerStatusJsonRefresh(true,"Installing...");
  124. ota_status.ota_total_len=0;
  125. ota_status.ota_actual_len=0;
  126. ota_status.lastpct=0;
  127. ota_status.newpct=0;
  128. gettimeofday(&ota_status.OTA_start, NULL);
  129. break;
  130. case HTTP_EVENT_HEADER_SENT:
  131. ESP_LOGD(TAG, "HTTP_EVENT_HEADER_SENT");
  132. break;
  133. case HTTP_EVENT_ON_HEADER:
  134. ESP_LOGD(TAG, "HTTP_EVENT_ON_HEADER, key=%s, value=%s",evt->header_key, evt->header_value);
  135. if (strcasecmp(evt->header_key, "location") == 0) {
  136. FREE_RESET(ota_status.redirected_url);
  137. ota_status.redirected_url=strdup(evt->header_value);
  138. ESP_LOGW(TAG,"OTA will redirect to url: %s",ota_status.redirected_url);
  139. }
  140. if (strcasecmp(evt->header_key, "content-length") == 0) {
  141. ota_status.ota_total_len = atol(evt->header_value);
  142. ESP_LOGW(TAG, "Content length found: %s, parsed to %d", evt->header_value, ota_status.ota_total_len);
  143. }
  144. break;
  145. case HTTP_EVENT_ON_DATA:
  146. if(!ota_status.bOTAStarted) {
  147. ESP_LOGD(TAG, "HTTP_EVENT_ON_DATA, status_code=%d, len=%d",esp_http_client_get_status_code(evt->client), evt->data_len);
  148. }
  149. break;
  150. case HTTP_EVENT_ON_FINISH:
  151. ESP_LOGD(TAG, "HTTP_EVENT_ON_FINISH");
  152. break;
  153. case HTTP_EVENT_DISCONNECTED:
  154. ESP_LOGD(TAG, "HTTP_EVENT_DISCONNECTED");
  155. break;
  156. }
  157. return ESP_OK;
  158. }
  159. esp_err_t init_config(char * url){
  160. memset(&ota_config, 0x00, sizeof(ota_config));
  161. ota_status.bInitialized = true;
  162. triggerStatusJsonRefresh(true,"Initializing...");
  163. if(url==NULL || strlen(url)==0){
  164. ESP_LOGE(TAG,"HTTP OTA called without a url");
  165. return ESP_FAIL;
  166. }
  167. ota_status.current_url= url;
  168. ota_config.cert_pem =get_certificate();
  169. ota_config.event_handler = _http_event_handler;
  170. ota_config.buffer_size = BUFFSIZE;
  171. //ota_config.disable_auto_redirect=true;
  172. ota_config.disable_auto_redirect=false;
  173. ota_config.skip_cert_common_name_check = false;
  174. ota_config.url = strdup(url);
  175. ota_config.max_redirection_count = 3;
  176. ota_write_data = heap_caps_malloc(ota_config.buffer_size+1 , MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT);
  177. //ota_write_data = malloc(ota_config.buffer_size+1);
  178. if(ota_write_data== NULL){
  179. ESP_LOGE(TAG,"Error allocating the ota buffer");
  180. return ESP_ERR_NO_MEM;
  181. }
  182. return ESP_OK;
  183. }
  184. esp_partition_t * _get_ota_partition(esp_partition_subtype_t subtype){
  185. esp_partition_t *ota_partition=NULL;
  186. ESP_LOGI(TAG, "Looking for OTA partition.");
  187. esp_partition_iterator_t it = esp_partition_find(ESP_PARTITION_TYPE_APP, subtype , NULL);
  188. if(it == NULL){
  189. ESP_LOGE(TAG,"Unable initialize partition iterator!");
  190. }
  191. else {
  192. ota_partition = (esp_partition_t *) esp_partition_get(it);
  193. if(ota_partition != NULL){
  194. ESP_LOGI(TAG, "Found OTA partition: %s.",ota_partition->label);
  195. }
  196. else {
  197. ESP_LOGE(TAG,"OTA partition not found! Unable update application.");
  198. }
  199. esp_partition_iterator_release(it);
  200. }
  201. return ota_partition;
  202. }
  203. esp_err_t _erase_last_boot_app_partition(esp_partition_t *ota_partition)
  204. {
  205. uint16_t num_passes=0;
  206. uint16_t remain_size=0;
  207. uint32_t single_pass_size=0;
  208. esp_err_t err=ESP_OK;
  209. char * ota_erase_size=config_alloc_get(NVS_TYPE_STR, "ota_erase_blk");
  210. if(ota_erase_size!=NULL) {
  211. single_pass_size = atol(ota_erase_size);
  212. ESP_LOGD(TAG,"OTA Erase block size is %d (from string: %s)",single_pass_size, ota_erase_size );
  213. free(ota_erase_size);
  214. }
  215. else {
  216. ESP_LOGW(TAG,"OTA Erase block config not found");
  217. single_pass_size = OTA_FLASH_ERASE_BLOCK;
  218. }
  219. if(single_pass_size % SPI_FLASH_SEC_SIZE !=0){
  220. uint32_t temp_single_pass_size = single_pass_size-(single_pass_size % SPI_FLASH_SEC_SIZE);
  221. ESP_LOGW(TAG,"Invalid erase block size of %u. Value should be a multiple of %d and will be adjusted to %u.", single_pass_size, SPI_FLASH_SEC_SIZE,temp_single_pass_size);
  222. single_pass_size=temp_single_pass_size;
  223. }
  224. ESP_LOGI(TAG,"Erasing flash partition of size %u in blocks of %d bytes", ota_partition->size, single_pass_size);
  225. num_passes=ota_partition->size/single_pass_size;
  226. remain_size=ota_partition->size-(num_passes*single_pass_size);
  227. ESP_LOGI(TAG,"Erasing in %d passes with blocks of %d bytes ", num_passes,single_pass_size);
  228. for(uint16_t i=0;i<num_passes;i++){
  229. ESP_LOGD(TAG,"Erasing flash (%u%%)",i/num_passes);
  230. ESP_LOGD(TAG,"Pass %d of %d, with chunks of %d bytes, from %d to %d", i+1, num_passes,single_pass_size,i*single_pass_size,i*single_pass_size+single_pass_size);
  231. err=esp_partition_erase_range(ota_partition, i*single_pass_size, single_pass_size);
  232. if(err!=ESP_OK) return err;
  233. // triggerStatusJsonRefresh(i%10==0?true:false,"Erasing flash (%u/%u)",i,num_passes);
  234. if(i%2) {
  235. triggerStatusJsonRefresh(false,"Erasing flash (%u/%u)",i,num_passes);
  236. }
  237. vTaskDelay(200/ portTICK_PERIOD_MS); // wait here for a short amount of time. This will help with reducing WDT errors
  238. }
  239. if(remain_size>0){
  240. err=esp_partition_erase_range(ota_partition, ota_partition->size-remain_size, remain_size);
  241. if(err!=ESP_OK) return err;
  242. }
  243. triggerStatusJsonRefresh(true,"Erasing flash complete.");
  244. taskYIELD();
  245. return ESP_OK;
  246. }
  247. static bool process_again(int status_code)
  248. {
  249. switch (status_code) {
  250. case HttpStatus_MovedPermanently:
  251. case HttpStatus_Found:
  252. case HttpStatus_Unauthorized:
  253. return true;
  254. default:
  255. return false;
  256. }
  257. return false;
  258. }
  259. static esp_err_t _http_handle_response_code(esp_http_client_handle_t http_client, int status_code)
  260. {
  261. esp_err_t err=ESP_OK;
  262. if (status_code == HttpStatus_MovedPermanently || status_code == HttpStatus_Found) {
  263. ESP_LOGW(TAG, "Handling HTTP redirection. ");
  264. err = esp_http_client_set_redirection(http_client);
  265. if (err != ESP_OK) {
  266. ESP_LOGE(TAG, "URL redirection Failed. %s", esp_err_to_name(err));
  267. return err;
  268. }
  269. } else if (status_code == HttpStatus_Unauthorized) {
  270. ESP_LOGW(TAG, "Handling Unauthorized. ");
  271. esp_http_client_add_auth(http_client);
  272. }
  273. ESP_LOGD(TAG, "Redirection done, checking if we need to read the data. ");
  274. if (process_again(status_code)) {
  275. char * local_buff = heap_caps_malloc(ota_config.buffer_size+1, MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT);
  276. //char * local_buff = malloc(ota_config.buffer_size+1);
  277. if(local_buff==NULL){
  278. ESP_LOGE(TAG,"Failed to allocate internal memory buffer for http processing");
  279. return ESP_ERR_NO_MEM;
  280. }
  281. while (1) {
  282. ESP_LOGD(TAG, "Reading data chunk. ");
  283. int data_read = esp_http_client_read(http_client, local_buff, ota_config.buffer_size);
  284. if (data_read < 0) {
  285. ESP_LOGE(TAG, "Error: SSL data read error");
  286. err= ESP_FAIL;
  287. break;
  288. } else if (data_read == 0) {
  289. ESP_LOGD(TAG, "No more data. ");
  290. err= ESP_OK;
  291. break;
  292. }
  293. }
  294. FREE_RESET(local_buff);
  295. }
  296. return err;
  297. }
  298. static esp_err_t _http_connect(esp_http_client_handle_t http_client)
  299. {
  300. esp_err_t err = ESP_FAIL;
  301. int status_code, header_ret;
  302. do {
  303. ESP_LOGD(TAG, "connecting the http client. ");
  304. err = esp_http_client_open(http_client, 0);
  305. if (err != ESP_OK) {
  306. ESP_LOGE(TAG, "Failed to open HTTP connection: %s", esp_err_to_name(err));
  307. return err;
  308. }
  309. ESP_LOGD(TAG, "Fetching headers");
  310. header_ret = esp_http_client_fetch_headers(http_client);
  311. if (header_ret < 0) {
  312. // Error found
  313. return header_ret;
  314. }
  315. ESP_LOGD(TAG, "HTTP Header fetch completed, found content length of %d",header_ret);
  316. status_code = esp_http_client_get_status_code(http_client);
  317. ESP_LOGD(TAG, "HTTP status code was %d",status_code);
  318. err = _http_handle_response_code(http_client, status_code);
  319. if (err != ESP_OK) {
  320. return err;
  321. }
  322. } while (process_again(status_code));
  323. return err;
  324. }
  325. void ota_task_cleanup(const char * message, ...){
  326. ota_status.bOTAThreadStarted=false;
  327. if(message!=NULL){
  328. va_list args;
  329. va_start(args, message);
  330. triggerStatusJsonRefresh(true,message, args);
  331. va_end(args);
  332. ESP_LOGE(TAG, "%s",ota_status.status_text);
  333. }
  334. FREE_RESET(ota_status.redirected_url);
  335. FREE_RESET(ota_status.current_url);
  336. FREE_RESET(ota_write_data);
  337. if(ota_http_client!=NULL) {
  338. esp_http_client_cleanup(ota_http_client);
  339. ota_http_client=NULL;
  340. }
  341. ota_status.bOTAStarted = false;
  342. task_fatal_error();
  343. }
  344. void ota_task(void *pvParameter)
  345. {
  346. esp_err_t err = ESP_OK;
  347. size_t buffer_size = BUFFSIZE;
  348. ESP_LOGD(TAG, "HTTP ota Thread started");
  349. const esp_partition_t *configured = esp_ota_get_boot_partition();
  350. const esp_partition_t *running = esp_ota_get_running_partition();
  351. const esp_partition_t * update_partition = esp_ota_get_next_update_partition(NULL);
  352. ESP_LOGI(TAG, "esp_ota_get_next_update_partition returned : partition [%s] subtype %d at offset 0x%x",
  353. update_partition->label, update_partition->subtype, update_partition->address);
  354. if (configured != running) {
  355. ESP_LOGW(TAG, "Configured OTA boot partition at offset 0x%08x, but running from offset 0x%08x", configured->address, running->address);
  356. ESP_LOGW(TAG, "(This can happen if either the OTA boot data or preferred boot image become corrupted somehow.)");
  357. }
  358. ESP_LOGI(TAG, "Running partition [%s] type %d subtype %d (offset 0x%08x)", running->label, running->type, running->subtype, running->address);
  359. _printMemStats();
  360. ESP_LOGI(TAG,"Initializing OTA configuration");
  361. err = init_config(pvParameter);
  362. if(err!=ESP_OK){
  363. ota_task_cleanup("Error: Failed to initialize OTA.");
  364. return;
  365. }
  366. /* Locate and erase ota application partition */
  367. ESP_LOGW(TAG,"**************** Expecting WATCHDOG errors below during flash erase. This is OK and not to worry about **************** ");
  368. triggerStatusJsonRefresh(true,"Erasing OTA partition");
  369. esp_partition_t *ota_partition = _get_ota_partition(ESP_PARTITION_SUBTYPE_APP_OTA_0);
  370. if(ota_partition == NULL){
  371. ESP_LOGE(TAG,"Unable to locate OTA application partition. ");
  372. ota_task_cleanup("Error: OTA application partition not found. (%s)",esp_err_to_name(err));
  373. return;
  374. }
  375. _printMemStats();
  376. err=_erase_last_boot_app_partition(ota_partition);
  377. if(err!=ESP_OK){
  378. ota_task_cleanup("Error: Unable to erase last APP partition. (%s)",esp_err_to_name(err));
  379. return;
  380. }
  381. _printMemStats();
  382. ota_status.bOTAStarted = true;
  383. triggerStatusJsonRefresh(true,"Starting OTA...");
  384. ota_http_client = esp_http_client_init(&ota_config);
  385. if (ota_http_client == NULL) {
  386. ota_task_cleanup("Error: Failed to initialize HTTP connection.");
  387. return;
  388. }
  389. _printMemStats();
  390. // Open the http connection and follow any redirection
  391. err = _http_connect(ota_http_client);
  392. if (err != ESP_OK) {
  393. ota_task_cleanup("Error: HTTP Start read failed. (%s)",esp_err_to_name(err));
  394. return;
  395. }
  396. _printMemStats();
  397. esp_ota_handle_t update_handle = 0 ;
  398. int binary_file_length = 0;
  399. /*deal with all receive packet*/
  400. bool image_header_was_checked = false;
  401. while (1) {
  402. int data_read = esp_http_client_read(ota_http_client, ota_write_data, buffer_size);
  403. if (data_read < 0) {
  404. ota_task_cleanup("Error: Data read error");
  405. return;
  406. } else if (data_read > 0) {
  407. if (image_header_was_checked == false) {
  408. esp_app_desc_t new_app_info;
  409. if (data_read > sizeof(esp_image_header_t) + sizeof(esp_image_segment_header_t) + sizeof(esp_app_desc_t)) {
  410. // check current version with downloading
  411. memcpy(&new_app_info, &ota_write_data[sizeof(esp_image_header_t) + sizeof(esp_image_segment_header_t)], sizeof(esp_app_desc_t));
  412. ESP_LOGI(TAG, "New firmware version: %s", new_app_info.version);
  413. esp_app_desc_t running_app_info;
  414. if (esp_ota_get_partition_description(running, &running_app_info) == ESP_OK) {
  415. ESP_LOGI(TAG, "Running recovery version: %s", running_app_info.version);
  416. }
  417. const esp_partition_t* last_invalid_app = esp_ota_get_last_invalid_partition();
  418. esp_app_desc_t invalid_app_info;
  419. if (esp_ota_get_partition_description(last_invalid_app, &invalid_app_info) == ESP_OK) {
  420. ESP_LOGI(TAG, "Last invalid firmware version: %s", invalid_app_info.version);
  421. }
  422. // check current version with last invalid partition
  423. // if (last_invalid_app != NULL) {
  424. // if (memcmp(invalid_app_info.version, new_app_info.version, sizeof(new_app_info.version)) == 0) {
  425. // ESP_LOGW(TAG, "New version is the same as invalid version.");
  426. // ESP_LOGW(TAG, "Previously, there was an attempt to launch the firmware with %s version, but it failed.", invalid_app_info.version);
  427. // ESP_LOGW(TAG, "The firmware has been rolled back to the previous version.");
  428. // ota_task_cleanup("esp_ota_begin failed (%s)", esp_err_to_name(err));
  429. // }
  430. // }
  431. if (memcmp(new_app_info.version, running_app_info.version, sizeof(new_app_info.version)) == 0) {
  432. ESP_LOGW(TAG, "Current running version is the same as a new.");
  433. }
  434. image_header_was_checked = true;
  435. // Call OTA Begin with a small partition size - this drives the erase operation which was already done;
  436. err = esp_ota_begin(ota_partition, 512, &update_handle);
  437. if (err != ESP_OK) {
  438. ota_task_cleanup("esp_ota_begin failed (%s)", esp_err_to_name(err));
  439. return;
  440. }
  441. ESP_LOGD(TAG, "esp_ota_begin succeeded");
  442. } else {
  443. ota_task_cleanup("Error: Binary file too large for the current partition");
  444. return;
  445. }
  446. }
  447. err = esp_ota_write( update_handle, (const void *)ota_write_data, data_read);
  448. if (err != ESP_OK) {
  449. ota_task_cleanup("Error: OTA Partition write failure. (%s)",esp_err_to_name(err));
  450. return;
  451. }
  452. binary_file_length += data_read;
  453. ESP_LOGD(TAG, "Written image length %d", binary_file_length);
  454. ota_status.ota_actual_len=binary_file_length;
  455. if(ota_get_pct_complete()%5 == 0) ota_status.newpct = ota_get_pct_complete();
  456. if(ota_status.lastpct!=ota_status.newpct ) {
  457. gettimeofday(&tv, NULL);
  458. uint32_t elapsed_ms= (tv.tv_sec-ota_status.OTA_start.tv_sec )*1000+(tv.tv_usec-ota_status.OTA_start.tv_usec)/1000;
  459. ESP_LOGI(TAG,"OTA progress : %d/%d (%d pct), %d KB/s", ota_status.ota_actual_len, ota_status.ota_total_len, ota_status.newpct, elapsed_ms>0?ota_status.ota_actual_len*1000/elapsed_ms/1024:0);
  460. triggerStatusJsonRefresh(true,"Downloading & writing update.");
  461. ota_status.lastpct=ota_status.newpct;
  462. }
  463. taskYIELD();
  464. } else if (data_read == 0) {
  465. ESP_LOGI(TAG, "Connection closed");
  466. break;
  467. }
  468. }
  469. ESP_LOGI(TAG, "Total Write binary data length: %d", binary_file_length);
  470. if (ota_status.ota_total_len != binary_file_length) {
  471. ota_task_cleanup("Error: Error in receiving complete file");
  472. return;
  473. }
  474. _printMemStats();
  475. err = esp_ota_end(update_handle);
  476. if (err != ESP_OK) {
  477. ota_task_cleanup("Error: %s",esp_err_to_name(err));
  478. return;
  479. }
  480. _printMemStats();
  481. err = esp_ota_set_boot_partition(ota_partition);
  482. if (err == ESP_OK) {
  483. ESP_LOGI(TAG,"OTA Process completed successfully!");
  484. triggerStatusJsonRefresh(true,"Success!");
  485. vTaskDelay(1500/ portTICK_PERIOD_MS); // wait here to give the UI a chance to refresh
  486. esp_restart();
  487. } else {
  488. ota_task_cleanup("Error: Unable to update boot partition [%s]",esp_err_to_name(err));
  489. return;
  490. }
  491. ota_task_cleanup(NULL);
  492. return;
  493. }
  494. esp_err_t process_recovery_ota(const char * bin_url){
  495. int ret = 0;
  496. uint16_t stack_size, task_priority;
  497. if(ota_status.bOTAThreadStarted){
  498. ESP_LOGE(TAG,"OTA Already started. ");
  499. return ESP_FAIL;
  500. }
  501. memset(&ota_status, 0x00, sizeof(ota_status));
  502. ota_status.bOTAThreadStarted=true;
  503. char * urlPtr=strdup(bin_url);
  504. // the first thing we need to do here is to erase the firmware url
  505. // to avoid a boot loop
  506. #ifdef CONFIG_ESP32_WIFI_TASK_PINNED_TO_CORE_1
  507. #define OTA_CORE 0
  508. #warning "OTA will run on core 0"
  509. #else
  510. #pragma message "OTA will run on core 1"
  511. #define OTA_CORE 1
  512. #endif
  513. ESP_LOGI(TAG, "Starting ota on core %u for : %s", OTA_CORE,urlPtr);
  514. char * num_buffer=config_alloc_get(NVS_TYPE_STR, "ota_stack");
  515. if(num_buffer!=NULL) {
  516. stack_size= atol(num_buffer);
  517. free(num_buffer);
  518. num_buffer=NULL;
  519. }
  520. else {
  521. ESP_LOGW(TAG,"OTA stack size config not found");
  522. stack_size = OTA_STACK_SIZE;
  523. }
  524. num_buffer=config_alloc_get(NVS_TYPE_STR, "ota_prio");
  525. if(num_buffer!=NULL) {
  526. task_priority= atol(num_buffer);
  527. free(num_buffer);
  528. num_buffer=NULL;
  529. }
  530. else {
  531. ESP_LOGW(TAG,"OTA task priority not found");
  532. task_priority= OTA_TASK_PRIOTITY;
  533. }
  534. ESP_LOGD(TAG,"OTA task stack size %d, priority %d (%d %s ESP_TASK_MAIN_PRIO)",stack_size , task_priority, abs(task_priority-ESP_TASK_MAIN_PRIO), task_priority-ESP_TASK_MAIN_PRIO>0?"above":"below");
  535. ret=xTaskCreatePinnedToCore(&ota_task, "ota_task", stack_size , (void *)urlPtr, task_priority, NULL, OTA_CORE);
  536. //ret=xTaskCreate(&ota_task, "ota_task", 1024*20, (void *)urlPtr, ESP_TASK_MAIN_PRIO+2, NULL);
  537. if (ret != pdPASS) {
  538. ESP_LOGI(TAG, "create thread %s failed", "ota_task");
  539. return ESP_FAIL;
  540. }
  541. return ESP_OK;
  542. }
  543. esp_err_t start_ota(const char * bin_url)
  544. {
  545. // uint8_t * config_alloc_get_default(NVS_TYPE_BLOB, "certs", server_cert_pem_start , server_cert_pem_end-server_cert_pem_start);
  546. #if RECOVERY_APPLICATION
  547. return process_recovery_ota(bin_url);
  548. #else
  549. ESP_LOGW(TAG, "Called to update the firmware from url: %s",bin_url);
  550. if(config_set_value(NVS_TYPE_STR, "fwurl", bin_url) != ESP_OK){
  551. ESP_LOGE(TAG,"Failed to save the OTA url into nvs cache");
  552. return ESP_FAIL;
  553. }
  554. if(!wait_for_commit()){
  555. ESP_LOGW(TAG,"Unable to commit configuration. ");
  556. }
  557. ESP_LOGW(TAG, "Rebooting to recovery to complete the installation");
  558. return guided_factory();
  559. return ESP_OK;
  560. #endif
  561. }