-
Notifications
You must be signed in to change notification settings - Fork 0
/
TinyArduinoWebServer
448 lines (382 loc) · 10.7 KB
/
TinyArduinoWebServer
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
//This file requires the TinyWebServer Library
//Please Check the list of inclusions below
#include <SPI.h>
#include <Ethernet.h>
#include <Flash.h>
#include <SD.h>
#include <TinyWebServer.h>
#include <pin.h>
#include <util.h>
#include <EEPROM.h>
// EEPROM locations
const int eepromMacFlag = 0; // 1 byte
const int eepromMacAddress = 1; // 3 bytes
// Default MAC address for the ethernet controller.
// Unique MAC address can be stored in EEPROM using Set_MAC_Address sketch
byte mac[] = {0x90, 0xA2, 0xDA, 0x00, 0xFF, 0xFF};
const int outputStringLen = 20;
char outputString[outputStringLen]; // buffer used for constructing output strings
#define DEBUG 1
boolean file_handler(TinyWebServer& web_server);
boolean index_handler(TinyWebServer& web_server);
boolean pins_handler(TinyWebServer& web_server);
boolean digital_pin_handler(TinyWebServer& web_server);
// Helpers
void parse_path_string(const char* str, int size, char **messages);
void get_request_data(TinyWebServer &web_server, char *str);
// Types of actions our Arduino can take
enum ActionTypes {
GETTEMP
};
// Hardcoded host where the angular files are stored
const char *HOST = "10.0.1.2:9000";
// Pins we're interested in using
const int numPins = 4;
Pin pins[numPins] = {
Pin(9, OUTPUT_T),
Pin(8, OUTPUT_T),
Pin(7, INPUT_T),
Pin(4, INPUT_T),
};
// Our OneWire interface (the temp sensor)
//OneWire ds(7);
// Our mac address
//static uint8_t mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
// Our static IP
//byte ip[] = { 10, 0, 1, 32 };
// Send the GET / index.html
boolean index_handler(TinyWebServer& web_server)
{
web_server.send_error_code(200);
web_server.send_content_type("text/html\r\n");
web_server.print(F("<html><head><title>Temperature sensor</title></head>"));
web_server.print(F("<body>"));
web_server.print(F("<script>window.ip=\""));
web_server.print(outputString);
web_server.print(F("\"</script>"));
//web_server.print(F("<script id=\"appscript\" src=\"http://"));
//web_server.print(HOST);
//web_server.print(F("/scripts/scripts.js\"></script>"));
web_server.print(F("<h1>Hello</h1>")); // -- replaces above
web_server.print(F("</body></html>"));
return true;
}
// API
// GET /pins
boolean pins_handler(TinyWebServer& web_server)
{
web_server.send_error_code(200);
web_server.send_content_type("application/json");
web_server.end_headers();
pinsToString(web_server);
return true;
}
// POST /pins/update
boolean digital_pin_handler(TinyWebServer& web_server)
{
const char* action_str_len = web_server.get_header_value("Content-Length");
Serial.print("Content-Length: "); Serial.println(web_server.get_header_value("Content-Length"));
Serial.print("Host: "); Serial.println(web_server.get_header_value("Host"));
int len = atoi(action_str_len);
char* data = (char*)malloc(len);
if (data) memset(data, 0, len);
get_request_data(web_server, len, data);
Serial.print(data);
// DIGITAL
#if DEBUG
Serial.print(F("digital_pin_handler: ")); Serial.print(data); Serial.print(F(" (")); Serial.print(len); Serial.print(F(")\n"));
#endif
int sLen = strlen(data);
char ch;
int valueInt, pinInt, actionInt, modeInt;
ActionTypes actionT;
float currTemp;
int i = 0;
char * pch;
//while(i < sLen) {
// If we run across
Serial.println(data);
//sscanf(data, "\"pin:\" *%i, *\"value:\" *%i", &pinInt, &valueInt);
pch = strtok(data, " ,:\"{}");
/*while(pch!= NULL){
Serial.println(pch);
pch = strtok(NULL, " ,:\"{}");
}*/
Serial.println(pch);
pch = strtok(NULL, " ,:\"{}");
Serial.println(pch);
pinInt = atoi(pch);
Serial.println(pinInt);
pch = strtok(NULL, " ,:\"{}");
Serial.println(pch);
pch = strtok(NULL, " ,:\"{}");
Serial.println(pch);
valueInt = atoi(pch);
Serial.println(valueInt);
Pin *p = select_pin(pinInt);
p->setState(valueInt);
//Pin *p = select_pin(pinInt);
//p->setState(valueInt);
/*if (data[i] == 'p') {
// We are parsing a new pin
pinInt = (int)(data[++i] - '0');
Pin *p = select_pin(pinInt);
#if DEBUG
Serial.print(F("Pin: ")); Serial.print(pinInt); Serial.print(F("\n"));
#endif
while(data[i++] != 'p' && i < sLen) {
// We're in a pin object
switch (data[i]) {
case 'v':
i++;
valueInt = (int)(data[i] - '0');
#if DEBUG
Serial.print(F("Value: ")); Serial.print(valueInt); Serial.print(F("\n"));
#endif
p->setState(valueInt);
i++;
break;
case 'a':
i++;
actionInt = (int)(data[i] - '0');
actionT = (ActionTypes)(actionInt);
#if DEBUG
Serial.print(F("Action: ")); Serial.print(actionT); Serial.print(F("\n"));
#endif
switch (actionT) {
// case GETTEMP:
// currTemp = getTemp(ds);
// p->setCurrentValue(currTemp);
// break;
#if DEBUG
default:
Serial.print(F("Unknown action: ")); Serial.print(actionT); Serial.print(F("\n"));
#endif
}
break;
case 'm':
i++;
modeInt = (int)(data[i] - '0');
#if DEBUG
Serial.print(F("Mode: ")); Serial.print(modeInt); Serial.print(F("\n"));
#endif
p->setMode(modeInt);
break;
default:
#if DEBUG
Serial.print(F("Unknown: ")); Serial.print(data[i]); Serial.print(F("\n"));
#endif
}
}
}*/
// }
free(data);
web_server.send_error_code(200);
web_server.send_content_type("application/json");
web_server.end_headers();
pinsToString(web_server);
#if DEBUG
printProgStats();
#endif
return true;
}
TinyWebServer::PathHandler handlers[] = {
{"/pins/update", TinyWebServer::POST, &digital_pin_handler},
{"/pins", TinyWebServer::GET, &pins_handler},
{"/", TinyWebServer::GET, &index_handler },
{NULL},
};
const char* headers[] = {
"Content-Length",
//"Host",
NULL
};
TinyWebServer web = TinyWebServer(handlers, headers);
void setup()
{
#if DEBUG
Serial.begin(9600);
#endif
#if DEBUG
Serial.print(F("Setting up pins...\n"));
#endif
// numPins = SetupArduino(pins);
for(int i=0; i < numPins; i++){
pins[i].InitializeState();
}
UpdatePinsState();
#if DEBUG
for(int i=0; i < numPins; i++){
pins[i].Print();
}
#endif
// if (!card.init(SPI_FULL_SPEED, 4)) {
// Serial << F("card failed\n");
// }
// // initialize a FAT volume
// if (!volume.init(&card)) {
// Serial << F("vol.init failed!\n");
// }
// root.openRoot(volume);
// root.ls();
//#if DEBUG
// Serial.print(F("Setting up the Ethernet card at: "));
// Serial.print(ip_to_str(ip));
// Serial.print(F("\n"));
//#endif
// Ethernet.begin(mac, ip);
// start the Ethernet connection and the server:
// Retrieve MAC address from EEPROM if present
if (EEPROM.read(eepromMacFlag) == '#') {
Serial.println("Retrieving MAC address from EEPROM");
for (int i = 0; i < 3; i++) {
mac[i+3] = EEPROM.read(eepromMacAddress + i);
}
}
else {
Serial.println("No MAC address stored in EEPROM");
Serial.println("Using default MAC address");
}
snprintf(outputString, outputStringLen, "%02x:%02x:%02x:%02x:%02x:%02x", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
Serial.print("MAC Address: ");
Serial.println(outputString);
Serial.println("DHCP...");
while (Ethernet.begin(mac) == 0) {
Serial.println("No DHCP");
delay(1000);
Serial.println("DHCP...");
}
Serial.print("IP address: ");
Serial.println(Ethernet.localIP());
// Start the web server.
//#if DEBUG
// Serial.print(F("Web server starting...\n"));
//#endif
web.begin();
#if DEBUG
Serial.print(F("Ready to accept HTTP requests.\n\n"));
#endif
#if DEBUG
printProgStats();
#endif
}
void loop()
{
web.process();
}
// Iterate over pins and update each of their states
void UpdatePinsState()
{
for(int i=0; i<numPins; i++)
pins[i].getState();
}
/*
* Pin to string on the webserver helper
* This takes a web_server instance and
* writes the JSON array associated with
* each of the pins
*/
bool pinsToString(TinyWebServer& web_server)
{
UpdatePinsState();
web_server.print(F("{\"pins\":["));
int len = numPins;
for(int i=0; i<len; i++) {
web_server.print(F("{\"pin\":"));
web_server.print(pins[i].getPin());
web_server.print(F(",\"value\":"));
web_server.print(pins[i].getState());
web_server.print(F("}"));
if ((i+1) < len)
web_server.print(F(","));
}
web_server.print(F("]}"));
return true;
}
bool pinToString(TinyWebServer& web_server, int pin_number)
{
UpdatePinsState();
Pin *p = select_pin(pin_number);
web_server.print(F("{\"pin\":"));
web_server.print(p->getPin());
web_server.print(F(",\"value\":"));
web_server.print(p->getCurrentValue());
web_server.print(F("}"));
return true;
}
/*
* Count the number of '/'
* characters in the pathstring
*/
int count_forward_slashes(String pathstring) {
int p = 0;
int count = 0;
while (pathstring[p] != '\0')
if (pathstring[p++] == '/')
count++;
return count;
}
/*
* Parse the requested URL into
* an array of strings
*/
void parse_path_string(const char* cStr, int size, char** messages) {
char* str = strdup(cStr);
char *p;
int i = 0;
#if DEBUG
Serial << "string: " << str << "\n";
#endif
for(str = strtok_r(str,"/",&p); str; str = strtok_r(NULL, "/", &p)) {
int len = strlen(str);
char *msg = (char *)malloc((len + 1) * sizeof(char)); // sizeof(char) == 1
strncpy(msg, str, len + 1);
messages[i] = msg;
i++;
}
}
/*
* Read the remaining data from a request
* based upon the 'X-Action-Len' header
*/
void get_request_data(TinyWebServer& web_server, int length_str, char* str)
{
char ch;
Client& client = web_server.get_client();
if(client.available())
for(int i=0; i<length_str; i++) {
ch = (char)client.read();
if (ch != NULL && ch != '\n')
str[i] = ch;
}
str[length_str] = '\0';
}
/*
* Select the pin object from the
* pin array based upon the pinNumber
*/
Pin *select_pin(uint8_t pinNumber)
{
for(int i=0; i<numPins; i++)
if (pins[i].getPin() == pinNumber)
return &pins[i];
return NULL;
}
/*
* Get the free ram
*/
int freeRam()
{
extern int __heap_start, *__brkval;
int v;
return (int) &v - (__brkval == 0 ? (int) &__heap_start : (int) __brkval);
}
void printProgStats()
{
#if DEBUG
int freeR = freeRam();
Serial.print(F("Free ram: "));
Serial.print(freeR);
Serial.print(F("\n"));
#endif
}