wifi.cpp 11 KB

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