server_main.cpp 16 KB

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