]> vault307.fbx.one Git - webserver.git/blob - web_server.py
pico w micropython webserver
[webserver.git] / web_server.py
1 import network, socket, time, machine
2
3 cat=machine.Pin(15,machine.Pin.OUT)
4 red=machine.Pin(18,machine.Pin.OUT)
5 green=machine.Pin(19,machine.Pin.OUT)
6
7 ssid='SSID'
8 password='PSSWD'
9
10 def connect():
11 wlan=network.WLAN(network.STA_IF)
12 wlan.active(True)
13 wlan.connect(ssid,password)
14 while wlan.isconnected() == False:
15 print('Waiting for connection...')
16 time.sleep(1)
17 ip=wlan.ifconfig()[0]
18 print(f'Connected on {ip}')
19 return ip
20
21 def open_socket(ip):
22 address=(ip,80)
23 connection=socket.socket()
24 connection.bind(address)
25 connection.listen(1)
26 return connection
27
28
29 def webpage(Gstate,Rstate,state):
30 html=f"""
31 <!DOCTYPE html>
32 <html lang="en">
33 <head>
34 <meta charset="UTF-8" />
35 <meta name="viewport" content="width=device-width, initial-scale=1.0" />
36 </head>
37 <body>
38 <form action="./lighton">
39 <input type="submit" value="Cat on" />
40 </form>
41 <form action="./lightoff" />
42 <input type="submit" value="Cat off" />
43 </form>
44 <form action="./redon">
45 <input type="submit" value="Red on"/>
46 </form>
47 <form action="./redoff">
48 <input type="submit" value="Red off"/>
49 </form>
50 <form action="./greenon">
51 <input type="submit" value="Green on"/>
52 </form>
53 <form action="./greenoff">
54 <input type="submit" value="Green off"/>
55 </form>
56 <p>Cat is {state}</p>
57 <p>Red is {Rstate}</p>
58 <p>Green is {Gstate}</p>
59 </body>
60 </html>
61 """
62 return html
63
64 def serve(connection):
65 state='OFF'
66 Rstate='OFF'
67 Gstate='OFF'
68
69 while True:
70 client=connection.accept()[0]
71 request=client.recv(1024)
72 request=str(request)
73 try:
74 request=request.split()[1]
75 except IndexError:
76 pass
77 if request=='/lighton?':
78 cat.on()
79 state='ON'
80 elif request=='/lightoff?':
81 cat.off()
82 state='OFF'
83 elif request=='/redon?':
84 red.on()
85 Rstate='ON'
86 elif request=='/redoff?':
87 red.off()
88 Rstate='OFF'
89 elif request=='/greenon?':
90 green.on()
91 Gstate='ON'
92 elif request=='/greenoff?':
93 green.off()
94 Gstate='OFF'
95 html=webpage(Gstate,Rstate,state)
96 client.send(html)
97 client.close()
98
99 try:
100 ip=connect()
101 connection=open_socket(ip)
102 serve(connection)
103 except KeyboardInterrupt:
104 machine.reset()