Fork of the espurna firmware for `mhsw` switches
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

605 lines
16 KiB

8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
6 years ago
  1. /*
  2. WIFI MODULE
  3. Copyright (C) 2016-2018 by Xose Pérez <xose dot perez at gmail dot com>
  4. */
  5. #include "JustWifi.h"
  6. #include <Ticker.h>
  7. uint32_t _wifi_scan_client_id = 0;
  8. bool _wifi_wps_running = false;
  9. uint8_t _wifi_ap_mode = WIFI_AP_FALLBACK;
  10. // -----------------------------------------------------------------------------
  11. // PRIVATE
  12. // -----------------------------------------------------------------------------
  13. void _wifiCheckAP() {
  14. if ((WIFI_AP_FALLBACK == _wifi_ap_mode) &&
  15. (jw.connected()) &&
  16. ((WiFi.getMode() & WIFI_AP) > 0) &&
  17. (WiFi.softAPgetStationNum() == 0)
  18. ) {
  19. jw.enableAP(false);
  20. }
  21. }
  22. void _wifiConfigure() {
  23. jw.setHostname(getSetting("hostname").c_str());
  24. #if USE_PASSWORD
  25. jw.setSoftAP(getSetting("hostname").c_str(), getSetting("adminPass", ADMIN_PASS).c_str());
  26. #else
  27. jw.setSoftAP(getSetting("hostname").c_str());
  28. #endif
  29. jw.setConnectTimeout(WIFI_CONNECT_TIMEOUT);
  30. wifiReconnectCheck();
  31. jw.enableAPFallback(true);
  32. jw.cleanNetworks();
  33. _wifi_ap_mode = getSetting("apmode", WIFI_AP_FALLBACK).toInt();
  34. // If system is flagged unstable we do not init wifi networks
  35. #if SYSTEM_CHECK_ENABLED
  36. if (!systemCheck()) return;
  37. #endif
  38. // Clean settings
  39. _wifiClean(WIFI_MAX_NETWORKS);
  40. int i;
  41. for (i = 0; i< WIFI_MAX_NETWORKS; i++) {
  42. if (getSetting("ssid" + String(i)).length() == 0) break;
  43. if (getSetting("ip" + String(i)).length() == 0) {
  44. jw.addNetwork(
  45. getSetting("ssid" + String(i)).c_str(),
  46. getSetting("pass" + String(i)).c_str()
  47. );
  48. } else {
  49. jw.addNetwork(
  50. getSetting("ssid" + String(i)).c_str(),
  51. getSetting("pass" + String(i)).c_str(),
  52. getSetting("ip" + String(i)).c_str(),
  53. getSetting("gw" + String(i)).c_str(),
  54. getSetting("mask" + String(i)).c_str(),
  55. getSetting("dns" + String(i)).c_str()
  56. );
  57. }
  58. }
  59. jw.scanNetworks(getSetting("wifiScan", WIFI_SCAN_NETWORKS).toInt() == 1);
  60. }
  61. void _wifiScan(uint32_t client_id = 0) {
  62. DEBUG_MSG_P(PSTR("[WIFI] Start scanning\n"));
  63. #if WEB_SUPPORT
  64. String output;
  65. #endif
  66. unsigned char result = WiFi.scanNetworks();
  67. if (result == WIFI_SCAN_FAILED) {
  68. DEBUG_MSG_P(PSTR("[WIFI] Scan failed\n"));
  69. #if WEB_SUPPORT
  70. output = String("Failed scan");
  71. #endif
  72. } else if (result == 0) {
  73. DEBUG_MSG_P(PSTR("[WIFI] No networks found\n"));
  74. #if WEB_SUPPORT
  75. output = String("No networks found");
  76. #endif
  77. } else {
  78. DEBUG_MSG_P(PSTR("[WIFI] %d networks found:\n"), result);
  79. // Populate defined networks with scan data
  80. for (int8_t i = 0; i < result; ++i) {
  81. String ssid_scan;
  82. int32_t rssi_scan;
  83. uint8_t sec_scan;
  84. uint8_t* BSSID_scan;
  85. int32_t chan_scan;
  86. bool hidden_scan;
  87. char buffer[128];
  88. WiFi.getNetworkInfo(i, ssid_scan, sec_scan, rssi_scan, BSSID_scan, chan_scan, hidden_scan);
  89. snprintf_P(buffer, sizeof(buffer),
  90. PSTR("BSSID: %02X:%02X:%02X:%02X:%02X:%02X SEC: %s RSSI: %3d CH: %2d SSID: %s"),
  91. BSSID_scan[1], BSSID_scan[2], BSSID_scan[3], BSSID_scan[4], BSSID_scan[5], BSSID_scan[6],
  92. (sec_scan != ENC_TYPE_NONE ? "YES" : "NO "),
  93. rssi_scan,
  94. chan_scan,
  95. (char *) ssid_scan.c_str()
  96. );
  97. DEBUG_MSG_P(PSTR("[WIFI] > %s\n"), buffer);
  98. #if WEB_SUPPORT
  99. if (client_id > 0) output = output + String(buffer) + String("<br />");
  100. #endif
  101. }
  102. }
  103. #if WEB_SUPPORT
  104. if (client_id > 0) {
  105. output = String("{\"scanResult\": \"") + output + String("\"}");
  106. wsSend(client_id, output.c_str());
  107. }
  108. #endif
  109. WiFi.scanDelete();
  110. }
  111. bool _wifiClean(unsigned char num) {
  112. bool changed = false;
  113. int i = 0;
  114. // Clean defined settings
  115. while (i < num) {
  116. // Skip on first non-defined setting
  117. if (!hasSetting("ssid", i)) {
  118. delSetting("ssid", i);
  119. break;
  120. }
  121. // Delete empty values
  122. if (!hasSetting("pass", i)) delSetting("pass", i);
  123. if (!hasSetting("ip", i)) delSetting("ip", i);
  124. if (!hasSetting("gw", i)) delSetting("gw", i);
  125. if (!hasSetting("mask", i)) delSetting("mask", i);
  126. if (!hasSetting("dns", i)) delSetting("dns", i);
  127. ++i;
  128. }
  129. // Delete all other settings
  130. while (i < WIFI_MAX_NETWORKS) {
  131. changed = hasSetting("ssid", i);
  132. delSetting("ssid", i);
  133. delSetting("pass", i);
  134. delSetting("ip", i);
  135. delSetting("gw", i);
  136. delSetting("mask", i);
  137. delSetting("dns", i);
  138. ++i;
  139. }
  140. return changed;
  141. }
  142. // Inject hardcoded networks
  143. void _wifiInject() {
  144. if (strlen(WIFI1_SSID)) {
  145. if (!hasSetting("ssid", 0)) {
  146. setSetting("ssid", 0, WIFI1_SSID);
  147. setSetting("pass", 0, WIFI1_PASS);
  148. setSetting("ip", 0, WIFI1_IP);
  149. setSetting("gw", 0, WIFI1_GW);
  150. setSetting("mask", 0, WIFI1_MASK);
  151. setSetting("dns", 0, WIFI1_DNS);
  152. }
  153. if (strlen(WIFI2_SSID)) {
  154. if (!hasSetting("ssid", 1)) {
  155. setSetting("ssid", 1, WIFI2_SSID);
  156. setSetting("pass", 1, WIFI2_PASS);
  157. setSetting("ip", 1, WIFI2_IP);
  158. setSetting("gw", 1, WIFI2_GW);
  159. setSetting("mask", 1, WIFI2_MASK);
  160. setSetting("dns", 1, WIFI2_DNS);
  161. }
  162. }
  163. }
  164. }
  165. void _wifiCallback(justwifi_messages_t code, char * parameter) {
  166. if (MESSAGE_WPS_START == code) {
  167. _wifi_wps_running = true;
  168. }
  169. if (MESSAGE_WPS_ERROR == code) {
  170. _wifi_wps_running = false;
  171. }
  172. if (MESSAGE_WPS_SUCCESS == code) {
  173. String ssid = WiFi.SSID();
  174. String pass = WiFi.psk();
  175. // Look for the same SSID
  176. uint8_t count = 0;
  177. while (count < WIFI_MAX_NETWORKS) {
  178. if (!hasSetting("ssid", count)) break;
  179. if (ssid.equals(getSetting("ssid", count, ""))) break;
  180. count++;
  181. }
  182. // If we have reached the max we overwrite the first one
  183. if (WIFI_MAX_NETWORKS == count) count = 0;
  184. setSetting("ssid", count, ssid);
  185. setSetting("pass", count, pass);
  186. _wifi_wps_running = false;
  187. }
  188. }
  189. #if WIFI_AP_CAPTIVE
  190. #include "DNSServer.h"
  191. DNSServer _wifi_dnsServer;
  192. void _wifiCaptivePortal(justwifi_messages_t code, char * parameter) {
  193. if (MESSAGE_ACCESSPOINT_CREATED == code) {
  194. _wifi_dnsServer.setErrorReplyCode(DNSReplyCode::NoError);
  195. _wifi_dnsServer.start(53, "*", WiFi.softAPIP());
  196. DEBUG_MSG_P(PSTR("[WIFI] Captive portal enabled\n"));
  197. }
  198. if (MESSAGE_CONNECTED == code) {
  199. _wifi_dnsServer.stop();
  200. DEBUG_MSG_P(PSTR("[WIFI] Captive portal disabled\n"));
  201. }
  202. }
  203. #endif // WIFI_AP_CAPTIVE
  204. #if DEBUG_SUPPORT
  205. void _wifiDebugCallback(justwifi_messages_t code, char * parameter) {
  206. // -------------------------------------------------------------------------
  207. if (code == MESSAGE_SCANNING) {
  208. DEBUG_MSG_P(PSTR("[WIFI] Scanning\n"));
  209. }
  210. if (code == MESSAGE_SCAN_FAILED) {
  211. DEBUG_MSG_P(PSTR("[WIFI] Scan failed\n"));
  212. }
  213. if (code == MESSAGE_NO_NETWORKS) {
  214. DEBUG_MSG_P(PSTR("[WIFI] No networks found\n"));
  215. }
  216. if (code == MESSAGE_NO_KNOWN_NETWORKS) {
  217. DEBUG_MSG_P(PSTR("[WIFI] No known networks found\n"));
  218. }
  219. if (code == MESSAGE_FOUND_NETWORK) {
  220. DEBUG_MSG_P(PSTR("[WIFI] %s\n"), parameter);
  221. }
  222. // -------------------------------------------------------------------------
  223. if (code == MESSAGE_CONNECTING) {
  224. DEBUG_MSG_P(PSTR("[WIFI] Connecting to %s\n"), parameter);
  225. }
  226. if (code == MESSAGE_CONNECT_WAITING) {
  227. // too much noise
  228. }
  229. if (code == MESSAGE_CONNECT_FAILED) {
  230. DEBUG_MSG_P(PSTR("[WIFI] Could not connect to %s\n"), parameter);
  231. }
  232. if (code == MESSAGE_CONNECTED) {
  233. wifiDebug(WIFI_STA);
  234. }
  235. if (code == MESSAGE_DISCONNECTED) {
  236. DEBUG_MSG_P(PSTR("[WIFI] Disconnected\n"));
  237. }
  238. // -------------------------------------------------------------------------
  239. if (code == MESSAGE_ACCESSPOINT_CREATING) {
  240. DEBUG_MSG_P(PSTR("[WIFI] Creating access point\n"));
  241. }
  242. if (code == MESSAGE_ACCESSPOINT_CREATED) {
  243. wifiDebug(WIFI_AP);
  244. }
  245. if (code == MESSAGE_ACCESSPOINT_FAILED) {
  246. DEBUG_MSG_P(PSTR("[WIFI] Could not create access point\n"));
  247. }
  248. if (code == MESSAGE_ACCESSPOINT_DESTROYED) {
  249. DEBUG_MSG_P(PSTR("[WIFI] Access point destroyed\n"));
  250. }
  251. // -------------------------------------------------------------------------
  252. if (code == MESSAGE_WPS_START) {
  253. DEBUG_MSG_P(PSTR("[WIFI] WPS started\n"));
  254. }
  255. if (code == MESSAGE_WPS_SUCCESS) {
  256. DEBUG_MSG_P(PSTR("[WIFI] WPS succeded!\n"));
  257. }
  258. if (code == MESSAGE_WPS_ERROR) {
  259. DEBUG_MSG_P(PSTR("[WIFI] WPS failed\n"));
  260. }
  261. }
  262. #endif // DEBUG_SUPPORT
  263. // -----------------------------------------------------------------------------
  264. // SETTINGS
  265. // -----------------------------------------------------------------------------
  266. #if TERMINAL_SUPPORT
  267. void _wifiInitCommands() {
  268. settingsRegisterCommand(F("WIFI.RESET"), [](Embedis* e) {
  269. _wifiConfigure();
  270. wifiDisconnect();
  271. DEBUG_MSG_P(PSTR("+OK\n"));
  272. });
  273. settingsRegisterCommand(F("WIFI.AP"), [](Embedis* e) {
  274. wifiStartAP();
  275. DEBUG_MSG_P(PSTR("+OK\n"));
  276. });
  277. settingsRegisterCommand(F("WIFI.WPS"), [](Embedis* e) {
  278. wifiStartWPS();
  279. DEBUG_MSG_P(PSTR("+OK\n"));
  280. });
  281. settingsRegisterCommand(F("WIFI.SCAN"), [](Embedis* e) {
  282. _wifiScan();
  283. DEBUG_MSG_P(PSTR("+OK\n"));
  284. });
  285. }
  286. #endif
  287. // -----------------------------------------------------------------------------
  288. // WEB
  289. // -----------------------------------------------------------------------------
  290. #if WEB_SUPPORT
  291. bool _wifiWebSocketOnReceive(const char * key, JsonVariant& value) {
  292. if (strncmp(key, "wifi", 4) == 0) return true;
  293. if (strncmp(key, "ssid", 4) == 0) return true;
  294. if (strncmp(key, "pass", 4) == 0) return true;
  295. if (strncmp(key, "ip", 2) == 0) return true;
  296. if (strncmp(key, "gw", 2) == 0) return true;
  297. if (strncmp(key, "mask", 4) == 0) return true;
  298. if (strncmp(key, "dns", 3) == 0) return true;
  299. return false;
  300. }
  301. void _wifiWebSocketOnSend(JsonObject& root) {
  302. root["maxNetworks"] = WIFI_MAX_NETWORKS;
  303. root["wifiScan"] = getSetting("wifiScan", WIFI_SCAN_NETWORKS).toInt() == 1;
  304. JsonArray& wifi = root.createNestedArray("wifi");
  305. for (byte i=0; i<WIFI_MAX_NETWORKS; i++) {
  306. if (!hasSetting("ssid", i)) break;
  307. JsonObject& network = wifi.createNestedObject();
  308. network["ssid"] = getSetting("ssid", i, "");
  309. network["pass"] = getSetting("pass", i, "");
  310. network["ip"] = getSetting("ip", i, "");
  311. network["gw"] = getSetting("gw", i, "");
  312. network["mask"] = getSetting("mask", i, "");
  313. network["dns"] = getSetting("dns", i, "");
  314. }
  315. }
  316. void _wifiWebSocketOnAction(uint32_t client_id, const char * action, JsonObject& data) {
  317. if (strcmp(action, "scan") == 0) _wifi_scan_client_id = client_id;
  318. }
  319. #endif
  320. // -----------------------------------------------------------------------------
  321. // API
  322. // -----------------------------------------------------------------------------
  323. String getIP() {
  324. if (WiFi.getMode() == WIFI_AP) {
  325. return WiFi.softAPIP().toString();
  326. }
  327. return WiFi.localIP().toString();
  328. }
  329. String getNetwork() {
  330. if (WiFi.getMode() == WIFI_AP) {
  331. return jw.getAPSSID();
  332. }
  333. return WiFi.SSID();
  334. }
  335. bool wifiConnected() {
  336. return jw.connected();
  337. }
  338. void wifiDisconnect() {
  339. jw.disconnect();
  340. }
  341. void wifiStartAP(bool only) {
  342. if (only) {
  343. jw.enableSTA(false);
  344. jw.disconnect();
  345. jw.resetReconnectTimeout();
  346. }
  347. jw.enableAP(true);
  348. }
  349. void wifiStartAP() {
  350. wifiStartAP(true);
  351. }
  352. void wifiStartWPS() {
  353. jw.startWPS();
  354. }
  355. void wifiReconnectCheck() {
  356. bool connected = false;
  357. #if WEB_SUPPORT
  358. if (wsConnected()) connected = true;
  359. #endif
  360. #if TELNET_SUPPORT
  361. if (telnetConnected()) connected = true;
  362. #endif
  363. jw.setReconnectTimeout(connected ? 0 : WIFI_RECONNECT_INTERVAL);
  364. }
  365. uint8_t wifiState() {
  366. uint8_t state = 0;
  367. if (jw.connected()) state += WIFI_STATE_STA;
  368. if (jw.connectable()) state += WIFI_STATE_AP;
  369. if (_wifi_wps_running) state += WIFI_STATE_WPS;
  370. return state;
  371. }
  372. void wifiDebug(WiFiMode_t modes) {
  373. bool footer = false;
  374. if (((modes & WIFI_STA) > 0) && ((WiFi.getMode() & WIFI_STA) > 0)) {
  375. uint8_t * bssid = WiFi.BSSID();
  376. DEBUG_MSG_P(PSTR("[WIFI] ------------------------------------- MODE STA\n"));
  377. DEBUG_MSG_P(PSTR("[WIFI] SSID %s\n"), WiFi.SSID().c_str());
  378. DEBUG_MSG_P(PSTR("[WIFI] IP %s\n"), WiFi.localIP().toString().c_str());
  379. DEBUG_MSG_P(PSTR("[WIFI] MAC %s\n"), WiFi.macAddress().c_str());
  380. DEBUG_MSG_P(PSTR("[WIFI] GW %s\n"), WiFi.gatewayIP().toString().c_str());
  381. DEBUG_MSG_P(PSTR("[WIFI] DNS %s\n"), WiFi.dnsIP().toString().c_str());
  382. DEBUG_MSG_P(PSTR("[WIFI] MASK %s\n"), WiFi.subnetMask().toString().c_str());
  383. DEBUG_MSG_P(PSTR("[WIFI] HOST http://%s.local\n"), WiFi.hostname().c_str());
  384. DEBUG_MSG_P(PSTR("[WIFI] BSSID %02X:%02X:%02X:%02X:%02X:%02X\n"),
  385. bssid[0], bssid[1], bssid[2], bssid[3], bssid[4], bssid[5], bssid[6]
  386. );
  387. DEBUG_MSG_P(PSTR("[WIFI] CH %d\n"), WiFi.channel());
  388. DEBUG_MSG_P(PSTR("[WIFI] RSSI %d\n"), WiFi.RSSI());
  389. footer = true;
  390. }
  391. if (((modes & WIFI_AP) > 0) && ((WiFi.getMode() & WIFI_AP) > 0)) {
  392. DEBUG_MSG_P(PSTR("[WIFI] -------------------------------------- MODE AP\n"));
  393. DEBUG_MSG_P(PSTR("[WIFI] SSID %s\n"), jw.getAPSSID().c_str());
  394. DEBUG_MSG_P(PSTR("[WIFI] PASS %s\n"), getSetting("adminPass", ADMIN_PASS).c_str());
  395. DEBUG_MSG_P(PSTR("[WIFI] IP %s\n"), WiFi.softAPIP().toString().c_str());
  396. DEBUG_MSG_P(PSTR("[WIFI] MAC %s\n"), WiFi.softAPmacAddress().c_str());
  397. footer = true;
  398. }
  399. if (WiFi.getMode() == 0) {
  400. DEBUG_MSG_P(PSTR("[WIFI] ------------------------------------- MODE OFF\n"));
  401. DEBUG_MSG_P(PSTR("[WIFI] No connection\n"));
  402. footer = true;
  403. }
  404. if (footer) {
  405. DEBUG_MSG_P(PSTR("[WIFI] ----------------------------------------------\n"));
  406. }
  407. }
  408. void wifiDebug() {
  409. wifiDebug(WIFI_AP_STA);
  410. }
  411. void wifiRegister(wifi_callback_f callback) {
  412. jw.subscribe(callback);
  413. }
  414. // -----------------------------------------------------------------------------
  415. // INITIALIZATION
  416. // -----------------------------------------------------------------------------
  417. void wifiSetup() {
  418. WiFi.setSleepMode(WIFI_SLEEP_MODE);
  419. _wifiInject();
  420. _wifiConfigure();
  421. // Message callbacks
  422. wifiRegister(_wifiCallback);
  423. #if WIFI_AP_CAPTIVE
  424. wifiRegister(_wifiCaptivePortal);
  425. #endif
  426. #if DEBUG_SUPPORT
  427. wifiRegister(_wifiDebugCallback);
  428. #endif
  429. #if WEB_SUPPORT
  430. wsOnSendRegister(_wifiWebSocketOnSend);
  431. wsOnReceiveRegister(_wifiWebSocketOnReceive);
  432. wsOnAfterParseRegister(_wifiConfigure);
  433. wsOnActionRegister(_wifiWebSocketOnAction);
  434. #endif
  435. #if TERMINAL_SUPPORT
  436. _wifiInitCommands();
  437. #endif
  438. // Register loop
  439. espurnaRegisterLoop(wifiLoop);
  440. }
  441. void wifiLoop() {
  442. // Main wifi loop
  443. jw.loop();
  444. // Process captrive portal DNS queries if in AP mode only
  445. #if WIFI_AP_CAPTIVE
  446. if ((WiFi.getMode() & WIFI_AP) == WIFI_AP) {
  447. _wifi_dnsServer.processNextRequest();
  448. }
  449. #endif
  450. // Do we have a pending scan?
  451. if (_wifi_scan_client_id > 0) {
  452. _wifiScan(_wifi_scan_client_id);
  453. _wifi_scan_client_id = 0;
  454. }
  455. // Check if we should disable AP
  456. static unsigned long last = 0;
  457. if (millis() - last > 60000) {
  458. last = millis();
  459. _wifiCheckAP();
  460. }
  461. }