import network
import time
import config
from machine import Pin, UART, WDT
from umqtt.simple import MQTTClient

prefix = config.MQTT_ID + "/"
print("Booting...")

led = Pin("LED", machine.Pin.OUT)
led.value(1)
time.sleep(0.1)
led.value(0)
time.sleep(0.1)
led.value(1)
time.sleep(0.1)
led.value(0)

wdt = WDT()

print("Setting up WLAN")
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(config.WIFI_SSID, config.WIFI_PASS)

wdt.feed()
while not wlan.isconnected() and wlan.status() >= 0:
    print("Connecting...")
    led.value(1)
    time.sleep(0.5)
    led.value(0)
    time.sleep(0.5)
    wdt.feed()
    
print("Connected!")
led.value(0)

wdt.feed()
print("Setting up MQTT")
client = MQTTClient(config.MQTT_ID, config.MQTT_BROKER,user=None, password=None, keepalive=300, ssl=False, ssl_params={})
client.connect()
client.publish(prefix + 'status', "connected")

wdt.feed()
print("Setting up UART")
uart = machine.UART(0, 115200,invert=UART.INV_RX)

def readUntil(uartObject, termination, maxlen=-1, includeTermination=True):
    terminatedFlag=False
    result = ''
    while maxlen < 0 or len(result) < maxlen:
        if uartObject.any():
            result += chr(uartObject.read(1)[0])
            for terminal in termination:
                if result.endswith(terminal):
                    terminatedFlag=True
                    if not includeTermination:
                         result = result[:-len(terminal)]
                    break
            if(terminatedFlag==True):
                return result
        time.sleep_us(10)
    return result

def parse_han_protocol(data):
    data = data.replace("'b'", "")
    data_list = data.split("\\r\\n")
    data_dir = {}
   
    for line in data_list:
        try:
            if line.startswith("1-0:1.8.0"):
                data_dir["kWh"] = str(float(line.split("(")[1].split("*")[0]))
            if line.startswith("1-0:1.7.0"):
                data_dir["kW"] = str(float(line.split("(")[1].split("*")[0]))
            if line.startswith("1-0:21.7.0"):
                data_dir["L1_kW"] = str(float(line.split("(")[1].split("*")[0]))
            if line.startswith("1-0:41.7.0"):
                data_dir["L2_kW"] = str(float(line.split("(")[1].split("*")[0]))
            if line.startswith("1-0:61.7.0"):
                data_dir["L3_kW"] = str(float(line.split("(")[1].split("*")[0]))
        except:
            pass
        
    return data_dir
            
data = ""

wdt.feed()
print("Running...")
while True:
    led.value(0)
    wdt.feed()

    if uart.any():
        led.value(1)
        try:
            rx_data = str(uart.readline())
        except Exception as e:
            print(e)
            client.publish(prefix + "error", str(e).encode())

        if "!" in rx_data:              
            try:
                data_dir = parse_han_protocol(data)
                for key in data_dir:
                    client.publish(prefix + key, data_dir[key].encode())
            except Exception as e:
                print(e)
                client.publish(prefix + "error", str(e).encode())
            
            data = ""
            
        else:
            try:
                data = data + rx_data
            except Exception as e:
                print(e)
                client.publish(prefix + "error", str(e).encode())
               
                

        
    
    

