#!/bin/python

import dht
from machine import Pin, Timer
from micropyserver import MicroPyServer
from micropyserver_utils import send_response

DHT_PIN = 26
RELAY_PIN = 4
UPDATE_INTERVAL_S = 2 

name = "Test Sensor"
server = MicroPyServer()
dht = dht.DHT22(Pin(DHT_PIN))
relay = Pin(RELAY_PIN, Pin.OUT)
update_timer = Timer(0)
index_template = ""

temp = 0
humidity = 0

def read(_):
    global temp, humidity
    try:
        dht.measure()
    except:
        return

    temp = dht.temperature()
    humidity = dht.humidity()

def serve_root(_):
    global server, temp, humidity, index_template, relay

    relay_status = "On" if relay.value() else "Off"
    index = index_template.replace('{name}', name).replace('{temp}', str(temp)).replace('{humidity}', str(humidity)).replace('{relay_status}', relay_status)

    send_response(server, index)

def toggle_relay(_):
    global relay
    val = relay.value()
    relay.value(not val)

    send_response(server, ' ', http_code=303, content_type="text/plain", extend_headers=["Location: /"])

def relay_off(_):
    global relay
    relay.value(0)
    send_response(server, ' ', http_code=303, content_type="text/plain", extend_headers=["Location: /"])


def relay_on(_):
    global relay
    relay.value(1)
    send_response(server, ' ', http_code=303, content_type="text/plain", extend_headers=["Location: /"])

def init():
    init_timer()
    init_webserver()

def init_timer():
    global update_timer
    update_timer = update_timer.init(period=UPDATE_INTERVAL_S * 1000, callback=read)

def init_webserver():
    load_index_template()
    server.add_route('/', serve_root)
    server.add_route('/toggle', toggle_relay)
    server.add_route('/off', relay_off)
    server.add_route('/on', relay_on)
    
def load_index_template():
    global index_template
    with open('index.html') as index_html:
        index_template = ''.join(index_html.readlines())

def main():
    global server
    init()
    server.start()


if __name__ == "__main__":
    main()



