summaryrefslogtreecommitdiff
path: root/portal.cpp
blob: 5013249b4bd30733bd05ad8b7aa780082abb8fad (plain)
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
#include "portal.h"

//#define DEBUG

#define NONE -1
#define BLINK -2
#define FADEIN -3
#define FADEOUT -4

const IPAddress apIP(192, 168, 1, 1);
const char* apSSID;

boolean isAPactive;
String scanSSIDList;

int apiOverrides[4] = {NONE, NONE, NONE, NONE};
boolean requestLedUpdate = false;

DNSServer dnsServer;
ESP8266WebServer webServer(80);

#define ICONPATH "http://openweathermap.org/img/w/"
String weatherIcon = "";

void portalSetup(String ssid) {
  apSSID = ssid.c_str();

  WiFi.hostname(ssid);
  // connect to configured network or fallback to setup AP
  if (!enterClientMode(NULL, NULL)) {
    enterAPMode();  // let the user enter the credentials
  }
  startWebServer();
}

void portalLoop() {
  if (isAPactive) {
    dnsServer.processNextRequest();
  }
  webServer.handleClient();
}

boolean isConnected() {
  return !isAPactive;
}

void startWebServer() {
#ifdef DEBUG
  Serial.print(F("Starting Web Server at "));
  Serial.print(WiFi.softAPIP()); Serial.print(" "); Serial.println(WiFi.localIP());
#endif

  webServer.on("/settings", []() {
    String s = "<h1>WLAN-Einstellungen</h1><p>Bitte wähle deinen Accesspoint und gib das Passwort ein.</p>";
    s += "<form method=\"get\" action=\"setap\"><label>SSID: </label><select name=\"ssid\">";
    s += scanSSIDList;
    s += "</select><br>Passwort: <input name=\"pass\" length=64 type=\"password\"><input type=\"submit\"></form>";
    webServer.send(200, "text/html", makePage("WLAN-Einstellungen", s));
  });

  webServer.on("/setap", []() {
    String ssid = urlDecode(webServer.arg("ssid"));
#ifdef DEBUG
    Serial.print(F("Connecting to: ")); Serial.println(ssid);
#endif
    String pass = urlDecode(webServer.arg("pass"));

    String s = "<h1>Einrichtung abgeschlossen.</h1><p>Das Gerät wird zu \"";
    s += ssid;
    s += "\" verbunden.";
    webServer.send(200, "text/html", makePage("WLAN-Einstellungen", s));

    if (!enterClientMode(ssid.c_str(), pass.c_str())) {
      enterAPMode();  // wrong passphrase
    }
  });

  webServer.on("/reset", []() {
    String s = "<h1>Zurückgesetzt</h1><p>Zum Einstellen bitte mit dem Accesspoint \"Snowman\" verbinden.</p>";
    webServer.send(200, "text/html", makePage("Zurücksetzen", s));
    enterAPMode();
  });

  webServer.on("/api", []() {
    String response = "";

    for (int n = 0; n < webServer.args(); n++) {
      String sArgName = webServer.argName(n);

      if (sArgName.startsWith("led")) {
        String sPinNumber = sArgName.substring(3);
        if (sPinNumber == "") {
          String msg = "API: Invalid argument '" + sArgName + "' - pin number invalid\n";
          response += msg;
#ifdef DEBUG
          Serial.print(msg);
#endif
          continue;
        }
        int pinNumber = sPinNumber.toInt();
        if (pinNumber < 0 || pinNumber > 3) {
          String msg = "API: Invalid argument '" + sArgName + "' - pin number out of range\n";
          response += msg;
#ifdef DEBUG
          Serial.print(msg);
#endif
          continue;
        }
        
        String sArg = webServer.arg(n);
        int val = -1;
        if (sArg == "fade" || sArg == "fadein") {
          val = FADEIN;
        } else if (sArg == "fadeout") {
          val = FADEOUT;
        } else if (sArg == "blink") {
          val = BLINK;
        } else if (sArg == "clear") {
          val = NONE;
        } else {
          val = sArg.toInt();
        }
        
        if ((val != FADEIN && val != FADEOUT && val != BLINK && val != NONE && val < 0) || val > PWMRANGE) {
          String msg = "API: Value out of range for argument '" + sArgName + "': '" + String(val) + "'\n";
          response += msg;
#ifdef DEBUG
          Serial.print(msg);
#endif
          continue;
        }
        String msg = "API: Overriding pin " + String(pinNumber) + " to " + String(val) + "\n";
        response += msg;
#ifdef DEBUG
        Serial.print(msg);
#endif
        apiOverrides[pinNumber] = val;
        requestLedUpdate = true;
      }
      if (webServer.argName(n) == "clear") {
        if (webServer.arg(n) == "true") {
          for (int j = 0; j < 4; j++) {
            apiOverrides[j] = NONE;
          }
        }
        String msg = "API: Cleared pin overrides\n";
        response += msg;
#ifdef DEBUG
        Serial.print(msg);
#endif
        requestLedUpdate = true;
      }
    }

    webServer.send(200, "text/html", makePage("API", "<pre>" + response + "</pre>"));
  });

  webServer.on("/", []() {
    String s = "<h1>Snowman</h1><p><a href=\"/reset\">Einstellungen zurücksetzen</a></p>";
    s += "<p><a href=\"/settings\">Einstellungen ändern</a></p>";
    s += "<p><img src=\"" ICONPATH + weatherIcon + ".png\" /></p>";
    webServer.send(200, "text/html", makePage("Snowman", s));
  });

  webServer.onNotFound([]() {
    String redirect = "http://" + ipToStr(apIP) + "/settings";
    webServer.send(200, "text/html", makeRedirectPage(redirect, 2));
  });

  webServer.begin();
}

