diff --git a/boot.py b/boot.py index 91135a5..ba015a1 100644 --- a/boot.py +++ b/boot.py @@ -36,3 +36,6 @@ break else: print("Connection could not be made.\n") + +if sta_if.isconnected(): + print("Connected as: {}".format(sta_if.ifconfig()[0])) diff --git a/simple_web_server/main.py b/simple_web_server/main.py index b860471..2a8dbe3 100644 --- a/simple_web_server/main.py +++ b/simple_web_server/main.py @@ -10,26 +10,61 @@ import machine import ntptime, utime from machine import RTC -from time import sleep - +seconds = ntptime.time() rtc = RTC() -try: - seconds = ntptime.time() -except: - seconds = 0 rtc.datetime(utime.localtime(seconds)) +adc = machine.ADC(0) + def time(): body = """ - -

Time

-

%s

- - -""" % str(rtc.datetime()) + +

Time

+

%s

+ + + """ % str(rtc.datetime()) return response_template % body + +def dummy(): + body = "This is a dummy endpoint" + + return response_template % body + +pin = machine.Pin(16, machine.Pin.OUT) + +def light_on: + pin.value(1) + body = "You turned a light on!" + return response_template % body + +def light_off: + pin.value(0) + body = "You turned a light off!" + return response_template % body +switch_pin = machine.Pin(10, machine.Pin.IN) + +def switch(): + body = "{state: " . switch_pin.value() . "}" + return response_template % body + +adc = machine.ADC(0) + +def light: + body = "{value: " . adc.read() . "}" + return response_template % body + +handlers = { + 'time': time, + 'dummy': dummy, + 'light_on': light_on, + 'light_off': light_off, + 'switch': switch, + 'light': light, +} + def main(): s = socket.socket() ai = socket.getaddrinfo("0.0.0.0", 8080) @@ -42,7 +77,6 @@ def main(): print("Listening, connect your browser to http://:8080/") while True: - sleep(.5) res = s.accept() client_s = res[0] client_addr = res[1] @@ -50,11 +84,21 @@ def main(): print("Request:") print(req) - response = time() + # The first line of a request looks like "GET /arbitrary/path/ HTTP/1.1". + # This grabs that first line and whittles it down to just "/arbitrary/path/" + path = req.decode().split("\r\n")[0].split(" ")[1] + + # Given the path, identify the correct handler to use + handler = handlers[path.strip('/').split('/')[0]] + + response = handler() + # A handler returns an entire response in the form of a multi-line string. + # This breaks up the response into single strings, byte-encodes them, and + # joins them back together with b"\r\n". Then it sends that to the client. client_s.send(b"\r\n".join([line.encode() for line in response.split("\n")])) client_s.close() print() -main() +main() \ No newline at end of file