server_main.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789
  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 <cstring>
  17. #include "Helper.h"
  18. httpd_handle_t server = NULL;
  19. std::string starttime = "";
  20. static const char *TAG = "MAIN SERVER";
  21. // Writes JSON in small chunks so a complete response buffer is never allocated.
  22. class JsonChunkWriter
  23. {
  24. public:
  25. explicit JsonChunkWriter(httpd_req_t *request)
  26. : req(request), used(0), error(ESP_OK)
  27. {
  28. }
  29. void appendLiteral(const char *text)
  30. {
  31. if (error != ESP_OK || text == nullptr)
  32. {
  33. return;
  34. }
  35. appendBytes(text, strlen(text));
  36. }
  37. void appendStringField(const char *key, const char *value, bool &firstField)
  38. {
  39. appendFieldPrefix(key, firstField);
  40. appendLiteral("\"");
  41. appendEscapedString(value);
  42. appendLiteral("\"");
  43. }
  44. void appendNumberField(const char *key, unsigned long long value, bool &firstField)
  45. {
  46. appendFieldPrefix(key, firstField);
  47. appendUnsignedDecimal(value);
  48. }
  49. void appendUnsignedStringField(const char *key, unsigned long long value, bool &firstField)
  50. {
  51. appendFieldPrefix(key, firstField);
  52. appendLiteral("\"");
  53. appendUnsignedDecimal(value);
  54. appendLiteral("\"");
  55. }
  56. void appendNullField(const char *key, bool &firstField)
  57. {
  58. appendFieldPrefix(key, firstField);
  59. appendLiteral("null");
  60. }
  61. esp_err_t finish()
  62. {
  63. if (error != ESP_OK)
  64. {
  65. return error;
  66. }
  67. flush();
  68. if (error != ESP_OK)
  69. {
  70. return error;
  71. }
  72. return httpd_resp_send_chunk(req, nullptr, 0);
  73. }
  74. private:
  75. static constexpr size_t BUFFER_SIZE = 128;
  76. httpd_req_t *req;
  77. char buffer[BUFFER_SIZE];
  78. size_t used;
  79. esp_err_t error;
  80. void flush()
  81. {
  82. if (error != ESP_OK || used == 0)
  83. {
  84. return;
  85. }
  86. error = httpd_resp_send_chunk(req, buffer, used);
  87. used = 0;
  88. }
  89. void appendBytes(const char *data, size_t length)
  90. {
  91. if (error != ESP_OK)
  92. {
  93. return;
  94. }
  95. while (length > 0 && error == ESP_OK)
  96. {
  97. const size_t available = BUFFER_SIZE - used;
  98. const size_t copyLength = (length < available) ? length : available;
  99. memcpy(buffer + used, data, copyLength);
  100. used += copyLength;
  101. data += copyLength;
  102. length -= copyLength;
  103. if (used == BUFFER_SIZE)
  104. {
  105. flush();
  106. }
  107. }
  108. }
  109. // Avoid printf's optional long-long format support in the ESP-IDF minimal libc.
  110. void appendUnsignedDecimal(unsigned long long value)
  111. {
  112. char digits[20];
  113. size_t length = 0;
  114. do
  115. {
  116. digits[length++] = static_cast<char>('0' + (value % 10));
  117. value /= 10;
  118. } while (value != 0 && length < sizeof(digits));
  119. while (length > 0 && error == ESP_OK)
  120. {
  121. const char digit = digits[--length];
  122. appendBytes(&digit, 1);
  123. }
  124. }
  125. void appendEscapedString(const char *value)
  126. {
  127. if (error != ESP_OK) return;
  128. if (value == nullptr) value = "";
  129. const unsigned char *cursor =
  130. reinterpret_cast<const unsigned char *>(value);
  131. while (*cursor != '\0' && error == ESP_OK)
  132. {
  133. char escaped[7];
  134. size_t escapedLength = 1;
  135. switch (*cursor)
  136. {
  137. case '"': escaped[0] = '\\'; escaped[1] = '"'; escapedLength = 2; break;
  138. case '\\': escaped[0] = '\\'; escaped[1] = '\\'; escapedLength = 2; break;
  139. case '\b': escaped[0] = '\\'; escaped[1] = 'b'; escapedLength = 2; break;
  140. case '\f': escaped[0] = '\\'; escaped[1] = 'f'; escapedLength = 2; break;
  141. case '\n': escaped[0] = '\\'; escaped[1] = 'n'; escapedLength = 2; break;
  142. case '\r': escaped[0] = '\\'; escaped[1] = 'r'; escapedLength = 2; break;
  143. case '\t': escaped[0] = '\\'; escaped[1] = 't'; escapedLength = 2; break;
  144. default:
  145. if (*cursor < 0x20)
  146. {
  147. const int length = snprintf(escaped, sizeof(escaped), "\\u%04x", *cursor);
  148. if (length != 6) { error = ESP_FAIL; return; }
  149. escapedLength = 6;
  150. }
  151. else if (*cursor < 0x80)
  152. {
  153. escaped[0] = static_cast<char>(*cursor);
  154. }
  155. else
  156. {
  157. // Preserve valid UTF-8; replace malformed bytes so the JSON remains parseable.
  158. const unsigned char b1 = cursor[1];
  159. const unsigned char b2 = (b1 != 0) ? cursor[2] : 0;
  160. const unsigned char b3 = (b2 != 0) ? cursor[3] : 0;
  161. size_t n = 0;
  162. if (*cursor >= 0xC2 && *cursor <= 0xDF && b1 >= 0x80 && b1 <= 0xBF) n = 2;
  163. else if (*cursor == 0xE0 && b1 >= 0xA0 && b1 <= 0xBF && b2 >= 0x80 && b2 <= 0xBF) n = 3;
  164. else if (((*cursor >= 0xE1 && *cursor <= 0xEC) || (*cursor >= 0xEE && *cursor <= 0xEF)) && b1 >= 0x80 && b1 <= 0xBF && b2 >= 0x80 && b2 <= 0xBF) n = 3;
  165. else if (*cursor == 0xED && b1 >= 0x80 && b1 <= 0x9F && b2 >= 0x80 && b2 <= 0xBF) n = 3;
  166. else if (*cursor == 0xF0 && b1 >= 0x90 && b1 <= 0xBF && b2 >= 0x80 && b2 <= 0xBF && b3 >= 0x80 && b3 <= 0xBF) n = 4;
  167. else if (*cursor >= 0xF1 && *cursor <= 0xF3 && b1 >= 0x80 && b1 <= 0xBF && b2 >= 0x80 && b2 <= 0xBF && b3 >= 0x80 && b3 <= 0xBF) n = 4;
  168. else if (*cursor == 0xF4 && b1 >= 0x80 && b1 <= 0x8F && b2 >= 0x80 && b2 <= 0xBF && b3 >= 0x80 && b3 <= 0xBF) n = 4;
  169. if (n != 0)
  170. {
  171. appendBytes(reinterpret_cast<const char *>(cursor), n);
  172. cursor += n;
  173. continue;
  174. }
  175. appendLiteral("\\ufffd");
  176. ++cursor;
  177. continue;
  178. }
  179. break;
  180. }
  181. appendBytes(escaped, escapedLength);
  182. ++cursor;
  183. }
  184. }
  185. void appendFieldPrefix(const char *key, bool &firstField)
  186. {
  187. if (error != ESP_OK)
  188. {
  189. return;
  190. }
  191. if (!firstField)
  192. {
  193. appendLiteral(",");
  194. }
  195. firstField = false;
  196. appendLiteral("\"");
  197. appendEscapedString(key);
  198. appendLiteral("\":");
  199. }
  200. };
  201. /* An HTTP GET handler */
  202. esp_err_t info_get_handler(httpd_req_t *req)
  203. {
  204. #ifdef DEBUG_DETAIL_ON
  205. LogFile.WriteHeapInfo("info_get_handler - Start");
  206. #endif
  207. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "info_get_handler");
  208. char _query[200];
  209. char _valuechar[30];
  210. std::string _task;
  211. if (httpd_req_get_url_query_str(req, _query, 200) != ESP_OK)
  212. {
  213. return httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, "invalid query string");
  214. }
  215. ESP_LOGD(TAG, "Query: %s", _query);
  216. if (httpd_query_key_value(_query, "type", _valuechar, 30) != ESP_OK)
  217. {
  218. return httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, "missing or invalid 'type' query parameter (too long value?)");
  219. }
  220. ESP_LOGD(TAG, "type is found: %s", _valuechar);
  221. _task = std::string(_valuechar);
  222. httpd_resp_set_hdr(req, "Access-Control-Allow-Origin", "*");
  223. if (_task.compare("GitBranch") == 0)
  224. {
  225. httpd_resp_sendstr(req, libfive_git_branch());
  226. return ESP_OK;
  227. }
  228. else if (_task.compare("GitTag") == 0)
  229. {
  230. httpd_resp_sendstr(req, libfive_git_version());
  231. return ESP_OK;
  232. }
  233. else if (_task.compare("GitRevision") == 0)
  234. {
  235. httpd_resp_sendstr(req, libfive_git_revision());
  236. return ESP_OK;
  237. }
  238. else if (_task.compare("BuildTime") == 0)
  239. {
  240. httpd_resp_sendstr(req, build_time());
  241. return ESP_OK;
  242. }
  243. else if (_task.compare("FirmwareVersion") == 0)
  244. {
  245. httpd_resp_sendstr(req, getFwVersion().c_str());
  246. return ESP_OK;
  247. }
  248. else if (_task.compare("HTMLVersion") == 0)
  249. {
  250. httpd_resp_sendstr(req, getHTMLversion().c_str());
  251. return ESP_OK;
  252. }
  253. else if (_task.compare("Hostname") == 0)
  254. {
  255. std::string zw;
  256. zw = std::string(wlan_config.hostname);
  257. httpd_resp_sendstr(req, zw.c_str());
  258. return ESP_OK;
  259. }
  260. else if (_task.compare("IP") == 0)
  261. {
  262. std::string *zw;
  263. zw = getIPAddress();
  264. httpd_resp_sendstr(req, zw->c_str());
  265. return ESP_OK;
  266. }
  267. else if (_task.compare("SSID") == 0)
  268. {
  269. std::string *zw;
  270. zw = getSSID();
  271. httpd_resp_sendstr(req, zw->c_str());
  272. return ESP_OK;
  273. }
  274. else if (_task.compare("FlowStatus") == 0)
  275. {
  276. std::string zw;
  277. zw = std::string("FlowStatus");
  278. httpd_resp_sendstr(req, zw.c_str());
  279. return ESP_OK;
  280. }
  281. else if (_task.compare("Round") == 0)
  282. {
  283. char formated[10] = "";
  284. snprintf(formated, sizeof(formated), "%d", getCountFlowRounds());
  285. httpd_resp_sendstr(req, formated);
  286. return ESP_OK;
  287. }
  288. else if (_task.compare("SDCardPartitionSize") == 0)
  289. {
  290. std::string zw;
  291. zw = getSDCardPartitionSize();
  292. httpd_resp_sendstr(req, zw.c_str());
  293. return ESP_OK;
  294. }
  295. else if (_task.compare("SDCardFreePartitionSpace") == 0)
  296. {
  297. std::string zw;
  298. zw = getSDCardFreePartitionSpace();
  299. httpd_resp_sendstr(req, zw.c_str());
  300. return ESP_OK;
  301. }
  302. else if (_task.compare("SDCardPartitionAllocationSize") == 0)
  303. {
  304. std::string zw;
  305. zw = getSDCardPartitionAllocationSize();
  306. httpd_resp_sendstr(req, zw.c_str());
  307. return ESP_OK;
  308. }
  309. else if (_task.compare("SDCardManufacturer") == 0)
  310. {
  311. std::string zw;
  312. zw = getSDCardManufacturer();
  313. httpd_resp_sendstr(req, zw.c_str());
  314. return ESP_OK;
  315. }
  316. else if (_task.compare("SDCardName") == 0)
  317. {
  318. std::string zw;
  319. zw = getSDCardName();
  320. httpd_resp_sendstr(req, zw.c_str());
  321. return ESP_OK;
  322. }
  323. else if (_task.compare("SDCardCapacity") == 0)
  324. {
  325. std::string zw;
  326. zw = getSDCardCapacity();
  327. httpd_resp_sendstr(req, zw.c_str());
  328. return ESP_OK;
  329. }
  330. else if (_task.compare("SDCardSectorSize") == 0)
  331. {
  332. std::string zw;
  333. zw = getSDCardSectorSize();
  334. httpd_resp_sendstr(req, zw.c_str());
  335. return ESP_OK;
  336. }
  337. else if (_task.compare("ChipCores") == 0)
  338. {
  339. esp_chip_info_t chipInfo;
  340. esp_chip_info(&chipInfo);
  341. httpd_resp_sendstr(req, to_string(chipInfo.cores).c_str());
  342. return ESP_OK;
  343. }
  344. else if (_task.compare("ChipRevision") == 0)
  345. {
  346. esp_chip_info_t chipInfo;
  347. esp_chip_info(&chipInfo);
  348. httpd_resp_sendstr(req, to_string(chipInfo.revision).c_str());
  349. return ESP_OK;
  350. }
  351. else if (_task.compare("ChipFeatures") == 0)
  352. {
  353. esp_chip_info_t chipInfo;
  354. esp_chip_info(&chipInfo);
  355. httpd_resp_sendstr(req, to_string(chipInfo.features).c_str());
  356. return ESP_OK;
  357. }
  358. else
  359. {
  360. char formatted[256];
  361. snprintf(formatted, sizeof(formatted), "Unknown value for parameter info 'type': '%s'\n", _task.c_str());
  362. return httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, formatted);
  363. }
  364. return ESP_OK;
  365. }
  366. esp_err_t starttime_get_handler(httpd_req_t *req)
  367. {
  368. httpd_resp_set_hdr(req, "Access-Control-Allow-Origin", "*");
  369. httpd_resp_send(req, starttime.c_str(), starttime.length());
  370. return ESP_OK;
  371. }
  372. esp_err_t hello_main_handler(httpd_req_t *req)
  373. {
  374. #ifdef DEBUG_DETAIL_ON
  375. LogFile.WriteHeapInfo("hello_main_handler - Start");
  376. #endif
  377. char filepath[50];
  378. ESP_LOGD(TAG, "uri: %s\n", req->uri);
  379. int _pos;
  380. esp_err_t res;
  381. char *base_path = (char*) req->user_ctx;
  382. std::string filetosend(base_path);
  383. const char *filename = get_path_from_uri(filepath, base_path,
  384. req->uri - 1, sizeof(filepath));
  385. ESP_LOGD(TAG, "1 uri: %s, filename: %s, filepath: %s", req->uri, filename, filepath);
  386. if ((strcmp(req->uri, "/") == 0))
  387. {
  388. {
  389. filetosend = filetosend + "/html/index.html";
  390. }
  391. }
  392. else
  393. {
  394. filetosend = filetosend + "/html" + std::string(req->uri);
  395. _pos = filetosend.find("?");
  396. if (_pos > -1){
  397. filetosend = filetosend.substr(0, _pos);
  398. }
  399. }
  400. if (filetosend == "/sdcard/html/index.html") {
  401. if (isSetSystemStatusFlag(SYSTEM_STATUS_PSRAM_BAD) || // Initialization failed with crritical errors!
  402. isSetSystemStatusFlag(SYSTEM_STATUS_CAM_BAD) ||
  403. isSetSystemStatusFlag(SYSTEM_STATUS_SDCARD_CHECK_BAD) ||
  404. isSetSystemStatusFlag(SYSTEM_STATUS_FOLDER_CHECK_BAD))
  405. {
  406. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "We have a critical error, not serving main page!");
  407. char buf[20];
  408. std::string message = "<h1>AI on the Edge Device</h1><b>We have one or more critical errors:</b><br>";
  409. for (int i = 0; i < 32; i++) {
  410. if (isSetSystemStatusFlag((SystemStatusFlag_t)(1<<i))) {
  411. snprintf(buf, sizeof(buf), "0x%08X", 1<<i);
  412. message += std::string(buf) + "<br>";
  413. }
  414. }
  415. 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!";
  416. message += "<br><br><button onclick=\"window.location.href='/reboot';\">Reboot</button>";
  417. message += "&nbsp;<button onclick=\"window.open('/ota_page.html');\">OTA Update</button>";
  418. message += "&nbsp;<button onclick=\"window.open('/log.html');\">Log Viewer</button>";
  419. message += "&nbsp;<button onclick=\"window.open('/info.html');\">Show System Info</button>";
  420. httpd_resp_send(req, message.c_str(), message.length());
  421. return ESP_OK;
  422. }
  423. else if (isSetupModusActive()) {
  424. ESP_LOGD(TAG, "System is in setup mode --> index.html --> setup.html");
  425. filetosend = "/sdcard/html/setup.html";
  426. }
  427. }
  428. ESP_LOGD(TAG, "Filename: %s", filename);
  429. ESP_LOGD(TAG, "File requested: %s", filetosend.c_str());
  430. if (!filename) {
  431. ESP_LOGE(TAG, "Filename is too long");
  432. /* Respond with 414 Error */
  433. httpd_resp_send_err(req, HTTPD_414_URI_TOO_LONG, "Filename too long");
  434. return ESP_FAIL;
  435. }
  436. res = send_file(req, filetosend); // send_file() already terminates the chunked response
  437. if (res != ESP_OK)
  438. return res;
  439. /* Respond with an empty chunk to signal HTTP response completion */
  440. // httpd_resp_sendstr(req, "");
  441. // httpd_resp_send_chunk(req, NULL, 0);
  442. #ifdef DEBUG_DETAIL_ON
  443. LogFile.WriteHeapInfo("hello_main_handler - Stop");
  444. #endif
  445. return ESP_OK;
  446. }
  447. esp_err_t img_tmp_handler(httpd_req_t *req)
  448. {
  449. char filepath[50];
  450. ESP_LOGD(TAG, "uri: %s", req->uri);
  451. char *base_path = (char*) req->user_ctx;
  452. std::string filetosend(base_path);
  453. const char *filename = get_path_from_uri(filepath, base_path,
  454. req->uri + sizeof("/img_tmp/") - 1, sizeof(filepath));
  455. ESP_LOGD(TAG, "1 uri: %s, filename: %s, filepath: %s", req->uri, filename, filepath);
  456. filetosend = filetosend + "/img_tmp/" + std::string(filename);
  457. ESP_LOGD(TAG, "File to upload: %s", filetosend.c_str());
  458. // send_file() already terminates the chunked response
  459. return send_file(req, filetosend);
  460. }
  461. esp_err_t img_tmp_virtual_handler(httpd_req_t *req)
  462. {
  463. #ifdef DEBUG_DETAIL_ON
  464. LogFile.WriteHeapInfo("img_tmp_virtual_handler - Start");
  465. #endif
  466. char filepath[50];
  467. ESP_LOGD(TAG, "uri: %s", req->uri);
  468. char *base_path = (char*) req->user_ctx;
  469. std::string filetosend(base_path);
  470. const char *filename = get_path_from_uri(filepath, base_path,
  471. req->uri + sizeof("/img_tmp/") - 1, sizeof(filepath));
  472. ESP_LOGD(TAG, "1 uri: %s, filename: %s, filepath: %s", req->uri, filename, filepath);
  473. filetosend = std::string(filename);
  474. ESP_LOGD(TAG, "File to upload: %s", filetosend.c_str());
  475. // Only the test_take URL opts into temporary preview settings.
  476. if (filetosend == "raw.jpg")
  477. {
  478. bool previewCapture = false;
  479. char query[64] = "";
  480. char preview[8] = "";
  481. if (httpd_req_get_url_query_str(req, query, sizeof(query)) == ESP_OK &&
  482. httpd_query_key_value(query, "preview", preview, sizeof(preview)) == ESP_OK)
  483. {
  484. previewCapture = (strcmp(preview, "1") == 0);
  485. }
  486. return GetRawJPG(req, previewCapture);
  487. }
  488. // Serve alg.jpg, alg_roi.jpg or digit and analog ROIs
  489. if (ESP_OK == GetJPG(filetosend, req))
  490. return ESP_OK;
  491. #ifdef DEBUG_DETAIL_ON
  492. LogFile.WriteHeapInfo("img_tmp_virtual_handler - Done");
  493. #endif
  494. // File was not served already --> serve with img_tmp_handler
  495. return img_tmp_handler(req);
  496. }
  497. esp_err_t sysinfo_handler(httpd_req_t *req)
  498. {
  499. // Take one snapshot of resource and card information for this response.
  500. const ESPHeapStats heap = getESPHeapStats();
  501. const SDCardDetails sdCard = getSDCardDetails();
  502. esp_chip_info_t chipInfo = {};
  503. esp_chip_info(&chipInfo);
  504. const std::string *hostnameValue = getHostname();
  505. const std::string *ipAddressValue = getIPAddress();
  506. const std::string *ssidValue = getSSID();
  507. const std::string hostname = hostnameValue ? *hostnameValue : std::string();
  508. const std::string ipAddress = ipAddressValue ? *ipAddressValue : std::string();
  509. const std::string ssid = ssidValue ? *ssidValue : std::string();
  510. const std::string uptime = getFormatedUptime(false);
  511. char cpuTemperature[16];
  512. snprintf(cpuTemperature, sizeof(cpuTemperature), "%d", (int)temperatureRead());
  513. httpd_resp_set_hdr(req, "Access-Control-Allow-Origin", "*");
  514. httpd_resp_set_type(req, "application/json");
  515. JsonChunkWriter json(req);
  516. json.appendLiteral("[{");
  517. bool firstField = true;
  518. // Keep the original /sysinfo fields and their string types for existing clients.
  519. json.appendStringField("firmware", libfive_git_version(), firstField);
  520. json.appendStringField("firmwareVersion", getFwVersion().c_str(), firstField);
  521. json.appendStringField("htmlVersion", getHTMLversion().c_str(), firstField);
  522. json.appendStringField("buildtime", build_time(), firstField);
  523. json.appendStringField("gitbranch", libfive_git_branch(), firstField);
  524. json.appendStringField("gittag", libfive_git_version(), firstField);
  525. json.appendStringField("gitrevision", libfive_git_revision(), firstField);
  526. json.appendStringField("html", getHTMLversion().c_str(), firstField);
  527. json.appendStringField("cputemp", cpuTemperature, firstField);
  528. json.appendStringField("hostname", hostname.c_str(), firstField);
  529. json.appendStringField("IPv4", ipAddress.c_str(), firstField);
  530. json.appendUnsignedStringField("freeHeapMem", heap.totalFree, firstField);
  531. // Additional fields consumed by info.html.
  532. json.appendStringField("starttime", starttime.c_str(), firstField);
  533. json.appendStringField("uptime", uptime.c_str(), firstField);
  534. json.appendStringField("SSID", ssid.c_str(), firstField);
  535. json.appendNumberField("chipCores", chipInfo.cores, firstField);
  536. json.appendNumberField("chipRevision", chipInfo.revision, firstField);
  537. json.appendNumberField("chipFeatures", chipInfo.features, firstField);
  538. if (sdCard.cardAvailable)
  539. {
  540. json.appendStringField("sdCardManufacturer", sdCard.manufacturer.c_str(), firstField);
  541. json.appendStringField("sdCardName", sdCard.name.c_str(), firstField);
  542. json.appendStringField("sdCardCapacity", sdCard.capacityMB.c_str(), firstField);
  543. json.appendStringField("sdCardSectorSize", sdCard.sectorSizeBytes.c_str(), firstField);
  544. }
  545. else
  546. {
  547. json.appendNullField("sdCardManufacturer", firstField);
  548. json.appendNullField("sdCardName", firstField);
  549. json.appendNullField("sdCardCapacity", firstField);
  550. json.appendNullField("sdCardSectorSize", firstField);
  551. }
  552. if (sdCard.partitionAvailable)
  553. {
  554. json.appendStringField("sdCardPartitionSize", sdCard.partitionSizeMB.c_str(), firstField);
  555. json.appendStringField("sdCardFreePartitionSpace", sdCard.partitionFreeMB.c_str(), firstField);
  556. json.appendStringField("sdCardPartitionAllocationSize",
  557. sdCard.partitionAllocationSizeBytes.c_str(), firstField);
  558. }
  559. else
  560. {
  561. json.appendNullField("sdCardPartitionSize", firstField);
  562. json.appendNullField("sdCardFreePartitionSpace", firstField);
  563. json.appendNullField("sdCardPartitionAllocationSize", firstField);
  564. }
  565. json.appendNumberField("RAMTotalFree", heap.totalFree, firstField);
  566. json.appendNumberField("ExtRAMFree", heap.externalFree, firstField);
  567. json.appendNumberField("ExtRAMLargestFree", heap.externalLargestFreeBlock, firstField);
  568. json.appendNumberField("ExtRAMMinFree", heap.externalMinFree, firstField);
  569. json.appendNumberField("IntRAMFree", heap.internalFree, firstField);
  570. json.appendNumberField("IntRAMLargestFree", heap.internalLargestFreeBlock, firstField);
  571. json.appendNumberField("IntRAMMinFree", heap.internalMinFree, firstField);
  572. json.appendLiteral("}]");
  573. return json.finish();
  574. }
  575. void register_server_main_uri(httpd_handle_t server, const char *base_path)
  576. {
  577. httpd_uri_t info_get_handle = {
  578. .uri = "/info", // Match all URIs of type /path/to/file
  579. .method = HTTP_GET,
  580. .handler = APPLY_BASIC_AUTH_FILTER(info_get_handler),
  581. .user_ctx = (void*) base_path // Pass server data as context
  582. };
  583. httpd_register_uri_handler(server, &info_get_handle);
  584. httpd_uri_t sysinfo_handle = {
  585. .uri = "/sysinfo", // Match all URIs of type /path/to/file
  586. .method = HTTP_GET,
  587. .handler = APPLY_BASIC_AUTH_FILTER(sysinfo_handler),
  588. .user_ctx = (void*) base_path // Pass server data as context
  589. };
  590. httpd_register_uri_handler(server, &sysinfo_handle);
  591. httpd_uri_t starttime_tmp_handle = {
  592. .uri = "/starttime", // Match all URIs of type /path/to/file
  593. .method = HTTP_GET,
  594. .handler = APPLY_BASIC_AUTH_FILTER(starttime_get_handler),
  595. .user_ctx = NULL // Pass server data as context
  596. };
  597. httpd_register_uri_handler(server, &starttime_tmp_handle);
  598. httpd_uri_t img_tmp_handle = {
  599. .uri = "/img_tmp/*", // Match all URIs of type /path/to/file
  600. .method = HTTP_GET,
  601. .handler = APPLY_BASIC_AUTH_FILTER(img_tmp_virtual_handler),
  602. .user_ctx = (void*) base_path // Pass server data as context
  603. };
  604. httpd_register_uri_handler(server, &img_tmp_handle);
  605. httpd_uri_t main_rest_handle = {
  606. .uri = "/*", // Match all URIs of type /path/to/file
  607. .method = HTTP_GET,
  608. .handler = APPLY_BASIC_AUTH_FILTER(hello_main_handler),
  609. .user_ctx = (void*) base_path // Pass server data as context
  610. };
  611. httpd_register_uri_handler(server, &main_rest_handle);
  612. }
  613. httpd_handle_t start_webserver(void)
  614. {
  615. httpd_handle_t server = NULL;
  616. httpd_config_t config = HTTPD_DEFAULT_CONFIG();
  617. config.task_priority = tskIDLE_PRIORITY+5; // Tested: higher server priority improves Web-UI responsiveness under load
  618. config.stack_size = 8 * 2048; // 16 KB; tested with image and OTA requests
  619. config.core_id = 1; // previously -> 2023-01-02: 0, 2022-12-11: tskNO_AFFINITY;
  620. config.server_port = 80;
  621. config.ctrl_port = 32768;
  622. config.max_open_sockets = 5; // Conservative HTTP client limit; lwIP socket pool configured separately
  623. config.max_uri_handlers = 43; // Make sure this fits all URI handlers. Memory usage in bytes: 6*max_uri_handlers
  624. config.max_resp_headers = 8;
  625. config.backlog_conn = 5;
  626. config.lru_purge_enable = true; // this cuts old connections if new ones are needed.
  627. config.recv_wait_timeout = 5; // default: 5 20210924 --> previously 30
  628. config.send_wait_timeout = 5; // default: 5 20210924 --> previously 30
  629. config.global_user_ctx = NULL;
  630. config.global_user_ctx_free_fn = NULL;
  631. config.global_transport_ctx = NULL;
  632. config.global_transport_ctx_free_fn = NULL;
  633. config.open_fn = NULL;
  634. config.close_fn = NULL;
  635. // config.uri_match_fn = NULL;
  636. config.uri_match_fn = httpd_uri_match_wildcard;
  637. starttime = getCurrentTimeString("%Y%m%d-%H%M%S");
  638. // Start the httpd server
  639. ESP_LOGI(TAG, "Starting server on port: '%d'", config.server_port);
  640. if (httpd_start(&server, &config) == ESP_OK) {
  641. // Set URI handlers
  642. ESP_LOGI(TAG, "Registering URI handlers");
  643. return server;
  644. }
  645. ESP_LOGI(TAG, "Error starting server!");
  646. return NULL;
  647. }
  648. void stop_webserver(httpd_handle_t server)
  649. {
  650. httpd_stop(server);
  651. }
  652. void disconnect_handler(void* arg, esp_event_base_t event_base,
  653. int32_t event_id, void* event_data)
  654. {
  655. httpd_handle_t* server = (httpd_handle_t*) arg;
  656. if (*server) {
  657. ESP_LOGI(TAG, "Stopping webserver");
  658. stop_webserver(*server);
  659. *server = NULL;
  660. }
  661. }
  662. void connect_handler(void* arg, esp_event_base_t event_base,
  663. int32_t event_id, void* event_data)
  664. {
  665. httpd_handle_t* server = (httpd_handle_t*) arg;
  666. if (*server == NULL) {
  667. ESP_LOGI(TAG, "Starting webserver");
  668. *server = start_webserver();
  669. }
  670. }