server_main.cpp 15 KB

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