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.

613 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. #if !defined(JUSTWIFI_DISABLE_WPS)
  278. settingsRegisterCommand(F("WIFI.WPS"), [](Embedis* e) {
  279. wifiStartWPS();
  280. DEBUG_MSG_P(PSTR("+OK\n"));
  281. });
  282. #endif
  283. settingsRegisterCommand(F("WIFI.SCAN"), [](Embedis* e) {
  284. _wifiScan();
  285. DEBUG_MSG_P(PSTR("+OK\n"));
  286. });
  287. }
  288. #endif
  289. // -----------------------------------------------------------------------------
  290. // WEB
  291. // -----------------------------------------------------------------------------
  292. #if WEB_SUPPORT
  293. bool _wifiWebSocketOnReceive(const char * key, JsonVariant& value) {
  294. if (strncmp(key, "wifi", 4) == 0) return true;
  295. if (strncmp(key, "ssid", 4) == 0) return true;
  296. if (strncmp(key, "pass", 4) == 0) return true;
  297. if (strncmp(key, "ip", 2) == 0) return true;
  298. if (strncmp(key, "gw", 2) == 0) return true;
  299. if (strncmp(key, "mask", 4) == 0) return true;
  300. if (strncmp(key, "dns", 3) == 0) return true;
  301. return false;
  302. }
  303. void _wifiWebSocketOnSend(JsonObject& root) {
  304. root["maxNetworks"] = WIFI_MAX_NETWORKS;
  305. root["wifiScan"] = getSetting("wifiScan", WIFI_SCAN_NETWORKS).toInt() == 1;
  306. JsonArray& wifi = root.createNestedArray("wifi");
  307. for (byte i=0; i<WIFI_MAX_NETWORKS; i++) {
  308. if (!hasSetting("ssid", i)) break;
  309. JsonObject& network = wifi.createNestedObject();
  310. network["ssid"] = getSetting("ssid", i, "");
  311. network["pass"] = getSetting("pass", i, "");
  312. network["ip"] = getSetting("ip", i, "");
  313. network["gw"] = getSetting("gw", i, "");
  314. network["mask"] = getSetting("mask", i, "");
  315. network["dns"] = getSetting("dns", i, "");
  316. }
  317. }
  318. void _wifiWebSocketOnAction(uint32_t client_id, const char * action, JsonObject& data) {
  319. if (strcmp(action, "scan") == 0) _wifi_scan_client_id = client_id;
  320. }
  321. #endif
  322. // -----------------------------------------------------------------------------
  323. // INFO
  324. // -----------------------------------------------------------------------------
  325. void wifiDebug(WiFiMode_t modes) {
  326. bool footer = false;
  327. if (((modes & WIFI_STA) > 0) && ((WiFi.getMode() & WIFI_STA) > 0)) {
  328. uint8_t * bssid = WiFi.BSSID();
  329. DEBUG_MSG_P(PSTR("[WIFI] ------------------------------------- MODE STA\n"));
  330. DEBUG_MSG_P(PSTR("[WIFI] SSID %s\n"), WiFi.SSID().c_str());
  331. DEBUG_MSG_P(PSTR("[WIFI] IP %s\n"), WiFi.localIP().toString().c_str());
  332. DEBUG_MSG_P(PSTR("[WIFI] MAC %s\n"), WiFi.macAddress().c_str());
  333. DEBUG_MSG_P(PSTR("[WIFI] GW %s\n"), WiFi.gatewayIP().toString().c_str());
  334. DEBUG_MSG_P(PSTR("[WIFI] DNS %s\n"), WiFi.dnsIP().toString().c_str());
  335. DEBUG_MSG_P(PSTR("[WIFI] MASK %s\n"), WiFi.subnetMask().toString().c_str());
  336. DEBUG_MSG_P(PSTR("[WIFI] HOST http://%s.local\n"), WiFi.hostname().c_str());
  337. DEBUG_MSG_P(PSTR("[WIFI] BSSID %02X:%02X:%02X:%02X:%02X:%02X\n"),
  338. bssid[0], bssid[1], bssid[2], bssid[3], bssid[4], bssid[5], bssid[6]
  339. );
  340. DEBUG_MSG_P(PSTR("[WIFI] CH %d\n"), WiFi.channel());
  341. DEBUG_MSG_P(PSTR("[WIFI] RSSI %d\n"), WiFi.RSSI());
  342. footer = true;
  343. }
  344. if (((modes & WIFI_AP) > 0) && ((WiFi.getMode() & WIFI_AP) > 0)) {
  345. DEBUG_MSG_P(PSTR("[WIFI] -------------------------------------- MODE AP\n"));
  346. DEBUG_MSG_P(PSTR("[WIFI] SSID %s\n"), getSetting("hostname").c_str());
  347. DEBUG_MSG_P(PSTR("[WIFI] PASS %s\n"), getSetting("adminPass", ADMIN_PASS).c_str());
  348. DEBUG_MSG_P(PSTR("[WIFI] IP %s\n"), WiFi.softAPIP().toString().c_str());
  349. DEBUG_MSG_P(PSTR("[WIFI] MAC %s\n"), WiFi.softAPmacAddress().c_str());
  350. footer = true;
  351. }
  352. if (WiFi.getMode() == 0) {
  353. DEBUG_MSG_P(PSTR("[WIFI] ------------------------------------- MODE OFF\n"));
  354. DEBUG_MSG_P(PSTR("[WIFI] No connection\n"));
  355. footer = true;
  356. }
  357. if (footer) {
  358. DEBUG_MSG_P(PSTR("[WIFI] ----------------------------------------------\n"));
  359. }
  360. }
  361. void wifiDebug() {
  362. wifiDebug(WIFI_AP_STA);
  363. }
  364. // -----------------------------------------------------------------------------
  365. // API
  366. // -----------------------------------------------------------------------------
  367. String getIP() {
  368. if (WiFi.getMode() == WIFI_AP) {
  369. return WiFi.softAPIP().toString();
  370. }
  371. return WiFi.localIP().toString();
  372. }
  373. String getNetwork() {
  374. if (WiFi.getMode() == WIFI_AP) {
  375. return jw.getAPSSID();
  376. }
  377. return WiFi.SSID();
  378. }
  379. bool wifiConnected() {
  380. return jw.connected();
  381. }
  382. void wifiDisconnect() {
  383. jw.disconnect();
  384. }
  385. void wifiStartAP(bool only) {
  386. if (only) {
  387. jw.enableSTA(false);
  388. jw.disconnect();
  389. jw.resetReconnectTimeout();
  390. }
  391. jw.enableAP(true);
  392. }
  393. void wifiStartAP() {
  394. wifiStartAP(true);
  395. }
  396. #if !defined(JUSTWIFI_DISABLE_WPS)
  397. void wifiStartWPS() {
  398. jw.startWPS();
  399. }
  400. #endif
  401. void wifiReconnectCheck() {
  402. bool connected = false;
  403. #if WEB_SUPPORT
  404. if (wsConnected()) connected = true;
  405. #endif
  406. #if TELNET_SUPPORT
  407. if (telnetConnected()) connected = true;
  408. #endif
  409. jw.setReconnectTimeout(connected ? 0 : WIFI_RECONNECT_INTERVAL);
  410. }
  411. uint8_t wifiState() {
  412. uint8_t state = 0;
  413. if (jw.connected()) state += WIFI_STATE_STA;
  414. if (jw.connectable()) state += WIFI_STATE_AP;
  415. if (_wifi_wps_running) state += WIFI_STATE_WPS;
  416. return state;
  417. }
  418. void wifiRegister(wifi_callback_f callback) {
  419. jw.subscribe(callback);
  420. }
  421. // -----------------------------------------------------------------------------
  422. // INITIALIZATION
  423. // -----------------------------------------------------------------------------
  424. void wifiSetup() {
  425. WiFi.setSleepMode(WIFI_SLEEP_MODE);
  426. _wifiInject();
  427. _wifiConfigure();
  428. // Message callbacks
  429. wifiRegister(_wifiCallback);
  430. #if WIFI_AP_CAPTIVE
  431. wifiRegister(_wifiCaptivePortal);
  432. #endif
  433. #if DEBUG_SUPPORT
  434. wifiRegister(_wifiDebugCallback);
  435. #endif
  436. #if WEB_SUPPORT
  437. wsOnSendRegister(_wifiWebSocketOnSend);
  438. wsOnReceiveRegister(_wifiWebSocketOnReceive);
  439. wsOnAfterParseRegister(_wifiConfigure);
  440. wsOnActionRegister(_wifiWebSocketOnAction);
  441. #endif
  442. #if TERMINAL_SUPPORT
  443. _wifiInitCommands();
  444. #endif
  445. // Register loop
  446. espurnaRegisterLoop(wifiLoop);
  447. }
  448. void wifiLoop() {
  449. // Main wifi loop
  450. jw.loop();
  451. // Process captrive portal DNS queries if in AP mode only
  452. #if WIFI_AP_CAPTIVE
  453. if ((WiFi.getMode() & WIFI_AP) == WIFI_AP) {
  454. _wifi_dnsServer.processNextRequest();
  455. }
  456. #endif
  457. // Do we have a pending scan?
  458. if (_wifi_scan_client_id > 0) {
  459. _wifiScan(_wifi_scan_client_id);
  460. _wifi_scan_client_id = 0;
  461. }
  462. // Check if we should disable AP
  463. static unsigned long last = 0;
  464. if (millis() - last > 60000) {
  465. last = millis();
  466. _wifiCheckAP();
  467. }
  468. }