server_main.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600
  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. static void appendJsonStringField(std::string &json, const char *key,
  21. const std::string &value, bool &firstField)
  22. {
  23. if (!firstField)
  24. {
  25. json.push_back(',');
  26. }
  27. firstField = false;
  28. json.push_back('"');
  29. json.append(key);
  30. json.append("\":\"");
  31. for (unsigned char ch : value)
  32. {
  33. switch (ch)
  34. {
  35. case '"': json.append("\\\""); break;
  36. case '\\': json.append("\\\\"); break;
  37. case '\b': json.append("\\b"); break;
  38. case '\f': json.append("\\f"); break;
  39. case '\n': json.append("\\n"); break;
  40. case '\r': json.append("\\r"); break;
  41. case '\t': json.append("\\t"); break;
  42. default:
  43. if (ch < 0x20)
  44. {
  45. char escaped[7];
  46. snprintf(escaped, sizeof(escaped), "\\u%04x", ch);
  47. json.append(escaped);
  48. }
  49. else
  50. {
  51. json.push_back(static_cast<char>(ch));
  52. }
  53. break;
  54. }
  55. }
  56. json.push_back('"');
  57. }
  58. /* An HTTP GET handler */
  59. esp_err_t info_get_handler(httpd_req_t *req)
  60. {
  61. #ifdef DEBUG_DETAIL_ON
  62. LogFile.WriteHeapInfo("info_get_handler - Start");
  63. #endif
  64. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "info_get_handler");
  65. char _query[200];
  66. char _valuechar[30];
  67. std::string _task;
  68. if (httpd_req_get_url_query_str(req, _query, 200) != ESP_OK)
  69. {
  70. return httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, "invalid query string");
  71. }
  72. ESP_LOGD(TAG, "Query: %s", _query);
  73. if (httpd_query_key_value(_query, "type", _valuechar, 30) != ESP_OK)
  74. {
  75. return httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, "missing or invalid 'type' query parameter (too long value?)");
  76. }
  77. ESP_LOGD(TAG, "type is found: %s", _valuechar);
  78. _task = std::string(_valuechar);
  79. httpd_resp_set_hdr(req, "Access-Control-Allow-Origin", "*");
  80. if (_task.compare("GitBranch") == 0)
  81. {
  82. httpd_resp_sendstr(req, libfive_git_branch());
  83. return ESP_OK;
  84. }
  85. else if (_task.compare("GitTag") == 0)
  86. {
  87. httpd_resp_sendstr(req, libfive_git_version());
  88. return ESP_OK;
  89. }
  90. else if (_task.compare("GitRevision") == 0)
  91. {
  92. httpd_resp_sendstr(req, libfive_git_revision());
  93. return ESP_OK;
  94. }
  95. else if (_task.compare("BuildTime") == 0)
  96. {
  97. httpd_resp_sendstr(req, build_time());
  98. return ESP_OK;
  99. }
  100. else if (_task.compare("FirmwareVersion") == 0)
  101. {
  102. httpd_resp_sendstr(req, getFwVersion().c_str());
  103. return ESP_OK;
  104. }
  105. else if (_task.compare("HTMLVersion") == 0)
  106. {
  107. httpd_resp_sendstr(req, getHTMLversion().c_str());
  108. return ESP_OK;
  109. }
  110. else if (_task.compare("Hostname") == 0)
  111. {
  112. std::string zw;
  113. zw = std::string(wlan_config.hostname);
  114. httpd_resp_sendstr(req, zw.c_str());
  115. return ESP_OK;
  116. }
  117. else if (_task.compare("IP") == 0)
  118. {
  119. std::string *zw;
  120. zw = getIPAddress();
  121. httpd_resp_sendstr(req, zw->c_str());
  122. return ESP_OK;
  123. }
  124. else if (_task.compare("SSID") == 0)
  125. {
  126. std::string *zw;
  127. zw = getSSID();
  128. httpd_resp_sendstr(req, zw->c_str());
  129. return ESP_OK;
  130. }
  131. else if (_task.compare("FlowStatus") == 0)
  132. {
  133. std::string zw;
  134. zw = std::string("FlowStatus");
  135. httpd_resp_sendstr(req, zw.c_str());
  136. return ESP_OK;
  137. }
  138. else if (_task.compare("Round") == 0)
  139. {
  140. char formated[10] = "";
  141. snprintf(formated, sizeof(formated), "%d", getCountFlowRounds());
  142. httpd_resp_sendstr(req, formated);
  143. return ESP_OK;
  144. }
  145. else if (_task.compare("SDCardPartitionSize") == 0)
  146. {
  147. std::string zw;
  148. zw = getSDCardPartitionSize();
  149. httpd_resp_sendstr(req, zw.c_str());
  150. return ESP_OK;
  151. }
  152. else if (_task.compare("SDCardFreePartitionSpace") == 0)
  153. {
  154. std::string zw;
  155. zw = getSDCardFreePartitionSpace();
  156. httpd_resp_sendstr(req, zw.c_str());
  157. return ESP_OK;
  158. }
  159. else if (_task.compare("SDCardPartitionAllocationSize") == 0)
  160. {
  161. std::string zw;
  162. zw = getSDCardPartitionAllocationSize();
  163. httpd_resp_sendstr(req, zw.c_str());
  164. return ESP_OK;
  165. }
  166. else if (_task.compare("SDCardManufacturer") == 0)
  167. {
  168. std::string zw;
  169. zw = getSDCardManufacturer();
  170. httpd_resp_sendstr(req, zw.c_str());
  171. return ESP_OK;
  172. }
  173. else if (_task.compare("SDCardName") == 0)
  174. {
  175. std::string zw;
  176. zw = getSDCardName();
  177. httpd_resp_sendstr(req, zw.c_str());
  178. return ESP_OK;
  179. }
  180. else if (_task.compare("SDCardCapacity") == 0)
  181. {
  182. std::string zw;
  183. zw = getSDCardCapacity();
  184. httpd_resp_sendstr(req, zw.c_str());
  185. return ESP_OK;
  186. }
  187. else if (_task.compare("SDCardSectorSize") == 0)
  188. {
  189. std::string zw;
  190. zw = getSDCardSectorSize();
  191. httpd_resp_sendstr(req, zw.c_str());
  192. return ESP_OK;
  193. }
  194. else if (_task.compare("ChipCores") == 0)
  195. {
  196. esp_chip_info_t chipInfo;
  197. esp_chip_info(&chipInfo);
  198. httpd_resp_sendstr(req, to_string(chipInfo.cores).c_str());
  199. return ESP_OK;
  200. }
  201. else if (_task.compare("ChipRevision") == 0)
  202. {
  203. esp_chip_info_t chipInfo;
  204. esp_chip_info(&chipInfo);
  205. httpd_resp_sendstr(req, to_string(chipInfo.revision).c_str());
  206. return ESP_OK;
  207. }
  208. else if (_task.compare("ChipFeatures") == 0)
  209. {
  210. esp_chip_info_t chipInfo;
  211. esp_chip_info(&chipInfo);
  212. httpd_resp_sendstr(req, to_string(chipInfo.features).c_str());
  213. return ESP_OK;
  214. }
  215. else
  216. {
  217. char formatted[256];
  218. snprintf(formatted, sizeof(formatted), "Unknown value for parameter info 'type': '%s'\n", _task.c_str());
  219. return httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, formatted);
  220. }
  221. return ESP_OK;
  222. }
  223. esp_err_t starttime_get_handler(httpd_req_t *req)
  224. {
  225. httpd_resp_set_hdr(req, "Access-Control-Allow-Origin", "*");
  226. httpd_resp_send(req, starttime.c_str(), starttime.length());
  227. return ESP_OK;
  228. }
  229. esp_err_t hello_main_handler(httpd_req_t *req)
  230. {
  231. #ifdef DEBUG_DETAIL_ON
  232. LogFile.WriteHeapInfo("hello_main_handler - Start");
  233. #endif
  234. char filepath[50];
  235. ESP_LOGD(TAG, "uri: %s\n", req->uri);
  236. int _pos;
  237. esp_err_t res;
  238. char *base_path = (char*) req->user_ctx;
  239. std::string filetosend(base_path);
  240. const char *filename = get_path_from_uri(filepath, base_path,
  241. req->uri - 1, sizeof(filepath));
  242. ESP_LOGD(TAG, "1 uri: %s, filename: %s, filepath: %s", req->uri, filename, filepath);
  243. if ((strcmp(req->uri, "/") == 0))
  244. {
  245. {
  246. filetosend = filetosend + "/html/index.html";
  247. }
  248. }
  249. else
  250. {
  251. filetosend = filetosend + "/html" + std::string(req->uri);
  252. _pos = filetosend.find("?");
  253. if (_pos > -1){
  254. filetosend = filetosend.substr(0, _pos);
  255. }
  256. }
  257. if (filetosend == "/sdcard/html/index.html") {
  258. if (isSetSystemStatusFlag(SYSTEM_STATUS_PSRAM_BAD) || // Initialization failed with crritical errors!
  259. isSetSystemStatusFlag(SYSTEM_STATUS_CAM_BAD) ||
  260. isSetSystemStatusFlag(SYSTEM_STATUS_SDCARD_CHECK_BAD) ||
  261. isSetSystemStatusFlag(SYSTEM_STATUS_FOLDER_CHECK_BAD))
  262. {
  263. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "We have a critical error, not serving main page!");
  264. char buf[20];
  265. std::string message = "<h1>AI on the Edge Device</h1><b>We have one or more critical errors:</b><br>";
  266. for (int i = 0; i < 32; i++) {
  267. if (isSetSystemStatusFlag((SystemStatusFlag_t)(1<<i))) {
  268. snprintf(buf, sizeof(buf), "0x%08X", 1<<i);
  269. message += std::string(buf) + "<br>";
  270. }
  271. }
  272. 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!";
  273. message += "<br><br><button onclick=\"window.location.href='/reboot';\">Reboot</button>";
  274. message += "&nbsp;<button onclick=\"window.open('/ota_page.html');\">OTA Update</button>";
  275. message += "&nbsp;<button onclick=\"window.open('/log.html');\">Log Viewer</button>";
  276. message += "&nbsp;<button onclick=\"window.open('/info.html');\">Show System Info</button>";
  277. httpd_resp_send(req, message.c_str(), message.length());
  278. return ESP_OK;
  279. }
  280. else if (isSetupModusActive()) {
  281. ESP_LOGD(TAG, "System is in setup mode --> index.html --> setup.html");
  282. filetosend = "/sdcard/html/setup.html";
  283. }
  284. }
  285. ESP_LOGD(TAG, "Filename: %s", filename);
  286. ESP_LOGD(TAG, "File requested: %s", filetosend.c_str());
  287. if (!filename) {
  288. ESP_LOGE(TAG, "Filename is too long");
  289. /* Respond with 414 Error */
  290. httpd_resp_send_err(req, HTTPD_414_URI_TOO_LONG, "Filename too long");
  291. return ESP_FAIL;
  292. }
  293. res = send_file(req, filetosend); // send_file() already terminates the chunked response
  294. if (res != ESP_OK)
  295. return res;
  296. /* Respond with an empty chunk to signal HTTP response completion */
  297. // httpd_resp_sendstr(req, "");
  298. // httpd_resp_send_chunk(req, NULL, 0);
  299. #ifdef DEBUG_DETAIL_ON
  300. LogFile.WriteHeapInfo("hello_main_handler - Stop");
  301. #endif
  302. return ESP_OK;
  303. }
  304. esp_err_t img_tmp_handler(httpd_req_t *req)
  305. {
  306. char filepath[50];
  307. ESP_LOGD(TAG, "uri: %s", req->uri);
  308. char *base_path = (char*) req->user_ctx;
  309. std::string filetosend(base_path);
  310. const char *filename = get_path_from_uri(filepath, base_path,
  311. req->uri + sizeof("/img_tmp/") - 1, sizeof(filepath));
  312. ESP_LOGD(TAG, "1 uri: %s, filename: %s, filepath: %s", req->uri, filename, filepath);
  313. filetosend = filetosend + "/img_tmp/" + std::string(filename);
  314. ESP_LOGD(TAG, "File to upload: %s", filetosend.c_str());
  315. // send_file() already terminates the chunked response
  316. return send_file(req, filetosend);
  317. }
  318. esp_err_t img_tmp_virtual_handler(httpd_req_t *req)
  319. {
  320. #ifdef DEBUG_DETAIL_ON
  321. LogFile.WriteHeapInfo("img_tmp_virtual_handler - Start");
  322. #endif
  323. char filepath[50];
  324. ESP_LOGD(TAG, "uri: %s", req->uri);
  325. char *base_path = (char*) req->user_ctx;
  326. std::string filetosend(base_path);
  327. const char *filename = get_path_from_uri(filepath, base_path,
  328. req->uri + sizeof("/img_tmp/") - 1, sizeof(filepath));
  329. ESP_LOGD(TAG, "1 uri: %s, filename: %s, filepath: %s", req->uri, filename, filepath);
  330. filetosend = std::string(filename);
  331. ESP_LOGD(TAG, "File to upload: %s", filetosend.c_str());
  332. // Only the test_take URL opts into temporary preview settings.
  333. if (filetosend == "raw.jpg")
  334. {
  335. bool previewCapture = false;
  336. char query[64] = "";
  337. char preview[8] = "";
  338. if (httpd_req_get_url_query_str(req, query, sizeof(query)) == ESP_OK &&
  339. httpd_query_key_value(query, "preview", preview, sizeof(preview)) == ESP_OK)
  340. {
  341. previewCapture = (strcmp(preview, "1") == 0);
  342. }
  343. return GetRawJPG(req, previewCapture);
  344. }
  345. // Serve alg.jpg, alg_roi.jpg or digit and analog ROIs
  346. if (ESP_OK == GetJPG(filetosend, req))
  347. return ESP_OK;
  348. #ifdef DEBUG_DETAIL_ON
  349. LogFile.WriteHeapInfo("img_tmp_virtual_handler - Done");
  350. #endif
  351. // File was not served already --> serve with img_tmp_handler
  352. return img_tmp_handler(req);
  353. }
  354. esp_err_t sysinfo_handler(httpd_req_t *req)
  355. {
  356. // Collect each group once. In particular, SD partition statistics share one f_getfree()
  357. // call instead of performing three separate FATFS queries.
  358. const ESPHeapStats heap = getESPHeapStats();
  359. const SDCardDetails sdCard = getSDCardDetails();
  360. esp_chip_info_t chipInfo = {};
  361. esp_chip_info(&chipInfo);
  362. const std::string *hostnameValue = getHostname();
  363. const std::string *ipAddressValue = getIPAddress();
  364. const std::string *ssidValue = getSSID();
  365. const std::string hostname = hostnameValue ? *hostnameValue : std::string();
  366. const std::string ipAddress = ipAddressValue ? *ipAddressValue : std::string();
  367. const std::string ssid = ssidValue ? *ssidValue : std::string();
  368. std::string json;
  369. json.reserve(1400);
  370. json.append("[{");
  371. bool firstField = true;
  372. // Keep the original /sysinfo keys and array/object envelope for existing clients.
  373. appendJsonStringField(json, "firmware", libfive_git_version(), firstField);
  374. appendJsonStringField(json, "buildtime", build_time(), firstField);
  375. appendJsonStringField(json, "gitbranch", libfive_git_branch(), firstField);
  376. appendJsonStringField(json, "gittag", libfive_git_version(), firstField);
  377. appendJsonStringField(json, "gitrevision", libfive_git_revision(), firstField);
  378. appendJsonStringField(json, "html", getHTMLversion(), firstField);
  379. appendJsonStringField(json, "cputemp", std::to_string((int)temperatureRead()), firstField);
  380. appendJsonStringField(json, "hostname", hostname, firstField);
  381. appendJsonStringField(json, "IPv4", ipAddress, firstField);
  382. appendJsonStringField(json, "freeHeapMem", std::to_string((unsigned long long)heap.totalFree), firstField);
  383. // Additional fields used by info.html.
  384. appendJsonStringField(json, "starttime", starttime, firstField);
  385. appendJsonStringField(json, "uptime", getFormatedUptime(false), firstField);
  386. appendJsonStringField(json, "SSID", ssid, firstField);
  387. appendJsonStringField(json, "chipCores", std::to_string(chipInfo.cores), firstField);
  388. appendJsonStringField(json, "chipRevision", std::to_string(chipInfo.revision), firstField);
  389. appendJsonStringField(json, "chipFeatures", std::to_string(chipInfo.features), firstField);
  390. appendJsonStringField(json, "sdCardManufacturer", sdCard.manufacturer, firstField);
  391. appendJsonStringField(json, "sdCardName", sdCard.name, firstField);
  392. appendJsonStringField(json, "sdCardCapacity", sdCard.capacityMB, firstField);
  393. appendJsonStringField(json, "sdCardSectorSize", sdCard.sectorSizeBytes, firstField);
  394. appendJsonStringField(json, "sdCardPartitionSize", sdCard.partitionSizeMB, firstField);
  395. appendJsonStringField(json, "sdCardFreePartitionSpace", sdCard.partitionFreeMB, firstField);
  396. appendJsonStringField(json, "sdCardPartitionAllocationSize", sdCard.partitionAllocationSizeBytes, firstField);
  397. appendJsonStringField(json, "RAMTotalFree", std::to_string((unsigned long long)heap.totalFree), firstField);
  398. appendJsonStringField(json, "ExtRAMFree", std::to_string((unsigned long long)heap.externalFree), firstField);
  399. appendJsonStringField(json, "ExtRAMLargestFree", std::to_string((unsigned long long)heap.externalLargestFreeBlock), firstField);
  400. appendJsonStringField(json, "ExtRAMMinFree", std::to_string((unsigned long long)heap.externalMinFree), firstField);
  401. appendJsonStringField(json, "IntRAMFree", std::to_string((unsigned long long)heap.internalFree), firstField);
  402. appendJsonStringField(json, "IntRAMLargestFree", std::to_string((unsigned long long)heap.internalLargestFreeBlock), firstField);
  403. appendJsonStringField(json, "IntRAMMinFree", std::to_string((unsigned long long)heap.internalMinFree), firstField);
  404. json.append("}]");
  405. httpd_resp_set_hdr(req, "Access-Control-Allow-Origin", "*");
  406. httpd_resp_set_type(req, "application/json");
  407. return httpd_resp_send(req, json.c_str(), json.length());
  408. }
  409. void register_server_main_uri(httpd_handle_t server, const char *base_path)
  410. {
  411. httpd_uri_t info_get_handle = {
  412. .uri = "/info", // Match all URIs of type /path/to/file
  413. .method = HTTP_GET,
  414. .handler = APPLY_BASIC_AUTH_FILTER(info_get_handler),
  415. .user_ctx = (void*) base_path // Pass server data as context
  416. };
  417. httpd_register_uri_handler(server, &info_get_handle);
  418. httpd_uri_t sysinfo_handle = {
  419. .uri = "/sysinfo", // Match all URIs of type /path/to/file
  420. .method = HTTP_GET,
  421. .handler = APPLY_BASIC_AUTH_FILTER(sysinfo_handler),
  422. .user_ctx = (void*) base_path // Pass server data as context
  423. };
  424. httpd_register_uri_handler(server, &sysinfo_handle);
  425. httpd_uri_t starttime_tmp_handle = {
  426. .uri = "/starttime", // Match all URIs of type /path/to/file
  427. .method = HTTP_GET,
  428. .handler = APPLY_BASIC_AUTH_FILTER(starttime_get_handler),
  429. .user_ctx = NULL // Pass server data as context
  430. };
  431. httpd_register_uri_handler(server, &starttime_tmp_handle);
  432. httpd_uri_t img_tmp_handle = {
  433. .uri = "/img_tmp/*", // Match all URIs of type /path/to/file
  434. .method = HTTP_GET,
  435. .handler = APPLY_BASIC_AUTH_FILTER(img_tmp_virtual_handler),
  436. .user_ctx = (void*) base_path // Pass server data as context
  437. };
  438. httpd_register_uri_handler(server, &img_tmp_handle);
  439. httpd_uri_t main_rest_handle = {
  440. .uri = "/*", // Match all URIs of type /path/to/file
  441. .method = HTTP_GET,
  442. .handler = APPLY_BASIC_AUTH_FILTER(hello_main_handler),
  443. .user_ctx = (void*) base_path // Pass server data as context
  444. };
  445. httpd_register_uri_handler(server, &main_rest_handle);
  446. }
  447. httpd_handle_t start_webserver(void)
  448. {
  449. httpd_handle_t server = NULL;
  450. httpd_config_t config = HTTPD_DEFAULT_CONFIG();
  451. config.task_priority = tskIDLE_PRIORITY+5; // Tested: higher server priority improves Web-UI responsiveness under load
  452. config.stack_size = 8 * 2048; // 16 KB; tested with image and OTA requests
  453. config.core_id = 1; // previously -> 2023-01-02: 0, 2022-12-11: tskNO_AFFINITY;
  454. config.server_port = 80;
  455. config.ctrl_port = 32768;
  456. config.max_open_sockets = 5; // Conservative HTTP client limit; lwIP socket pool configured separately
  457. config.max_uri_handlers = 43; // Make sure this fits all URI handlers. Memory usage in bytes: 6*max_uri_handlers
  458. config.max_resp_headers = 8;
  459. config.backlog_conn = 5;
  460. config.lru_purge_enable = true; // this cuts old connections if new ones are needed.
  461. config.recv_wait_timeout = 5; // default: 5 20210924 --> previously 30
  462. config.send_wait_timeout = 5; // default: 5 20210924 --> previously 30
  463. config.global_user_ctx = NULL;
  464. config.global_user_ctx_free_fn = NULL;
  465. config.global_transport_ctx = NULL;
  466. config.global_transport_ctx_free_fn = NULL;
  467. config.open_fn = NULL;
  468. config.close_fn = NULL;
  469. // config.uri_match_fn = NULL;
  470. config.uri_match_fn = httpd_uri_match_wildcard;
  471. starttime = getCurrentTimeString("%Y%m%d-%H%M%S");
  472. // Start the httpd server
  473. ESP_LOGI(TAG, "Starting server on port: '%d'", config.server_port);
  474. if (httpd_start(&server, &config) == ESP_OK) {
  475. // Set URI handlers
  476. ESP_LOGI(TAG, "Registering URI handlers");
  477. return server;
  478. }
  479. ESP_LOGI(TAG, "Error starting server!");
  480. return NULL;
  481. }
  482. void stop_webserver(httpd_handle_t server)
  483. {
  484. httpd_stop(server);
  485. }
  486. void disconnect_handler(void* arg, esp_event_base_t event_base,
  487. int32_t event_id, void* event_data)
  488. {
  489. httpd_handle_t* server = (httpd_handle_t*) arg;
  490. if (*server) {
  491. ESP_LOGI(TAG, "Stopping webserver");
  492. stop_webserver(*server);
  493. *server = NULL;
  494. }
  495. }
  496. void connect_handler(void* arg, esp_event_base_t event_base,
  497. int32_t event_id, void* event_data)
  498. {
  499. httpd_handle_t* server = (httpd_handle_t*) arg;
  500. if (*server == NULL) {
  501. ESP_LOGI(TAG, "Starting webserver");
  502. *server = start_webserver();
  503. }
  504. }