server_main.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486
  1. #include "defines.h"
  2. #include "server_main.h"
  3. #include <stdio.h>
  4. #include <string>
  5. #include <esp_log.h>
  6. #include <esp_chip_info.h>
  7. #include <esp_wifi.h>
  8. #include <netdb.h>
  9. #include "server_help.h"
  10. #include "ClassLogFile.h"
  11. #include "time_sntp.h"
  12. #include "connect_wifi_sta.h"
  13. #include "read_network_config.h"
  14. #include "../main/version.h"
  15. #include "MainFlowControl.h"
  16. #include "basic_auth.h"
  17. #include "Helper.h"
  18. static const char *TAG = "MAIN SERVER";
  19. std::string webserver_start_time = "";
  20. esp_err_t main_handler(httpd_req_t *req)
  21. {
  22. char filepath[50];
  23. ESP_LOGD(TAG, "uri: %s\n", req->uri);
  24. int _pos;
  25. esp_err_t res;
  26. char *base_path = (char *)req->user_ctx;
  27. std::string filetosend(base_path);
  28. const char *filename = get_path_from_uri(filepath, base_path, req->uri - 1, sizeof(filepath));
  29. ESP_LOGD(TAG, "1 uri: %s, filename: %s, filepath: %s", req->uri, filename, filepath);
  30. if ((strcmp(req->uri, "/") == 0))
  31. {
  32. filetosend = filetosend + "/html/index.html";
  33. }
  34. else
  35. {
  36. filetosend = filetosend + "/html" + std::string(req->uri);
  37. _pos = filetosend.find("?");
  38. if (_pos > -1)
  39. {
  40. filetosend = filetosend.substr(0, _pos);
  41. }
  42. }
  43. if (filetosend == "/sdcard/html/index.html")
  44. {
  45. // Initialization failed with crritical errors!
  46. if (is_set_system_statusflag(SYSTEM_STATUS_PSRAM_BAD) || is_set_system_statusflag(SYSTEM_STATUS_CAM_BAD) ||
  47. is_set_system_statusflag(SYSTEM_STATUS_SDCARD_CHECK_BAD) || is_set_system_statusflag(SYSTEM_STATUS_FOLDER_CHECK_BAD))
  48. {
  49. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "We have a critical error, not serving main page!");
  50. char buf[20];
  51. std::string message = "<h1>AI on the Edge Device</h1><b>We have one or more critical errors:</b><br>";
  52. for (int i = 0; i < 32; i++)
  53. {
  54. if (is_set_system_statusflag((SystemStatusFlag_t)(1 << i)))
  55. {
  56. snprintf(buf, sizeof(buf), "0x%08X", 1 << i);
  57. message += std::string(buf) + "<br>";
  58. }
  59. }
  60. message += "<br>Please check logs with log viewer and/or <a href=\"https://jomjol.github.io/AI-on-the-edge-device-docs/Error-Codes\" target=_blank>jomjol.github.io/AI-on-the-edge-device-docs/Error-Codes</a> for more information!";
  61. message += "<br><br><button onclick=\"window.location.href='/reboot';\">Reboot</button>";
  62. message += "&nbsp;<button onclick=\"window.open('/ota_page.html');\">OTA Update</button>";
  63. message += "&nbsp;<button onclick=\"window.open('/log.html');\">Log Viewer</button>";
  64. message += "&nbsp;<button onclick=\"window.open('/info.html');\">Show System Info</button>";
  65. httpd_resp_send(req, message.c_str(), message.length());
  66. return ESP_OK;
  67. }
  68. else if (isSetupModusActive())
  69. {
  70. ESP_LOGD(TAG, "System is in setup mode --> index.html --> setup.html");
  71. filetosend = "/sdcard/html/setup.html";
  72. }
  73. }
  74. ESP_LOGD(TAG, "Filename: %s", filename);
  75. ESP_LOGD(TAG, "File requested: %s", filetosend.c_str());
  76. if (!filename)
  77. {
  78. ESP_LOGE(TAG, "Filename is too long");
  79. /* Respond with 414 Error */
  80. httpd_resp_send_err(req, HTTPD_414_URI_TOO_LONG, "Filename too long");
  81. return ESP_FAIL;
  82. }
  83. res = send_file(req, filetosend);
  84. /* Respond with an empty chunk to signal HTTP response completion */
  85. httpd_resp_send_chunk(req, NULL, 0);
  86. if (res != ESP_OK)
  87. {
  88. return res;
  89. }
  90. return ESP_OK;
  91. }
  92. esp_err_t start_time_handler(httpd_req_t *req)
  93. {
  94. httpd_resp_set_hdr(req, "Access-Control-Allow-Origin", "*");
  95. httpd_resp_send(req, webserver_start_time.c_str(), webserver_start_time.length());
  96. return ESP_OK;
  97. }
  98. esp_err_t sysinfo_handler(httpd_req_t *req)
  99. {
  100. std::string zw;
  101. std::string cputemp = std::to_string((int)read_tempsensor());
  102. std::string gitversion = libfive_git_version();
  103. std::string buildtime = build_time();
  104. std::string gitbranch = libfive_git_branch();
  105. std::string gittag = libfive_git_version();
  106. std::string gitrevision = libfive_git_revision();
  107. std::string htmlversion = getHTMLversion();
  108. char freeheapmem[11];
  109. sprintf(freeheapmem, "%lu", (long)get_heapsize());
  110. zw = string("[{") +
  111. "\"firmware\": \"" + gitversion + "\"," +
  112. "\"buildtime\": \"" + buildtime + "\"," +
  113. "\"gitbranch\": \"" + gitbranch + "\"," +
  114. "\"gittag\": \"" + gittag + "\"," +
  115. "\"gitrevision\": \"" + gitrevision + "\"," +
  116. "\"html\": \"" + htmlversion + "\"," +
  117. "\"cputemp\": \"" + cputemp + "\"," +
  118. "\"hostname\": \"" + network_config.hostname + "\"," +
  119. "\"IPv4\": \"" + network_config.ipaddress + "\"," +
  120. "\"freeHeapMem\": \"" + freeheapmem + "\"" +
  121. "}]";
  122. httpd_resp_set_type(req, "application/json");
  123. httpd_resp_send(req, zw.c_str(), zw.length());
  124. return ESP_OK;
  125. }
  126. /* An HTTP GET handler */
  127. esp_err_t info_handler(httpd_req_t *req)
  128. {
  129. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "info_handler");
  130. char _query[200];
  131. char _valuechar[30];
  132. std::string _task;
  133. if (httpd_req_get_url_query_str(req, _query, 200) != ESP_OK)
  134. {
  135. return httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, "invalid query string");
  136. }
  137. ESP_LOGD(TAG, "Query: %s", _query);
  138. if (httpd_query_key_value(_query, "type", _valuechar, 30) != ESP_OK)
  139. {
  140. return httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, "missing or invalid 'type' query parameter (too long value?)");
  141. }
  142. ESP_LOGD(TAG, "type is found: %s", _valuechar);
  143. _task = std::string(_valuechar);
  144. httpd_resp_set_hdr(req, "Access-Control-Allow-Origin", "*");
  145. if (_task.compare("GitBranch") == 0)
  146. {
  147. httpd_resp_sendstr(req, libfive_git_branch());
  148. return ESP_OK;
  149. }
  150. else if (_task.compare("GitTag") == 0)
  151. {
  152. httpd_resp_sendstr(req, libfive_git_version());
  153. return ESP_OK;
  154. }
  155. else if (_task.compare("GitRevision") == 0)
  156. {
  157. httpd_resp_sendstr(req, libfive_git_revision());
  158. return ESP_OK;
  159. }
  160. else if (_task.compare("BuildTime") == 0)
  161. {
  162. httpd_resp_sendstr(req, build_time());
  163. return ESP_OK;
  164. }
  165. else if (_task.compare("FirmwareVersion") == 0)
  166. {
  167. httpd_resp_sendstr(req, getFwVersion().c_str());
  168. return ESP_OK;
  169. }
  170. else if (_task.compare("HTMLVersion") == 0)
  171. {
  172. httpd_resp_sendstr(req, getHTMLversion().c_str());
  173. return ESP_OK;
  174. }
  175. else if (_task.compare("Hostname") == 0)
  176. {
  177. std::string zw = std::string(network_config.hostname);
  178. httpd_resp_sendstr(req, zw.c_str());
  179. return ESP_OK;
  180. }
  181. else if (_task.compare("IP") == 0)
  182. {
  183. std::string zw = std::string(network_config.ipaddress);
  184. httpd_resp_sendstr(req, zw.c_str());
  185. return ESP_OK;
  186. }
  187. else if (_task.compare("SSID") == 0)
  188. {
  189. std::string zw = std::string(network_config.ssid);
  190. httpd_resp_sendstr(req, zw.c_str());
  191. return ESP_OK;
  192. }
  193. else if (_task.compare("FlowStatus") == 0)
  194. {
  195. std::string zw = std::string("FlowStatus");
  196. httpd_resp_sendstr(req, zw.c_str());
  197. return ESP_OK;
  198. }
  199. else if (_task.compare("Round") == 0)
  200. {
  201. char formated[10] = "";
  202. snprintf(formated, sizeof(formated), "%d", getCountFlowRounds());
  203. httpd_resp_sendstr(req, formated);
  204. return ESP_OK;
  205. }
  206. else if (_task.compare("SDCardPartitionSize") == 0)
  207. {
  208. std::string zw;
  209. zw = get_sd_card_partition_size();
  210. httpd_resp_sendstr(req, zw.c_str());
  211. return ESP_OK;
  212. }
  213. else if (_task.compare("SDCardFreePartitionSpace") == 0)
  214. {
  215. std::string zw;
  216. zw = get_sd_card_free_partition_space();
  217. httpd_resp_sendstr(req, zw.c_str());
  218. return ESP_OK;
  219. }
  220. else if (_task.compare("SDCardPartitionAllocationSize") == 0)
  221. {
  222. std::string zw;
  223. zw = get_sd_card_partition_allocation_size();
  224. httpd_resp_sendstr(req, zw.c_str());
  225. return ESP_OK;
  226. }
  227. else if (_task.compare("SDCardManufacturer") == 0)
  228. {
  229. std::string zw;
  230. zw = get_sd_card_manufacturer();
  231. httpd_resp_sendstr(req, zw.c_str());
  232. return ESP_OK;
  233. }
  234. else if (_task.compare("SDCardName") == 0)
  235. {
  236. std::string zw;
  237. zw = get_sd_card_name();
  238. httpd_resp_sendstr(req, zw.c_str());
  239. return ESP_OK;
  240. }
  241. else if (_task.compare("SDCardCapacity") == 0)
  242. {
  243. std::string zw;
  244. zw = get_sd_card_capacity();
  245. httpd_resp_sendstr(req, zw.c_str());
  246. return ESP_OK;
  247. }
  248. else if (_task.compare("SDCardSectorSize") == 0)
  249. {
  250. std::string zw;
  251. zw = get_sd_card_sector_size();
  252. httpd_resp_sendstr(req, zw.c_str());
  253. return ESP_OK;
  254. }
  255. else if (_task.compare("ChipCores") == 0)
  256. {
  257. esp_chip_info_t chipInfo;
  258. esp_chip_info(&chipInfo);
  259. httpd_resp_sendstr(req, to_string(chipInfo.cores).c_str());
  260. return ESP_OK;
  261. }
  262. else if (_task.compare("ChipRevision") == 0)
  263. {
  264. esp_chip_info_t chipInfo;
  265. esp_chip_info(&chipInfo);
  266. httpd_resp_sendstr(req, to_string(chipInfo.revision).c_str());
  267. return ESP_OK;
  268. }
  269. else if (_task.compare("ChipFeatures") == 0)
  270. {
  271. esp_chip_info_t chipInfo;
  272. esp_chip_info(&chipInfo);
  273. httpd_resp_sendstr(req, to_string(chipInfo.features).c_str());
  274. return ESP_OK;
  275. }
  276. else
  277. {
  278. char formatted[256];
  279. snprintf(formatted, sizeof(formatted), "Unknown value for parameter info 'type': '%s'\n", _task.c_str());
  280. return httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, formatted);
  281. }
  282. return ESP_OK;
  283. }
  284. esp_err_t img_tmp_handler(httpd_req_t *req)
  285. {
  286. char filepath[50];
  287. ESP_LOGD(TAG, "uri: %s", req->uri);
  288. char *base_path = (char *)req->user_ctx;
  289. std::string filetosend(base_path);
  290. const char *filename = get_path_from_uri(filepath, base_path, req->uri + sizeof("/img_tmp/") - 1, sizeof(filepath));
  291. ESP_LOGD(TAG, "1 uri: %s, filename: %s, filepath: %s", req->uri, filename, filepath);
  292. filetosend = filetosend + "/img_tmp/" + std::string(filename);
  293. ESP_LOGD(TAG, "File to upload: %s", filetosend.c_str());
  294. esp_err_t res = send_file(req, filetosend);
  295. if (res != ESP_OK)
  296. {
  297. return res;
  298. }
  299. /* Respond with an empty chunk to signal HTTP response completion */
  300. httpd_resp_send_chunk(req, NULL, 0);
  301. return ESP_OK;
  302. }
  303. esp_err_t img_tmp_virtual_handler(httpd_req_t *req)
  304. {
  305. char filepath[50];
  306. ESP_LOGD(TAG, "uri: %s", req->uri);
  307. char *base_path = (char *)req->user_ctx;
  308. std::string filetosend(base_path);
  309. const char *filename = get_path_from_uri(filepath, base_path, req->uri + sizeof("/img_tmp/") - 1, sizeof(filepath));
  310. ESP_LOGD(TAG, "1 uri: %s, filename: %s, filepath: %s", req->uri, filename, filepath);
  311. filetosend = std::string(filename);
  312. ESP_LOGD(TAG, "File to upload: %s", filetosend.c_str());
  313. // Serve raw.jpg
  314. if (filetosend == "raw.jpg")
  315. {
  316. return GetRawJPG(req);
  317. }
  318. // Serve alg.jpg, alg_roi.jpg or digit and analog ROIs
  319. if (ESP_OK == GetJPG(filetosend, req))
  320. {
  321. return ESP_OK;
  322. }
  323. // File was not served already --> serve with img_tmp_handler
  324. return img_tmp_handler(req);
  325. }
  326. esp_err_t wifi_scan_handler(httpd_req_t *req)
  327. {
  328. std::string data = string("{\n");
  329. data = data + wifi_scan_ap() + "\n";
  330. data = data + string("}");
  331. httpd_resp_set_type(req, "application/json");
  332. httpd_resp_send(req, data.c_str(), data.length());
  333. // Respond with an empty chunk to signal HTTP response completion
  334. httpd_resp_send_chunk(req, NULL, 0);
  335. return ESP_OK;
  336. }
  337. httpd_handle_t start_webserver(void)
  338. {
  339. httpd_handle_t my_webserver_httpd_handle = NULL;
  340. httpd_config_t my_webserver_httpd_config = HTTPD_DEFAULT_CONFIG();
  341. my_webserver_httpd_config.task_priority = tskIDLE_PRIORITY + 3; // previously -> 2022-12-11: tskIDLE_PRIORITY+1; 2021-09-24: tskIDLE_PRIORITY+5
  342. my_webserver_httpd_config.stack_size = 12288; // previously -> 2023-01-02: 32768
  343. my_webserver_httpd_config.core_id = 1; // previously -> 2023-01-02: 0, 2022-12-11: tskNO_AFFINITY;
  344. my_webserver_httpd_config.server_port = 80;
  345. my_webserver_httpd_config.ctrl_port = 32768;
  346. my_webserver_httpd_config.max_open_sockets = 5; // 20210921 --> previously 7
  347. my_webserver_httpd_config.max_uri_handlers = 42; // Make sure this fits all URI handlers. Memory usage in bytes: 6*max_uri_handlers
  348. my_webserver_httpd_config.max_resp_headers = 8;
  349. my_webserver_httpd_config.backlog_conn = 5;
  350. my_webserver_httpd_config.lru_purge_enable = true; // this cuts old connections if new ones are needed.
  351. my_webserver_httpd_config.recv_wait_timeout = 5; // default: 5 20210924 --> previously 30
  352. my_webserver_httpd_config.send_wait_timeout = 5; // default: 5 20210924 --> previously 30
  353. my_webserver_httpd_config.global_user_ctx = NULL;
  354. my_webserver_httpd_config.global_user_ctx_free_fn = NULL;
  355. my_webserver_httpd_config.global_transport_ctx = NULL;
  356. my_webserver_httpd_config.global_transport_ctx_free_fn = NULL;
  357. my_webserver_httpd_config.open_fn = NULL;
  358. my_webserver_httpd_config.close_fn = NULL;
  359. // my_webserver_httpd_config.uri_match_fn = NULL;
  360. my_webserver_httpd_config.uri_match_fn = httpd_uri_match_wildcard;
  361. webserver_start_time = getCurrentTimeString("%Y%m%d-%H%M%S");
  362. // Start the httpd server
  363. ESP_LOGI(TAG, "Starting server on port: '%d'", my_webserver_httpd_config.server_port);
  364. if (httpd_start(&my_webserver_httpd_handle, &my_webserver_httpd_config) == ESP_OK)
  365. {
  366. // Set URI handlers
  367. ESP_LOGI(TAG, "Registering URI handlers");
  368. return my_webserver_httpd_handle;
  369. }
  370. ESP_LOGI(TAG, "Error starting server!");
  371. return NULL;
  372. }
  373. void stop_webserver(httpd_handle_t server)
  374. {
  375. httpd_stop(server);
  376. }
  377. void webserver_register_uri(httpd_handle_t server, const char *base_path)
  378. {
  379. httpd_uri_t info_handle = {
  380. .uri = "/info", // Match all URIs of type /path/to/file
  381. .method = HTTP_GET,
  382. .handler = APPLY_BASIC_AUTH_FILTER(info_handler),
  383. .user_ctx = (void *)base_path // Pass server data as context
  384. };
  385. httpd_register_uri_handler(server, &info_handle);
  386. httpd_uri_t sysinfo_handle = {
  387. .uri = "/sysinfo", // Match all URIs of type /path/to/file
  388. .method = HTTP_GET,
  389. .handler = APPLY_BASIC_AUTH_FILTER(sysinfo_handler),
  390. .user_ctx = (void *)base_path // Pass server data as context
  391. };
  392. httpd_register_uri_handler(server, &sysinfo_handle);
  393. httpd_uri_t wifi_scan_handle = {
  394. .uri = "/wifiscan", // Match all URIs of type /path/to/file
  395. .method = HTTP_GET,
  396. .handler = APPLY_BASIC_AUTH_FILTER(wifi_scan_handler),
  397. .user_ctx = (void *)base_path // Pass server data as context
  398. };
  399. httpd_register_uri_handler(server, &wifi_scan_handle);
  400. httpd_uri_t start_time_handle = {
  401. .uri = "/starttime", // Match all URIs of type /path/to/file
  402. .method = HTTP_GET,
  403. .handler = APPLY_BASIC_AUTH_FILTER(start_time_handler),
  404. .user_ctx = NULL // Pass server data as context
  405. };
  406. httpd_register_uri_handler(server, &start_time_handle);
  407. httpd_uri_t img_tmp_handle = {
  408. .uri = "/img_tmp/*", // Match all URIs of type /path/to/file
  409. .method = HTTP_GET,
  410. .handler = APPLY_BASIC_AUTH_FILTER(img_tmp_virtual_handler),
  411. .user_ctx = (void *)base_path // Pass server data as context
  412. };
  413. httpd_register_uri_handler(server, &img_tmp_handle);
  414. httpd_uri_t main_rest_handle = {
  415. .uri = "/*", // Match all URIs of type /path/to/file
  416. .method = HTTP_GET,
  417. .handler = APPLY_BASIC_AUTH_FILTER(main_handler),
  418. .user_ctx = (void *)base_path // Pass server data as context
  419. };
  420. httpd_register_uri_handler(server, &main_rest_handle);
  421. }