server_main.cpp 15 KB

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