This repository has been archived by the owner on Dec 9, 2019. It is now read-only.
forked from dc42/DuetWiFiServer
/
RepRapWiFi.cpp
487 lines (439 loc) · 13.7 KB
/
RepRapWiFi.cpp
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
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
#include <ESP8266WiFi.h>
#include <ESP8266mDNS.h>
#include <DNSServer.h>
#include "RepRapWebServer.h"
#include <EEPROM.h>
#include <FS.h>
#include <ESP8266SSDP.h>
#include "PooledStrings.cpp"
#include "SPITransaction.h"
#include "Config.h"
extern "C" {
#include "user_interface.h" // for struct rst_info
}
#ifdef SHOW_PASSWORDS
# define PASSWORD_INPUT_TYPE "\"text\""
#else
# define PASSWORD_INPUT_TYPE "\"password\""
#endif
#define BUTTON_PIN -1
#define MAX_WIFI_FAIL 50
#define MAX_LOGGED_IN_CLIENTS 3
char ssid[32], pass[64], webhostname[64];
IPAddress sessions[MAX_LOGGED_IN_CLIENTS];
uint8_t loggedInClientsNum = 0;
MDNSResponder mdns;
RepRapWebServer server(80);
WiFiServer tcp(23);
WiFiClient tcpclient;
DNSServer dns;
String wifiConfigHtml;
enum class OperatingState
{
Unknown = 0,
Client = 1,
AccessPoint = 2
};
OperatingState currentState = OperatingState::Unknown;
ADC_MODE(ADC_VCC); // need this for the ESP.getVcc() call to work
void fsHandler();
void handleRr();
void handleRrUpload();
void urldecode(String &input);
void StartAccessPoint();
void SendInfoToSam();
bool TryToConnect();
void setup() {
Serial.begin(115200);
delay(20);
EEPROM.begin(512);
delay(20);
// Set up the SPI subsystem
SPITransaction::Init();
// Try to connect using the saved parameters
bool success = TryToConnect();
if (success)
{
if (mdns.begin(webhostname, WiFi.localIP()))
{
MDNS.addService("http", "tcp", 80);
}
SSDP.setSchemaURL("description.xml");
SSDP.setHTTPPort(80);
SSDP.setName(webhostname);
SSDP.setSerialNumber(WiFi.macAddress());
SSDP.setURL("reprap.htm");
SSDP.begin();
SPIFFS.begin();
server.servePrinter(true);
server.onNotFound(fsHandler);
server.onPrefix("/rr_", HTTP_ANY, handleRr, handleRrUpload);
server.on("/description.xml", HTTP_GET, [](){SSDP.schema(server.client());});
Serial.println(WiFi.localIP().toString());
server.begin();
tcp.begin();
// NOTE: setNoDelay activates the Nagle algorithm on client PCBs, so it isn't surprising that this doesn't work:
// The following causes a crash using release 2.1.0 of the Arduino ESP8266 core, and is probably unsafe even on 2.0.0
//tcp.setNoDelay(true);
currentState = OperatingState::Client;
}
else
{
StartAccessPoint();
currentState = OperatingState::AccessPoint;
}
SendInfoToSam();
}
void loop()
{
switch (currentState)
{
case OperatingState::Client:
server.handleClient();
break;
case OperatingState::AccessPoint:
server.handleClient();
dns.processNextRequest();
break;
default:
break;
}
SPITransaction::DoTransaction();
if (SPITransaction::DataReady())
{
Serial.print("Incoming data, opcode=");
Serial.print(SPITransaction::GetOpcode(), HEX);
Serial.print(", length=");
size_t length;
(void)SPITransaction::GetData(length);
Serial.print(length);
Serial.println();
SPITransaction::IncomingDataTaken();
}
yield();
}
// Try to connect using the saved SSID and password, returning true if successful
bool TryToConnect()
{
EEPROM.get(0, ssid);
EEPROM.get(32, pass);
EEPROM.get(32+64, webhostname);
wifi_station_set_hostname(webhostname); // must do thia before calling WiFi.begin()
uint8_t failcount = 0;
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, pass);
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
failcount++;
if (failcount % 2 == 0)
{
Serial.println("WAIT WIFI " + String(MAX_WIFI_FAIL/2 - (failcount/2)));
}
if (failcount > MAX_WIFI_FAIL) // 1 min
{
Serial.println("WIFI ERROR");
WiFi.mode(WIFI_STA);
WiFi.disconnect();
delay(100);
return false;
}
}
return true;
}
void StartAccessPoint()
{
uint8_t num_ssids = WiFi.scanNetworks();
// TODO: NONE? OTHER?
wifiConfigHtml = F("<html><body><h1>Select your WiFi network:</h1><br /><form method=\"POST\">");
for (uint8_t i = 0; i < num_ssids; i++) {
wifiConfigHtml += "<input type=\"radio\" id=\"" + WiFi.SSID(i) + "\"name=\"ssid\" value=\"" + WiFi.SSID(i) + "\" /><label for=\"" + WiFi.SSID(i) + "\">" + WiFi.SSID(i) + "</label><br />";
}
wifiConfigHtml += F("<label for=\"password\">WiFi Password:</label><input type=" PASSWORD_INPUT_TYPE " id=\"password\" name=\"password\" /><br />");
wifiConfigHtml += F("<p><label for=\"webhostname\">Duet host name: </label><input type=\"text\" id=\"webhostname\" name=\"webhostname\" value=\"duetwifi\" /><br />");
wifiConfigHtml += F("<i>(This would allow you to access your printer by name instead of IP address. I.e. http://duetwifi/)</i></p>");
wifiConfigHtml += F("<input type=\"submit\" value=\"Save and reboot\" /></form></body></html>");
Serial.println("Found " + String(num_ssids) + " WIFI");
delay(5000);
IPAddress apIP(192, 168, 1, 1);
WiFi.mode(WIFI_AP);
WiFi.softAPConfig(apIP, apIP, IPAddress(255, 255, 255, 0));
WiFi.softAP(softApName);
Serial.println("WiFi -> DuetWiFi");
dns.setErrorReplyCode(DNSReplyCode::NoError);
dns.start(53, "*", apIP);
server.on("/", HTTP_GET, []() {
server.send(200, FPSTR(STR_MIME_TEXT_HTML), wifiConfigHtml);
});
server.on("/", HTTP_POST, []() {
if (server.args() <= 0) {
server.send(500, FPSTR(STR_MIME_TEXT_PLAIN), F("Got no data, go back and retry"));
return;
}
for (uint8_t e = 0; e < server.args(); e++) {
String argument = server.arg(e);
urldecode(argument);
if (server.argName(e) == "password") argument.toCharArray(pass, 64);//pass = server.arg(e);
else if (server.argName(e) == "ssid") argument.toCharArray(ssid, 32);//ssid = server.arg(e);
else if (server.argName(e) == "webhostname") argument.toCharArray(webhostname, 64);
}
EEPROM.put(0, ssid);
EEPROM.put(32, pass);
EEPROM.put(32+64, webhostname);
EEPROM.commit();
server.send(200, FPSTR(STR_MIME_TEXT_HTML), F("<h1>All set!</h1><br /><p>(Please reboot me.)</p>"));
Serial.println("SSID: " + String(ssid) + ", PASS: " + String(pass));
delay(50);
ESP.restart();
});
server.begin();
Serial.println(WiFi.softAPIP().toString());
}
// Schedule an info message to the SAM processor
void SendInfoToSam()
{
{
struct
{
uint32_t formatVersion;
uint32_t ip;
uint32_t freeHeap;
uint32_t resetReason;
uint32_t flashSize;
int32_t rssi;
uint16_t operatingState;
uint16_t vcc;
char firmwareVersion[16];
char hostName[64];
char ssid[32];
} response;
response.formatVersion = 2;
response.ip = static_cast<uint32_t>(WiFi.localIP());
response.freeHeap = ESP.getFreeHeap();
response.resetReason = ESP.getResetInfoPtr()->reason;
response.flashSize = ESP.getFlashChipRealSize();
response.rssi = WiFi.RSSI();
response.operatingState = (uint32_t)currentState;
response.vcc = ESP.getVcc();
strncpy(response.firmwareVersion, firmwareVersion, sizeof(response.firmwareVersion));
memcpy(response.hostName, webhostname, sizeof(response.hostName));
switch (currentState)
{
case OperatingState::Client:
memcpy(response.ssid, ssid, sizeof(response.ssid));
break;
case OperatingState::AccessPoint:
strncpy(response.ssid, softApName, sizeof(response.ssid));
break;
default:
response.ssid[0] = 0;
break;
}
SPITransaction::ScheduleInfoMessage(SPITransaction::ttNetworkInfo, &response, sizeof(response));
}
}
void fsHandler()
{
String path = server.uri();
if (path.endsWith("/"))
{
path += F("reprap.htm"); // default to reprap.htm as the index page
}
File dataFile = SPIFFS.open(path, "r");
if (!dataFile && !path.endsWith(".gz") && path.length() <= 29)
{
// Requested file not found and wasn't a zipped file, so see if we have a zipped version
dataFile = SPIFFS.open(path + ".gz", "r");
}
if (!dataFile)
{
server.send(404, FPSTR(STR_MIME_APPLICATION_JSON), "{\"err\": \"404: " + server.uri() + " NOT FOUND\"}");
return;
}
// No need to add the file size or encoding headers here because streamFile() does that automatically
String dataType;
if (path.endsWith(".html") || path.endsWith(".htm")) dataType = FPSTR(STR_MIME_TEXT_HTML);
else if (path.endsWith(".css")) dataType = F("text/css");
else if (path.endsWith(".js")) dataType = F("application/javascript");
else if (path.endsWith(".gz")) dataType = F("application/x-gzip");
else dataType = FPSTR(STR_MIME_TEXT_PLAIN);
server.streamFile(dataFile, dataType); // this will automatically set the content encoding if it is a zipped file
server.client().stop();
dataFile.close();
}
// Handle a rr_ request from the client
void handleRr() {
#ifdef SPI_DEBUG
Serial.print("handleRr: ");
Serial.print(server.uri());
Serial.println();
#endif
uint32_t postLength = server.getPostLength();
String text = server.fullUri();
if (postLength != 0)
{
text += "&length=" + (String)postLength; // pass the post length to the SAM as well
}
const uint32_t ip = static_cast<uint32_t>(server.client().remoteIP());
SPITransaction::ScheduleRequestMessage(SPITransaction::trTypeRequest | SPITransaction::ttRr, ip, postLength == 0, text.c_str() + 4, text.length() - 4);
uint32_t now = millis();
bool hadReply = false;
uint32_t fragment = 1;
do
{
// Send our data and/or get a response
SPITransaction::DoTransaction(); // try to do a transaction, if the SAM is willing
// See if we have a response yet
if (SPITransaction::DataReady())
{
uint32_t opcode = SPITransaction::GetOpcode();
size_t length;
const uint8_t *data = (const uint8_t*)SPITransaction::GetData(length);
if (opcode == (SPITransaction::trTypeResponse | SPITransaction::ttRr))
{
#ifdef SPI_DEBUG
Serial.print("Reply");
for (size_t i = 0; i <= length; ++i)
{
Serial.print(" ");
Serial.print((unsigned int)data[i], HEX);
}
Serial.println();
#endif
bool isLast;
uint32_t fragment = SPITransaction::GetFragment(isLast);
if (fragment == 0 && length >= 8)
{
uint32_t rc = *(const uint32_t*)data;
uint32_t contentLength = *(const uint32_t*)(data + 4);
if (rc & SPITransaction::rcJson)
{
server.send(rc & SPITransaction::rcNumber, contentLength, FPSTR(STR_MIME_APPLICATION_JSON), data + 8, length - 8, isLast);
}
else
{
server.send(rc & SPITransaction::rcNumber, contentLength, FPSTR(STR_MIME_TEXT_PLAIN), data + 8, length - 8, isLast);
}
}
else
{
server.sendContent(data, length, isLast);
}
SPITransaction::IncomingDataTaken();
if (isLast)
{
#if 0
// Actually we should be able to close the connection here, but this can sometimes
// lead to misbehaviour - especially when dealing with lots of fileinfo requests
server.client().stop();
#endif
hadReply = true;
}
else
{
// Make sure this request doesn't time out if we're still sending, else we break rr_download for large files
now = millis();
}
}
else
{
// Serial.print("Incoming data, opcode=");
// Serial.print(opcode, HEX);
// Serial.print(", length=");
// Serial.print(length);
// Serial.println();
SPITransaction::IncomingDataTaken();
}
}
// Send our next fragment of postdata
if (postLength != 0)
{
uint8_t* buf;
size_t len;
if (SPITransaction::GetBufferAddress(&buf, len)) // if the output buffer is free
{
if (len > postLength)
{
len = postLength;
}
size_t len2 = server.readPostdata(server.client(), buf, len);
if (len2 != len)
{
Serial.print("read ");
Serial.print(len2);
Serial.print(" bytes but ");
Serial.print(postLength);
Serial.println(" remaining");
}
if (len2 != 0)
{
postLength -= len2;
#ifdef SPI_DEBUG
Serial.print("sending POST fragment, bytes=");
Serial.print(len2);
Serial.print(" remaining=");
Serial.println(postLength);
#endif
SPITransaction::SchedulePostdataMessage(SPITransaction::trTypeRequest | SPITransaction::ttRr, ip, len2, fragment, postLength == 0);
++fragment;
now = millis();
}
else
{
Serial.println("read 0 bytes");
}
}
else
{
yield();
//delay(1);
}
}
else
{
yield();
//delay(1);
}
// Quit if all done
if (hadReply && postLength == 0)
{
return;
}
} while (millis() - now < 5000);
server.send(200, FPSTR(STR_MIME_APPLICATION_JSON), FPSTR(STR_JSON_ERR_1));
}
void handleRrUpload() {
}
void urldecode(String &input) { // LAL ^_^
input.replace("%0A", String('\n'));
input.replace("%20", " ");
input.replace("+", " ");
input.replace("%21", "!");
input.replace("%22", "\"");
input.replace("%23", "#");
input.replace("%24", "$");
input.replace("%25", "%");
input.replace("%26", "&");
input.replace("%27", "\'");
input.replace("%28", "(");
input.replace("%29", ")");
input.replace("%30", "*");
input.replace("%31", "+");
input.replace("%2C", ",");
input.replace("%2E", ".");
input.replace("%2F", "/");
input.replace("%2C", ",");
input.replace("%3A", ":");
input.replace("%3A", ";");
input.replace("%3C", "<");
input.replace("%3D", "=");
input.replace("%3E", ">");
input.replace("%3F", "?");
input.replace("%40", "@");
input.replace("%5B", "[");
input.replace("%5C", "\\");
input.replace("%5D", "]");
input.replace("%5E", "^");
input.replace("%5F", "-");
input.replace("%60", "`");
}