server_ota.cpp 18 KB

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