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

net = 'Wokwi-GUEST'
pas = ''

clientId = 'crrifrsrgxxy'
broker = 'demo.thingsboard.io'
usuario= 'espaçofronteirafinal'
          #prox3kd13767txillxco
topico = b'v1/devices/me/telemetry'
topRPCReq = 'v1/devices/me/rpc/request/'
topRPCResp = 'v1/devices/me/rpc/response/'

chave = Pin(23, Pin.IN, Pin.PULL_DOWN)

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)
    sleep_ms(200)
    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 procMsg(t, p):
    print (f'Tópico: {t}')
    print (f'Mensagem: {p}')
    
    
conexao, conectado = ativaWifi(net,pas)

print (conectado)

if conectado:
    settime()
    mqtt = MQTTClient(clientId, broker, user = usuario, password='')
    mqtt.set_callback(procMsg)
    print ('preconect')
    mqtt.connect()
    print('posconect')
    mqtt.subscribe((topRPCReq+'+').encode())

dados = {'ts': time()*1000, 
         'values':{'conta':0, 'key': False}}

while True:
    mqtt.check_msg()
    print (dados)
    dados['ts'] = (time() + 946684800)*1000
    dados['values']['conta'] += 1
    dados['values']['key'] = bool(chave.value())
    
    payload = dumps(dados).encode()
    
    mqtt.publish(topico, payload)
    sleep_ms(1000)