server_remote.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474
  1. #include "defines.h"
  2. #include "server_remote.h"
  3. #include "connect_wifi_ap.h"
  4. #include <string.h>
  5. #include <string>
  6. #include <freertos/FreeRTOS.h>
  7. #include <freertos/task.h>
  8. #include <esp_mac.h>
  9. #include <esp_wifi.h>
  10. #include <esp_log.h>
  11. #include <nvs_flash.h>
  12. #include <stdio.h>
  13. #include <lwip/err.h>
  14. #include <lwip/sys.h>
  15. #include "time_sntp.h"
  16. #include "ClassLogFile.h"
  17. #include "server_help.h"
  18. #include "Helper.h"
  19. #include "statusled.h"
  20. #include "server_ota.h"
  21. #include "basic_auth.h"
  22. static const char *TAG = "REMOTE SERVER";
  23. std::string remote_webserver_start_time = "";
  24. bool is_config_ini = false;
  25. bool is_wlan_ini = false;
  26. void remote_send_http_response(httpd_req_t *req)
  27. {
  28. std::string message = "<h1>AI-on-the-edge - BASIC SETUP</h1><p>This is an access point with a minimal server to setup the minimum required files and information on the device and the SD-card. ";
  29. message += "This mode is always started if one of the following files is missing: /wlan.ini or the /config/config.ini.<p>";
  30. message += "The setup is done in 3 steps: 1. upload full inital configuration (sd-card content), 2. store WLAN access information, 3. reboot (and connect to WLANs)<p><p>";
  31. message += "Please follow the below instructions.<p>";
  32. httpd_resp_send_chunk(req, message.c_str(), strlen(message.c_str()));
  33. is_wlan_ini = (file_exists(WLAN_CONFIG_FILE) || file_exists(NETWORK_CONFIG_FILE));
  34. if (!is_config_ini)
  35. {
  36. message = "<h3>1. Upload initial configuration to sd-card</h3><p>";
  37. message += "The configuration file config.ini is missing and most propably the full configuration and html folder on the sd-card. ";
  38. message += "This is normal after the first flashing of the firmware and an empty sd-card. Please upload \"remote_setup.zip\", which contains a full inital configuration.<p>";
  39. message += "<input id=\"newfile\" type=\"file\"><br>";
  40. message += "<button class=\"button\" style=\"width:300px\" id=\"doUpdate\" type=\"button\" onclick=\"upload()\">Upload File</button><p>";
  41. message += "The upload might take up to 60s. After a succesfull upload the page will be updated.";
  42. httpd_resp_send_chunk(req, message.c_str(), strlen(message.c_str()));
  43. message = "<script language=\"JavaScript\">";
  44. message += "function upload() {";
  45. message += "var xhttp = new XMLHttpRequest();";
  46. message += "xhttp.onreadystatechange = function() {if (xhttp.readyState == 4) {if (xhttp.status == 200) {location.reload();}}};";
  47. message += "var filePath = document.getElementById(\"newfile\").value.split(/[\\\\/]/).pop();";
  48. message += "var file = document.getElementById(\"newfile\").files[0];";
  49. message += "if (!file.name.includes(\"remote-setup\")){if (!confirm(\"The zip file name should contain '...remote-setup...'. Are you sure that you have downloaded the correct file?\"))return;};";
  50. message += "var upload_path = \"/upload/firmware/\" + filePath; xhttp.open(\"POST\", upload_path, true); xhttp.send(file);document.reload();";
  51. message += "document.getElementById(\"doUpdate\").disabled = true;}";
  52. message += "</script>";
  53. httpd_resp_send_chunk(req, message.c_str(), strlen(message.c_str()));
  54. return;
  55. }
  56. if (!is_wlan_ini)
  57. {
  58. message = "<h3>2. WLAN access credentials</h3><p>";
  59. message += "<table>";
  60. message += "<tr><td>WLAN-SSID</td><td><input type=\"text\" name=\"ssid\" id=\"ssid\"></td><td>SSID of the WLAN</td></tr>";
  61. message += "<tr><td>WLAN-Password</td><td><input type=\"text\" name=\"password\" id=\"password\"></td><td>ATTENTION: the password will not be encrypted during the sending.</td><tr>";
  62. message += "</table><p>";
  63. message += "<h4>ATTENTION:<h4>Be sure about the WLAN settings. They cannot be reset afterwards. If ssid or password is wrong, you need to take out the sd-card and manually change them in \"wlan.ini\"!<p>";
  64. httpd_resp_send_chunk(req, message.c_str(), strlen(message.c_str()));
  65. message = "<button class=\"button\" type=\"button\" onclick=\"wr()\">Write wlan.ini</button>";
  66. message += "<script language=\"JavaScript\">async function wr(){";
  67. message += "api = \"/config?\"+\"ssid=\"+document.getElementById(\"ssid\").value+\"&pwd=\"+document.getElementById(\"password\").value;";
  68. message += "fetch(api);await new Promise(resolve => setTimeout(resolve, 1000));location.reload();}</script>";
  69. httpd_resp_send_chunk(req, message.c_str(), strlen(message.c_str()));
  70. return;
  71. }
  72. message = "<h3>3. Reboot</h3><p>";
  73. message += "After triggering the reboot, the zip-files gets extracted and written to the sd-card.<br>The ESP32 will restart two times and then connect to your access point. Please find the IP in your router settings and access it with the new ip-address.<p>";
  74. message += "The first update and initialization process can take up to 3 minutes before you find it in the wlan. Error logs can be found on the console / serial logout.<p>Have fun!<p>";
  75. message += "<button class=\"button\" type=\"button\" onclick=\"rb()\")>Reboot to first setup.</button>";
  76. message += "<script language=\"JavaScript\">async function rb(){";
  77. message += "api = \"/reboot\";";
  78. message += "fetch(api);await new Promise(resolve => setTimeout(resolve, 1000));location.reload();}</script>";
  79. httpd_resp_send_chunk(req, message.c_str(), strlen(message.c_str()));
  80. }
  81. esp_err_t remote_test_handler(httpd_req_t *req)
  82. {
  83. remote_send_http_response(req);
  84. httpd_resp_send_chunk(req, NULL, 0);
  85. return ESP_OK;
  86. }
  87. esp_err_t remote_reboot_handler(httpd_req_t *req)
  88. {
  89. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Trigger reboot due to firmware update.");
  90. doRebootOTA();
  91. return ESP_OK;
  92. }
  93. esp_err_t remote_config_ini_handler(httpd_req_t *req)
  94. {
  95. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "config_ini_handler");
  96. char _query[400];
  97. char _valuechar[100];
  98. std::string _ssid = "";
  99. std::string _pwd = "";
  100. std::string _hostname = "";
  101. std::string _ip = "";
  102. std::string _gateway = "";
  103. std::string _netmask = "";
  104. std::string _dns = "";
  105. std::string _rssithreshold = ""; // rssi threshold for WIFI roaming
  106. if (httpd_req_get_url_query_str(req, _query, 400) == ESP_OK)
  107. {
  108. ESP_LOGD(TAG, "Query: %s", _query);
  109. if (httpd_query_key_value(_query, "ssid", _valuechar, 100) == ESP_OK)
  110. {
  111. ESP_LOGD(TAG, "ssid is found: %s", _valuechar);
  112. _ssid = url_decode(std::string(_valuechar));
  113. }
  114. if (httpd_query_key_value(_query, "pwd", _valuechar, 100) == ESP_OK)
  115. {
  116. ESP_LOGD(TAG, "pwd is found: %s", _valuechar);
  117. _pwd = url_decode(std::string(_valuechar));
  118. }
  119. if (httpd_query_key_value(_query, "ssid", _valuechar, 100) == ESP_OK)
  120. {
  121. ESP_LOGD(TAG, "ssid is found: %s", _valuechar);
  122. _ssid = url_decode(std::string(_valuechar));
  123. }
  124. if (httpd_query_key_value(_query, "hn", _valuechar, 100) == ESP_OK)
  125. {
  126. ESP_LOGD(TAG, "hostname is found: %s", _valuechar);
  127. _hostname = url_decode(std::string(_valuechar));
  128. }
  129. if (httpd_query_key_value(_query, "ip", _valuechar, 100) == ESP_OK)
  130. {
  131. ESP_LOGD(TAG, "ip is found: %s", _valuechar);
  132. _ip = url_decode(std::string(_valuechar));
  133. }
  134. if (httpd_query_key_value(_query, "gw", _valuechar, 100) == ESP_OK)
  135. {
  136. ESP_LOGD(TAG, "gateway is found: %s", _valuechar);
  137. _gateway = url_decode(std::string(_valuechar));
  138. }
  139. if (httpd_query_key_value(_query, "nm", _valuechar, 100) == ESP_OK)
  140. {
  141. ESP_LOGD(TAG, "netmask is found: %s", _valuechar);
  142. _netmask = url_decode(std::string(_valuechar));
  143. }
  144. if (httpd_query_key_value(_query, "dns", _valuechar, 100) == ESP_OK)
  145. {
  146. ESP_LOGD(TAG, "dns is found: %s", _valuechar);
  147. _dns = url_decode(std::string(_valuechar));
  148. }
  149. if (httpd_query_key_value(_query, "rssithreshold", _valuechar, 100) == ESP_OK)
  150. {
  151. ESP_LOGD(TAG, "rssithreshold is found: %s", _valuechar);
  152. _rssithreshold = url_decode(std::string(_valuechar));
  153. }
  154. }
  155. FILE *pFile = fopen(NETWORK_CONFIG_FILE, "w");
  156. std::string text = ";++++++++++++++++++++++++++++++++++\n";
  157. text += "; AI on the edge - WLAN configuration\n";
  158. text += "; ssid: Name of WLAN network (mandatory), e.g. \"WLAN-SSID\"\n";
  159. text += "; password: Password of WLAN network (mandatory), e.g. \"PASSWORD\"\n\n";
  160. fputs(text.c_str(), pFile);
  161. if (_ssid.length())
  162. {
  163. _ssid = "ssid = \"" + _ssid + "\"\n";
  164. }
  165. else
  166. {
  167. _ssid = "ssid = \"\"\n";
  168. }
  169. fputs(_ssid.c_str(), pFile);
  170. if (_pwd.length())
  171. {
  172. _pwd = "password = \"" + _pwd + "\"\n";
  173. }
  174. else
  175. {
  176. _pwd = "password = \"\"\n";
  177. }
  178. fputs(_pwd.c_str(), pFile);
  179. text = "\n;++++++++++++++++++++++++++++++++++\n";
  180. text += "; Hostname: Name of device in network\n";
  181. text += "; This parameter can be configured via WebUI configuration\n";
  182. text += "; Default: \"watermeter\", if nothing is configured\n\n";
  183. fputs(text.c_str(), pFile);
  184. if (_hostname.length())
  185. {
  186. _hostname = "hostname = \"" + _hostname + "\"\n";
  187. }
  188. else
  189. {
  190. _hostname = ";hostname = \"watermeter\"\n";
  191. }
  192. fputs(_hostname.c_str(), pFile);
  193. text = "\n;++++++++++++++++++++++++++++++++++\n";
  194. text += "; Fixed IP: If you like to use fixed IP instead of DHCP (default), the following\n";
  195. text += "; parameters needs to be configured: ip, gateway, netmask are mandatory, dns optional\n\n";
  196. fputs(text.c_str(), pFile);
  197. if (_ip.length())
  198. {
  199. _ip = "ip = \"" + _ip + "\"\n";
  200. }
  201. else
  202. {
  203. _ip = ";ip = \"xxx.xxx.xxx.xxx\"\n";
  204. }
  205. fputs(_ip.c_str(), pFile);
  206. if (_gateway.length())
  207. {
  208. _gateway = "gateway = \"" + _gateway + "\"\n";
  209. }
  210. else
  211. {
  212. _gateway = ";gateway = \"xxx.xxx.xxx.xxx\"\n";
  213. }
  214. fputs(_gateway.c_str(), pFile);
  215. if (_netmask.length())
  216. {
  217. _netmask = "netmask = \"" + _netmask + "\"\n";
  218. }
  219. else
  220. {
  221. _netmask = ";netmask = \"xxx.xxx.xxx.xxx\"\n";
  222. }
  223. fputs(_netmask.c_str(), pFile);
  224. text = "\n;++++++++++++++++++++++++++++++++++\n";
  225. text += "; DNS server (optional, if no DNS is configured, gateway address will be used)\n\n";
  226. fputs(text.c_str(), pFile);
  227. if (_dns.length())
  228. {
  229. _dns = "dns = \"" + _dns + "\"\n";
  230. }
  231. else
  232. {
  233. _dns = ";dns = \"xxx.xxx.xxx.xxx\"\n";
  234. }
  235. fputs(_dns.c_str(), pFile);
  236. text = "\n;++++++++++++++++++++++++++++++++++\n";
  237. text += "; WIFI Roaming:\n";
  238. text += "; Network assisted roaming protocol is activated by default\n";
  239. text += "; AP / mesh system needs to support roaming protocol 802.11k/v\n";
  240. text += ";\n";
  241. text += "; Optional feature (usually not neccessary):\n";
  242. text += "; RSSI Threshold for client requested roaming query (RSSI < RSSIThreshold)\n";
  243. text += "; Note: This parameter can be configured via WebUI configuration\n";
  244. text += "; Default: 0 = Disable client requested roaming query\n\n";
  245. fputs(text.c_str(), pFile);
  246. if (_rssithreshold.length())
  247. {
  248. _rssithreshold = "RSSIThreshold = " + _rssithreshold + "\n";
  249. }
  250. else
  251. {
  252. _rssithreshold = "RSSIThreshold = 0\n";
  253. }
  254. fputs(_rssithreshold.c_str(), pFile);
  255. fflush(pFile);
  256. fclose(pFile);
  257. std::string zw = "ota without parameter - should not be the case!";
  258. httpd_resp_set_hdr(req, "Access-Control-Allow-Origin", "*");
  259. httpd_resp_send(req, zw.c_str(), zw.length());
  260. ESP_LOGD(TAG, "end config.ini");
  261. return ESP_OK;
  262. }
  263. esp_err_t remote_upload_post_handler(httpd_req_t *req)
  264. {
  265. printf("Starting the post handler\n");
  266. make_dir("/sdcard/config");
  267. make_dir("/sdcard/firmware");
  268. make_dir("/sdcard/html");
  269. make_dir("/sdcard/img_tmp");
  270. make_dir("/sdcard/log");
  271. make_dir("/sdcard/demo");
  272. printf("After starting the post handler\n");
  273. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "remote_upload_post_handler");
  274. char filepath[FILE_PATH_MAX];
  275. const char *filename = get_path_from_uri(filepath, "/sdcard", req->uri + sizeof("/upload") - 1, sizeof(filepath));
  276. if (!filename)
  277. {
  278. httpd_resp_send_err(req, HTTPD_414_URI_TOO_LONG, "Filename too long");
  279. return ESP_FAIL;
  280. }
  281. printf("filepath: %s, filename: %s\n", filepath, filename);
  282. delete_file(std::string(filepath));
  283. FILE *pFile = fopen(filepath, "w");
  284. if (!pFile)
  285. {
  286. ESP_LOGE(TAG, "Failed to create file: %s", filepath);
  287. httpd_resp_send_err(req, HTTPD_500_INTERNAL_SERVER_ERROR, "Failed to create file");
  288. return ESP_FAIL;
  289. }
  290. ESP_LOGI(TAG, "Receiving file: %s...", filename);
  291. char buf[1024];
  292. int received;
  293. int remaining = req->content_len;
  294. printf("remaining: %d\n", remaining);
  295. while (remaining > 0)
  296. {
  297. ESP_LOGI(TAG, "Remaining size: %d", remaining);
  298. if ((received = httpd_req_recv(req, buf, MIN(remaining, 1024))) <= 0)
  299. {
  300. if (received == HTTPD_SOCK_ERR_TIMEOUT)
  301. {
  302. continue;
  303. }
  304. fclose(pFile);
  305. unlink(filepath);
  306. ESP_LOGE(TAG, "File reception failed!");
  307. httpd_resp_send_err(req, HTTPD_500_INTERNAL_SERVER_ERROR, "Failed to receive file");
  308. return ESP_FAIL;
  309. }
  310. if (received && (received != fwrite(buf, 1, received, pFile)))
  311. {
  312. fclose(pFile);
  313. unlink(filepath);
  314. ESP_LOGE(TAG, "File write failed!");
  315. httpd_resp_send_err(req, HTTPD_500_INTERNAL_SERVER_ERROR, "Failed to write file to storage");
  316. return ESP_FAIL;
  317. }
  318. remaining -= received;
  319. }
  320. fclose(pFile);
  321. is_config_ini = true;
  322. pFile = fopen("/sdcard/update.txt", "w");
  323. std::string temp_string = "/sdcard" + std::string(filename);
  324. fwrite(temp_string.c_str(), strlen(temp_string.c_str()), 1, pFile);
  325. fclose(pFile);
  326. ESP_LOGI(TAG, "File reception complete");
  327. httpd_resp_set_hdr(req, "Location", "/test");
  328. httpd_resp_set_status(req, "303 See Other");
  329. httpd_resp_set_hdr(req, "Location", "/test");
  330. httpd_resp_send_chunk(req, NULL, 0);
  331. ESP_LOGI(TAG, "Update page send out");
  332. return ESP_OK;
  333. }
  334. httpd_handle_t start_remote_webserver(void)
  335. {
  336. httpd_handle_t my_remote_webserver_httpd_handle = NULL;
  337. httpd_config_t my_remote_webserver_httpd_config = HTTPD_DEFAULT_CONFIG();
  338. remote_webserver_start_time = getCurrentTimeString("%Y%m%d-%H%M%S");
  339. my_remote_webserver_httpd_config.uri_match_fn = httpd_uri_match_wildcard;
  340. // Start the httpd server
  341. ESP_LOGI(TAG, "Starting server on port: '%d'", my_remote_webserver_httpd_config.server_port);
  342. if (httpd_start(&my_remote_webserver_httpd_handle, &my_remote_webserver_httpd_config) == ESP_OK)
  343. {
  344. // Set URI handlers
  345. ESP_LOGI(TAG, "Registering URI handlers");
  346. return my_remote_webserver_httpd_handle;
  347. }
  348. ESP_LOGI(TAG, "Error starting ap server!");
  349. return NULL;
  350. }
  351. void stop_remote_webserver(httpd_handle_t server)
  352. {
  353. httpd_stop(server);
  354. }
  355. httpd_handle_t remote_webserver_register_uri(httpd_handle_t server)
  356. {
  357. httpd_uri_t reboot_handle = {
  358. .uri = "/reboot",
  359. .method = HTTP_GET,
  360. .handler = APPLY_BASIC_AUTH_FILTER(remote_reboot_handler),
  361. .user_ctx = NULL,
  362. };
  363. httpd_register_uri_handler(server, &reboot_handle);
  364. httpd_uri_t config_ini_handle = {
  365. .uri = "/config",
  366. .method = HTTP_GET,
  367. .handler = APPLY_BASIC_AUTH_FILTER(remote_config_ini_handler),
  368. .user_ctx = NULL,
  369. };
  370. httpd_register_uri_handler(server, &config_ini_handle);
  371. /* URI handler for uploading files to server */
  372. httpd_uri_t file_uploadAP = {
  373. .uri = "/upload/*",
  374. .method = HTTP_POST,
  375. .handler = APPLY_BASIC_AUTH_FILTER(remote_upload_post_handler),
  376. .user_ctx = NULL,
  377. };
  378. httpd_register_uri_handler(server, &file_uploadAP);
  379. httpd_uri_t test_uri = {
  380. .uri = "*",
  381. .method = HTTP_GET,
  382. .handler = APPLY_BASIC_AUTH_FILTER(remote_test_handler),
  383. .user_ctx = NULL,
  384. };
  385. httpd_register_uri_handler(server, &test_uri);
  386. return NULL;
  387. }