server_ota.cpp 24 KB

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