server_ota.cpp 23 KB

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