int getAPIOverride(int pin) {
  return apiOverrides[pin];
}

boolean apiNeedLedUpdate() {
  return requestLedUpdate;
}

void apiUpdatedLeds() {
  requestLedUpdate = false;
}

void setWeatherIcon(String id) {
  weatherIcon = id;
}

// must enter AP mode after scanning (SSID & PW get lost)
void scanSSIDs() {
#ifdef DEBUG
  Serial.println(F("Scanning networks"));
#endif

  WiFi.disconnect();
  WiFi.mode(WIFI_STA);
  delay(100);

  int n = WiFi.scanNetworks();
  delay(100);
  scanSSIDList = "";
  for (int i = 0; i < n; ++i) {
    scanSSIDList += "<option value=\"";
    scanSSIDList += WiFi.SSID(i);  // FIXME XSS attack possible?
    scanSSIDList += "\">";
    scanSSIDList += WiFi.SSID(i);
    scanSSIDList += "</option>";
  }

#ifdef DEBUG
  Serial.println(F("Finished scanning"));
#endif
}


// also read https://github.com/esp8266/Arduino/issues/529

// sets up an AP for the user to enter his/her WiFi credentials
void enterAPMode() {
#ifdef DEBUG
  Serial.println(F("Entering AP mode"));
#endif

  scanSSIDs();

  // create ad hoc setup-network
  WiFi.disconnect();
  WiFi.mode(WIFI_AP);
  isAPactive = true;
  delay(100);
  WiFi.softAPConfig(apIP, apIP, IPAddress(255, 255, 255, 0));
  WiFi.softAP(apSSID);
#ifdef DEBUG
  Serial.println(F("Started Access Point"));
#endif

  dnsServer.start(apIP);
}

// returns true if successfully connected to the last AP
boolean enterClientMode(const char* ssid, const char *passphrase) {
  dnsServer.stop();

  if (ssid && strlen(ssid) > 0) {  // if ssid is not given, try to connect to the memorized AP
    WiFi.disconnect();
    WiFi.begin(ssid, passphrase);  // register credentials
  }
  WiFi.mode(WIFI_STA);
  isAPactive = false;
  delay(100);

  // SSID and password are memorized until WiFi.begin()
  // https://github.com/esp8266/Arduino/issues/244
  int count = 0;
#ifdef DEBUG
  Serial.print(F("Waiting for Wi-Fi connection to ")); Serial.println(WiFi.SSID());
#endif
  while (count++ < 30) {  // attempt for about 30 * 1/2 = 15 seconds
    if (WiFi.status() == WL_CONNECTED) {
#ifdef DEBUG
      Serial.println(); Serial.println(F("Connected!"));
#endif
      return true;
    }
    delay(500);
#ifdef DEBUG
    Serial.print(".");
#endif
  }
#ifdef DEBUG
  Serial.println(); Serial.println(F("Not connected"));
#endif
  return false;
}