server_ota.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566
  1. #include "server_ota.h"
  2. #include <string>
  3. #include "string.h"
  4. #include <esp_task_wdt.h>
  5. #include <string.h>
  6. #include "freertos/FreeRTOS.h"
  7. #include "freertos/task.h"
  8. #include "esp_system.h"
  9. #include "esp_event.h"
  10. #include "esp_event.h"
  11. #include "esp_log.h"
  12. #include <esp_ota_ops.h>
  13. #include "esp_http_client.h"
  14. #include "esp_flash_partitions.h"
  15. #include "esp_vfs.h"
  16. #include "esp_partition.h"
  17. #include "esp_app_format.h"
  18. #include <nvs.h>
  19. #include "nvs_flash.h"
  20. #include "driver/gpio.h"
  21. // #include "protocol_examples_common.h"
  22. #include "errno.h"
  23. #include <sys/stat.h>
  24. #include "server_tflite.h"
  25. #include "server_file.h"
  26. #include "server_GPIO.h"
  27. #include "ClassLogFile.h"
  28. #include "Helper.h"
  29. // #define DEBUG_DETAIL_ON
  30. #define BUFFSIZE 1024
  31. #define HASH_LEN 32 /* SHA-256 digest length */
  32. /*an ota data write buffer ready to write to the flash*/
  33. static char ota_write_data[BUFFSIZE + 1] = { 0 };
  34. #define OTA_URL_SIZE 256
  35. static const char *TAGPARTOTA = "server_ota";
  36. esp_err_t handler_reboot(httpd_req_t *req);
  37. static void infinite_loop(void)
  38. {
  39. int i = 0;
  40. ESP_LOGI(TAGPARTOTA, "When a new firmware is available on the server, press the reset button to download it");
  41. while(1) {
  42. ESP_LOGI(TAGPARTOTA, "Waiting for a new firmware... %d", ++i);
  43. vTaskDelay(2000 / portTICK_PERIOD_MS);
  44. }
  45. }
  46. static bool ota_update_task(std::string fn)
  47. {
  48. esp_err_t err;
  49. /* update handle : set by esp_ota_begin(), must be freed via esp_ota_end() */
  50. esp_ota_handle_t update_handle = 0 ;
  51. const esp_partition_t *update_partition = NULL;
  52. ESP_LOGI(TAGPARTOTA, "Starting OTA update");
  53. const esp_partition_t *configured = esp_ota_get_boot_partition();
  54. const esp_partition_t *running = esp_ota_get_running_partition();
  55. if (configured != running) {
  56. #if (ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 0, 0))
  57. ESP_LOGW(TAGPARTOTA, "Configured OTA boot partition at offset 0x%08lx, but running from offset 0x%08lx",
  58. #else
  59. ESP_LOGW(TAGPARTOTA, "Configured OTA boot partition at offset 0x%08x, but running from offset 0x%08x",
  60. #endif
  61. configured->address, running->address);
  62. ESP_LOGW(TAGPARTOTA, "(This can happen if either the OTA boot data or preferred boot image become somehow corrupted.)");
  63. }
  64. #if (ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 0, 0))
  65. ESP_LOGI(TAGPARTOTA, "Running partition type %d subtype %d (offset 0x%08lx)",
  66. #else
  67. ESP_LOGI(TAGPARTOTA, "Running partition type %d subtype %d (offset 0x%08x)",
  68. #endif
  69. running->type, running->subtype, running->address);
  70. update_partition = esp_ota_get_next_update_partition(NULL);
  71. #if (ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 0, 0))
  72. ESP_LOGI(TAGPARTOTA, "Writing to partition subtype %d at offset 0x%lx",
  73. #else
  74. ESP_LOGI(TAGPARTOTA, "Writing to partition subtype %d at offset 0x%x",
  75. #endif
  76. update_partition->subtype, update_partition->address);
  77. // assert(update_partition != NULL);
  78. int binary_file_length = 0;
  79. // deal with all receive packet
  80. bool image_header_was_checked = false;
  81. int data_read;
  82. FILE* f = OpenFileAndWait(fn.c_str(), "rb"); // vorher nur "r"
  83. if (f == NULL) { // File does not exist
  84. return false;
  85. }
  86. data_read = fread(ota_write_data, 1, BUFFSIZE, f);
  87. while (data_read > 0) {
  88. if (data_read < 0) {
  89. ESP_LOGE(TAGPARTOTA, "Error: SSL data read error");
  90. return false;
  91. } else if (data_read > 0) {
  92. if (image_header_was_checked == false) {
  93. esp_app_desc_t new_app_info;
  94. if (data_read > sizeof(esp_image_header_t) + sizeof(esp_image_segment_header_t) + sizeof(esp_app_desc_t)) {
  95. // check current version with downloading
  96. memcpy(&new_app_info, &ota_write_data[sizeof(esp_image_header_t) + sizeof(esp_image_segment_header_t)], sizeof(esp_app_desc_t));
  97. ESP_LOGI(TAGPARTOTA, "New firmware version: %s", new_app_info.version);
  98. esp_app_desc_t running_app_info;
  99. if (esp_ota_get_partition_description(running, &running_app_info) == ESP_OK) {
  100. ESP_LOGI(TAGPARTOTA, "Running firmware version: %s", running_app_info.version);
  101. }
  102. const esp_partition_t* last_invalid_app = esp_ota_get_last_invalid_partition();
  103. esp_app_desc_t invalid_app_info;
  104. if (esp_ota_get_partition_description(last_invalid_app, &invalid_app_info) == ESP_OK) {
  105. ESP_LOGI(TAGPARTOTA, "Last invalid firmware version: %s", invalid_app_info.version);
  106. }
  107. // check current version with last invalid partition
  108. if (last_invalid_app != NULL) {
  109. if (memcmp(invalid_app_info.version, new_app_info.version, sizeof(new_app_info.version)) == 0) {
  110. ESP_LOGW(TAGPARTOTA, "New version is the same as invalid version.");
  111. ESP_LOGW(TAGPARTOTA, "Previously, there was an attempt to launch the firmware with %s version, but it failed.", invalid_app_info.version);
  112. ESP_LOGW(TAGPARTOTA, "The firmware has been rolled back to the previous version.");
  113. infinite_loop();
  114. }
  115. }
  116. /*
  117. if (memcmp(new_app_info.version, running_app_info.version, sizeof(new_app_info.version)) == 0) {
  118. ESP_LOGW(TAGPARTOTA, "Current running version is the same as a new. We will not continue the update.");
  119. infinite_loop();
  120. }
  121. */
  122. image_header_was_checked = true;
  123. err = esp_ota_begin(update_partition, OTA_SIZE_UNKNOWN, &update_handle);
  124. if (err != ESP_OK) {
  125. ESP_LOGE(TAGPARTOTA, "esp_ota_begin failed (%s)", esp_err_to_name(err));
  126. return false;
  127. }
  128. ESP_LOGI(TAGPARTOTA, "esp_ota_begin succeeded");
  129. } else {
  130. ESP_LOGE(TAGPARTOTA, "received package is not fit len");
  131. return false;
  132. }
  133. }
  134. err = esp_ota_write( update_handle, (const void *)ota_write_data, data_read);
  135. if (err != ESP_OK) {
  136. return false;
  137. }
  138. binary_file_length += data_read;
  139. ESP_LOGD(TAGPARTOTA, "Written image length %d", binary_file_length);
  140. } else if (data_read == 0) {
  141. //
  142. // * As esp_http_client_read never returns negative error code, we rely on
  143. // * `errno` to check for underlying transport connectivity closure if any
  144. //
  145. if (errno == ECONNRESET || errno == ENOTCONN) {
  146. ESP_LOGE(TAGPARTOTA, "Connection closed, errno = %d", errno);
  147. break;
  148. }
  149. }
  150. data_read = fread(ota_write_data, 1, BUFFSIZE, f);
  151. }
  152. fclose(f);
  153. ESP_LOGI(TAGPARTOTA, "Total Write binary data length: %d", binary_file_length);
  154. err = esp_ota_end(update_handle);
  155. if (err != ESP_OK) {
  156. if (err == ESP_ERR_OTA_VALIDATE_FAILED) {
  157. ESP_LOGE(TAGPARTOTA, "Image validation failed, image is corrupted");
  158. }
  159. ESP_LOGE(TAGPARTOTA, "esp_ota_end failed (%s)!", esp_err_to_name(err));
  160. return false;
  161. }
  162. err = esp_ota_set_boot_partition(update_partition);
  163. if (err != ESP_OK) {
  164. ESP_LOGE(TAGPARTOTA, "esp_ota_set_boot_partition failed (%s)!", esp_err_to_name(err));
  165. }
  166. // ESP_LOGI(TAGPARTOTA, "Prepare to restart system!");
  167. // esp_restart();
  168. return true ;
  169. }
  170. static void print_sha256 (const uint8_t *image_hash, const char *label)
  171. {
  172. char hash_print[HASH_LEN * 2 + 1];
  173. hash_print[HASH_LEN * 2] = 0;
  174. for (int i = 0; i < HASH_LEN; ++i) {
  175. sprintf(&hash_print[i * 2], "%02x", image_hash[i]);
  176. }
  177. ESP_LOGI(TAGPARTOTA, "%s: %s", label, hash_print);
  178. }
  179. static bool diagnostic(void)
  180. {
  181. return true;
  182. }
  183. void CheckOTAUpdate(void)
  184. {
  185. ESP_LOGI(TAGPARTOTA, "Start CheckOTAUpdateCheck...");
  186. uint8_t sha_256[HASH_LEN] = { 0 };
  187. esp_partition_t partition;
  188. // get sha256 digest for the partition table
  189. partition.address = ESP_PARTITION_TABLE_OFFSET;
  190. partition.size = ESP_PARTITION_TABLE_MAX_LEN;
  191. partition.type = ESP_PARTITION_TYPE_DATA;
  192. esp_partition_get_sha256(&partition, sha_256);
  193. print_sha256(sha_256, "SHA-256 for the partition table: ");
  194. // get sha256 digest for bootloader
  195. partition.address = ESP_BOOTLOADER_OFFSET;
  196. partition.size = ESP_PARTITION_TABLE_OFFSET;
  197. partition.type = ESP_PARTITION_TYPE_APP;
  198. esp_partition_get_sha256(&partition, sha_256);
  199. print_sha256(sha_256, "SHA-256 for bootloader: ");
  200. // get sha256 digest for running partition
  201. esp_partition_get_sha256(esp_ota_get_running_partition(), sha_256);
  202. print_sha256(sha_256, "SHA-256 for current firmware: ");
  203. const esp_partition_t *running = esp_ota_get_running_partition();
  204. esp_ota_img_states_t ota_state;
  205. esp_err_t res_stat_partition = esp_ota_get_state_partition(running, &ota_state);
  206. switch (res_stat_partition)
  207. {
  208. case ESP_OK:
  209. ESP_LOGD(TAGPARTOTA, "CheckOTAUpdate Partition: ESP_OK");
  210. if (esp_ota_get_state_partition(running, &ota_state) == ESP_OK) {
  211. if (ota_state == ESP_OTA_IMG_PENDING_VERIFY) {
  212. // run diagnostic function ...
  213. bool diagnostic_is_ok = diagnostic();
  214. if (diagnostic_is_ok) {
  215. ESP_LOGI(TAGPARTOTA, "Diagnostics completed successfully! Continuing execution...");
  216. esp_ota_mark_app_valid_cancel_rollback();
  217. } else {
  218. ESP_LOGE(TAGPARTOTA, "Diagnostics failed! Start rollback to the previous version...");
  219. esp_ota_mark_app_invalid_rollback_and_reboot();
  220. }
  221. }
  222. }
  223. break;
  224. case ESP_ERR_INVALID_ARG:
  225. ESP_LOGD(TAGPARTOTA, "CheckOTAUpdate Partition: ESP_ERR_INVALID_ARG");
  226. break;
  227. case ESP_ERR_NOT_SUPPORTED:
  228. ESP_LOGD(TAGPARTOTA, "CheckOTAUpdate Partition: ESP_ERR_NOT_SUPPORTED");
  229. break;
  230. case ESP_ERR_NOT_FOUND:
  231. ESP_LOGD(TAGPARTOTA, "CheckOTAUpdate Partition: ESP_ERR_NOT_FOUND");
  232. break;
  233. }
  234. if (esp_ota_get_state_partition(running, &ota_state) == ESP_OK) {
  235. if (ota_state == ESP_OTA_IMG_PENDING_VERIFY) {
  236. // run diagnostic function ...
  237. bool diagnostic_is_ok = diagnostic();
  238. if (diagnostic_is_ok) {
  239. ESP_LOGI(TAGPARTOTA, "Diagnostics completed successfully! Continuing execution...");
  240. esp_ota_mark_app_valid_cancel_rollback();
  241. } else {
  242. ESP_LOGE(TAGPARTOTA, "Diagnostics failed! Start rollback to the previous version...");
  243. esp_ota_mark_app_invalid_rollback_and_reboot();
  244. }
  245. }
  246. }
  247. }
  248. esp_err_t handler_ota_update(httpd_req_t *req)
  249. {
  250. #ifdef DEBUG_DETAIL_ON
  251. LogFile.WriteHeapInfo("handler_ota_update - Start");
  252. #endif
  253. LogFile.WriteToFile(ESP_LOG_DEBUG, "handler_ota_update");
  254. char _query[200];
  255. char _filename[100];
  256. char _valuechar[30];
  257. std::string fn = "/sdcard/firmware/";
  258. bool _file_del = false;
  259. std::string _task = "";
  260. if (httpd_req_get_url_query_str(req, _query, 200) == ESP_OK)
  261. {
  262. ESP_LOGD(TAGPARTOTA, "Query: %s", _query);
  263. if (httpd_query_key_value(_query, "task", _valuechar, 30) == ESP_OK)
  264. {
  265. ESP_LOGD(TAGPARTOTA, "task is found: %s", _valuechar);
  266. _task = std::string(_valuechar);
  267. }
  268. if (httpd_query_key_value(_query, "file", _filename, 100) == ESP_OK)
  269. {
  270. fn.append(_filename);
  271. ESP_LOGD(TAGPARTOTA, "File: %s", fn.c_str());
  272. }
  273. if (httpd_query_key_value(_query, "delete", _filename, 100) == ESP_OK)
  274. {
  275. fn.append(_filename);
  276. _file_del = true;
  277. ESP_LOGD(TAGPARTOTA, "Delete Default File: %s", fn.c_str());
  278. }
  279. };
  280. if (_task.compare("update") == 0)
  281. {
  282. std::string filetype = toUpper(getFileType(fn));
  283. if (filetype.length() == 0)
  284. {
  285. std::string zw = "Update failed - no file specified (zip, bin, tfl, tlite)";
  286. httpd_resp_sendstr_chunk(req, zw.c_str());
  287. httpd_resp_sendstr_chunk(req, NULL);
  288. return ESP_OK;
  289. }
  290. if ((filetype == "TFLITE") || (filetype == "TFL"))
  291. {
  292. std::string out = "/sdcard/config/" + getFileFullFileName(fn);
  293. DeleteFile(out);
  294. CopyFile(fn, out);
  295. DeleteFile(fn);
  296. const char* resp_str = "Neural Network File copied.";
  297. httpd_resp_sendstr_chunk(req, resp_str);
  298. httpd_resp_sendstr_chunk(req, NULL);
  299. return ESP_OK;
  300. }
  301. if (filetype == "ZIP")
  302. {
  303. std::string in, out, outbin, zw, retfirmware;
  304. out = "/sdcard/html";
  305. outbin = "/sdcard/firmware";
  306. retfirmware = unzip_new(fn, out+"/", outbin+"/");
  307. if (retfirmware.length() > 0)
  308. {
  309. filetype = "BIN";
  310. fn = retfirmware;
  311. }
  312. else
  313. {
  314. zw = "Web Interface Update Successfull!\nNo reboot necessary.\n";
  315. httpd_resp_sendstr_chunk(req, zw.c_str());
  316. httpd_resp_sendstr_chunk(req, NULL);
  317. return ESP_OK;
  318. }
  319. }
  320. if (filetype == "BIN")
  321. {
  322. const char* resp_str;
  323. KillTFliteTasks();
  324. gpio_handler_deinit();
  325. if (ota_update_task(fn))
  326. {
  327. std::string zw = "reboot\n";
  328. httpd_resp_sendstr_chunk(req, zw.c_str());
  329. httpd_resp_sendstr_chunk(req, NULL);
  330. ESP_LOGD(TAGPARTOTA, "Send reboot");
  331. return ESP_OK;
  332. }
  333. resp_str = "Error during Firmware Update!!!\nPlease check output of console.";
  334. httpd_resp_send(req, resp_str, strlen(resp_str));
  335. #ifdef DEBUG_DETAIL_ON
  336. LogFile.WriteHeapInfo("handler_ota_update - Done");
  337. #endif
  338. return ESP_OK;
  339. }
  340. std::string zw = "Update failed - no valid file specified (zip, bin, tfl, tlite)!";
  341. httpd_resp_sendstr_chunk(req, zw.c_str());
  342. httpd_resp_sendstr_chunk(req, NULL);
  343. return ESP_OK;
  344. }
  345. if (_task.compare("unziphtml") == 0)
  346. {
  347. ESP_LOGD(TAGPARTOTA, "Task unziphtml");
  348. std::string in, out, zw;
  349. in = "/sdcard/firmware/html.zip";
  350. out = "/sdcard/html";
  351. delete_all_in_directory(out);
  352. unzip(in, out+"/");
  353. zw = "Web Interface Update Successfull!\nNo reboot necessary";
  354. httpd_resp_send(req, zw.c_str(), strlen(zw.c_str()));
  355. httpd_resp_sendstr_chunk(req, NULL);
  356. return ESP_OK;
  357. }
  358. if (_file_del)
  359. {
  360. ESP_LOGD(TAGPARTOTA, "Delete !! _file_del: %s", fn.c_str());
  361. struct stat file_stat;
  362. int _result = stat(fn.c_str(), &file_stat);
  363. ESP_LOGD(TAGPARTOTA, "Ergebnis %d\n", _result);
  364. if (_result == 0) {
  365. ESP_LOGD(TAGPARTOTA, "Deleting file : %s", fn.c_str());
  366. /* Delete file */
  367. unlink(fn.c_str());
  368. }
  369. else
  370. {
  371. ESP_LOGD(TAGPARTOTA, "File does not exist: %s", fn.c_str());
  372. }
  373. /* Respond with an empty chunk to signal HTTP response completion */
  374. std::string zw = "file deleted\n";
  375. ESP_LOGD(TAGPARTOTA, "%s", zw.c_str());
  376. httpd_resp_send(req, zw.c_str(), strlen(zw.c_str()));
  377. httpd_resp_send_chunk(req, NULL, 0);
  378. return ESP_OK;
  379. }
  380. const char* resp_str;
  381. KillTFliteTasks();
  382. gpio_handler_deinit();
  383. if (ota_update_task(fn))
  384. {
  385. resp_str = "Firmware Update Successfull! You can restart now.";
  386. }
  387. else
  388. {
  389. resp_str = "Error during Firmware Update!!! Please check console output.";
  390. }
  391. httpd_resp_send(req, resp_str, strlen(resp_str));
  392. #ifdef DEBUG_DETAIL_ON
  393. LogFile.WriteHeapInfo("handler_ota_update - Done");
  394. #endif
  395. return ESP_OK;
  396. };
  397. void hard_restart() {
  398. #if (ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 0, 0))
  399. esp_task_wdt_config_t wd_config;
  400. wd_config.timeout_ms = 1000;
  401. wd_config.idle_core_mask = (1 << portNUM_PROCESSORS) - 1; // Bitmask of all cores
  402. wd_config.trigger_panic = true;
  403. esp_task_wdt_init(&wd_config);
  404. #else
  405. esp_task_wdt_init(1,true);
  406. #endif
  407. esp_task_wdt_add(NULL);
  408. while(true);
  409. }
  410. void task_reboot(void *pvParameter)
  411. {
  412. while(1)
  413. {
  414. vTaskDelay(5000 / portTICK_PERIOD_MS);
  415. esp_restart();
  416. hard_restart();
  417. }
  418. vTaskDelete(NULL); //Delete this task if it exits from the loop above
  419. }
  420. void doReboot(){
  421. LogFile.WriteToFile(ESP_LOG_INFO, "Reboot triggered by Software (5s).");
  422. LogFile.WriteToFile(ESP_LOG_WARN, "Reboot in 5sec");
  423. xTaskCreate(&task_reboot, "reboot", configMINIMAL_STACK_SIZE * 64, NULL, 10, NULL);
  424. // KillTFliteTasks(); // kills itself
  425. gpio_handler_destroy();
  426. vTaskDelay(5000 / portTICK_PERIOD_MS);
  427. esp_restart();
  428. hard_restart();
  429. }
  430. esp_err_t handler_reboot(httpd_req_t *req)
  431. {
  432. #ifdef DEBUG_DETAIL_ON
  433. LogFile.WriteHeapInfo("handler_reboot - Start");
  434. #endif
  435. LogFile.WriteToFile(ESP_LOG_DEBUG, "handler_reboot");
  436. ESP_LOGI(TAGPARTOTA, "!!! System will restart within 5 sec!!!");
  437. const char* resp_str = "<body style='font-family: arial'> <h3 id=t></h3></body><script>var h='Rebooting!<br>The page will automatically reload in around 25..60s.<br>'; document.getElementById('t').innerHTML=h; setInterval(function (){h +='.'; document.getElementById('t').innerHTML=h; fetch(window.location.hostname,{mode: 'no-cors'}).then(r=>{parent.location.href=('/index.html');})}, 1000);</script>";
  438. httpd_resp_send(req, resp_str, strlen(resp_str));
  439. doReboot();
  440. #ifdef DEBUG_DETAIL_ON
  441. LogFile.WriteHeapInfo("handler_reboot - Done");
  442. #endif
  443. return ESP_OK;
  444. }
  445. void register_server_ota_sdcard_uri(httpd_handle_t server)
  446. {
  447. ESP_LOGI(TAGPARTOTA, "server_ota - Registering URI handlers");
  448. httpd_uri_t camuri = { };
  449. camuri.method = HTTP_GET;
  450. camuri.uri = "/ota";
  451. camuri.handler = handler_ota_update;
  452. camuri.user_ctx = (void*) "Do OTA";
  453. httpd_register_uri_handler(server, &camuri);
  454. camuri.method = HTTP_GET;
  455. camuri.uri = "/reboot";
  456. camuri.handler = handler_reboot;
  457. camuri.user_ctx = (void*) "Reboot";
  458. httpd_register_uri_handler(server, &camuri);
  459. }