server_ota.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686
  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. #ifdef ENABLE_MQTT
  27. #include "interface_mqtt.h"
  28. #endif //ENABLE_MQTT
  29. #include "ClassControllCamera.h"
  30. #include "connect_wlan.h"
  31. #include "ClassLogFile.h"
  32. #include "Helper.h"
  33. #include "../../include/defines.h"
  34. /*an ota data write buffer ready to write to the flash*/
  35. static char ota_write_data[SERVER_OTA_SCRATCH_BUFSIZE + 1] = { 0 };
  36. static const char *TAG = "OTA";
  37. esp_err_t handler_reboot(httpd_req_t *req);
  38. static bool ota_update_task(std::string fn);
  39. std::string _file_name_update;
  40. bool initial_setup = false;
  41. static void infinite_loop(void)
  42. {
  43. int i = 0;
  44. ESP_LOGI(TAG, "When a new firmware is available on the server, press the reset button to download it");
  45. while(1) {
  46. ESP_LOGI(TAG, "Waiting for a new firmware... %d", ++i);
  47. vTaskDelay(1000 / portTICK_PERIOD_MS);
  48. }
  49. }
  50. void task_do_Update_ZIP(void *pvParameter)
  51. {
  52. std::string filetype = toUpper(getFileType(_file_name_update));
  53. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "File: " + _file_name_update + " Filetype: " + filetype);
  54. if (filetype == "ZIP")
  55. {
  56. std::string in, out, outbin, zw, retfirmware;
  57. out = "/sdcard/html";
  58. outbin = "/sdcard/firmware";
  59. retfirmware = unzip_new(_file_name_update, out+"/", outbin+"/", "/sdcard/", initial_setup);
  60. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Files unzipped.");
  61. if (retfirmware.length() > 0)
  62. {
  63. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Found firmware.bin");
  64. ota_update_task(retfirmware);
  65. }
  66. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Trigger reboot due to firmware update.");
  67. doRebootOTA();
  68. } else if (filetype == "BIN")
  69. {
  70. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Do firmware update - file: " + _file_name_update);
  71. ota_update_task(_file_name_update);
  72. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Trigger reboot due to firmware update.");
  73. doRebootOTA();
  74. }
  75. else
  76. {
  77. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Only ZIP-Files support for update during startup!");
  78. }
  79. }
  80. void CheckUpdate()
  81. {
  82. FILE *pfile;
  83. if ((pfile = fopen("/sdcard/update.txt", "r")) == NULL)
  84. {
  85. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "No update triggered.");
  86. return;
  87. }
  88. char zw[1024] = "";
  89. fgets(zw, 1024, pfile);
  90. _file_name_update = std::string(zw);
  91. if (fgets(zw, 1024, pfile))
  92. {
  93. std::string _szw = std::string(zw);
  94. if (_szw == "init")
  95. {
  96. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Inital Setup triggered.");
  97. initial_setup = true; }
  98. }
  99. fclose(pfile);
  100. DeleteFile("/sdcard/update.txt"); // Prevent Boot Loop!!!
  101. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Update during boot triggered - Update File: " + _file_name_update);
  102. xTaskCreate(&task_do_Update_ZIP, "task_do_Update_ZIP", configMINIMAL_STACK_SIZE * 35, NULL, tskIDLE_PRIORITY+1, NULL);
  103. while(1) { // wait until reboot within task_do_Update_ZIP
  104. vTaskDelay(1000 / portTICK_PERIOD_MS);
  105. }
  106. }
  107. static bool ota_update_task(std::string fn)
  108. {
  109. esp_err_t err;
  110. /* update handle : set by esp_ota_begin(), must be freed via esp_ota_end() */
  111. esp_ota_handle_t update_handle = 0 ;
  112. const esp_partition_t *update_partition = NULL;
  113. ESP_LOGI(TAG, "Starting OTA update");
  114. const esp_partition_t *configured = esp_ota_get_boot_partition();
  115. const esp_partition_t *running = esp_ota_get_running_partition();
  116. if (configured != running) {
  117. ESP_LOGW(TAG, "Configured OTA boot partition at offset 0x%08x, but running from offset 0x%08x",
  118. configured->address, running->address);
  119. ESP_LOGW(TAG, "(This can happen if either the OTA boot data or preferred boot image become somehow corrupted.)");
  120. }
  121. ESP_LOGI(TAG, "Running partition type %d subtype %d (offset 0x%08x)",
  122. running->type, running->subtype, running->address);
  123. update_partition = esp_ota_get_next_update_partition(NULL);
  124. ESP_LOGI(TAG, "Writing to partition subtype %d at offset 0x%x",
  125. update_partition->subtype, update_partition->address);
  126. // assert(update_partition != NULL);
  127. int binary_file_length = 0;
  128. // deal with all receive packet
  129. bool image_header_was_checked = false;
  130. int data_read;
  131. FILE* f = fopen(fn.c_str(), "rb"); // previously only "r
  132. if (f == NULL) { // File does not exist
  133. return false;
  134. }
  135. data_read = fread(ota_write_data, 1, SERVER_OTA_SCRATCH_BUFSIZE, f);
  136. while (data_read > 0) {
  137. if (data_read < 0) {
  138. ESP_LOGE(TAG, "Error: SSL data read error");
  139. return false;
  140. } else if (data_read > 0) {
  141. if (image_header_was_checked == false) {
  142. esp_app_desc_t new_app_info;
  143. if (data_read > sizeof(esp_image_header_t) + sizeof(esp_image_segment_header_t) + sizeof(esp_app_desc_t)) {
  144. // check current version with downloading
  145. memcpy(&new_app_info, &ota_write_data[sizeof(esp_image_header_t) + sizeof(esp_image_segment_header_t)], sizeof(esp_app_desc_t));
  146. ESP_LOGI(TAG, "New firmware version: %s", new_app_info.version);
  147. esp_app_desc_t running_app_info;
  148. if (esp_ota_get_partition_description(running, &running_app_info) == ESP_OK) {
  149. ESP_LOGI(TAG, "Running firmware version: %s", running_app_info.version);
  150. }
  151. const esp_partition_t* last_invalid_app = esp_ota_get_last_invalid_partition();
  152. esp_app_desc_t invalid_app_info;
  153. if (esp_ota_get_partition_description(last_invalid_app, &invalid_app_info) == ESP_OK) {
  154. ESP_LOGI(TAG, "Last invalid firmware version: %s", invalid_app_info.version);
  155. }
  156. // check current version with last invalid partition
  157. if (last_invalid_app != NULL) {
  158. if (memcmp(invalid_app_info.version, new_app_info.version, sizeof(new_app_info.version)) == 0) {
  159. ESP_LOGW(TAG, "New version is the same as invalid version.");
  160. ESP_LOGW(TAG, "Previously, there was an attempt to launch the firmware with %s version, but it failed.", invalid_app_info.version);
  161. ESP_LOGW(TAG, "The firmware has been rolled back to the previous version.");
  162. infinite_loop();
  163. }
  164. }
  165. /*
  166. if (memcmp(new_app_info.version, running_app_info.version, sizeof(new_app_info.version)) == 0) {
  167. ESP_LOGW(TAG, "Current running version is the same as a new. We will not continue the update.");
  168. infinite_loop();
  169. }
  170. */
  171. image_header_was_checked = true;
  172. err = esp_ota_begin(update_partition, OTA_SIZE_UNKNOWN, &update_handle);
  173. if (err != ESP_OK) {
  174. ESP_LOGE(TAG, "esp_ota_begin failed (%s)", esp_err_to_name(err));
  175. return false;
  176. }
  177. ESP_LOGI(TAG, "esp_ota_begin succeeded");
  178. } else {
  179. ESP_LOGE(TAG, "received package is not fit len");
  180. return false;
  181. }
  182. }
  183. err = esp_ota_write( update_handle, (const void *)ota_write_data, data_read);
  184. if (err != ESP_OK) {
  185. return false;
  186. }
  187. binary_file_length += data_read;
  188. ESP_LOGD(TAG, "Written image length %d", binary_file_length);
  189. } else if (data_read == 0) {
  190. //
  191. // * As esp_http_client_read never returns negative error code, we rely on
  192. // * `errno` to check for underlying transport connectivity closure if any
  193. //
  194. if (errno == ECONNRESET || errno == ENOTCONN) {
  195. ESP_LOGE(TAG, "Connection closed, errno = %d", errno);
  196. break;
  197. }
  198. }
  199. data_read = fread(ota_write_data, 1, SERVER_OTA_SCRATCH_BUFSIZE, f);
  200. }
  201. fclose(f);
  202. ESP_LOGI(TAG, "Total Write binary data length: %d", binary_file_length);
  203. err = esp_ota_end(update_handle);
  204. if (err != ESP_OK) {
  205. if (err == ESP_ERR_OTA_VALIDATE_FAILED) {
  206. ESP_LOGE(TAG, "Image validation failed, image is corrupted");
  207. }
  208. ESP_LOGE(TAG, "esp_ota_end failed (%s)!", esp_err_to_name(err));
  209. return false;
  210. }
  211. err = esp_ota_set_boot_partition(update_partition);
  212. if (err != ESP_OK) {
  213. ESP_LOGE(TAG, "esp_ota_set_boot_partition failed (%s)!", esp_err_to_name(err));
  214. }
  215. // ESP_LOGI(TAG, "Prepare to restart system!");
  216. // esp_restart();
  217. return true ;
  218. }
  219. static void print_sha256 (const uint8_t *image_hash, const char *label)
  220. {
  221. char hash_print[HASH_LEN * 2 + 1];
  222. hash_print[HASH_LEN * 2] = 0;
  223. for (int i = 0; i < HASH_LEN; ++i) {
  224. sprintf(&hash_print[i * 2], "%02x", image_hash[i]);
  225. }
  226. ESP_LOGI(TAG, "%s: %s", label, hash_print);
  227. }
  228. static bool diagnostic(void)
  229. {
  230. return true;
  231. }
  232. void CheckOTAUpdate(void)
  233. {
  234. ESP_LOGI(TAG, "Start CheckOTAUpdateCheck...");
  235. uint8_t sha_256[HASH_LEN] = { 0 };
  236. esp_partition_t partition;
  237. // get sha256 digest for the partition table
  238. partition.address = ESP_PARTITION_TABLE_OFFSET;
  239. partition.size = ESP_PARTITION_TABLE_MAX_LEN;
  240. partition.type = ESP_PARTITION_TYPE_DATA;
  241. esp_partition_get_sha256(&partition, sha_256);
  242. print_sha256(sha_256, "SHA-256 for the partition table: ");
  243. // get sha256 digest for bootloader
  244. partition.address = ESP_BOOTLOADER_OFFSET;
  245. partition.size = ESP_PARTITION_TABLE_OFFSET;
  246. partition.type = ESP_PARTITION_TYPE_APP;
  247. esp_partition_get_sha256(&partition, sha_256);
  248. print_sha256(sha_256, "SHA-256 for bootloader: ");
  249. // get sha256 digest for running partition
  250. esp_partition_get_sha256(esp_ota_get_running_partition(), sha_256);
  251. print_sha256(sha_256, "SHA-256 for current firmware: ");
  252. const esp_partition_t *running = esp_ota_get_running_partition();
  253. esp_ota_img_states_t ota_state;
  254. esp_err_t res_stat_partition = esp_ota_get_state_partition(running, &ota_state);
  255. switch (res_stat_partition)
  256. {
  257. case ESP_OK:
  258. ESP_LOGD(TAG, "CheckOTAUpdate Partition: ESP_OK");
  259. if (esp_ota_get_state_partition(running, &ota_state) == ESP_OK) {
  260. if (ota_state == ESP_OTA_IMG_PENDING_VERIFY) {
  261. // run diagnostic function ...
  262. bool diagnostic_is_ok = diagnostic();
  263. if (diagnostic_is_ok) {
  264. ESP_LOGI(TAG, "Diagnostics completed successfully! Continuing execution...");
  265. esp_ota_mark_app_valid_cancel_rollback();
  266. } else {
  267. ESP_LOGE(TAG, "Diagnostics failed! Start rollback to the previous version...");
  268. esp_ota_mark_app_invalid_rollback_and_reboot();
  269. }
  270. }
  271. }
  272. break;
  273. case ESP_ERR_INVALID_ARG:
  274. ESP_LOGD(TAG, "CheckOTAUpdate Partition: ESP_ERR_INVALID_ARG");
  275. break;
  276. case ESP_ERR_NOT_SUPPORTED:
  277. ESP_LOGD(TAG, "CheckOTAUpdate Partition: ESP_ERR_NOT_SUPPORTED");
  278. break;
  279. case ESP_ERR_NOT_FOUND:
  280. ESP_LOGD(TAG, "CheckOTAUpdate Partition: ESP_ERR_NOT_FOUND");
  281. break;
  282. }
  283. if (esp_ota_get_state_partition(running, &ota_state) == ESP_OK) {
  284. if (ota_state == ESP_OTA_IMG_PENDING_VERIFY) {
  285. // run diagnostic function ...
  286. bool diagnostic_is_ok = diagnostic();
  287. if (diagnostic_is_ok) {
  288. ESP_LOGI(TAG, "Diagnostics completed successfully! Continuing execution...");
  289. esp_ota_mark_app_valid_cancel_rollback();
  290. } else {
  291. ESP_LOGE(TAG, "Diagnostics failed! Start rollback to the previous version...");
  292. esp_ota_mark_app_invalid_rollback_and_reboot();
  293. }
  294. }
  295. }
  296. }
  297. esp_err_t handler_ota_update(httpd_req_t *req)
  298. {
  299. #ifdef DEBUG_DETAIL_ON
  300. LogFile.WriteHeapInfo("handler_ota_update - Start");
  301. #endif
  302. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "handler_ota_update");
  303. char _query[200];
  304. char _filename[100];
  305. char _valuechar[30];
  306. std::string fn = "/sdcard/firmware/";
  307. bool _file_del = false;
  308. std::string _task = "";
  309. if (httpd_req_get_url_query_str(req, _query, 200) == ESP_OK)
  310. {
  311. ESP_LOGD(TAG, "Query: %s", _query);
  312. if (httpd_query_key_value(_query, "task", _valuechar, 30) == ESP_OK)
  313. {
  314. ESP_LOGD(TAG, "task is found: %s", _valuechar);
  315. _task = std::string(_valuechar);
  316. }
  317. if (httpd_query_key_value(_query, "file", _filename, 100) == ESP_OK)
  318. {
  319. fn.append(_filename);
  320. ESP_LOGD(TAG, "File: %s", fn.c_str());
  321. }
  322. if (httpd_query_key_value(_query, "delete", _filename, 100) == ESP_OK)
  323. {
  324. fn.append(_filename);
  325. _file_del = true;
  326. ESP_LOGD(TAG, "Delete Default File: %s", fn.c_str());
  327. }
  328. }
  329. if (_task.compare("emptyfirmwaredir") == 0)
  330. {
  331. ESP_LOGD(TAG, "Start empty directory /firmware");
  332. delete_all_in_directory("/sdcard/firmware");
  333. std::string zw = "firmware directory deleted - v2\n";
  334. ESP_LOGD(TAG, "%s", zw.c_str());
  335. printf("Ausgabe: %s\n", zw.c_str());
  336. httpd_resp_set_hdr(req, "Access-Control-Allow-Origin", "*");
  337. httpd_resp_send(req, zw.c_str(), strlen(zw.c_str()));
  338. /* Respond with an empty chunk to signal HTTP response completion */
  339. httpd_resp_send_chunk(req, NULL, 0);
  340. ESP_LOGD(TAG, "Done empty directory /firmware");
  341. return ESP_OK;
  342. }
  343. if (_task.compare("update") == 0)
  344. {
  345. std::string filetype = toUpper(getFileType(fn));
  346. if (filetype.length() == 0)
  347. {
  348. std::string zw = "Update failed - no file specified (zip, bin, tfl, tlite)";
  349. httpd_resp_sendstr_chunk(req, zw.c_str());
  350. httpd_resp_sendstr_chunk(req, NULL);
  351. return ESP_OK;
  352. }
  353. if ((filetype == "TFLITE") || (filetype == "TFL"))
  354. {
  355. std::string out = "/sdcard/config/" + getFileFullFileName(fn);
  356. DeleteFile(out);
  357. CopyFile(fn, out);
  358. DeleteFile(fn);
  359. const char* resp_str = "Neural Network File copied.";
  360. httpd_resp_sendstr_chunk(req, resp_str);
  361. httpd_resp_sendstr_chunk(req, NULL);
  362. return ESP_OK;
  363. }
  364. if ((filetype == "ZIP") || (filetype == "BIN"))
  365. {
  366. FILE *pfile;
  367. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Update for reboot.");
  368. pfile = fopen("/sdcard/update.txt", "w");
  369. fwrite(fn.c_str(), fn.length(), 1, pfile);
  370. fclose(pfile);
  371. std::string zw = "reboot\n";
  372. httpd_resp_sendstr_chunk(req, zw.c_str());
  373. httpd_resp_sendstr_chunk(req, NULL);
  374. ESP_LOGD(TAG, "Send reboot");
  375. return ESP_OK;
  376. }
  377. /*
  378. if (filetype == "BIN")
  379. {
  380. const char* resp_str;
  381. KillTFliteTasks();
  382. gpio_handler_deinit();
  383. if (ota_update_task(fn))
  384. {
  385. std::string zw = "reboot\n";
  386. httpd_resp_sendstr_chunk(req, zw.c_str());
  387. httpd_resp_sendstr_chunk(req, NULL);
  388. ESP_LOGD(TAG, "Send reboot");
  389. return ESP_OK;
  390. }
  391. resp_str = "Error during Firmware Update!!!\nPlease check output of console.";
  392. httpd_resp_send(req, resp_str, strlen(resp_str));
  393. #ifdef DEBUG_DETAIL_ON
  394. LogFile.WriteHeapInfo("handler_ota_update - Done");
  395. #endif
  396. return ESP_OK;
  397. }
  398. */
  399. std::string zw = "Update failed - no valid file specified (zip, bin, tfl, tlite)!";
  400. httpd_resp_sendstr_chunk(req, zw.c_str());
  401. httpd_resp_sendstr_chunk(req, NULL);
  402. return ESP_OK;
  403. }
  404. if (_task.compare("unziphtml") == 0)
  405. {
  406. ESP_LOGD(TAG, "Task unziphtml");
  407. std::string in, out, zw;
  408. in = "/sdcard/firmware/html.zip";
  409. out = "/sdcard/html";
  410. delete_all_in_directory(out);
  411. unzip(in, out+"/");
  412. zw = "Web Interface Update Successfull!\nNo reboot necessary";
  413. httpd_resp_send(req, zw.c_str(), strlen(zw.c_str()));
  414. httpd_resp_sendstr_chunk(req, NULL);
  415. return ESP_OK;
  416. }
  417. if (_file_del)
  418. {
  419. ESP_LOGD(TAG, "Delete !! _file_del: %s", fn.c_str());
  420. struct stat file_stat;
  421. int _result = stat(fn.c_str(), &file_stat);
  422. ESP_LOGD(TAG, "Ergebnis %d\n", _result);
  423. if (_result == 0) {
  424. ESP_LOGD(TAG, "Deleting file: %s", fn.c_str());
  425. /* Delete file */
  426. unlink(fn.c_str());
  427. }
  428. else
  429. {
  430. ESP_LOGD(TAG, "File does not exist: %s", fn.c_str());
  431. }
  432. /* Respond with an empty chunk to signal HTTP response completion */
  433. std::string zw = "file deleted\n";
  434. ESP_LOGD(TAG, "%s", zw.c_str());
  435. httpd_resp_send(req, zw.c_str(), strlen(zw.c_str()));
  436. httpd_resp_send_chunk(req, NULL, 0);
  437. return ESP_OK;
  438. }
  439. string zw = "ota without parameter - should not be the case!";
  440. httpd_resp_set_hdr(req, "Access-Control-Allow-Origin", "*");
  441. httpd_resp_send(req, zw.c_str(), strlen(zw.c_str()));
  442. httpd_resp_send_chunk(req, NULL, 0);
  443. ESP_LOGE(TAG, "ota without parameter - should not be the case!");
  444. /*
  445. const char* resp_str;
  446. KillTFliteTasks();
  447. gpio_handler_deinit();
  448. if (ota_update_task(fn))
  449. {
  450. resp_str = "Firmware Update Successfull! You can restart now.";
  451. }
  452. else
  453. {
  454. resp_str = "Error during Firmware Update!!! Please check console output.";
  455. }
  456. httpd_resp_send(req, resp_str, strlen(resp_str));
  457. */
  458. #ifdef DEBUG_DETAIL_ON
  459. LogFile.WriteHeapInfo("handler_ota_update - Done");
  460. #endif
  461. return ESP_OK;
  462. }
  463. void hard_restart()
  464. {
  465. esp_task_wdt_init(1,true);
  466. esp_task_wdt_add(NULL);
  467. while(true);
  468. }
  469. void task_reboot(void *KillAutoFlow)
  470. {
  471. // write a reboot, to identify a reboot by purpouse
  472. FILE* pfile = fopen("/sdcard/reboot.txt", "w");
  473. std::string _s_zw= "reboot";
  474. fwrite(_s_zw.c_str(), strlen(_s_zw.c_str()), 1, pfile);
  475. fclose(pfile);
  476. vTaskDelay(3000 / portTICK_PERIOD_MS);
  477. if ((bool)KillAutoFlow) {
  478. KillTFliteTasks(); // Kill autoflow task if executed in extra task, if not don't kill parent task
  479. }
  480. /* Stop service tasks */
  481. #ifdef ENABLE_MQTT
  482. MQTTdestroy_client(true);
  483. #endif //ENABLE_MQTT
  484. gpio_handler_destroy();
  485. esp_camera_deinit();
  486. WIFIDestroy();
  487. vTaskDelay(3000 / portTICK_PERIOD_MS);
  488. esp_restart(); // Reset type: CPU reset (Reset both CPUs)
  489. vTaskDelay(5000 / portTICK_PERIOD_MS);
  490. hard_restart(); // Reset type: System reset (Triggered by watchdog), if esp_restart stalls (WDT needs to be activated)
  491. ESP_LOGE(TAG, "Reboot failed!");
  492. vTaskDelete(NULL); //Delete this task if it comes to this point
  493. }
  494. void doReboot()
  495. {
  496. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Reboot triggered by Software (5s).");
  497. LogFile.WriteToFile(ESP_LOG_WARN, TAG, "Reboot in 5sec");
  498. BaseType_t xReturned = xTaskCreate(&task_reboot, "task_reboot", configMINIMAL_STACK_SIZE * 3, (void*) true, 10, NULL);
  499. if( xReturned != pdPASS )
  500. {
  501. ESP_LOGE(TAG, "task_reboot not created -> force reboot without killing flow");
  502. task_reboot((void*) false);
  503. }
  504. vTaskDelay(10000 / portTICK_PERIOD_MS); // Prevent serving web client fetch response until system is shuting down
  505. }
  506. void doRebootOTA()
  507. {
  508. LogFile.WriteToFile(ESP_LOG_WARN, TAG, "Reboot in 5sec");
  509. esp_camera_deinit();
  510. vTaskDelay(5000 / portTICK_PERIOD_MS);
  511. esp_restart(); // Reset type: CPU reset (Reset both CPUs)
  512. vTaskDelay(5000 / portTICK_PERIOD_MS);
  513. hard_restart(); // Reset type: System reset (Triggered by watchdog), if esp_restart stalls (WDT needs to be activated)
  514. }
  515. esp_err_t handler_reboot(httpd_req_t *req)
  516. {
  517. #ifdef DEBUG_DETAIL_ON
  518. LogFile.WriteHeapInfo("handler_reboot - Start");
  519. #endif
  520. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "handler_reboot");
  521. ESP_LOGI(TAG, "!!! System will restart within 5 sec!!!");
  522. std::string response =
  523. "<html><head><script>"
  524. "function m(h) {"
  525. "document.getElementById('t').innerHTML=h;"
  526. "setInterval(function (){h +='.'; document.getElementById('t').innerHTML=h;"
  527. "fetch('reboot_page.html',{mode: 'no-cors'}).then(r=>{parent.location.href=('index.html');})}, 1000);"
  528. "}</script></head></html><body style='font-family: arial'><h3 id=t></h3>"
  529. "<script>m('Rebooting!<br>The page will automatically reload in around 25..60s.<br><br>');</script>"
  530. "</body></html>";
  531. httpd_resp_set_hdr(req, "Access-Control-Allow-Origin", "*");
  532. httpd_resp_send(req, response.c_str(), strlen(response.c_str()));
  533. doReboot();
  534. #ifdef DEBUG_DETAIL_ON
  535. LogFile.WriteHeapInfo("handler_reboot - Done");
  536. #endif
  537. return ESP_OK;
  538. }
  539. void register_server_ota_sdcard_uri(httpd_handle_t server)
  540. {
  541. ESP_LOGI(TAG, "Registering URI handlers");
  542. httpd_uri_t camuri = { };
  543. camuri.method = HTTP_GET;
  544. camuri.uri = "/ota";
  545. camuri.handler = handler_ota_update;
  546. camuri.user_ctx = (void*) "Do OTA";
  547. httpd_register_uri_handler(server, &camuri);
  548. camuri.method = HTTP_GET;
  549. camuri.uri = "/reboot";
  550. camuri.handler = handler_reboot;
  551. camuri.user_ctx = (void*) "Reboot";
  552. httpd_register_uri_handler(server, &camuri);
  553. }