import ugfx, wifi, badge, urandom
from time import sleep

def drawGraph(xpos,ypos,xsize,ysize,data,unit = ''):
    maxdata = xsize
    #Draw Frame
    ugfx.line(xpos      ,ypos      ,xpos+xsize,ypos      ,ugfx.BLACK)
    ugfx.line(xpos      ,ypos      ,xpos      ,ypos+ysize,ugfx.BLACK)
    ugfx.line(xpos      ,ypos+ysize,xpos+xsize,ypos+ysize,ugfx.BLACK)
    ugfx.line(xpos+xsize,ypos      ,xpos+xsize,ypos+ysize,ugfx.BLACK)
    #Find Max and min values
    minyval =data[0]
    maxyval =data[0]
    for d in data:
        if d>maxyval:
            maxyval=d
        if d<minyval:
            minyval=d
    print("[GRAPH] Min X:" + str(minyval) +  " MaxX:" + str(maxyval))
    dataCount = 0
    xstart = xpos+xsize
    ystart = ypos+ysize
    maxy = int(ysize*0.9)
    lastx= xstart
    lasty= ystart
    count = 0
    #Draw
    ugfx.string(xpos+1,ypos+1,str(data[-1])+unit, "Roboto_Regular12", ugfx.BLACK)
    for d in reversed(data):
        dataCount = dataCount +1
        if dataCount>maxdata:
            break
        x = xstart-count
        y = ystart-int(d/maxyval*maxy)
        ugfx.line(lastx,lasty,x,y,ugfx.BLACK)
        lastx = x
        lasty = y
        count = count+1

psuvoltage='0.0'
psucurrent='0.0'
psutemperature='0.0'
current=['0.0','0.0', '0.0','0.0', '0.0','0.0']
notification=['','','','','','']
error=['','','','','','']
ledjes=[0,0,0,0,0,0]

laptopChargerVolt ='0.0'
laptopChargerCurrent ='0.0'
laptopChargerWatts ='0.0'
laptopChargerTemp ='0.0'
laptopChargerHumid ='0.0'

psuvoltagea     =['0.0']
psucurrenta     =['0.0']
psutemperaturea =['0.0']


ugfx.init()
ugfx.LUT_FULL
ugfx.input_init()
ugfx.clear(ugfx.BLACK)
ugfx.flush()
ugfx.clear(ugfx.WHITE)
ugfx.flush()
ugfx.clear(ugfx.BLACK)
ugfx.flush()
# Make sure WiFi is connected
wifi.init()

ugfx.clear(ugfx.WHITE);
ugfx.string(10,10,"Waiting for wifi...","Roboto_Regular12", 0)
ugfx.flush()

# Wait for WiFi connection
while not wifi.sta_if.isconnected():
    sleep(0.1)
    pass

ugfx.clear(ugfx.WHITE);
ugfx.string(10,10,"Connecting to MQTT...","Roboto_Regular12", 0)
ugfx.flush()

from umqtt.simple import MQTTClient


# Received messages from subscriptions will be delivered to this callback
def sub_cb(topic, msg):
    global psuvoltage
    global psucurrent
    global psutemperature
    global error
    global notification
    global ledjes
    
    global laptopChargerVolt
    global laptopChargerCurrent
    global laptopChargerWatts
    global laptopChargerTemp
    global laptopChargerHumid
    
    print((topic, msg))
    
    #lets strip all the extra characters
    message = (msg.decode('utf-8'))
    message = message.replace('\x08', '')
    message = message.replace('\x05', '')
    message = message.replace(',', '.')
    message = message.strip()
    
    if(topic.decode('utf-8')=='altpwr/psu/voltage'):
    	psuvoltage  = message
        psuvoltagea.append(float(message))
    if(topic.decode('utf-8')=='altpwr/psu/current'):
        psucurrent = message
        psucurrenta.append(float(message))
    if(topic.decode('utf-8')=='altpwr/psu/temperature'):
        psutemperature = message
        psutemperaturea.append(float(message))

    
    for x in range(0, 6):
        if(topic.decode('utf-8')=='altpwr/psu/'+str(x+1)+'/current'):
           current[x]=message
        if(topic.decode('utf-8')=='altpwr/psu/'+str(x+1)+'/message'):
           notification[x]=message
        if(topic.decode('utf-8')=='altpwr/psu/'+str(x+1)+'/error'):
           error[x]=message
           if(error[x]!=''):
               ledjes[x]=1
           else:
               ledjes[x]=0

    if(topic.decode('utf-8')=='altpwr/node/laptopChargeStation/temperature'):
    	laptopChargerTemp = message
    if(topic.decode('utf-8')=='altpwr/node/laptopChargeStation/humidity'):
        laptopChargerHumid = message
    if(topic.decode('utf-8')=='altpwr/node/laptopChargeStation/watts'):
        laptopChargerWatts = message
    if(topic.decode('utf-8')=='altpwr/node/laptopChargeStation/voltage'):
    	laptopChargerVolt = message
    if(topic.decode('utf-8')=='altpwr/node/laptopChargeStation/current'):
        laptopChargerCurrent = message
        
    ugfx.clear(ugfx.WHITE) 
    ugfx.string(112,1,"ALTPWR.NET PSU","Roboto_Black22", 0)
    badge.eink_png(0,0,'/lib/altpwrlaptopcharger/altpwr.png')
    ugfx.line(70,23,291,23,ugfx.BLACK)
    c = float(psucurrent)
    v = float(psuvoltage)
    psuwatts = c*v
    ugfx.string(70, 28, psuvoltage + "V, " + psucurrent + "A, " + str(psuwatts) + "Watts - " + psutemperature + "*C", "Roboto_Black18", ugfx.BLACK)
    
    drawGraph(70,35,100,40,psucurrenta)
    
    ugfx.string(70,65,"LaptopChargerStation:","Roboto_Black18", 0)
    ugfx.string(110,80,laptopChargerVolt +"V - " + laptopChargerCurrent + "A - " + laptopChargerWatts +  "Watts" ,"Roboto_Black18", 0)   
    ugfx.string(110,100,"Temp:" + laptopChargerTemp + "*C - Humid:" + laptopChargerHumid + "%" ,"Roboto_Black18", 0)
    ugfx.flush()

def main(server="mqtt.sha2017.org"):
    clientname = 'SHA2017Badge ' + str(urandom.getrandbits(30))
    c = MQTTClient(clientname, server)
    c.set_callback(sub_cb)
    c.connect()
    c.subscribe(b"altpwr/#")
    print('mqtt set')
    c.check_msg()
    while True:
        c.check_msg()
        sleep(0.1)
    c.disconnect()
    
def go_home(pushed):
    if(pushed):
        import machine
        machine.deepsleep(1)
        
ugfx.input_attach(ugfx.BTN_B, go_home)
main()