server_main.cpp 16 KB

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