server_ota.cpp 25 KB

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