from machine import reset, Pin, Timer
from rede import Rede
from time import sleep_ms, time, ticks_ms
from json import load, dumps, loads
from ntptime import settime
from umqtt.robust import MQTTClient
from processo import Volume
import gc
conta = 0
def cbTimer(t):
global taNaHora, limpeza, conta
taNaHora = True
conta += 1
if conta >= 120:
limpeza = True
conta = 0
def cbTimRede(t):
global retentarRede
reTentarRede = True
def debug(arg):
print(arg)
# Implementar aqui o callback do cliente mqtt
with open('config.json', 'r') as arq:
cfg = load(arq)
timRede = Timer(1)
retentarRede = False
try:
r = Rede(cfg['rede'], cfg['senha'], conecta = False, cb=debug)
r.conectar(tentativas=30)
if r.conectado:
settime()
cliente = MQTTClient(cfg["clientId"],
cfg["broker"],
user=cfg["userbroker"],
password='')
cliente.set_callback(procRPC)
cliente.connect()
cliente.subscribe((cfg['topRPCReq']+"/+").encode())
else:
print ('Sem conexão. Tentando em 30s')
timRede.init(mode = Timer.ONE_SHOT, period = 30000, callback = cbTimRede)
except OSError:
r = None # Verificar se r existe. Senão, começar de novo
taNaHora = False
timm = Timer(0)
timm.init(mode = Timer.PERIODIC, period = 500, callback = cbTimer)
limpeza = False
# Cria e inicializa a simulação
processo = Volume()
dados = {'ts':0,'values':{}}
# valor correto de timestamp -> 'ts':(time()+946684800)*1000
while True:
# tentativa de reconexão, se necessário
if retentarRede:
try:
if not r:
r = Rede(cfg['rede'], cfg['senha'], conecta = False, cb=debug)
r.conectar(tentativas=30)
if r.conectado:
settime()
cliente = MQTTClient(cfg["clientId"], cfg["broker"],
user=cfg["userbroker"], password='')
cliente.set_callback(procRPC)
cliente.connect()
cliente.subscribe((cfg[topRPCReq]+"/+").encode())
else:
print ('Sem conexão. Tentando em 30s')
timRede.init(mode = Timer.ONE_SHOT, period = 30000, callback = cbTimRede)
except OSError:
r = None # Verificar se r existe. Senão, começar de novo
retentarRede = False
try:
if r and r.conectado:
cliente.check_msg()
except OSError:
print('Não conectado')
processo.update()
# atualização da telemetria
if taNaHora:
#dados['ts'] = (time()+946684800)*1000
# inserir dados de telemetria aqui
taNaHora = False
# pausa para o WiFi e limpeza de memória
if limpeza:
sleep_ms(150)
gc.collect()
limpeza = False