wifi.cpp 14 KB

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