import network, socket, time, machine, si7021
from machine import Pin

cat=machine.Pin(14,machine.Pin.OUT)
red=machine.Pin(10,machine.Pin.OUT)
green=machine.Pin(11,machine.Pin.OUT)
sensor=si7021.Si7021(machine.I2C(0,sda=machine.Pin(0),scl=machine.Pin(1)))
temp=si7021.convert_celcius_to_fahrenheit(sensor.temperature)
relHum=sensor.relative_humidity

button = Pin(17,Pin.IN,Pin.PULL_UP) #not implemented at this time

ssid='SSID'
password='PSSWD'

def connect():
    wlan=network.WLAN(network.STA_IF)
    wlan.active(True)
    wlan.connect(ssid,password)
    while wlan.isconnected() == False:
        print('Waiting for connection...')
        time.sleep(1)
    ip=wlan.ifconfig()[0]
    print(f'Connected on {ip}')
    return ip

def open_socket(ip):
    address=(ip,80)
    connection=socket.socket()
    connection.bind(address)
    connection.listen(1)
    return connection

def get_html(html_name):
    with open(html_name, 'r') as file:
        html=file.read()
    return html

def serve(connection):
    state='OFF'
    RState='OFF'
    GSTate='OFF'
    
    while True:
        client=connection.accept()[0]
        request=client.recv(1024)
        request=str(request)
        try:
            response=get_html('index.html')
            request=request.split()[1]
        except IndexError:
            pass
        if request=='/lighton?':
            cat.on()
            state='ON'
        elif request=='/lightoff?':
            cat.off()
            state='OFF'
        elif request=='/redon?':
            red.on()
            RState='ON'
        elif request=='/redoff?':
            red.off()
            RState='OFF'
        elif request=='/greenon?':
            green.on()
            GSTate='ON'
        elif request=='/greenoff?':
            green.off()
            GSTate='OFF'
        
        response=response.replace('state', state)
        response=response.replace('RState', RState)
        response=response.replace('GSTate', GSTate)
        response=response.replace('temp', str(temp))
        response=response.replace('relHum', str(relHum))
        client.send('HTTP/1.0 200 OK\r\nContent-type: text/html\r\n\r\n')
        client.send(response)
        client.close()
    
try:
    ip=connect()
    connection=open_socket(ip)
    serve(connection)
except KeyboardInterrupt:
    pass
