-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnet.cpp
More file actions
87 lines (73 loc) · 2.09 KB
/
Copy pathnet.cpp
File metadata and controls
87 lines (73 loc) · 2.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
#include "net.h"
#include "config.h"
#include "credentials.h"
#include <WiFi.h>
#include <DNSServer.h>
#include <ESPmDNS.h>
#include <Preferences.h>
namespace {
Preferences prefs;
DNSServer dns;
net::Mode g_mode = net::MODE_AP;
const IPAddress kApIp(192, 168, 4, 1);
bool connectSTA(const String& ssid, const String& pass, uint32_t timeoutMs) {
WiFi.mode(WIFI_STA);
WiFi.setHostname(INKFRAME_HOSTNAME);
WiFi.begin(ssid.c_str(), pass.c_str());
uint32_t t0 = millis();
while (WiFi.status() != WL_CONNECTED && millis() - t0 < timeoutMs) delay(200);
return WiFi.status() == WL_CONNECTED;
}
void startAP() {
WiFi.mode(WIFI_AP);
WiFi.softAPConfig(kApIp, kApIp, IPAddress(255, 255, 255, 0));
WiFi.softAP(INKFRAME_AP_SSID, INKFRAME_AP_PASS);
dns.start(53, "*", kApIp); // captive portal: resolve everything to us
g_mode = net::MODE_AP;
}
} // namespace
net::Mode net::begin() {
prefs.begin("wifi", true);
String ssid = prefs.getString("ssid", "");
String pass = prefs.getString("pass", "");
prefs.end();
// No saved creds yet? Use the Wi-Fi baked in at build time (secrets.h).
if (ssid.isEmpty() && strlen(WIFI_SSID) > 0) {
ssid = WIFI_SSID;
pass = WIFI_PASS;
}
if (ssid.length() && connectSTA(ssid, pass, 15000)) {
g_mode = MODE_STA;
if (MDNS.begin(INKFRAME_HOSTNAME)) MDNS.addService("http", "tcp", 80);
return MODE_STA;
}
startAP();
return MODE_AP;
}
void net::loop() {
if (g_mode == MODE_AP) dns.processNextRequest();
}
bool net::isAp() { return g_mode == MODE_AP; }
String net::ip() {
return (g_mode == MODE_AP ? WiFi.softAPIP() : WiFi.localIP()).toString();
}
String net::ssid() {
return g_mode == MODE_AP ? String(INKFRAME_AP_SSID) : WiFi.SSID();
}
bool net::haveCreds() {
prefs.begin("wifi", true);
bool has = prefs.getString("ssid", "").length() > 0;
prefs.end();
return has;
}
void net::saveCreds(const String& ssid, const String& pass) {
prefs.begin("wifi", false);
prefs.putString("ssid", ssid);
prefs.putString("pass", pass);
prefs.end();
}
void net::clearCreds() {
prefs.begin("wifi", false);
prefs.clear();
prefs.end();
}