squeezelite-ota.c 23 KB

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