from machine import Pin, PWM, Timer
from network import WLAN, STA_IF
from time import sleep_ms, localtime
from json import loads, dumps
from umqtt.robust import MQTTClient

net = 'Wokwi-GUEST'
pas = ''

clientId = 'crrifrsrg'
broker = 'demo.thingsboard.io'
usuario= 'glhM5qdGDrySssnH0Ac6'

topico = b'v1/devices/me/telemetry'
topRPCGeral = 'v1/devices/me/rpc/request/'
topRPCResp = 'v1/devices/me/rpc/response/'


rele1= Pin(14, Pin.OUT, value=1)
rele2= Pin(27, Pin.OUT, value=1)
sensor= Pin(33, Pin.IN)

#rele1 = Pin (22, Pin.OUT)
#rele2 = Pin (23, Pin.OUT)
#sensor = Pin (26, Pin.IN, Pin.PULL_DOWN)
bot = Pin (25, Pin.IN, Pin.PULL_DOWN)
automatico = False
c = 0


tima = Timer(0)

def ativaWifi(rede, senha):
    # Retorna True se consegue conectar à rede, ou False do contrário
    # Faz 10 tentativas, separadas por 1s de tempo
    wifi = WLAN(STA_IF)
    wifi.active(True)
    if not wifi.isconnected():
        wifi.connect(rede, senha)
        tentativas = 0
        while not wifi.isconnected() and tentativas < 10:
            sleep_ms(1000)
            tentativas += 1
    if wifi.isconnected():
        return (wifi, True)
    else:
        return (wifi, False)


def entraAuto(t):
    global automatico

    automatico = True
    print("auto")
    


def rpc(t, p):
    global automatico, c, mqtt
    reqid = t.decode().replace(topRPCGeral,'')
    acao = loads(p.decode())
    print (acao)
    if acao['method'] == "getNivel":
        mqtt.publish((topRPCResp+reqid).encode(),
                      str(c).encode())
        #incluir retained
    elif acao['method'] == "setNivel":
        c = acao['params']
        print (acao['params'])
    elif acao['method'] == "getAuto":
        mqtt.publish((topRPCResp+reqid).encode(),
                      str(automatico).encode())
        #incluir retained
    elif acao['method'] == "setAuto":
        automatico = acao['params']
        print (acao['params'])

conexao, conectado = ativaWifi('Wokwi-GUEST','')

print (conectado)

if conectado:
    mqtt = MQTTClient(clientId, broker, user = usuario, password='')
    mqtt.set_callback(rpc)
    mqtt.connect()
    mqtt.subscribe(b"v1/devices/me/rpc/request/+")


automatico = 0

c = 0
#estado_bot = 0 
bAtual = bAnt = bot.value()
while True:
    if conectado:
        mqtt.check_msg()

    bAtual = bot.value()
    if bAtual != bAnt :  #AGUARDA BOTÃO
        if bAtual == 1:
            automatico = False
            tima.init(period=2000, mode=Timer.ONE_SHOT, callback=entraAuto)
        else:
            tima.deinit()
            if not automatico:                    
                c = c+1 
                if c > 3:
                    c = 0
        sleep_ms (250)
        bAnt = bAtual            

    if automatico:
        if sensor.value()==1:
            rele1.off()
            rele2.off()
            #print('ligado')
        else:
            rele1.on()
            rele2.on()
            #print('desligado')
        #sleep_ms(250)
    else:        
        if c == 0:
            rele1.on()
            rele2.on()

        elif c == 1:
            rele1.off()
            rele2.on()

        elif c == 2:
            rele2.off()
            rele1.on()       
        else:
            rele1.off()
            rele2.off()