Simple micropython HTTP server for ESP8266

switch web interface

This code is based on the Random Nerd Tutorial post

It exposes a webpage with a button that point to a query string such as ?switch=led. Based on the current GPIO state it switch on or off the led.

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

import socket
import network
import time
from machine import Pin

WIFI_SSID = "..."
WIFI_PASS = "..."

def connect_wifi():
print("Connecting to " + WIFI_SSID)
station = network.WLAN(network.STA_IF)
station.active(True)
station.connect(WIFI_SSID, WIFI_PASS)
while station.isconnected() == False:
pass

ifcfg = station.ifconfig()
ip = ''
if len(ifcfg) > 0:
ip = ifcfg[0]
print('wifi connected')
return ip


def web_page(is_on):

if not is_on:
gpio_state = "OFF"
else:
gpio_state = "ON"

html = """
<html>
<head>
<title>LED Switch</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
html { font-family: Helvetica; display:inline-block; margin: 0px auto; text-align: center;}
h1{color: #0F3376; padding: 2vh;}
p{font-size: 1.5rem;}
.button{display: inline-block; background-color: #336699; border: none; border-radius: 4px; color: white; padding: 16px 40px; text-decoration: none; font-size: 30px; margin: 2px; cursor: pointer;}
.button.OFF{ background-color: #333;}
</style>
</head>
<body>
<h1>LED Switch</h1>
<p><a href="/?switch=led">
<button class="button """ + gpio_state + """">Turn """ + gpio_state + """</button>
</a></p>
</body>
</html>"""

return html


def http_server():

led = Pin(2, Pin.OUT)
led.off()

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('', 80))
s.listen(5)

while True:

conn, addr = s.accept()

request = conn.recv(1024)
request = str(request)

if len(request) == 0:
continue

lines = request.split("\\r\\n")
if len(lines) == 0:
continue
line0 = lines[0]
lines = None

parts = line0.split(" ")
if len(parts) < 3:
continue

method, path, http_ver = parts

print('%s - %s %s' % (str(addr[0]), str(method), str(path)))

is_on = led.value() == 1
if path.find("switch=led") > -1:
if is_on:
led.off()
else:
led.on()
is_on = (not is_on)

response = web_page(is_on)
conn.send('HTTP/1.1 200 OK\n')
conn.send('Content-Type: text/html\n')
conn.send('Connection: close\n\n')
conn.sendall(response)
conn.close()


def run():
ip = connect_wifi()
print('Listening on http://%s' % ip)
http_server()


if __name__ == '__main__':
run()