Skip to content

Instantly share code, notes, and snippets.

@JustinTime42
Last active January 16, 2024 01:43
import usocket
import urequests
from machine import Pin
import network
import ujson
led = Pin(15, Pin.OUT)
ssid = 'allyourbase'
password = 'TheComplex42'
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(ssid, password)
def http_server():
addr = usocket.getaddrinfo('0.0.0.0', 80)[0][-1]
s = usocket.socket()
s.bind(addr)
s.listen(1)
print('listening on', addr)
while True:
cl, addr = s.accept()
print('client connected from', addr)
cl_file = cl.makefile('rwb', 0)
request_line = cl_file.readline()
method, uri, protocol = request_line.split(b' ')
if method == b'POST' and uri == b'/light':
headers = {}
body = None
while True:
line = cl_file.readline()
if not line or line == b'\r\n':
break
key, value = line.decode().strip().split(': ')
headers[key] = value
if 'Content-Length' in headers:
body = cl_file.read(int(headers['Content-Length']))
if body:
data = ujson.loads(body)
print(body)
garage_light_status = data.get('garage_light')
print('Garage light status:', garage_light_status)
else:
garage_light_status = 'on'
if garage_light_status == "toggle":
print(led.value())
if led.value() == 1:
led(0)
else:
led(1)
else:
led(1)
response = ujson.dumps({'garage_light': 'on' if led.value() else 'off'})
cl.send('HTTP/1.0 200 OK\r\nContent-Type: application/json\r\n\r\n')
cl.send(response)
cl.close()
if __name__ == '__main__':
http_server()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment