squeezelite-ota.c 27 KB

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