server_ota.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462
  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_loop.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 "ClassLogFile.h"
  26. #include "Helper.h"
  27. // #define DEBUG_DETAIL_ON
  28. #define BUFFSIZE 1024
  29. #define HASH_LEN 32 /* SHA-256 digest length */
  30. /*an ota data write buffer ready to write to the flash*/
  31. static char ota_write_data[BUFFSIZE + 1] = { 0 };
  32. #define OTA_URL_SIZE 256
  33. static void infinite_loop(void)
  34. {
  35. int i = 0;
  36. ESP_LOGI(TAGPARTOTA, "When a new firmware is available on the server, press the reset button to download it");
  37. while(1) {
  38. ESP_LOGI(TAGPARTOTA, "Waiting for a new firmware ... %d", ++i);
  39. vTaskDelay(2000 / portTICK_PERIOD_MS);
  40. }
  41. }
  42. static bool ota_example_task(std::string fn)
  43. {
  44. esp_err_t err;
  45. /* update handle : set by esp_ota_begin(), must be freed via esp_ota_end() */
  46. esp_ota_handle_t update_handle = 0 ;
  47. const esp_partition_t *update_partition = NULL;
  48. ESP_LOGI(TAGPARTOTA, "Starting OTA example");
  49. const esp_partition_t *configured = esp_ota_get_boot_partition();
  50. const esp_partition_t *running = esp_ota_get_running_partition();
  51. if (configured != running) {
  52. ESP_LOGW(TAGPARTOTA, "Configured OTA boot partition at offset 0x%08x, but running from offset 0x%08x",
  53. configured->address, running->address);
  54. ESP_LOGW(TAGPARTOTA, "(This can happen if either the OTA boot data or preferred boot image become corrupted somehow.)");
  55. }
  56. ESP_LOGI(TAGPARTOTA, "Running partition type %d subtype %d (offset 0x%08x)",
  57. running->type, running->subtype, running->address);
  58. update_partition = esp_ota_get_next_update_partition(NULL);
  59. ESP_LOGI(TAGPARTOTA, "Writing to partition subtype %d at offset 0x%x",
  60. update_partition->subtype, update_partition->address);
  61. // assert(update_partition != NULL);
  62. int binary_file_length = 0;
  63. // deal with all receive packet
  64. bool image_header_was_checked = false;
  65. int data_read;
  66. FILE* f = OpenFileAndWait(fn.c_str(), "rb"); // vorher nur "r"
  67. data_read = fread(ota_write_data, 1, BUFFSIZE, f);
  68. while (data_read > 0) {
  69. if (data_read < 0) {
  70. ESP_LOGE(TAGPARTOTA, "Error: SSL data read error");
  71. return false;
  72. } else if (data_read > 0) {
  73. if (image_header_was_checked == false) {
  74. esp_app_desc_t new_app_info;
  75. if (data_read > sizeof(esp_image_header_t) + sizeof(esp_image_segment_header_t) + sizeof(esp_app_desc_t)) {
  76. // check current version with downloading
  77. memcpy(&new_app_info, &ota_write_data[sizeof(esp_image_header_t) + sizeof(esp_image_segment_header_t)], sizeof(esp_app_desc_t));
  78. ESP_LOGI(TAGPARTOTA, "New firmware version: %s", new_app_info.version);
  79. esp_app_desc_t running_app_info;
  80. if (esp_ota_get_partition_description(running, &running_app_info) == ESP_OK) {
  81. ESP_LOGI(TAGPARTOTA, "Running firmware version: %s", running_app_info.version);
  82. }
  83. const esp_partition_t* last_invalid_app = esp_ota_get_last_invalid_partition();
  84. esp_app_desc_t invalid_app_info;
  85. if (esp_ota_get_partition_description(last_invalid_app, &invalid_app_info) == ESP_OK) {
  86. ESP_LOGI(TAGPARTOTA, "Last invalid firmware version: %s", invalid_app_info.version);
  87. }
  88. // check current version with last invalid partition
  89. if (last_invalid_app != NULL) {
  90. if (memcmp(invalid_app_info.version, new_app_info.version, sizeof(new_app_info.version)) == 0) {
  91. ESP_LOGW(TAGPARTOTA, "New version is the same as invalid version.");
  92. ESP_LOGW(TAGPARTOTA, "Previously, there was an attempt to launch the firmware with %s version, but it failed.", invalid_app_info.version);
  93. ESP_LOGW(TAGPARTOTA, "The firmware has been rolled back to the previous version.");
  94. infinite_loop();
  95. }
  96. }
  97. /*
  98. if (memcmp(new_app_info.version, running_app_info.version, sizeof(new_app_info.version)) == 0) {
  99. ESP_LOGW(TAGPARTOTA, "Current running version is the same as a new. We will not continue the update.");
  100. infinite_loop();
  101. }
  102. */
  103. image_header_was_checked = true;
  104. err = esp_ota_begin(update_partition, OTA_SIZE_UNKNOWN, &update_handle);
  105. if (err != ESP_OK) {
  106. ESP_LOGE(TAGPARTOTA, "esp_ota_begin failed (%s)", esp_err_to_name(err));
  107. return false;
  108. }
  109. ESP_LOGI(TAGPARTOTA, "esp_ota_begin succeeded");
  110. } else {
  111. ESP_LOGE(TAGPARTOTA, "received package is not fit len");
  112. return false;
  113. }
  114. }
  115. err = esp_ota_write( update_handle, (const void *)ota_write_data, data_read);
  116. if (err != ESP_OK) {
  117. return false;
  118. }
  119. binary_file_length += data_read;
  120. ESP_LOGD(TAGPARTOTA, "Written image length %d", binary_file_length);
  121. } else if (data_read == 0) {
  122. //
  123. // * As esp_http_client_read never returns negative error code, we rely on
  124. // * `errno` to check for underlying transport connectivity closure if any
  125. //
  126. if (errno == ECONNRESET || errno == ENOTCONN) {
  127. ESP_LOGE(TAGPARTOTA, "Connection closed, errno = %d", errno);
  128. break;
  129. }
  130. }
  131. data_read = fread(ota_write_data, 1, BUFFSIZE, f);
  132. }
  133. fclose(f);
  134. ESP_LOGI(TAGPARTOTA, "Total Write binary data length: %d", binary_file_length);
  135. err = esp_ota_end(update_handle);
  136. if (err != ESP_OK) {
  137. if (err == ESP_ERR_OTA_VALIDATE_FAILED) {
  138. ESP_LOGE(TAGPARTOTA, "Image validation failed, image is corrupted");
  139. }
  140. ESP_LOGE(TAGPARTOTA, "esp_ota_end failed (%s)!", esp_err_to_name(err));
  141. return false;
  142. }
  143. err = esp_ota_set_boot_partition(update_partition);
  144. if (err != ESP_OK) {
  145. ESP_LOGE(TAGPARTOTA, "esp_ota_set_boot_partition failed (%s)!", esp_err_to_name(err));
  146. }
  147. // ESP_LOGI(TAGPARTOTA, "Prepare to restart system!");
  148. // esp_restart();
  149. return true ;
  150. }
  151. static void print_sha256 (const uint8_t *image_hash, const char *label)
  152. {
  153. char hash_print[HASH_LEN * 2 + 1];
  154. hash_print[HASH_LEN * 2] = 0;
  155. for (int i = 0; i < HASH_LEN; ++i) {
  156. sprintf(&hash_print[i * 2], "%02x", image_hash[i]);
  157. }
  158. ESP_LOGI(TAGPARTOTA, "%s: %s", label, hash_print);
  159. }
  160. static bool diagnostic(void)
  161. {
  162. /*
  163. gpio_config_t io_conf;
  164. io_conf.intr_type = (gpio_int_type_t) GPIO_PIN_INTR_DISABLE;
  165. io_conf.mode = GPIO_MODE_INPUT;
  166. io_conf.pin_bit_mask = (1ULL << CONFIG_EXAMPLE_GPIO_DIAGNOSTIC);
  167. io_conf.pull_down_en = GPIO_PULLDOWN_DISABLE;
  168. io_conf.pull_up_en = GPIO_PULLUP_ENABLE;
  169. gpio_config(&io_conf);
  170. ESP_LOGI(TAGPARTOTA, "Diagnostics (5 sec)...");
  171. vTaskDelay(5000 / portTICK_PERIOD_MS);
  172. bool diagnostic_is_ok = gpio_get_level(CONFIG_EXAMPLE_GPIO_DIAGNOSTIC);
  173. gpio_reset_pin(CONFIG_EXAMPLE_GPIO_DIAGNOSTIC);
  174. return diagnostic_is_ok;
  175. */
  176. return true;
  177. }
  178. void CheckOTAUpdate(void)
  179. {
  180. ESP_LOGI(TAGPARTOTA, "Start CheckOTAUpdateCheck ...");
  181. printf("Start CheckOTAUpdateCheck ...\n");
  182. uint8_t sha_256[HASH_LEN] = { 0 };
  183. esp_partition_t partition;
  184. // get sha256 digest for the partition table
  185. partition.address = ESP_PARTITION_TABLE_OFFSET;
  186. partition.size = ESP_PARTITION_TABLE_MAX_LEN;
  187. partition.type = ESP_PARTITION_TYPE_DATA;
  188. esp_partition_get_sha256(&partition, sha_256);
  189. print_sha256(sha_256, "SHA-256 for the partition table: ");
  190. // get sha256 digest for bootloader
  191. partition.address = ESP_BOOTLOADER_OFFSET;
  192. partition.size = ESP_PARTITION_TABLE_OFFSET;
  193. partition.type = ESP_PARTITION_TYPE_APP;
  194. esp_partition_get_sha256(&partition, sha_256);
  195. print_sha256(sha_256, "SHA-256 for bootloader: ");
  196. // get sha256 digest for running partition
  197. esp_partition_get_sha256(esp_ota_get_running_partition(), sha_256);
  198. print_sha256(sha_256, "SHA-256 for current firmware: ");
  199. const esp_partition_t *running = esp_ota_get_running_partition();
  200. esp_ota_img_states_t ota_state;
  201. esp_err_t res_stat_partition = esp_ota_get_state_partition(running, &ota_state);
  202. switch (res_stat_partition)
  203. {
  204. case ESP_OK:
  205. printf("CheckOTAUpdate Partition: ESP_OK\n");
  206. if (esp_ota_get_state_partition(running, &ota_state) == ESP_OK) {
  207. if (ota_state == ESP_OTA_IMG_PENDING_VERIFY) {
  208. // run diagnostic function ...
  209. bool diagnostic_is_ok = diagnostic();
  210. if (diagnostic_is_ok) {
  211. ESP_LOGI(TAGPARTOTA, "Diagnostics completed successfully! Continuing execution ...");
  212. printf("Diagnostics completed successfully! Continuing execution ...\n");
  213. esp_ota_mark_app_valid_cancel_rollback();
  214. } else {
  215. ESP_LOGE(TAGPARTOTA, "Diagnostics failed! Start rollback to the previous version ...");
  216. printf("Diagnostics failed! Start rollback to the previous version ...\n");
  217. esp_ota_mark_app_invalid_rollback_and_reboot();
  218. }
  219. }
  220. }
  221. break;
  222. case ESP_ERR_INVALID_ARG:
  223. printf("CheckOTAUpdate Partition: ESP_ERR_INVALID_ARG\n");
  224. break;
  225. case ESP_ERR_NOT_SUPPORTED:
  226. printf("CheckOTAUpdate Partition: ESP_ERR_NOT_SUPPORTED\n");
  227. break;
  228. case ESP_ERR_NOT_FOUND:
  229. printf("CheckOTAUpdate Partition: ESP_ERR_NOT_FOUND\n");
  230. break;
  231. }
  232. if (esp_ota_get_state_partition(running, &ota_state) == ESP_OK) {
  233. if (ota_state == ESP_OTA_IMG_PENDING_VERIFY) {
  234. // run diagnostic function ...
  235. bool diagnostic_is_ok = diagnostic();
  236. if (diagnostic_is_ok) {
  237. ESP_LOGI(TAGPARTOTA, "Diagnostics completed successfully! Continuing execution ...");
  238. printf("Diagnostics completed successfully! Continuing execution ...\n");
  239. esp_ota_mark_app_valid_cancel_rollback();
  240. } else {
  241. ESP_LOGE(TAGPARTOTA, "Diagnostics failed! Start rollback to the previous version ...");
  242. printf("Diagnostics failed! Start rollback to the previous version ...\n");
  243. esp_ota_mark_app_invalid_rollback_and_reboot();
  244. }
  245. }
  246. }
  247. }
  248. esp_err_t handler_ota_update(httpd_req_t *req)
  249. {
  250. #ifdef DEBUG_DETAIL_ON
  251. LogFile.WriteHeapInfo("handler_ota_update - Start");
  252. #endif
  253. LogFile.WriteToFile("handler_ota_update");
  254. char _query[200];
  255. char _filename[30];
  256. char _valuechar[30];
  257. std::string fn = "/sdcard/firmware/";
  258. bool _file_del = false;
  259. std::string _task;
  260. if (httpd_req_get_url_query_str(req, _query, 200) == ESP_OK)
  261. {
  262. printf("Query: "); printf(_query); printf("\n");
  263. if (httpd_query_key_value(_query, "task", _valuechar, 30) == ESP_OK)
  264. {
  265. printf("task is found"); printf(_valuechar); printf("\n");
  266. _task = std::string(_valuechar);
  267. }
  268. if (httpd_query_key_value(_query, "file", _filename, 30) == ESP_OK)
  269. {
  270. fn.append(_filename);
  271. printf("File: "); printf(fn.c_str()); printf("\n");
  272. }
  273. if (httpd_query_key_value(_query, "delete", _filename, 30) == ESP_OK)
  274. {
  275. fn.append(_filename);
  276. _file_del = true;
  277. printf("Delete Default File: "); printf(fn.c_str()); printf("\n");
  278. }
  279. };
  280. if (_task.compare("unziphtml") == 0)
  281. {
  282. std::string in, out, zw;
  283. in = "/sdcard/firmware/html.zip";
  284. out = "/sdcard/html/";
  285. delete_all_in_directory(out);
  286. unzip(in, out);
  287. zw = "HTML Update Successfull!<br><br>No reboot necessary";
  288. httpd_resp_sendstr_chunk(req, zw.c_str());
  289. httpd_resp_sendstr_chunk(req, NULL);
  290. return ESP_OK;
  291. }
  292. if (_file_del)
  293. {
  294. struct stat file_stat;
  295. if (stat(fn.c_str(), &file_stat) != -1) {
  296. printf("Deleting file : %s", fn.c_str());
  297. /* Delete file */
  298. unlink(fn.c_str());
  299. }
  300. /* Respond with an empty chunk to signal HTTP response completion */
  301. httpd_resp_send_chunk(req, NULL, 0);
  302. return ESP_OK;
  303. }
  304. const char* resp_str;
  305. if (ota_example_task(fn))
  306. {
  307. resp_str = "Firmware Update Successfull!<br><br>You can restart now.";
  308. }
  309. else
  310. {
  311. resp_str = "Error during Firmware Update!!!<br><br>Please check output of console.";
  312. }
  313. httpd_resp_send(req, resp_str, strlen(resp_str));
  314. #ifdef DEBUG_DETAIL_ON
  315. LogFile.WriteHeapInfo("handler_ota_update - Done");
  316. #endif
  317. return ESP_OK;
  318. };
  319. void hard_restart() {
  320. esp_task_wdt_init(1,true);
  321. esp_task_wdt_add(NULL);
  322. while(true);
  323. }
  324. void task_reboot(void *pvParameter)
  325. {
  326. while(1)
  327. {
  328. vTaskDelay(5000 / portTICK_PERIOD_MS);
  329. esp_restart();
  330. hard_restart();
  331. }
  332. vTaskDelete(NULL); //Delete this task if it exits from the loop above
  333. }
  334. void doReboot(){
  335. LogFile.WriteToFile("Reboot - now");
  336. KillTFliteTasks();
  337. xTaskCreate(&task_reboot, "reboot", configMINIMAL_STACK_SIZE * 64, NULL, 10, NULL);
  338. vTaskDelay(5000 / portTICK_PERIOD_MS);
  339. esp_restart();
  340. hard_restart();
  341. }
  342. esp_err_t handler_reboot(httpd_req_t *req)
  343. {
  344. #ifdef DEBUG_DETAIL_ON
  345. LogFile.WriteHeapInfo("handler_reboot - Start");
  346. #endif
  347. LogFile.WriteToFile("handler_reboot");
  348. ESP_LOGI(TAGPARTOTA, "!!! System will restart within 5 sec!!!");
  349. const char* resp_str = "!!! System will restart within 5 sec!!!";
  350. httpd_resp_send(req, resp_str, strlen(resp_str));
  351. doReboot();
  352. #ifdef DEBUG_DETAIL_ON
  353. LogFile.WriteHeapInfo("handler_reboot - Done");
  354. #endif
  355. return ESP_OK;
  356. }
  357. void register_server_ota_sdcard_uri(httpd_handle_t server)
  358. {
  359. ESP_LOGI(TAGPARTOTA, "server_ota - Registering URI handlers");
  360. httpd_uri_t camuri = { };
  361. camuri.method = HTTP_GET;
  362. camuri.uri = "/ota";
  363. camuri.handler = handler_ota_update;
  364. camuri.user_ctx = (void*) "Do OTA";
  365. httpd_register_uri_handler(server, &camuri);
  366. camuri.method = HTTP_GET;
  367. camuri.uri = "/reboot";
  368. camuri.handler = handler_reboot;
  369. camuri.user_ctx = (void*) "Reboot";
  370. httpd_register_uri_handler(server, &camuri);
  371. }