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.

648 lines
18 KiB

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