2
0

wifi.cpp 13 KB

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