server_main.cpp 16 KB

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