import umqtt.simple
import easywifi
from machine import UART
def write_step(step,val):
  if val > 180.0:
    val = 180.0
  uart.write("s%i %i\n"%(step,180 - val))

def handle_co2(step,a):
  write_step(step, (a/4000.0)*180.0)

def handle_temp(step,a):
  write_step(step, ((a + 50.0)/100.0)*180.0)
  
def handle_rh(step,a):
  write_step(step, (a/100.0 )*180.0)
  
def sub_cb(topic, msg):
    print((topic, msg))
    try:
        tp = topic.decode("utf-8")
        ms = msg.decode("utf-8")
        s = ms.split(" ")[0]
        a = float(s)
        print(topic,"=",a)
        if tp == "revspace/sensors/co2":
           print("CO2, %i" %a)
           handle_co2(0,a)  
        elif tp == "revspace/sensors/co2/mhz19":
           print("CO2, %i" %a)
           handle_co2(1,a)  
        elif tp == "revspace/sensors/temperature/12/1":
           print("CO2, %i" %a)
           handle_temp(2,a)  
        elif tp == "revspace/sensors/temperature/12/2":
           print("CO2, %i" %a)
           handle_temp(3,a) 
        elif tp == "revspace/sensors/temperature/2/5":
           print("CO2, %i" %a)
           handle_temp(4,a)  
        elif tp == "revspace/sensors/temperature/5/1":
           print("CO2, %i" %a)
           handle_temp(5,a)  
        elif tp == "revspace/sensors/temperature/5/2":
           print("CO2, %i" %a)
           handle_temp(6,a)  
        elif tp == "revspace/sensors/temperature/5/3":
           print("CO2, %i" %a)
           handle_temp(7,a)  
        elif tp == "revspace/sensors/humdity":
           print("CO2, %i" %a)
           handle_rh(8,a)  
        elif tp == "revspace/sensors/humidity/2/5":
           print("CO2, %i" %a)
           handle_rh(9,a)  

    except:
    	print("boohbooh")
  
  
def main():
  global clnt
  global uart
  clnt = ""
  uart = UART(2,9600)
  print("WIFI")
  easywifi.enable()
  print("Init")
  clnt = umqtt.simple.MQTTClient("umqtt_client","revspace.nl")
  clnt.set_callback(sub_cb)
  print("Connect")
  clnt.connect()
  clnt.subscribe(b"revspace/#")
  while True:
    clnt.wait_msg()
    
main()