server_ota.cpp 24 KB

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