server_ota.cpp 18 KB

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