You are on page 1of 2

import time

from umqttsimple import MQTTClient


import ubinascii
import machine
from machine import Pin
import micropython

# MQTT broker info


mqtt_server = 'test.mosquitto.org'
mqtt_port = 1883
client_id = ubinascii.hexlify(machine.unique_id()) #leer el ID unico de la placa
ESP32

topic_sub = b'grupo9/esp32/salidas/pin2'
topic_pub = b'grupo9/esp32/salidas/pin2'

last_message = 0
message_interval = 5
counter = 0

led = Pin(2, Pin.OUT)


tem = 25.5
hum = 15.5

time1 = 0

def sub_cb(topic, msg):


print((topic, msg))
if topic == topic_sub and msg == b'on':
print('led on')
led.on()
if topic == topic_sub and msg == b'off':
print('led off')
led.off()

def connect_and_subscribe():
global client_id, mqtt_server, mqtt_port, topic_sub
client = MQTTClient(client_id, mqtt_server, mqtt_port)
client.set_callback(sub_cb)
client.connect()
client.subscribe(topic_sub)
print('Connected to %s MQTT broker, subscribed to %s topic' % (mqtt_server,
topic_sub))
return client

def restart_and_reconnect():
print('Failed to connect to MQTT broker. Reconnecting...')
time.sleep(10)
machine.reset()

def sub_tem_hum(time1):

time0 = time.sleep(10)
if(time0-time1>=10):
time1=time0
# codigo principal

try:
client = connect_and_subscribe()
except OSError as e:
restart_and_reconnect()

while True:
try:
client.check_msg()
if (time.time() - last_message) > message_interval:
msg = b'mensaje #%d' % counter
client.publish(topic_pub, msg)
print(msg)
last_message = time.time()
counter += 1
except OSError as e:
restart_and_reconnect()

You might also like