wifi.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433
  1. #include "common.h"
  2. #include "WiFi.h"
  3. #include "wifi.h"
  4. #include "config.h"
  5. #include "httpd.h"
  6. #include "led.h"
  7. #include <lwip/dns.h>
  8. #include <lwip/inet.h>
  9. #include <lwip/apps/sntp.h>
  10. #include <esp_sntp.h>
  11. #include <esp_wifi.h>
  12. static String ssid, password, hostname, dnsserver, sntpserver;
  13. static TimerHandle_t sta_failure_timer;
  14. static bool sta_timeout_enabled;
  15. static void sta_timeout(void)
  16. {
  17. // Enable the AP if the STA doesn't connect after a timeout
  18. WiFi.enableAP(true);
  19. }
  20. static void sta_timeout_enable(void)
  21. {
  22. if (!sta_failure_timer || sta_timeout_enabled)
  23. return;
  24. sta_timeout_enabled =
  25. xTimerStart(sta_failure_timer, 1);
  26. }
  27. static void sta_timeout_disable(void)
  28. {
  29. if (!sta_failure_timer || !sta_timeout_enabled)
  30. return;
  31. sta_timeout_enabled =
  32. !xTimerStop(sta_failure_timer, 1);
  33. }
  34. static void sntp_sync_cb(struct timeval *tv)
  35. {
  36. static uint8_t prev_sync_status = SNTP_SYNC_STATUS_RESET;
  37. uint8_t sync_status = sntp_get_sync_status();
  38. switch (sync_status) {
  39. case SNTP_SYNC_STATUS_RESET:
  40. sntp_set_sync_mode(SNTP_SYNC_MODE_IMMED); // Until first sync
  41. time_net_sync(NULL);
  42. break;
  43. case SNTP_SYNC_STATUS_COMPLETED:
  44. sntp_set_sync_mode(SNTP_SYNC_MODE_SMOOTH); // After successful sync
  45. time_net_sync(tv);
  46. break;
  47. default:
  48. break;
  49. }
  50. prev_sync_status = sync_status;
  51. }
  52. static void my_sntp_start()
  53. {
  54. setenv_bool("status.net.sntp.sync", false);
  55. if (getenv_bool("sntp.enabled")) {
  56. sntp_set_time_sync_notification_cb(sntp_sync_cb);
  57. sntp_setoperatingmode(SNTP_OPMODE_POLL);
  58. sntp_servermode_dhcp(!getenv_bool("ip4.dhcp.nosntp"));
  59. sntp_set_sync_mode(SNTP_SYNC_MODE_IMMED); // Until first sync
  60. sntp_init();
  61. } else {
  62. sntp_stop();
  63. }
  64. }
  65. static bool services_started;
  66. static void stop_services(void)
  67. {
  68. if (services_started) {
  69. esp_unregister_shutdown_handler(stop_services);
  70. my_httpd_stop();
  71. services_started = false;
  72. }
  73. }
  74. static inline bool invalid_ip(const ip_addr_t *ip)
  75. {
  76. return !memcmp(ip, &ip_addr_any, sizeof *ip);
  77. }
  78. static void start_services(void)
  79. {
  80. /* Always run after (re)connect */
  81. const ip_addr_t *dns_ip = dns_getserver(0);
  82. if (invalid_ip(dns_ip) || getenv_bool("ip4.dhcp.nodns")) {
  83. /* Static DNS server configuration */
  84. ip_addr_t addr;
  85. if (dnsserver != "" && inet_aton(dnsserver.c_str(), &addr)) {
  86. if (memcmp(dns_ip, &addr, sizeof addr))
  87. dns_setserver(0, &addr);
  88. }
  89. }
  90. {
  91. dns_ip = dns_getserver(0);
  92. const char *dns_server_str = inet_ntoa(*dns_ip);
  93. printf("[DNS] DNS server: %s\n", dns_server_str);
  94. setenv_cond("status.net.dns.server", dns_server_str);
  95. }
  96. // If Arduino supported both of these at the same that would be
  97. // awesome, but it requires ESP-IDF reconfiguration...
  98. if (sntp_enabled()) {
  99. const ip_addr_t *sntp_ip = sntp_getserver(0);
  100. if (invalid_ip(sntp_ip)) {
  101. if (sntpserver != "") {
  102. sntp_setservername(0, sntpserver.c_str());
  103. sntp_ip = sntp_getserver(0);
  104. }
  105. }
  106. if (!invalid_ip(sntp_ip)) {
  107. const char *sntp_server = inet_ntoa(*sntp_ip);
  108. printf("[SNTP] Time server: %s\n", sntp_server);
  109. setenv_cond("status.net.sntp.server", sntp_server);
  110. } else {
  111. unsetenv("status.net.sntp.server");
  112. }
  113. }
  114. /* Only run on first start */
  115. if (!services_started) {
  116. services_started = true;
  117. my_httpd_start();
  118. esp_register_shutdown_handler(stop_services);
  119. }
  120. }
  121. static const char *ip_str(const IPAddress &ip)
  122. {
  123. static char ip_buf[4*4];
  124. const IPAddress ip_none(0,0,0,0);
  125. return strcpy(ip_buf, ip == ip_none ? "" : ip.toString().c_str());
  126. }
  127. static void setenv_ip(const char *var, const IPAddress &ip)
  128. {
  129. setenv_config(var, ip_str(ip));
  130. }
  131. static bool force_conn_update;
  132. static void WiFiEvent(WiFiEvent_t event, WiFiEventInfo_t info)
  133. {
  134. bool retry_sta = false;
  135. bool is_connect = false;
  136. enum connected {
  137. CON_STA = 1,
  138. CON_ETH = 2,
  139. CON_AP = 4
  140. };
  141. static unsigned int connected;
  142. unsigned int prev_connected = connected;
  143. static int ap_clients = 0;
  144. int prev_ap_clients = ap_clients;
  145. IPAddress wifi_local_ip = WiFi.localIP();
  146. const char *local_ip = ip_str(wifi_local_ip);
  147. switch (event) {
  148. case ARDUINO_EVENT_WIFI_READY:
  149. printf("[WIFI] Interface ready\n");
  150. break;
  151. case ARDUINO_EVENT_WIFI_SCAN_DONE:
  152. printf("[WIFI] Completed scan for access points\n");
  153. break;
  154. case ARDUINO_EVENT_WIFI_STA_START:
  155. printf("[WIFI] Client started\n");
  156. break;
  157. case ARDUINO_EVENT_WIFI_STA_STOP:
  158. printf("[WIFI] Clients stopped\n");
  159. connected &= ~CON_STA;
  160. break;
  161. case ARDUINO_EVENT_WIFI_STA_CONNECTED:
  162. printf("[WIFI] Connected to access point\n");
  163. break;
  164. case ARDUINO_EVENT_WIFI_STA_DISCONNECTED:
  165. printf("[WIFI] Disconnected from WiFi access point\n");
  166. connected &= ~CON_STA;
  167. retry_sta = true;
  168. break;
  169. case ARDUINO_EVENT_WIFI_STA_AUTHMODE_CHANGE:
  170. printf("[WIFI] Authentication mode of access point has changed\n");
  171. break;
  172. case ARDUINO_EVENT_WIFI_STA_GOT_IP:
  173. {
  174. printf("[WIFI] Obtained IP address: %s\n", local_ip);
  175. connected |= CON_STA;
  176. is_connect = true;
  177. break;
  178. }
  179. case ARDUINO_EVENT_WIFI_STA_LOST_IP:
  180. {
  181. printf("[WIFI] Lost IP address\n");
  182. connected &= ~CON_STA;
  183. retry_sta = true;
  184. break;
  185. }
  186. case ARDUINO_EVENT_WPS_ER_SUCCESS:
  187. printf("[WIFI] WiFi Protected Setup (WPS): succeeded in enrollee mode\n");
  188. break;
  189. case ARDUINO_EVENT_WPS_ER_FAILED:
  190. printf("[WIFI] WiFi Protected Setup (WPS): failed in enrollee mode\n");
  191. break;
  192. case ARDUINO_EVENT_WPS_ER_TIMEOUT:
  193. printf("[WIFI] WiFi Protected Setup (WPS): timeout in enrollee mode\n");
  194. break;
  195. case ARDUINO_EVENT_WPS_ER_PIN:
  196. printf("[WIFI] WiFi Protected Setup (WPS): pin code in enrollee mode\n");
  197. break;
  198. case ARDUINO_EVENT_WIFI_AP_START:
  199. printf("[WIFI] Access point started\n");
  200. ap_clients = 0;
  201. connected |= CON_AP;
  202. is_connect = true;
  203. break;
  204. case ARDUINO_EVENT_WIFI_AP_STOP:
  205. printf("[WIFI] Access point stopped\n");
  206. connected &= ~CON_AP;
  207. ap_clients = 0;
  208. break;
  209. case ARDUINO_EVENT_WIFI_AP_STACONNECTED:
  210. printf("[WIFI] Client connected\n");
  211. ap_clients++;
  212. break;
  213. case ARDUINO_EVENT_WIFI_AP_STADISCONNECTED:
  214. printf("[WIFI] Client disconnected\n");
  215. ap_clients--;
  216. break;
  217. case ARDUINO_EVENT_WIFI_AP_STAIPASSIGNED:
  218. printf("[WIFI] Assigned IP address %s to client\n",
  219. inet_ntoa(info.wifi_ap_staipassigned.ip));
  220. break;
  221. case ARDUINO_EVENT_WIFI_AP_PROBEREQRECVED:
  222. printf("[WIFI] Received probe request\n");
  223. break;
  224. case ARDUINO_EVENT_WIFI_AP_GOT_IP6:
  225. printf("[WIFI] AP IPv6 is preferred\n");
  226. break;
  227. case ARDUINO_EVENT_WIFI_STA_GOT_IP6:
  228. printf("[WIFI] STA IPv6 is preferred\n");
  229. is_connect = true;
  230. break;
  231. case ARDUINO_EVENT_ETH_GOT_IP6:
  232. printf("[ETH] Ethernet IPv6 is preferred\n");
  233. is_connect = true;
  234. break;
  235. case ARDUINO_EVENT_ETH_START:
  236. printf("[ETH] Ethernet started\n");
  237. break;
  238. case ARDUINO_EVENT_ETH_STOP:
  239. printf("[ETH] Ethernet stopped\n");
  240. connected &= ~CON_ETH;
  241. break;
  242. case ARDUINO_EVENT_ETH_CONNECTED:
  243. printf("[ETH] Ethernet connected\n");
  244. break;
  245. case ARDUINO_EVENT_ETH_DISCONNECTED:
  246. printf("[ETH] Ethernet disconnected\n");
  247. connected &= ~CON_ETH;
  248. retry_sta = true;
  249. break;
  250. case ARDUINO_EVENT_ETH_GOT_IP:
  251. printf("[ETH] Obtained IP address: %s\n", local_ip);
  252. connected |= CON_ETH;
  253. is_connect = true;
  254. break;
  255. default:
  256. break;
  257. }
  258. if (connected & ~CON_AP) {
  259. sta_timeout_disable();
  260. if (!ap_clients)
  261. WiFi.enableAP(false);
  262. } else if (ssid != "") {
  263. sta_timeout_enable();
  264. }
  265. unsigned int conn_change = force_conn_update ?
  266. -1U : (connected ^ prev_connected);
  267. if (conn_change) {
  268. force_conn_update = false;
  269. if (conn_change & CON_STA) {
  270. setenv_bool("status.net.sta.conn", connected & CON_STA);
  271. setenv_config("status.net.sta.ip4",
  272. connected & CON_STA ? local_ip : "");
  273. setenv_ip("status.net.sta.ip4.mask", WiFi.subnetMask());
  274. setenv_ip("status.net.sta.ip4.gw", WiFi.gatewayIP());
  275. }
  276. if (conn_change & CON_AP)
  277. setenv_bool("status.net.ap.conn", connected & CON_AP);
  278. if (conn_change & CON_ETH) {
  279. setenv_bool("status.net.eth.conn", connected & CON_ETH);
  280. setenv_config("status.net.eth.ip4",
  281. connected & CON_ETH ? local_ip : "");
  282. setenv_ip("status.net.eth.ip4.mask", WiFi.subnetMask());
  283. setenv_ip("status.net.eth.ip4.gw", WiFi.gatewayIP());
  284. }
  285. if (ssid == "") {
  286. // No network configured
  287. led_set(LED_GREEN, connected & CON_AP ? LED_FLASH_SLOW : LED_OFF);
  288. } else {
  289. led_set(LED_GREEN, connected & CON_AP ? LED_FLASH_FAST : LED_ON);
  290. }
  291. }
  292. if (is_connect) {
  293. start_services();
  294. }
  295. if (ap_clients != prev_ap_clients)
  296. setenv_ul("status.net.ap.clients", ap_clients);
  297. if (retry_sta) {
  298. WiFi.disconnect();
  299. WiFi.begin();
  300. }
  301. }
  302. static void setenv_mac(const char *var, const uint8_t mac[6])
  303. {
  304. char mac_str[3*6];
  305. snprintf(mac_str, sizeof mac_str, "%02x:%02x:%02x:%02x:%02x:%02x",
  306. mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
  307. setenv(var, mac_str, 1);
  308. }
  309. static void wifi_config_ap(void)
  310. {
  311. /* No network configuration set */
  312. IPAddress AP_IP = IPAddress(192,168,0,1);
  313. IPAddress AP_Netmask = IPAddress(255,255,255,0);
  314. IPAddress AP_Gateway = IPAddress(0,0,0,0); // No gateway
  315. unsigned int channel = time(NULL) % 11; // Pseudo-random
  316. uint8_t mac[6];
  317. char mac_str[6*3];
  318. char ap_ssid[64];
  319. WiFi.softAPmacAddress(mac);
  320. setenv_mac("status.net.ap.mac", mac);
  321. /* The last two bytes of the MAC */
  322. snprintf(ap_ssid, sizeof ap_ssid, "MAX80_%02X%02X", mac[4], mac[5]);
  323. printf("[WIFI] AP SSID %s IP %s netmask %s channel %u\n",
  324. ap_ssid, AP_IP.toString(), AP_Netmask.toString(), channel+1);
  325. setenv_cond("status.net.ap.ssid", ap_ssid);
  326. setenv_ip("status.net.ap.ip4", AP_IP);
  327. setenv_ip("status.net.ap.ip4.mask", AP_Netmask);
  328. setenv_ul("status.net.ap.clients", 0);
  329. WiFi.softAP(ap_ssid, NULL, channel+1, 0, 4, true);
  330. WiFi.softAPConfig(AP_IP, AP_Gateway, AP_Netmask);
  331. WiFi.softAPsetHostname(ap_ssid);
  332. // Conservative setting: 20 MHz (single channel) only; this is for
  333. // reliability, not performance.
  334. esp_wifi_set_bandwidth((wifi_interface_t)ESP_IF_WIFI_AP, WIFI_BW_HT20);
  335. // Enable unconditionally if no SSID
  336. WiFi.enableAP(ssid == "");
  337. }
  338. static void wifi_config_sta(void)
  339. {
  340. uint8_t mac[6];
  341. WiFi.macAddress(mac);
  342. setenv_mac("status.net.sta.mac", mac);
  343. setenv_cond("status.net.sta.ssid", ssid.c_str());
  344. if (ssid == "") {
  345. WiFi.enableSTA(false);
  346. return;
  347. }
  348. sta_failure_timer = xTimerCreate("wifi_sta", configTICK_RATE_HZ*30,
  349. pdFALSE, NULL,
  350. (TimerCallbackFunction_t)sta_timeout);
  351. sta_timeout_enable();
  352. WiFi.begin(ssid.c_str(), password.c_str());
  353. WiFi.setAutoConnect(true);
  354. WiFi.setAutoReconnect(true);
  355. WiFi.enableSTA(true);
  356. }
  357. static void wifi_config(void)
  358. {
  359. ssid = getenv("wifi.ssid");
  360. password = getenv("wifi.psk");
  361. hostname = getenv("hostname");
  362. dnsserver = getenv("ip4.dns");
  363. force_conn_update = true;
  364. WiFi.persistent(false);
  365. WiFi.setSleep(false);
  366. if (hostname != "")
  367. WiFi.hostname(hostname);
  368. wifi_config_sta();
  369. wifi_config_ap();
  370. }
  371. void SetupWiFi() {
  372. services_started = false;
  373. WiFi.onEvent(WiFiEvent);
  374. my_sntp_start();
  375. printf("[INFO] Setting up WiFi\n");
  376. wifi_config();
  377. }