2
0

squeezelite-ota.c 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794
  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 "squeezelite-ota.h"
  20. #include "esp_netif.h"
  21. #include "platform_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 "esp_ota_ops.h"
  31. #include "display.h"
  32. #include "gds.h"
  33. #include "gds_text.h"
  34. #include "gds_draw.h"
  35. #include "led_vu.h"
  36. #include "platform_esp32.h"
  37. #include "lwip/sockets.h"
  38. #include "globdefs.h"
  39. #include "tools.h"
  40. #define IF_DISPLAY(x) if(display) { x; }
  41. #ifdef CONFIG_ESP32_WIFI_TASK_PINNED_TO_CORE_1
  42. #define OTA_CORE 0
  43. #else
  44. #define OTA_CORE 1
  45. #endif
  46. static const char *TAG = "squeezelite-ota";
  47. esp_http_client_handle_t ota_http_client = NULL;
  48. #define IMAGE_HEADER_SIZE sizeof(esp_image_header_t) + sizeof(esp_image_segment_header_t) + sizeof(esp_app_desc_t) + 1
  49. #define BUFFSIZE 4096
  50. #define HASH_LEN 32 /* SHA-256 digest length */
  51. typedef struct {
  52. char * url;
  53. char * bin;
  54. uint32_t length;
  55. } ota_thread_parms_t ;
  56. static ota_thread_parms_t ota_thread_parms;
  57. typedef enum {
  58. OTA_TYPE_HTTP,
  59. OTA_TYPE_BUFFER,
  60. OTA_TYPE_INVALID
  61. } ota_type_t;
  62. typedef struct {
  63. size_t actual_image_len;
  64. float downloaded_image_len;
  65. float total_image_len;
  66. float remain_image_len;
  67. ota_type_t ota_type;
  68. char * ota_write_data;
  69. char * bin_data;
  70. bool bOTAStarted;
  71. size_t buffer_size;
  72. uint8_t lastpct;
  73. uint8_t newpct;
  74. uint8_t newdownloadpct;
  75. struct timeval OTA_start;
  76. bool bOTAThreadStarted;
  77. const esp_partition_t *configured;
  78. const esp_partition_t *running;
  79. const esp_partition_t * update_partition;
  80. const esp_partition_t* last_invalid_app ;
  81. const esp_partition_t * ota_partition;
  82. } ota_status_t;
  83. ota_status_t * ota_status;
  84. struct timeval tv;
  85. static esp_http_client_config_t http_client_config;
  86. void _printMemStats(){
  87. ESP_LOGD(TAG, "Heap internal:%zu (min:%zu) external:%zu (min:%zu) dma:%zu (min:%zu)",
  88. heap_caps_get_free_size(MALLOC_CAP_INTERNAL),
  89. heap_caps_get_minimum_free_size(MALLOC_CAP_INTERNAL),
  90. heap_caps_get_free_size(MALLOC_CAP_SPIRAM),
  91. heap_caps_get_minimum_free_size(MALLOC_CAP_SPIRAM),
  92. heap_caps_get_free_size(MALLOC_CAP_DMA),
  93. heap_caps_get_minimum_free_size(MALLOC_CAP_DMA));
  94. }
  95. uint8_t ota_get_pct_complete(){
  96. return ota_status->total_image_len==0?0:
  97. (uint8_t)((float)ota_status->actual_image_len/ota_status->total_image_len*100.0f);
  98. }
  99. uint8_t ota_get_pct_downloaded(){
  100. return ota_status->total_image_len==0?0:
  101. (uint8_t)(ota_status->downloaded_image_len/ota_status->total_image_len*100.0f);
  102. }
  103. typedef struct {
  104. int x1,y1,x2,y2,width,height;
  105. } rect_t;
  106. typedef struct _progress {
  107. int border_thickness;
  108. int sides_margin;
  109. int vertical_margin;
  110. int bar_tot_height;
  111. int bar_fill_height;
  112. rect_t border;
  113. rect_t filler;
  114. } progress_t;
  115. static progress_t * loc_displayer_get_progress_dft(){
  116. int start_coord_offset=0;
  117. static progress_t def={
  118. .border_thickness = 2,
  119. .sides_margin = 2,
  120. .bar_tot_height = 7,
  121. };
  122. def.bar_fill_height= def.bar_tot_height-(def.border_thickness*2);
  123. def.border.x1=start_coord_offset+def.sides_margin;
  124. IF_DISPLAY(def.border.x2=GDS_GetWidth(display)-def.sides_margin);
  125. // progress bar will be drawn at the bottom of the display
  126. IF_DISPLAY( def.border.y2= GDS_GetHeight(display)-def.border_thickness);
  127. def.border.y1= def.border.y2-def.bar_tot_height;
  128. def.border.width=def.border.x2-def.border.x1;
  129. def.border.height=def.border.y2-def.border.y1;
  130. def.filler.x1= def.border.x1+def.border_thickness;
  131. def.filler.x2= def.border.x2-def.border_thickness;
  132. def.filler.y1= def.border.y1+def.border_thickness;
  133. def.filler.y2= def.border.y2-def.border_thickness;
  134. def.filler.width=def.filler.x2-def.filler.x1;
  135. def.filler.height=def.filler.y2-def.filler.y1;
  136. assert(def.filler.width>0);
  137. assert(def.filler.height>0);
  138. assert(def.border.width>0);
  139. assert(def.border.height>0);
  140. assert(def.border.width>def.filler.width);
  141. assert(def.border.height>def.filler.height);
  142. return &def;
  143. }
  144. static void loc_displayer_progressbar(uint8_t pct){
  145. static progress_t * progress_coordinates;
  146. if(display) {
  147. if(!progress_coordinates) progress_coordinates = loc_displayer_get_progress_dft();
  148. int filler_x=progress_coordinates->filler.x1+(int)((float)progress_coordinates->filler.width*(float)pct/(float)100);
  149. ESP_LOGD(TAG,"Drawing %d,%d,%d,%d",progress_coordinates->border.x1,progress_coordinates->border.y1,progress_coordinates->border.x2,progress_coordinates->border.y2);
  150. GDS_DrawBox(display,progress_coordinates->border.x1,progress_coordinates->border.y1,progress_coordinates->border.x2,progress_coordinates->border.y2,GDS_COLOR_WHITE,false);
  151. ESP_LOGD(TAG,"Drawing %d,%d,%d,%d",progress_coordinates->filler.x1,progress_coordinates->filler.y1,filler_x,progress_coordinates->filler.y2);
  152. if(filler_x > progress_coordinates->filler.x1){
  153. GDS_DrawBox(display,progress_coordinates->filler.x1,progress_coordinates->filler.y1,filler_x,progress_coordinates->filler.y2,GDS_COLOR_WHITE,true);
  154. }
  155. else {
  156. // Clear the inner box
  157. GDS_DrawBox(display,progress_coordinates->filler.x1,progress_coordinates->filler.y1,progress_coordinates->filler.x2,progress_coordinates->filler.y2,GDS_COLOR_BLACK,true);
  158. }
  159. ESP_LOGD(TAG,"Updating Display");
  160. GDS_Update(display);
  161. }
  162. if (led_display) {
  163. led_vu_progress_bar(pct, LED_VU_BRIGHT);
  164. }
  165. }
  166. void sendMessaging(messaging_types type,const char * fmt, ...){
  167. va_list args;
  168. cJSON * msg = cJSON_CreateObject();
  169. size_t str_len=0;
  170. char * msg_str=NULL;
  171. va_start(args, fmt);
  172. str_len = vsnprintf(NULL,0,fmt,args)+1;
  173. if(str_len>0){
  174. msg_str = malloc_init_external(str_len);
  175. vsnprintf(msg_str,str_len,fmt,args);
  176. if(type == MESSAGING_WARNING){
  177. ESP_LOGW(TAG,"%s",msg_str);
  178. }
  179. else if (type == MESSAGING_ERROR){
  180. ESP_LOGE(TAG,"%s",msg_str);
  181. }
  182. else
  183. ESP_LOGI(TAG,"%s",msg_str);
  184. }
  185. else {
  186. ESP_LOGW(TAG, "Sending empty string message");
  187. }
  188. va_end(args);
  189. if(type!=MESSAGING_INFO){
  190. IF_DISPLAY(GDS_TextLine(display, 2, GDS_TEXT_LEFT, GDS_TEXT_CLEAR | GDS_TEXT_UPDATE, msg_str));
  191. }
  192. cJSON_AddStringToObject(msg,"ota_dsc",str_or_unknown(msg_str));
  193. free(msg_str);
  194. cJSON_AddNumberToObject(msg,"ota_pct", ota_get_pct_complete() );
  195. char * json_msg = cJSON_PrintUnformatted(msg);
  196. messaging_post_message(type, MESSAGING_CLASS_OTA, json_msg);
  197. free(json_msg);
  198. cJSON_Delete(msg);
  199. _printMemStats();
  200. }
  201. static void __attribute__((noreturn)) task_fatal_error(void)
  202. {
  203. ESP_LOGE(TAG, "Exiting task due to fatal error...");
  204. (void)vTaskDelete(NULL);
  205. while (1) {
  206. ;
  207. }
  208. }
  209. esp_err_t handle_http_on_data(esp_http_client_event_t *evt){
  210. int http_status= esp_http_client_get_status_code(evt->client);
  211. static char * recv_ptr=NULL;
  212. if(http_status == 200){
  213. if(!ota_status->bOTAStarted)
  214. {
  215. sendMessaging(MESSAGING_INFO,"Downloading firmware");
  216. ota_status->bOTAStarted = true;
  217. ota_status->total_image_len=esp_http_client_get_content_length(evt->client);
  218. ota_status->downloaded_image_len = 0;
  219. ota_status->newdownloadpct = 0;
  220. ota_status->bin_data= malloc_init_external(ota_status->total_image_len);
  221. if(ota_status->bin_data==NULL){
  222. sendMessaging(MESSAGING_ERROR,"Error: buffer alloc error");
  223. return ESP_FAIL;
  224. }
  225. recv_ptr=ota_status->bin_data;
  226. }
  227. // we're downloading the binary data file
  228. if (!esp_http_client_is_chunked_response(evt->client)) {
  229. memcpy(recv_ptr,evt->data,evt->data_len);
  230. ota_status->downloaded_image_len +=evt->data_len;
  231. recv_ptr+=evt->data_len;
  232. }
  233. if(ota_get_pct_downloaded()%5 == 0 && ota_get_pct_downloaded()%5!=ota_status->newdownloadpct) {
  234. ota_status->newdownloadpct= ota_get_pct_downloaded();
  235. loc_displayer_progressbar(ota_status->newdownloadpct);
  236. gettimeofday(&tv, NULL);
  237. uint32_t elapsed_ms= (tv.tv_sec-ota_status->OTA_start.tv_sec )*1000+(tv.tv_usec-ota_status->OTA_start.tv_usec)/1000;
  238. ESP_LOGI(TAG,"OTA download progress : %f/%f (%d pct), %f KB/s", ota_status->downloaded_image_len, ota_status->total_image_len, ota_status->newdownloadpct, elapsed_ms>0?ota_status->downloaded_image_len*1000/elapsed_ms/1024:0);
  239. sendMessaging(MESSAGING_INFO,"Downloading firmware %%%3d.",ota_status->newdownloadpct);
  240. }
  241. }
  242. return ESP_OK;
  243. }
  244. esp_err_t _http_event_handler(esp_http_client_event_t *evt)
  245. {
  246. // --------------
  247. // Received parameters
  248. //
  249. // esp_http_client_event_id_tevent_id event_id, to know the cause of the event
  250. // esp_http_client_handle_t client
  251. // esp_http_client_handle_t context
  252. // void *data data of the event
  253. // int data_len - data length of data
  254. // void *user_data -- user_data context, from esp_http_client_config_t user_data
  255. // char *header_key For HTTP_EVENT_ON_HEADER event_id, it�s store current http header key
  256. // char *header_value For HTTP_EVENT_ON_HEADER event_id, it�s store current http header value
  257. // --------------
  258. switch (evt->event_id) {
  259. case HTTP_EVENT_ERROR:
  260. ESP_LOGD(TAG, "HTTP_EVENT_ERROR");
  261. _printMemStats();
  262. break;
  263. case HTTP_EVENT_ON_CONNECTED:
  264. ESP_LOGD(TAG, "HTTP_EVENT_ON_CONNECTED");
  265. if(ota_status->bOTAStarted) sendMessaging(MESSAGING_INFO,"HTTP Connected");
  266. ota_status->total_image_len=0;
  267. ota_status->actual_image_len=0;
  268. ota_status->lastpct=0;
  269. ota_status->remain_image_len=0;
  270. ota_status->newpct=0;
  271. gettimeofday(&ota_status->OTA_start, NULL);
  272. break;
  273. case HTTP_EVENT_HEADER_SENT:
  274. ESP_LOGD(TAG, "HTTP_EVENT_HEADER_SENT");
  275. break;
  276. case HTTP_EVENT_ON_HEADER:
  277. ESP_LOGD(TAG, "HTTP_EVENT_ON_HEADER, key=%s, value=%s",evt->header_key, evt->header_value);
  278. // if (strcasecmp(evt->header_key, "location") == 0) {
  279. // ESP_LOGW(TAG,"OTA will redirect to url: %s",evt->header_value);
  280. // }
  281. // if (strcasecmp(evt->header_key, "content-length") == 0) {
  282. // ota_status->total_image_len = atol(evt->header_value);
  283. // ESP_LOGW(TAG, "Content length found: %s, parsed to %d", evt->header_value, ota_status->total_image_len);
  284. // }
  285. break;
  286. case HTTP_EVENT_ON_DATA:
  287. return handle_http_on_data(evt);
  288. break;
  289. case HTTP_EVENT_ON_FINISH:
  290. ESP_LOGD(TAG, "HTTP_EVENT_ON_FINISH");
  291. break;
  292. case HTTP_EVENT_DISCONNECTED:
  293. ESP_LOGD(TAG, "HTTP_EVENT_DISCONNECTED");
  294. break;
  295. }
  296. return ESP_OK;
  297. }
  298. esp_err_t init_config(ota_thread_parms_t * p_ota_thread_parms){
  299. memset(&http_client_config, 0x00, sizeof(http_client_config));
  300. sendMessaging(MESSAGING_INFO,"Initializing...");
  301. loc_displayer_progressbar(0);
  302. ota_status->ota_type= OTA_TYPE_INVALID;
  303. if(p_ota_thread_parms->url !=NULL && strlen(p_ota_thread_parms->url)>0 ){
  304. ota_status->ota_type= OTA_TYPE_HTTP;
  305. }
  306. else if(p_ota_thread_parms->bin!=NULL && p_ota_thread_parms->length > 0) {
  307. ota_status->ota_type= OTA_TYPE_BUFFER;
  308. }
  309. if( ota_status->ota_type== OTA_TYPE_INVALID ){
  310. ESP_LOGE(TAG,"HTTP OTA called without a url or a binary buffer");
  311. return ESP_ERR_INVALID_ARG;
  312. }
  313. ota_status->buffer_size = BUFFSIZE;
  314. ota_status->ota_write_data = heap_caps_malloc(ota_status->buffer_size+1 , (MALLOC_CAP_INTERNAL|MALLOC_CAP_8BIT));
  315. if(ota_status->ota_write_data== NULL){
  316. ESP_LOGE(TAG,"Error allocating the ota buffer");
  317. return ESP_ERR_NO_MEM;
  318. }
  319. switch (ota_status->ota_type) {
  320. case OTA_TYPE_HTTP:
  321. http_client_config.event_handler = _http_event_handler;
  322. http_client_config.disable_auto_redirect=false;
  323. http_client_config.skip_cert_common_name_check = false;
  324. http_client_config.url = strdup_psram(p_ota_thread_parms->url);
  325. http_client_config.max_redirection_count = 4;
  326. // buffer size below is for http read chunks
  327. http_client_config.buffer_size = 8192; //1024 ;
  328. http_client_config.buffer_size_tx = 8192;
  329. //http_client_config.timeout_ms = 5000;
  330. break;
  331. case OTA_TYPE_BUFFER:
  332. ota_status->bin_data = p_ota_thread_parms->bin;
  333. ota_status->total_image_len = p_ota_thread_parms->length;
  334. break;
  335. default:
  336. return ESP_FAIL;
  337. break;
  338. }
  339. return ESP_OK;
  340. }
  341. esp_partition_t * _get_ota_partition(esp_partition_subtype_t subtype){
  342. esp_partition_t *ota_partition=NULL;
  343. ESP_LOGD(TAG, "Looking for OTA partition.");
  344. esp_partition_iterator_t it = esp_partition_find(ESP_PARTITION_TYPE_APP, subtype , NULL);
  345. if(it == NULL){
  346. ESP_LOGE(TAG,"Unable initialize partition iterator!");
  347. }
  348. else {
  349. ota_partition = (esp_partition_t *) esp_partition_get(it);
  350. if(ota_partition != NULL){
  351. ESP_LOGD(TAG, "Found OTA partition: %s.",ota_partition->label);
  352. }
  353. else {
  354. ESP_LOGE(TAG,"OTA partition not found! Unable update application.");
  355. }
  356. esp_partition_iterator_release(it);
  357. }
  358. return ota_partition;
  359. }
  360. esp_err_t _erase_last_boot_app_partition(const esp_partition_t *ota_partition)
  361. {
  362. uint16_t num_passes=0;
  363. uint16_t remain_size=0;
  364. uint32_t single_pass_size=0;
  365. esp_err_t err=ESP_OK;
  366. char * ota_erase_size=config_alloc_get(NVS_TYPE_STR, "ota_erase_blk");
  367. if(ota_erase_size!=NULL) {
  368. single_pass_size = atol(ota_erase_size);
  369. ESP_LOGD(TAG,"OTA Erase block size is %d (from string: %s)",single_pass_size, ota_erase_size );
  370. free(ota_erase_size);
  371. }
  372. else {
  373. ESP_LOGW(TAG,"OTA Erase block config not found");
  374. single_pass_size = OTA_FLASH_ERASE_BLOCK;
  375. }
  376. if(single_pass_size % SPI_FLASH_SEC_SIZE !=0){
  377. uint32_t temp_single_pass_size = single_pass_size-(single_pass_size % SPI_FLASH_SEC_SIZE);
  378. 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);
  379. single_pass_size=temp_single_pass_size;
  380. }
  381. ESP_LOGD(TAG,"Erasing flash partition of size %u in blocks of %d bytes", ota_partition->size, single_pass_size);
  382. num_passes=ota_partition->size/single_pass_size;
  383. remain_size=ota_partition->size-(num_passes*single_pass_size);
  384. ESP_LOGI(TAG,"Erasing in %d passes with blocks of %d bytes ", num_passes,single_pass_size);
  385. for(uint16_t i=0;i<num_passes;i++){
  386. ESP_LOGD(TAG,"Erasing flash (%u%%)",i/num_passes);
  387. 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);
  388. err=esp_partition_erase_range(ota_partition, i*single_pass_size, single_pass_size);
  389. if(err!=ESP_OK) return err;
  390. if(i%2) {
  391. loc_displayer_progressbar((int)(((float)i/(float)num_passes)*100.0f));
  392. sendMessaging(MESSAGING_INFO,"Erasing flash (%u/%u)",i,num_passes);
  393. }
  394. vTaskDelay(100/ portTICK_PERIOD_MS); // wait here for a short amount of time. This will help with reducing WDT errors
  395. }
  396. if(remain_size>0){
  397. err=esp_partition_erase_range(ota_partition, ota_partition->size-remain_size, remain_size);
  398. if(err!=ESP_OK) return err;
  399. }
  400. sendMessaging(MESSAGING_INFO,"Erasing flash complete.");
  401. loc_displayer_progressbar(100);
  402. vTaskDelay(200/ portTICK_PERIOD_MS);
  403. return ESP_OK;
  404. }
  405. void ota_task_cleanup(const char * message, ...){
  406. ota_status->bOTAThreadStarted=false;
  407. loc_displayer_progressbar(0);
  408. if(message!=NULL){
  409. va_list args;
  410. va_start(args, message);
  411. sendMessaging(MESSAGING_ERROR,message, args);
  412. va_end(args);
  413. if (led_display) led_vu_color_red(LED_VU_BRIGHT);
  414. } else {
  415. if (led_display) led_vu_color_green(LED_VU_BRIGHT);
  416. }
  417. FREE_RESET(ota_status->ota_write_data);
  418. FREE_RESET(ota_status->bin_data);
  419. if(ota_http_client!=NULL) {
  420. esp_http_client_cleanup(ota_http_client);
  421. ota_http_client=NULL;
  422. }
  423. ota_status->bOTAStarted = false;
  424. task_fatal_error();
  425. }
  426. esp_err_t ota_buffer_all(){
  427. esp_err_t err=ESP_OK;
  428. if (ota_status->ota_type == OTA_TYPE_HTTP){
  429. IF_DISPLAY(GDS_TextLine(display, 2, GDS_TEXT_LEFT, GDS_TEXT_CLEAR | GDS_TEXT_UPDATE, "Downloading file"));
  430. ota_http_client = esp_http_client_init(&http_client_config);
  431. if (ota_http_client == NULL) {
  432. sendMessaging(MESSAGING_ERROR,"Error: Failed to initialize HTTP connection.");
  433. return ESP_FAIL;
  434. }
  435. _printMemStats();
  436. err = esp_http_client_perform(ota_http_client);
  437. if (err != ESP_OK) {
  438. sendMessaging(MESSAGING_ERROR,"Error: Failed to execute HTTP download. %s",esp_err_to_name(err));
  439. return ESP_FAIL;
  440. }
  441. if(ota_status->total_image_len<=0){
  442. sendMessaging(MESSAGING_ERROR,"Error: Invalid image length");
  443. return ESP_FAIL;
  444. }
  445. sendMessaging(MESSAGING_INFO,"Download success");
  446. }
  447. else {
  448. gettimeofday(&ota_status->OTA_start, NULL);
  449. }
  450. ota_status->remain_image_len=ota_status->total_image_len;
  451. return err;
  452. }
  453. int ota_buffer_read(){
  454. int data_read=0;
  455. if(ota_status->remain_image_len >ota_status->buffer_size){
  456. data_read = ota_status->buffer_size;
  457. } else {
  458. data_read = ota_status->remain_image_len;
  459. }
  460. memcpy(ota_status->ota_write_data, &ota_status->bin_data[ota_status->actual_image_len], data_read);
  461. ota_status->actual_image_len += data_read;
  462. ota_status->remain_image_len -= data_read;
  463. return data_read;
  464. }
  465. esp_err_t ota_header_check(){
  466. esp_app_desc_t new_app_info;
  467. esp_app_desc_t running_app_info;
  468. ota_status->configured = esp_ota_get_boot_partition();
  469. ota_status->running = esp_ota_get_running_partition();
  470. ota_status->last_invalid_app= esp_ota_get_last_invalid_partition();
  471. ota_status->ota_partition = _get_ota_partition(ESP_PARTITION_SUBTYPE_APP_OTA_0);
  472. ESP_LOGD(TAG, "Running partition [%s] type %d subtype %d (offset 0x%08x)", ota_status->running->label, ota_status->running->type, ota_status->running->subtype, ota_status->running->address);
  473. if (ota_status->total_image_len > ota_status->ota_partition->size){
  474. ota_task_cleanup("Error: Image size (%d) too large to fit in partition (%d).",ota_status->ota_partition->size,ota_status->total_image_len );
  475. return ESP_FAIL;
  476. }
  477. if(ota_status->ota_partition == NULL){
  478. ESP_LOGE(TAG,"Unable to locate OTA application partition. ");
  479. ota_task_cleanup("Error: OTA partition not found");
  480. return ESP_FAIL;
  481. }
  482. if (ota_status->configured != ota_status->running) {
  483. ESP_LOGW(TAG, "Configured OTA boot partition at offset 0x%08x, but running from offset 0x%08x", ota_status->configured->address, ota_status->running->address);
  484. ESP_LOGW(TAG, "(This can happen if either the OTA boot data or preferred boot image become corrupted somehow.)");
  485. }
  486. ESP_LOGD(TAG, "Next ota update partition is: [%s] subtype %d at offset 0x%x",
  487. ota_status->update_partition->label, ota_status->update_partition->subtype, ota_status->update_partition->address);
  488. if (ota_status->total_image_len >= IMAGE_HEADER_SIZE) {
  489. // check current version with downloading
  490. memcpy(&new_app_info, &ota_status->bin_data[sizeof(esp_image_header_t) + sizeof(esp_image_segment_header_t)], sizeof(esp_app_desc_t));
  491. ESP_LOGI(TAG, "New firmware version: %s", new_app_info.version);
  492. if (esp_ota_get_partition_description(ota_status->running, &running_app_info) == ESP_OK) {
  493. ESP_LOGD(TAG, "Running recovery version: %s", running_app_info.version);
  494. }
  495. sendMessaging(MESSAGING_INFO,"New version is : %s",new_app_info.version);
  496. esp_app_desc_t invalid_app_info;
  497. if (esp_ota_get_partition_description(ota_status->last_invalid_app, &invalid_app_info) == ESP_OK) {
  498. ESP_LOGD(TAG, "Last invalid firmware version: %s", invalid_app_info.version);
  499. }
  500. if (memcmp(new_app_info.version, running_app_info.version, sizeof(new_app_info.version)) == 0) {
  501. ESP_LOGW(TAG, "Current running version is the same as a new.");
  502. }
  503. return ESP_OK;
  504. }
  505. else{
  506. ota_task_cleanup("Error: Binary file too small");
  507. }
  508. return ESP_FAIL;
  509. }
  510. void ota_task(void *pvParameter)
  511. {
  512. esp_err_t err = ESP_OK;
  513. int data_read = 0;
  514. IF_DISPLAY(GDS_TextSetFont(display,2,GDS_GetHeight(display)>32?&Font_droid_sans_fallback_15x17:&Font_droid_sans_fallback_11x13,-2))
  515. IF_DISPLAY( GDS_ClearExt(display, true));
  516. IF_DISPLAY(GDS_TextLine(display, 1, GDS_TEXT_LEFT, GDS_TEXT_CLEAR | GDS_TEXT_UPDATE, "Firmware update"));
  517. IF_DISPLAY(GDS_TextLine(display, 2, GDS_TEXT_LEFT, GDS_TEXT_CLEAR | GDS_TEXT_UPDATE, "Initializing"));
  518. loc_displayer_progressbar(0);
  519. ESP_LOGD(TAG, "HTTP ota Thread started");
  520. _printMemStats();
  521. ota_status->update_partition = esp_ota_get_next_update_partition(NULL);
  522. ESP_LOGD(TAG,"Initializing OTA configuration");
  523. err = init_config(pvParameter);
  524. if(err!=ESP_OK){
  525. ota_task_cleanup("Error: Failed to initialize OTA.");
  526. return;
  527. }
  528. _printMemStats();
  529. sendMessaging(MESSAGING_INFO,"Starting OTA...");
  530. err=ota_buffer_all();
  531. if(err!=ESP_OK){
  532. ota_task_cleanup(NULL);
  533. return;
  534. }
  535. if(ota_header_check()!=ESP_OK){
  536. ota_task_cleanup(NULL);
  537. return;
  538. }
  539. /* Locate and erase ota application partition */
  540. sendMessaging(MESSAGING_INFO,"Formatting OTA partition");
  541. ESP_LOGW(TAG,"**************** Expecting WATCHDOG errors below during flash erase. This is OK and not to worry about **************** ");
  542. IF_DISPLAY(GDS_TextLine(display, 2, GDS_TEXT_LEFT, GDS_TEXT_CLEAR | GDS_TEXT_UPDATE, "Formatting partition"));
  543. _printMemStats();
  544. err=_erase_last_boot_app_partition(ota_status->ota_partition);
  545. if(err!=ESP_OK){
  546. ota_task_cleanup("Error: Unable to erase last APP partition. (%s)",esp_err_to_name(err));
  547. return;
  548. }
  549. loc_displayer_progressbar(0);
  550. _printMemStats();
  551. // Call OTA Begin with a small partition size - this minimizes the time spent in erasing partition,
  552. // which was already done above
  553. esp_ota_handle_t update_handle = 0 ;
  554. gettimeofday(&ota_status->OTA_start, NULL);
  555. err = esp_ota_begin(ota_status->ota_partition, 512, &update_handle);
  556. if (err != ESP_OK) {
  557. ota_task_cleanup("esp_ota_begin failed (%s)", esp_err_to_name(err));
  558. return;
  559. }
  560. ESP_LOGD(TAG, "esp_ota_begin succeeded");
  561. IF_DISPLAY(GDS_TextLine(display, 2, GDS_TEXT_LEFT, GDS_TEXT_CLEAR | GDS_TEXT_UPDATE, "Writing image..."));
  562. while (ota_status->remain_image_len>0) {
  563. data_read = ota_buffer_read();
  564. if (data_read <= 0) {
  565. ota_task_cleanup("Error: Data read error");
  566. return;
  567. } else if (data_read > 0) {
  568. err = esp_ota_write( update_handle, (const void *)ota_status->ota_write_data, data_read);
  569. if (err != ESP_OK) {
  570. ota_task_cleanup("Error: OTA Partition write failure. (%s)",esp_err_to_name(err));
  571. return;
  572. }
  573. ESP_LOGD(TAG, "Written image length %d", ota_status->actual_image_len);
  574. if(ota_get_pct_complete()%5 == 0) ota_status->newpct = ota_get_pct_complete();
  575. if(ota_status->lastpct!=ota_status->newpct ) {
  576. loc_displayer_progressbar(ota_status->newpct);
  577. gettimeofday(&tv, NULL);
  578. uint32_t elapsed_ms= (tv.tv_sec-ota_status->OTA_start.tv_sec )*1000+(tv.tv_usec-ota_status->OTA_start.tv_usec)/1000;
  579. ESP_LOGI(TAG,"OTA progress : %d/%.0f (%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);
  580. sendMessaging(MESSAGING_INFO,"Writing binary file %3d %%.",ota_status->newpct);
  581. ota_status->lastpct=ota_status->newpct;
  582. }
  583. taskYIELD();
  584. } else if (data_read == 0) {
  585. ESP_LOGD(TAG, "End of OTA data stream");
  586. break;
  587. }
  588. }
  589. ESP_LOGI(TAG, "Total Write binary data length: %d", ota_status->actual_image_len);
  590. if (ota_status->total_image_len != ota_status->actual_image_len) {
  591. ota_task_cleanup("Error: Error in receiving complete file");
  592. return;
  593. }
  594. _printMemStats();
  595. loc_displayer_progressbar(100);
  596. err = esp_ota_end(update_handle);
  597. if (err != ESP_OK) {
  598. ota_task_cleanup("Error: %s",esp_err_to_name(err));
  599. return;
  600. }
  601. _printMemStats();
  602. err = esp_ota_set_boot_partition(ota_status->ota_partition);
  603. if (err == ESP_OK) {
  604. ESP_LOGI(TAG,"OTA Process completed successfully!");
  605. sendMessaging(MESSAGING_INFO,"Success!");
  606. IF_DISPLAY(GDS_TextLine(display, 2, GDS_TEXT_LEFT, GDS_TEXT_CLEAR | GDS_TEXT_UPDATE, "Success!"));
  607. vTaskDelay(3500/ portTICK_PERIOD_MS); // wait here to give the UI a chance to refresh
  608. IF_DISPLAY(GDS_Clear(display,GDS_COLOR_BLACK));
  609. esp_restart();
  610. } else {
  611. ota_task_cleanup("Error: Unable to update boot partition [%s]",esp_err_to_name(err));
  612. return;
  613. }
  614. ota_task_cleanup(NULL);
  615. return;
  616. }
  617. esp_err_t process_recovery_ota(const char * bin_url, char * bin_buffer, uint32_t length){
  618. int ret = 0;
  619. uint16_t stack_size, task_priority;
  620. if(ota_status && ota_status->bOTAThreadStarted){
  621. ESP_LOGE(TAG,"OTA Already started. ");
  622. return ESP_FAIL;
  623. }
  624. ota_status = malloc_init_external(sizeof(ota_status_t));
  625. ota_status->bOTAThreadStarted=true;
  626. if(bin_url){
  627. ota_thread_parms.url =strdup_psram(bin_url);
  628. ESP_LOGD(TAG, "Starting ota on core %u for : %s", OTA_CORE,ota_thread_parms.url);
  629. }
  630. else {
  631. ota_thread_parms.bin = bin_buffer;
  632. ota_thread_parms.length = length;
  633. ESP_LOGD(TAG, "Starting ota on core %u for file upload", OTA_CORE);
  634. }
  635. char * num_buffer=config_alloc_get(NVS_TYPE_STR, "ota_stack");
  636. if(num_buffer!=NULL) {
  637. stack_size= atol(num_buffer);
  638. FREE_AND_NULL(num_buffer);
  639. }
  640. else {
  641. ESP_LOGW(TAG,"OTA stack size config not found");
  642. stack_size = OTA_STACK_SIZE;
  643. }
  644. num_buffer=config_alloc_get(NVS_TYPE_STR, "ota_prio");
  645. if(num_buffer!=NULL) {
  646. task_priority= atol(num_buffer);
  647. FREE_AND_NULL(num_buffer);
  648. }
  649. else {
  650. ESP_LOGW(TAG,"OTA task priority not found");
  651. task_priority= OTA_TASK_PRIOTITY;
  652. }
  653. 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");
  654. // ret=xTaskCreatePinnedToCore(&ota_task, "ota_task", stack_size , (void *)&ota_thread_parms, task_priority, NULL, OTA_CORE);
  655. ret=xTaskCreate(&ota_task, "ota_task", stack_size , (void *)&ota_thread_parms, task_priority, NULL);
  656. if (ret != pdPASS) {
  657. ESP_LOGE(TAG, "create thread %s failed", "ota_task");
  658. return ESP_FAIL;
  659. }
  660. return ESP_OK;
  661. }
  662. extern void set_lms_server_details(in_addr_t ip, u16_t hport, u16_t cport);
  663. in_addr_t discover_ota_server(int max) {
  664. struct sockaddr_in d;
  665. struct sockaddr_in s;
  666. char buf[32], port_d[] = "JSON", clip_d[] = "CLIP";
  667. struct pollfd pollinfo;
  668. uint8_t len;
  669. uint16_t hport=9000;
  670. uint16_t cport=9090;
  671. int disc_sock = socket(AF_INET, SOCK_DGRAM, 0);
  672. socklen_t enable = 1;
  673. setsockopt(disc_sock, SOL_SOCKET, SO_BROADCAST, (const void *)&enable, sizeof(enable));
  674. len = sprintf(buf,"e%s%c%s", port_d, '\0', clip_d) + 1;
  675. memset(&d, 0, sizeof(d));
  676. d.sin_family = AF_INET;
  677. d.sin_port = htons(3483);
  678. d.sin_addr.s_addr = htonl(INADDR_BROADCAST);
  679. pollinfo.fd = disc_sock;
  680. pollinfo.events = POLLIN;
  681. do {
  682. ESP_LOGI(TAG,"sending LMS discovery for OTA Update");
  683. memset(&s, 0, sizeof(s));
  684. if (sendto(disc_sock, buf, len, 0, (struct sockaddr *)&d, sizeof(d)) < 0) {
  685. ESP_LOGE(TAG,"error sending discovery");
  686. }
  687. else {
  688. if (poll(&pollinfo, 1, 5000) == 1) {
  689. char readbuf[64], *p;
  690. socklen_t slen = sizeof(s);
  691. memset(readbuf, 0, sizeof(readbuf));
  692. recvfrom(disc_sock, readbuf, sizeof(readbuf) - 1, 0, (struct sockaddr *)&s, &slen);
  693. ESP_LOGI(TAG,"got response from: %s:%d - %s", inet_ntoa(s.sin_addr), ntohs(s.sin_port),readbuf);
  694. if ((p = strstr(readbuf, port_d)) != NULL) {
  695. p += strlen(port_d);
  696. hport = atoi(p + 1);
  697. }
  698. if ((p = strstr(readbuf, clip_d)) != NULL) {
  699. p += strlen(clip_d);
  700. cport = atoi(p + 1);
  701. }
  702. server_notify(s.sin_addr.s_addr, hport, cport);
  703. }
  704. }
  705. } while (s.sin_addr.s_addr == 0 && (!max || --max));
  706. closesocket(disc_sock);
  707. return s.sin_addr.s_addr;
  708. }