Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 40 additions & 2 deletions simple_web_server/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,21 @@
except:
import socket

response_404 = """HTTP/1.0 404 NOT FOUND

<h1>404 Not Found</h1>
"""

response_500 = """HTTP/1.0 500 INTERNAL SERVER ERROR

<h1>500 Internal Server Error</h1>
"""

response_template = """HTTP/1.0 200 OK

%s
"""

import machine
import ntptime, utime
from machine import RTC
Expand All @@ -30,6 +41,25 @@ def time():

return response_template % body

def dummy():
body = "This is a dummy endpoint"

return response_template % body

switch_pin = machine.Pin(10, machine.Pin.IN)

def switch():
body = "{state: " . switch_pin.value() . "}"
return response_template % body

handlers = {
'time': time,
'dummy': dummy,
'light_on': light_on,
'light_off': light_off,
'switch': switch,
}

def main():
s = socket.socket()
ai = socket.getaddrinfo("0.0.0.0", 8080)
Expand All @@ -49,8 +79,16 @@ def main():
req = client_s.recv(4096)
print("Request:")
print(req)

response = time()

try:
path = req.decore().split("\r\n")[0].split(" ")[1]
handler = handlers[path.strip('/').split('/')[0]]
response = handler()
except KeyError:
response = response_404
except Exception as e:
response = response_500
print(str(e))

client_s.send(b"\r\n".join([line.encode() for line in response.split("\n")]))

Expand Down