wifi.cpp 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  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. if (prev_sync_status != sync_status) {
  42. printf("[SNTP] time synchronization lost\n");
  43. }
  44. break;
  45. case SNTP_SYNC_STATUS_COMPLETED:
  46. sntp_set_sync_mode(SNTP_SYNC_MODE_SMOOTH); // After successful sync
  47. if (prev_sync_status != sync_status) {
  48. char timebuf[64];
  49. const struct tm *tm = localtime(&tv->tv_sec);
  50. strftime(timebuf, sizeof timebuf, "%a %Y-%m-%d %H:%M:%S %z", tm);
  51. printf("[SNTP] Time synchronized: %s\n", timebuf);
  52. }
  53. break;
  54. default:
  55. break;
  56. }
  57. prev_sync_status = sync_status;
  58. }
  59. static void my_sntp_start()
  60. {
  61. sntp_set_time_sync_notification_cb(sntp_sync_cb);
  62. sntp_setoperatingmode(SNTP_OPMODE_POLL);
  63. sntp_servermode_dhcp(1);
  64. sntp_set_sync_mode(SNTP_SYNC_MODE_IMMED); // Until first sync
  65. sntp_init();
  66. }
  67. static bool services_started;
  68. static void stop_services(void)
  69. {
  70. if (services_started) {
  71. esp_unregister_shutdown_handler(stop_services);
  72. my_httpd_stop();
  73. services_started = false;
  74. }
  75. }
  76. static inline bool invalid_ip(const ip_addr_t *ip)
  77. {
  78. return !memcmp(ip, &ip_addr_any, sizeof *ip);
  79. }
  80. static void start_services(void)
  81. {
  82. /* Always run after (re)connect */
  83. const ip_addr_t *dns_ip = dns_getserver(0);
  84. if (invalid_ip(dns_ip) || getenv_bool("ip4.dhcp.nodns")) {
  85. /* Static DNS server configuration */
  86. ip_addr_t addr;
  87. if (dnsserver != "" && inet_aton(dnsserver.c_str(), &addr)) {
  88. dns_setserver(0, &addr);
  89. }
  90. }
  91. dns_ip = dns_getserver(0);
  92. printf("[DNS] DNS server: %s\n", inet_ntoa(*dns_ip));
  93. // If Arduino supported both of these at the same that would be
  94. // awesome, but it requires ESP-IDF reconfiguration...
  95. const ip_addr_t *sntp_ip = sntp_getserver(0);
  96. if (invalid_ip(sntp_ip) || getenv_bool("ip4.dhcp.nosntp")) {
  97. if (sntpserver != "")
  98. sntp_setservername(0, sntpserver.c_str());
  99. }
  100. sntp_ip = sntp_getserver(0);
  101. printf("[SNTP] Time server: %s\n", inet_ntoa(*sntp_ip));
  102. /* Only run on first start */
  103. if (!services_started) {
  104. services_started = true;
  105. my_httpd_start();
  106. esp_register_shutdown_handler(stop_services);
  107. }
  108. }
  109. static String wifi_local_ip(void)
  110. {
  111. return WiFi.localIP().toString();
  112. }
  113. static void WiFiEvent(WiFiEvent_t event, WiFiEventInfo_t info)
  114. {
  115. bool retry_sta = false;
  116. bool is_connect = false;
  117. enum connected {
  118. CON_STA = 1,
  119. CON_ETH = 2,
  120. CON_AP = 4
  121. };
  122. static int connected;
  123. static int ap_clients = 0;
  124. switch (event) {
  125. case ARDUINO_EVENT_WIFI_READY:
  126. printf("[WIFI] Interface ready\n");
  127. break;
  128. case ARDUINO_EVENT_WIFI_SCAN_DONE:
  129. printf("[WIFI] Completed scan for access points\n");
  130. break;
  131. case ARDUINO_EVENT_WIFI_STA_START:
  132. printf("[WIFI] Client started\n");
  133. break;
  134. case ARDUINO_EVENT_WIFI_STA_STOP:
  135. printf("[WIFI] Clients stopped\n");
  136. connected &= ~CON_STA;
  137. break;
  138. case ARDUINO_EVENT_WIFI_STA_CONNECTED:
  139. printf("[WIFI] Connected to access point\n");
  140. break;
  141. case ARDUINO_EVENT_WIFI_STA_DISCONNECTED:
  142. printf("[WIFI] Disconnected from WiFi access point\n");
  143. connected &= ~CON_STA;
  144. retry_sta = true;
  145. break;
  146. case ARDUINO_EVENT_WIFI_STA_AUTHMODE_CHANGE:
  147. printf("[WIFI] Authentication mode of access point has changed\n");
  148. break;
  149. case ARDUINO_EVENT_WIFI_STA_GOT_IP:
  150. printf("[WIFI] Obtained IP address: %s\n", wifi_local_ip().c_str());
  151. connected |= CON_STA;
  152. is_connect = true;
  153. break;
  154. case ARDUINO_EVENT_WIFI_STA_LOST_IP:
  155. printf("[WIFI] Lost IP address and IP address is reset to 0\n");
  156. connected &= ~CON_STA;
  157. retry_sta = true;
  158. break;
  159. case ARDUINO_EVENT_WPS_ER_SUCCESS:
  160. printf("[WIFI] WiFi Protected Setup (WPS): succeeded in enrollee mode\n");
  161. break;
  162. case ARDUINO_EVENT_WPS_ER_FAILED:
  163. printf("[WIFI] WiFi Protected Setup (WPS): failed in enrollee mode\n");
  164. break;
  165. case ARDUINO_EVENT_WPS_ER_TIMEOUT:
  166. printf("[WIFI] WiFi Protected Setup (WPS): timeout in enrollee mode\n");
  167. break;
  168. case ARDUINO_EVENT_WPS_ER_PIN:
  169. printf("[WIFI] WiFi Protected Setup (WPS): pin code in enrollee mode\n");
  170. break;
  171. case ARDUINO_EVENT_WIFI_AP_START:
  172. printf("[WIFI] Access point started\n");
  173. ap_clients = 0;
  174. connected |= CON_AP;
  175. is_connect = true;
  176. break;
  177. case ARDUINO_EVENT_WIFI_AP_STOP:
  178. printf("[WIFI] Access point stopped\n");
  179. connected &= ~CON_AP;
  180. ap_clients = 0;
  181. break;
  182. case ARDUINO_EVENT_WIFI_AP_STACONNECTED:
  183. printf("[WIFI] Client connected\n");
  184. ap_clients++;
  185. break;
  186. case ARDUINO_EVENT_WIFI_AP_STADISCONNECTED:
  187. printf("[WIFI] Client disconnected\n");
  188. ap_clients--;
  189. break;
  190. case ARDUINO_EVENT_WIFI_AP_STAIPASSIGNED:
  191. printf("[WIFI] Assigned IP address %s to client\n",
  192. inet_ntoa(info.wifi_ap_staipassigned.ip));
  193. break;
  194. case ARDUINO_EVENT_WIFI_AP_PROBEREQRECVED:
  195. printf("[WIFI] Received probe request\n");
  196. break;
  197. case ARDUINO_EVENT_WIFI_AP_GOT_IP6:
  198. printf("[WIFI] AP IPv6 is preferred\n");
  199. break;
  200. case ARDUINO_EVENT_WIFI_STA_GOT_IP6:
  201. printf("[WIFI] STA IPv6 is preferred\n");
  202. is_connect = true;
  203. break;
  204. case ARDUINO_EVENT_ETH_GOT_IP6:
  205. printf("[ETH] Ethernet IPv6 is preferred\n");
  206. is_connect = true;
  207. break;
  208. case ARDUINO_EVENT_ETH_START:
  209. printf("[ETH] Ethernet started\n");
  210. break;
  211. case ARDUINO_EVENT_ETH_STOP:
  212. printf("[ETH] Ethernet stopped\n");
  213. connected &= ~CON_ETH;
  214. break;
  215. case ARDUINO_EVENT_ETH_CONNECTED:
  216. printf("[ETH] Ethernet connected\n");
  217. break;
  218. case ARDUINO_EVENT_ETH_DISCONNECTED:
  219. printf("[ETH] Ethernet disconnected\n");
  220. connected &= ~CON_ETH;
  221. retry_sta = true;
  222. break;
  223. case ARDUINO_EVENT_ETH_GOT_IP:
  224. printf("[ETH] Obtained IP address: %s\n", wifi_local_ip().c_str());
  225. connected |= CON_ETH;
  226. is_connect = true;
  227. default:
  228. break;
  229. }
  230. if (connected & ~CON_AP) {
  231. sta_timeout_disable();
  232. if (!ap_clients)
  233. WiFi.enableAP(false);
  234. } else if (ssid != "") {
  235. sta_timeout_enable();
  236. }
  237. if (ssid == "") {
  238. // No network configured
  239. led_set(LED_GREEN, connected & CON_AP ? LED_FLASH_SLOW : LED_OFF);
  240. } else {
  241. led_set(LED_GREEN, connected & CON_AP ? LED_FLASH_FAST : LED_ON);
  242. }
  243. /* Maybe need to do these in a different thread? */
  244. if (is_connect) {
  245. start_services();
  246. }
  247. if (retry_sta) {
  248. WiFi.disconnect();
  249. WiFi.begin();
  250. }
  251. }
  252. static void wifi_config_ap(void)
  253. {
  254. /* No network configuration set */
  255. IPAddress AP_IP = IPAddress(192,168,0,1);
  256. IPAddress AP_Netmask = IPAddress(255,255,255,0);
  257. IPAddress AP_Gateway = IPAddress(0,0,0,0); // No gateway
  258. unsigned int channel = time(NULL) % 11; // Pseudo-random
  259. uint8_t mac[6];
  260. char ap_ssid[64];
  261. WiFi.macAddress(mac);
  262. /* The last two bytes of the MAC */
  263. snprintf(ap_ssid, sizeof ap_ssid, "MAX80_%02X%02X", mac[4], mac[5]);
  264. printf("[WIFI] AP SSID %s IP %s netmask %s channel %u\n",
  265. ap_ssid, AP_IP.toString(), AP_Netmask.toString(), channel+1);
  266. printf("WiFi.softAP\n");
  267. WiFi.softAP(ap_ssid, NULL, channel+1, 0, 4, true);
  268. printf("WiFi.softAPConfig\n");
  269. WiFi.softAPConfig(AP_IP, AP_Gateway, AP_Netmask);
  270. printf("WiFi.softAPsetHostname\n");
  271. WiFi.softAPsetHostname(ap_ssid);
  272. // Conservative setting: 20 MHz (single channel) only; this is for
  273. // reliability, not performance.
  274. printf("esp_wifi_set_bandwidth\n");
  275. esp_wifi_set_bandwidth((wifi_interface_t)ESP_IF_WIFI_AP, WIFI_BW_HT20);
  276. printf("WiFi.enableAP\n");
  277. WiFi.enableAP(ssid == "");
  278. printf("wifi_config_ap done\n");
  279. }
  280. static void wifi_config_sta(void)
  281. {
  282. if (ssid == "") {
  283. WiFi.enableSTA(false);
  284. return;
  285. }
  286. sta_failure_timer = xTimerCreate("wifi_sta", configTICK_RATE_HZ*30,
  287. pdFALSE, NULL,
  288. (TimerCallbackFunction_t)sta_timeout);
  289. sta_timeout_enable();
  290. WiFi.begin(ssid.c_str(), password.c_str());
  291. WiFi.setAutoConnect(true);
  292. WiFi.setAutoReconnect(true);
  293. WiFi.enableSTA(true);
  294. }
  295. static void wifi_config(void)
  296. {
  297. ssid = getenv("wifi.ssid");
  298. password = getenv("wifi.psk");
  299. hostname = getenv("hostname");
  300. sntpserver = getenv_bool("sntp") ? getenv("sntp.server") : "";
  301. dnsserver = getenv("ip4.dns");
  302. WiFi.persistent(false);
  303. WiFi.setSleep(false);
  304. if (hostname != "")
  305. WiFi.hostname(hostname);
  306. wifi_config_sta();
  307. wifi_config_ap();
  308. }
  309. void SetupWiFi() {
  310. services_started = false;
  311. WiFi.onEvent(WiFiEvent);
  312. my_sntp_start();
  313. printf("[INFO] Setting up WiFi\n");
  314. wifi_config();
  315. }