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
50 changes: 41 additions & 9 deletions web_server/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,29 +8,28 @@
<h1>404 Not Found</h1>
"""

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

response_500 = """HTTP/1.0 500 INTERNAL ERROR
<h1>500 Internal Server Error</h1>
"""



response_template = """HTTP/1.0 200 OK

%s
"""

import machine
import ntptime, utime
from machine import RTC
from time import sleep

rtc = RTC()
try:
seconds = ntptime.time()
except:
seconds = 0

rtc = RTC()
rtc.datetime(utime.localtime(seconds))


def time():
body = """<html>
<body>
Expand All @@ -42,18 +41,51 @@ def time():

return response_template % body


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

return response_template % body

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

led = machine.Pin(9, machine.Pin.OUT)


def light_on():
led.value(1)
body = "You turned the light on!"
return response_template % body


def light_off():
led.value(0)
body = 'You turned the light off!'
return response_template % body


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


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

adc = machine.ADC(0)

def light_level():
body = "{value: " + str(adc.read()) + "}"
return response_template % body

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


def main():
s = socket.socket()
ai = socket.getaddrinfo("0.0.0.0", 8080)
Expand All @@ -63,7 +95,7 @@ def main():

s.bind(addr)
s.listen(5)
print("Listening, connect your browser to http://<this_host>:8080")
print("Listening, connect your browser to http://<this_host>:8080/")

while True:
res = s.accept()
Expand All @@ -88,4 +120,4 @@ def main():
client_s.close()
print()

main()
main()