server_ota.cpp 14 KB

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