server_main.cpp 15 KB

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