pico-w-clock/webserver.py
Sagi Dayan 7c36d8eea3 initial commit
Signed-off-by: Sagi Dayan <sagidayan@gmail.com>
2023-04-22 14:58:04 +03:00

97 lines
3.2 KiB
Python

import re
try:
import usocket as socket #importing socket
except:
import socket
from io_state import state
css_file = open('style.css', 'r')
css = css_file.read()
css_file.close()
html_file = open("index.html", "r")
html = html_file.read()
html_file.close()
def web_page():
return html \
.replace("{day_light_class}", "" if state.is_day_on() else "grayscale") \
.replace("{night_light_class}", "" if state.is_night_on() else "grayscale") \
.replace("{time_h}", str(state.get_time_h())) \
.replace("{time_m}", str(state.get_time_m())) \
.replace("{time_s}", str(state.get_time_s())) \
.replace("{mode_auto}", "checked" if state.is_auto_mode() else "") \
.replace("{mode_manual}", "" if state.is_auto_mode() else "checked") \
.replace("{day_on_time}", f"{state.get_day_on_time()[0]:02}:{state.get_day_on_time()[1]:02}") \
.replace("{night_on_time}", f"{state.get_day_off_time()[0]:02}:{state.get_day_off_time()[1]:02}") \
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #creating socket object
s.bind(('0.0.0.0', 80))
s.listen(5)
s.settimeout(0.5)
def accept_connection():
try:
global s
conn, addr = s.accept()
request = str(conn.recv(1024))
if request.find('/style.css') >= 0:
conn.send(css)
conn.close()
return
elif request.find('/update_mode/auto/') >= 0:
print("Update mode to auto.")
state.set_auto_mode(True)
elif request.find('/update_mode/manual/') >= 0:
print("Update mode to manual.")
state.set_auto_mode(False)
elif request.find('/stime/') >= 0:
timestamp_regex = re.compile(r'stime\/(\d+):(\d+):(\d+)\/')
h = int(timestamp_regex.search(request).group(1))
m = int(timestamp_regex.search(request).group(2))
_s = int(timestamp_regex.search(request).group(3))
print(f"Changing current time to: {h}:{m}:{_s}")
state.set_time(h, m, _s)
elif request.find('/toggle_day/') >= 0:
print("toggle day")
state.set_auto_mode(False)
state.toggle_day()
elif request.find('/toggle_night/') >= 0:
print("toggle night.")
state.set_auto_mode(False)
state.toggle_night()
elif request.find('/set_day_time/') >= 0:
times_regex = re.compile(r'time\/(\d+)\/(\d+)/')
h = int(times_regex.search(request).group(1))
m = int(times_regex.search(request).group(2))
print(f'Changing time for day_on to {h}:{m}')
state.set_times(True, h, m)
elif request.find('/set_night_time/') >= 0:
times_regex = re.compile(r'time\/(\d+)\/(\d+)/')
h = int(times_regex.search(request).group(1))
m = int(times_regex.search(request).group(2))
print(f'Changing time for day_off to {h}:{m}')
state.set_times(False, h, m)
response = web_page()
conn.send(response)
conn.close()
except OSError as e:
try:
conn.close()
print(f'ERROR: connection closed: {e}')
except:
pass
except Exception as e:
pass