-
Notifications
You must be signed in to change notification settings - Fork 14
/
04_http_server.js
85 lines (81 loc) · 2.51 KB
/
04_http_server.js
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
/*
A simple example to control the built-in LED
over a HTML web page
http://espruino.local:8080
*/
var wifi = require('Wifi');
var http = require('http');
var led = NodeMCU.D4;
// connect to the Wi-Fi AP with the informations
// provided in example 03_wifi.js, saved with wifi.save()
wifi.restore();
wifi.setHostname('espruino');
http.createServer(function(req, res) {
switch(req.method) {
case 'GET':
switch(req.url) {
case '':
case '/':
res.writeHead(200);
res.write('<html>');
res.write(' <head>');
res.write(' <title>LED Control</title>');
res.write(' </head>');
res.write(' <body>');
res.write(' <h1>Control the built-in LED</h1>');
res.write(' <form action="/led/on" method="POST">');
res.write(' <button type="submit">Turn on</button>');
res.write(' </form>');
res.write(' <form action="/led/off" method="POST">');
res.write(' <button type="submit">Turn off</button>');
res.write(' </form>');
res.write(' </body>');
res.write('</html>');
break;
default:
console.log('INFO: URL not handled, ' + req.url);
res.writeHead(404);
break;
}
break;
case 'POST':
switch(req.url) {
case '/led/on':
console.log('INFO: Turn on the LED');
digitalWrite(led, LOW);
res.writeHead(200);
res.write('<html>');
res.write(' <head>');
res.write(' <title>LED Control</title>');
res.write(' </head>');
res.write(' <body>');
res.write(' <a href="/">Back</a>');
res.write(' </body>');
res.write('</html>');
break;
case '/led/off':
console.log('INFO: Turn off the LED');
digitalWrite(led, HIGH);
res.writeHead(200);
res.write('<html>');
res.write(' <head>');
res.write(' <title>LED Control</title>');
res.write(' </head>');
res.write(' <body>');
res.write(' <a href="/">Back</a>');
res.write(' </body>');
res.write('</html>');
break;
default:
console.log('INFO: URL not handled, ' + req.url);
res.writeHead(404);
break;
}
break;
default:
console.log('INFO: Method not handled, ' + req.method);
res.writeHead(405);
break;
}
res.end();
}).listen(8080);