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.

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