from machine import Pin, ADC
from time import sleep_ms, localtime
from network import WLAN, STA_IF
from ntptime import settime
from umqtt.robust import MQTTClient
from json import loads, dumps
topTele = b'ifrsrgauto/infoindustrial/telemetria/0948'
def conectarWiFi(nomerede, senharede):
r = WLAN(STA_IF)
r.active(True) # Ativa rede
if not r.isconnected():
r.connect(nomerede, senharede)
tentativas = 0
while not r.isconnected() and tentativas < 20:
sleep_ms(500)
tentativas += 1
return r, r.isconnected()
rede, conectado = conectarWiFi(nomerede='Wokwi-GUEST', senharede='')
if conectado:
print(localtime())
settime()
mqtt = MQTTClient('crr690823','broker.hivemq.com')
mqtt.connect()
print(localtime())
sensor = ADC(Pin(4))
dicDados = {'timestamp': '2000-1-1T0:0:0',
'valorADC': 0}
while True:
t = localtime()
dicDados['valorADC'] = sensor.read_u16()
dicDados['timestamp'] = f'{t[0]}-{t[1]}-{t[2]}T{t[3]}:{t[4]}:{t[5]}'
if conectado:
msg = dumps(dicDados)
mqtt.publish(topTele, msg.encode())
print (dicDados)
sleep_ms(1000)