-
Notifications
You must be signed in to change notification settings - Fork 3
/
TestWebServer.py
88 lines (73 loc) · 2.19 KB
/
TestWebServer.py
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
import ESPWebServer
import network
import machine
GPIO_NUM = 2 # Builtin led (D4)
# Wi-Fi configuration
STA_SSID = "MEE_MI"
STA_PSK = "PinkFloyd1969"
# Disable AP interface
ap_if = network.WLAN(network.AP_IF)
if ap_if.active():
ap_if.active(False)
# Connect to Wi-Fi if not connected
sta_if = network.WLAN(network.STA_IF)
if not ap_if.active():
sta_if.active(True)
if not sta_if.isconnected():
sta_if.connect(STA_SSID, STA_PSK)
# Wait for connecting to Wi-Fi
while not sta_if.isconnected():
pass
# Show IP address
print("Server started @", sta_if.ifconfig()[0])
# Get pin object for controlling builtin LED
pin = machine.Pin(GPIO_NUM, machine.Pin.OUT)
pin.on() # Turn LED off (it use sinking input)
# Dictionary for template file
ledData = {
"title":"Remote LED",
"color":"red",
"status":"Off",
"switch":"on"
}
# Update information
def updateInfo(socket):
global ledData, color, status, switch
ledData["color"] = "red" if pin.value() else "green"
ledData["status"] = "Off" if pin.value() else "On"
ledData["switch"] = "on" if pin.value() else "off"
ESPWebServer.ok(
socket,
"200",
ledData["status"])
# Handler for path "/cmd?led=[on|off]"
def handleCmd(socket, args):
if 'led' in args:
if args['led'] == 'on':
pin.off()
elif args['led'] == 'off':
pin.on()
updateInfo(socket)
else:
ESPWebServer.err(socket, "400", "Bad Request")
# handler for path "/switch"
def handleSwitch(socket, args):
pin.value(not pin.value()) # Switch back and forth
updateInfo(socket)
# Start the server @ port 8899
# ESPWebServer.begin(8899)
ESPWebServer.begin() # use default 80 port
# Register handler for each path
# ESPWebServer.onPath("/", handleRoot)
ESPWebServer.onPath("/cmd", handleCmd)
ESPWebServer.onPath("/switch", handleSwitch)
# Setting the path to documents
ESPWebServer.setDocPath("/")
# Setting data for template
ESPWebServer.setTplData(ledData)
try:
while True:
# Let server process requests
ESPWebServer.handleClient()
except:
ESPWebServer.close()