server_ota.cpp 23 KB

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