connect_wlan._cpp_ 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539
  1. #include "connect_wlan.h"
  2. #include <string.h>
  3. #include "freertos/FreeRTOS.h"
  4. #include "freertos/task.h"
  5. #include "freertos/event_groups.h"
  6. #include "esp_wifi.h"
  7. #include "esp_log.h"
  8. #include <fstream>
  9. #include <vector>
  10. #include <sstream>
  11. #include "Helper.h"
  12. static const char *TAG = "connect_wlan";
  13. std::string ssid = "";
  14. std::string passphrase = "";
  15. std::string hostname = "";
  16. std::string ipaddress = "";
  17. std::string gw = "";
  18. std::string netmask = "";
  19. std::string dns = "";
  20. std::string std_hostname = "watermeter";
  21. #define BLINK_GPIO GPIO_NUM_33
  22. static EventGroupHandle_t s_wifi_event_group;
  23. #define WIFI_CONNECTED_BIT BIT0
  24. #define WIFI_FAIL_BIT BIT1
  25. static int s_retry_num = 0;
  26. std::vector<string> ZerlegeZeile(std::string input, std::string _delimiter = "")
  27. {
  28. std::vector<string> Output;
  29. std::string delimiter = " =,";
  30. if (_delimiter.length() > 0){
  31. delimiter = _delimiter;
  32. }
  33. input = trim(input, delimiter);
  34. size_t pos = findDelimiterPos(input, delimiter);
  35. std::string token;
  36. while (pos != std::string::npos) {
  37. token = input.substr(0, pos);
  38. token = trim(token, delimiter);
  39. Output.push_back(token);
  40. input.erase(0, pos + 1);
  41. input = trim(input, delimiter);
  42. pos = findDelimiterPos(input, delimiter);
  43. }
  44. Output.push_back(input);
  45. return Output;
  46. }
  47. void blinkstatus(int dauer, int _anzahl)
  48. {
  49. gpio_reset_pin(BLINK_GPIO);
  50. gpio_set_direction(BLINK_GPIO, GPIO_MODE_OUTPUT);
  51. for (int i = 0; i < _anzahl; ++i)
  52. {
  53. gpio_set_level(BLINK_GPIO, 0);
  54. vTaskDelay(dauer / portTICK_PERIOD_MS);
  55. gpio_set_level(BLINK_GPIO, 1);
  56. vTaskDelay(dauer / portTICK_PERIOD_MS);
  57. }
  58. }
  59. void strinttoip4(std::string ip, int &a, int &b, int &c, int &d) {
  60. std::stringstream s(ip);
  61. char ch; //to temporarily store the '.'
  62. s >> a >> ch >> b >> ch >> c >> ch >> d;
  63. }
  64. static void event_handler_neu(void* arg, esp_event_base_t event_base,
  65. int32_t event_id, void* event_data)
  66. {
  67. if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_START) {
  68. blinkstatus(200, 1);
  69. esp_wifi_connect();
  70. } else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_DISCONNECTED) {
  71. blinkstatus(200, 5);
  72. esp_wifi_connect();
  73. s_retry_num++;
  74. ESP_LOGI(TAG, "retry to connect to the AP");
  75. } else if (event_base == IP_EVENT && event_id == IP_EVENT_STA_GOT_IP) {
  76. blinkstatus(1000, 3);
  77. ip_event_got_ip_t* event = (ip_event_got_ip_t*) event_data;
  78. ESP_LOGI(TAG, "got ip:" IPSTR, IP2STR(&event->ip_info.ip));
  79. s_retry_num = 0;
  80. xEventGroupSetBits(s_wifi_event_group, WIFI_CONNECTED_BIT);
  81. }
  82. }
  83. void initialise_wifi()
  84. {
  85. s_wifi_event_group = xEventGroupCreate();
  86. ESP_ERROR_CHECK(esp_netif_init());
  87. ESP_ERROR_CHECK(esp_event_loop_create_default());
  88. esp_netif_create_default_wifi_sta();
  89. wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
  90. ESP_ERROR_CHECK(esp_wifi_init(&cfg));
  91. esp_event_handler_instance_t instance_any_id;
  92. esp_event_handler_instance_t instance_got_ip;
  93. ESP_ERROR_CHECK(esp_event_handler_instance_register(WIFI_EVENT,
  94. ESP_EVENT_ANY_ID,
  95. &event_handler_neu,
  96. NULL,
  97. &instance_any_id));
  98. ESP_ERROR_CHECK(esp_event_handler_instance_register(IP_EVENT,
  99. IP_EVENT_STA_GOT_IP,
  100. &event_handler_neu,
  101. NULL,
  102. &instance_got_ip));
  103. wifi_config_t wifi_config = { };
  104. strcpy((char*)wifi_config.sta.ssid, (const char*)ssid.c_str());
  105. strcpy((char*)wifi_config.sta.password, (const char*)passphrase.c_str());
  106. ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_STA) );
  107. ESP_ERROR_CHECK(esp_wifi_set_config(ESP_IF_WIFI_STA, &wifi_config) );
  108. ESP_ERROR_CHECK(esp_wifi_start() );
  109. ESP_LOGI(TAG, "wifi_init_sta finished.");
  110. // Waiting until either the connection is established (WIFI_CONNECTED_BIT) or connection failed for the maximum
  111. // number of re-tries (WIFI_FAIL_BIT). The bits are set by event_handler() (see above)
  112. EventBits_t bits = xEventGroupWaitBits(s_wifi_event_group,
  113. WIFI_CONNECTED_BIT | WIFI_FAIL_BIT,
  114. pdFALSE,
  115. pdFALSE,
  116. portMAX_DELAY);
  117. // xEventGroupWaitBits() returns the bits before the call returned, hence we can test which event actually
  118. // happened.
  119. if (bits & WIFI_CONNECTED_BIT) {
  120. ESP_LOGI(TAG, "connected to ap SSID:%s password:%s",
  121. ssid.c_str(), passphrase.c_str());
  122. } else if (bits & WIFI_FAIL_BIT) {
  123. ESP_LOGI(TAG, "Failed to connect to SSID:%s, password:%s",
  124. ssid.c_str(), passphrase.c_str());
  125. } else {
  126. ESP_LOGE(TAG, "UNEXPECTED EVENT");
  127. }
  128. // The event will not be processed after unregister
  129. ESP_ERROR_CHECK(esp_event_handler_instance_unregister(IP_EVENT, IP_EVENT_STA_GOT_IP, instance_got_ip));
  130. ESP_ERROR_CHECK(esp_event_handler_instance_unregister(WIFI_EVENT, ESP_EVENT_ANY_ID, instance_any_id));
  131. vEventGroupDelete(s_wifi_event_group);
  132. tcpip_adapter_ip_info_t ip_info;
  133. ESP_ERROR_CHECK(tcpip_adapter_get_ip_info(TCPIP_ADAPTER_IF_STA, &ip_info));
  134. ipaddress = std::string(ip4addr_ntoa(&ip_info.ip));
  135. netmask = std::string(ip4addr_ntoa(&ip_info.netmask));
  136. gw = std::string(ip4addr_ntoa(&ip_info.gw));
  137. printf("IPv4 : %s\n", ip4addr_ntoa(&ip_info.ip));
  138. printf("HostName : %s\n", hostname.c_str());
  139. }
  140. void initialise_wifi_fixed_ip2()
  141. {
  142. s_wifi_event_group = xEventGroupCreate();
  143. ESP_ERROR_CHECK(esp_netif_init());
  144. ESP_ERROR_CHECK(esp_event_loop_create_default());
  145. esp_netif_t *my_sta = esp_netif_create_default_wifi_sta();
  146. esp_netif_dhcpc_stop(my_sta);
  147. esp_netif_ip_info_t ip_info;
  148. int a, b, c, d;
  149. strinttoip4(ipaddress, a, b, c, d);
  150. IP4_ADDR(&ip_info.ip, a, b, c, d);
  151. strinttoip4(gw, a, b, c, d);
  152. IP4_ADDR(&ip_info.gw, a, b, c, d);
  153. strinttoip4(netmask, a, b, c, d);
  154. IP4_ADDR(&ip_info.netmask, a, b, c, d);
  155. esp_netif_set_ip_info(my_sta, &ip_info);
  156. wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
  157. ESP_ERROR_CHECK(esp_wifi_init(&cfg));
  158. if (dns.length() > 0) {
  159. esp_netif_dns_info_t dns_info;
  160. ip4_addr_t ip;
  161. ip.addr = esp_ip4addr_aton(dns.c_str());
  162. ip_addr_set_ip4_u32(&dns_info.ip, ip.addr);
  163. ESP_ERROR_CHECK(esp_netif_set_dns_info(my_sta, ESP_NETIF_DNS_MAIN, &dns_info));
  164. }
  165. esp_event_handler_instance_t instance_any_id;
  166. esp_event_handler_instance_t instance_got_ip;
  167. ESP_ERROR_CHECK(esp_event_handler_instance_register(WIFI_EVENT,
  168. ESP_EVENT_ANY_ID,
  169. &event_handler_neu,
  170. NULL,
  171. &instance_any_id));
  172. ESP_ERROR_CHECK(esp_event_handler_instance_register(IP_EVENT,
  173. IP_EVENT_STA_GOT_IP,
  174. &event_handler_neu,
  175. NULL,
  176. &instance_got_ip));
  177. wifi_config_t wifi_config = { };
  178. strcpy((char*)wifi_config.sta.ssid, (const char*)ssid.c_str());
  179. strcpy((char*)wifi_config.sta.password, (const char*)passphrase.c_str());
  180. ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_STA) );
  181. ESP_ERROR_CHECK(esp_wifi_set_config(ESP_IF_WIFI_STA, &wifi_config) );
  182. ESP_ERROR_CHECK(esp_wifi_start() );
  183. ESP_LOGI(TAG, "wifi_init_sta finished.");
  184. // Waiting until either the connection is established (WIFI_CONNECTED_BIT) or connection failed for the maximum
  185. // number of re-tries (WIFI_FAIL_BIT). The bits are set by event_handler() (see above)
  186. EventBits_t bits = xEventGroupWaitBits(s_wifi_event_group,
  187. WIFI_CONNECTED_BIT | WIFI_FAIL_BIT,
  188. pdFALSE,
  189. pdFALSE,
  190. portMAX_DELAY);
  191. // xEventGroupWaitBits() returns the bits before the call returned, hence we can test which event actually
  192. // happened.
  193. if (bits & WIFI_CONNECTED_BIT) {
  194. ESP_LOGI(TAG, "connected to ap SSID:%s password:%s",
  195. ssid.c_str(), passphrase.c_str());
  196. } else if (bits & WIFI_FAIL_BIT) {
  197. ESP_LOGI(TAG, "Failed to connect to SSID:%s, password:%s",
  198. ssid.c_str(), passphrase.c_str());
  199. } else {
  200. ESP_LOGE(TAG, "UNEXPECTED EVENT");
  201. }
  202. // The event will not be processed after unregister
  203. ESP_ERROR_CHECK(esp_event_handler_instance_unregister(IP_EVENT, IP_EVENT_STA_GOT_IP, instance_got_ip));
  204. ESP_ERROR_CHECK(esp_event_handler_instance_unregister(WIFI_EVENT, ESP_EVENT_ANY_ID, instance_any_id));
  205. vEventGroupDelete(s_wifi_event_group);
  206. tcpip_adapter_ip_info_t ip_info2;
  207. ESP_ERROR_CHECK(tcpip_adapter_get_ip_info(TCPIP_ADAPTER_IF_STA, &ip_info2));
  208. ipaddress = std::string(ip4addr_ntoa(&ip_info2.ip));
  209. netmask = std::string(ip4addr_ntoa(&ip_info2.netmask));
  210. gw = std::string(ip4addr_ntoa(&ip_info2.gw));
  211. }
  212. void ConnectToWLAN()
  213. {
  214. if (ipaddress.length() == 0 || gw.length() == 0 || netmask.length() == 0)
  215. {
  216. printf("Connect to WLAN with dyn. IP\n");
  217. initialise_wifi();
  218. }
  219. else
  220. {
  221. printf("Connect to WLAN with fixed IP\n");
  222. initialise_wifi_fixed_ip2();
  223. }
  224. }
  225. bool ChangeHostName(std::string fn, std::string _newhostname)
  226. {
  227. if (_newhostname == hostname)
  228. return false;
  229. string line = "";
  230. std::vector<string> zerlegt;
  231. bool found = false;
  232. std::vector<string> neuesfile;
  233. FILE* pFile;
  234. fn = FormatFileName(fn);
  235. pFile = OpenFileAndWait(fn.c_str(), "r");
  236. printf("file loaded\n");
  237. if (pFile == NULL)
  238. return false;
  239. char zw[1024];
  240. fgets(zw, 1024, pFile);
  241. line = std::string(zw);
  242. while ((line.size() > 0) || !(feof(pFile)))
  243. {
  244. printf("%s", line.c_str());
  245. zerlegt = ZerlegeZeile(line, "=");
  246. zerlegt[0] = trim(zerlegt[0], " ");
  247. if ((zerlegt.size() > 1) && (toUpper(zerlegt[0]) == "HOSTNAME")){
  248. line = "hostname = \"" + _newhostname + "\"\n";
  249. found = true;
  250. }
  251. neuesfile.push_back(line);
  252. if (fgets(zw, 1024, pFile) == NULL)
  253. {
  254. line = "";
  255. }
  256. else
  257. {
  258. line = std::string(zw);
  259. }
  260. }
  261. if (!found)
  262. {
  263. line = "hostname = \"" + _newhostname + "\"\n";
  264. neuesfile.push_back(line);
  265. }
  266. fclose(pFile);
  267. pFile = OpenFileAndWait(fn.c_str(), "w+");
  268. for (int i = 0; i < neuesfile.size(); ++i)
  269. {
  270. fputs(neuesfile[i].c_str(), pFile);
  271. }
  272. fclose(pFile);
  273. return true;
  274. }
  275. void LoadWlanFromFile(std::string fn)
  276. {
  277. string line = "";
  278. std::vector<string> zerlegt;
  279. hostname = std_hostname;
  280. FILE* pFile;
  281. fn = FormatFileName(fn);
  282. pFile = OpenFileAndWait(fn.c_str(), "r");
  283. printf("file loaded\n");
  284. if (pFile == NULL)
  285. return;
  286. char zw[1024];
  287. fgets(zw, 1024, pFile);
  288. line = std::string(zw);
  289. while ((line.size() > 0) || !(feof(pFile)))
  290. {
  291. printf("%s", line.c_str());
  292. zerlegt = ZerlegeZeile(line, "=");
  293. zerlegt[0] = trim(zerlegt[0], " ");
  294. for (int i = 2; i < zerlegt.size(); ++i)
  295. zerlegt[i] = zerlegt[i-1] + zerlegt[i];
  296. if ((zerlegt.size() > 1) && (toUpper(zerlegt[0]) == "HOSTNAME")){
  297. hostname = trim(zerlegt[1]);
  298. if ((hostname[0] == '"') && (hostname[hostname.length()-1] == '"')){
  299. hostname = hostname.substr(1, hostname.length()-2);
  300. }
  301. }
  302. if ((zerlegt.size() > 1) && (toUpper(zerlegt[0]) == "SSID")){
  303. ssid = trim(zerlegt[1]);
  304. if ((ssid[0] == '"') && (ssid[ssid.length()-1] == '"')){
  305. ssid = ssid.substr(1, ssid.length()-2);
  306. }
  307. }
  308. if ((zerlegt.size() > 1) && (toUpper(zerlegt[0]) == "PASSWORD")){
  309. passphrase = zerlegt[1];
  310. if ((passphrase[0] == '"') && (passphrase[passphrase.length()-1] == '"')){
  311. passphrase = passphrase.substr(1, passphrase.length()-2);
  312. }
  313. }
  314. if ((zerlegt.size() > 1) && (toUpper(zerlegt[0]) == "IP")){
  315. ipaddress = zerlegt[1];
  316. if ((ipaddress[0] == '"') && (ipaddress[ipaddress.length()-1] == '"')){
  317. ipaddress = ipaddress.substr(1, ipaddress.length()-2);
  318. }
  319. }
  320. if ((zerlegt.size() > 1) && (toUpper(zerlegt[0]) == "GATEWAY")){
  321. gw = zerlegt[1];
  322. if ((gw[0] == '"') && (gw[gw.length()-1] == '"')){
  323. gw = gw.substr(1, gw.length()-2);
  324. }
  325. }
  326. if ((zerlegt.size() > 1) && (toUpper(zerlegt[0]) == "NETMASK")){
  327. netmask = zerlegt[1];
  328. if ((netmask[0] == '"') && (netmask[netmask.length()-1] == '"')){
  329. netmask = netmask.substr(1, netmask.length()-2);
  330. }
  331. }
  332. if ((zerlegt.size() > 1) && (toUpper(zerlegt[0]) == "DNS")){
  333. dns = zerlegt[1];
  334. if ((dns[0] == '"') && (dns[dns.length()-1] == '"')){
  335. dns = dns.substr(1, dns.length()-2);
  336. }
  337. }
  338. if (fgets(zw, 1024, pFile) == NULL)
  339. {
  340. line = "";
  341. }
  342. else
  343. {
  344. line = std::string(zw);
  345. }
  346. }
  347. fclose(pFile);
  348. // Check if Hostname was empty in .ini if yes set to std_hostname
  349. if(hostname.length() <= 0){
  350. hostname = std_hostname;
  351. }
  352. printf("\nWLan: %s, %s\n", ssid.c_str(), passphrase.c_str());
  353. printf("Hostename: %s\n", hostname.c_str());
  354. printf("Fixed IP: %s, Gateway %s, Netmask %s, DNS %s\n", ipaddress.c_str(), gw.c_str(), netmask.c_str(), dns.c_str());
  355. }
  356. void LoadNetConfigFromFile(std::string _fn, std::string &_ip, std::string &_gw, std::string &_netmask, std::string &_dns)
  357. {
  358. string line = "";
  359. std::vector<string> zerlegt;
  360. FILE* pFile;
  361. _fn = FormatFileName(_fn);
  362. pFile = OpenFileAndWait(_fn.c_str(), "r");
  363. if (pFile == NULL)
  364. return;
  365. char zw[1024];
  366. fgets(zw, 1024, pFile);
  367. line = std::string(zw);
  368. while ((line.size() > 0) || !(feof(pFile)))
  369. {
  370. printf("%s", line.c_str());
  371. zerlegt = ZerlegeZeile(line, "=");
  372. zerlegt[0] = trim(zerlegt[0], " ");
  373. if ((zerlegt.size() > 1) && (toUpper(zerlegt[0]) == "IP")){
  374. _ip = zerlegt[1];
  375. if ((_ip[0] == '"') && (_ip[_ip.length()-1] == '"')){
  376. _ip = _ip.substr(1, _ip.length()-2);
  377. }
  378. }
  379. if ((zerlegt.size() > 1) && (toUpper(zerlegt[0]) == "GATEWAY")){
  380. _gw = zerlegt[1];
  381. if ((_gw[0] == '"') && (_gw[_gw.length()-1] == '"')){
  382. _gw = _gw.substr(1, _gw.length()-2);
  383. }
  384. }
  385. if ((zerlegt.size() > 1) && (toUpper(zerlegt[0]) == "NETMASK")){
  386. _netmask = zerlegt[1];
  387. if ((_netmask[0] == '"') && (_netmask[_netmask.length()-1] == '"')){
  388. _netmask = _netmask.substr(1, _netmask.length()-2);
  389. }
  390. }
  391. if ((zerlegt.size() > 1) && (toUpper(zerlegt[0]) == "DNS")){
  392. _dns = zerlegt[1];
  393. if ((_dns[0] == '"') && (_dns[_dns.length()-1] == '"')){
  394. _dns = _dns.substr(1, _dns.length()-2);
  395. }
  396. }
  397. if (fgets(zw, 1024, pFile) == NULL)
  398. {
  399. line = "";
  400. }
  401. else
  402. {
  403. line = std::string(zw);
  404. }
  405. }
  406. fclose(pFile);
  407. }
  408. std::string getHostname(){
  409. return hostname;
  410. }
  411. std::string getIPAddress(){
  412. return ipaddress;
  413. }
  414. std::string getSSID(){
  415. return ssid;
  416. }
  417. std::string getNetMask(){
  418. return netmask;
  419. }
  420. std::string getGW(){
  421. return gw;
  422. }