import time
from umqtt.simple import MQTTClient
from machine import RTC
import machine
import network
import esp
from machine import Pin
import dht
import ntptime
import ujson
import random
esp.osdebug(None)
import gc
gc.collect()
print("Hello, ESP32!")
ssid = 'Wokwi-GUEST'
password = ''
mqtt_server = 'broker.mqttdashboard.com'
topic_pub = 'tallercicom2023/ABCDE/dht22'
topic_led = 'tallercicom2023/ABCDE/led'
message_interval=5
last_message=0
led = Pin(13, Pin.OUT)
sensor = dht.DHT22(Pin(15))
print("Connecting to WiFi", end="")
sta_if = network.WLAN(network.STA_IF)
sta_if.active(True)
sta_if.connect('Wokwi-GUEST', '')
while not sta_if.isconnected():
print(".", end="")
time.sleep(0.1)
print(" Connected!")
ntptime.settime()
UTC_OFFSET = -5 * 60 * 60
random_number = ''.join(str(random.randint(0, 9)) for _ in range(8))
client_id = 'wokwi-dhtt22-'+random_number
print("cliente: {}".format (client_id))
def read_sensor():
try:
sensor.measure()
actual_time = time.localtime(time.time() + UTC_OFFSET)
timestamp=str(actual_time[0])+"/"+str(actual_time[1])+"/"+str(actual_time[2])+" "+str(actual_time[3])+":"+str(actual_time[4])+":"+str(actual_time[5])
medition = ujson.dumps({
"temp": sensor.temperature(),
"humidity": sensor.humidity(),
"timestamp": timestamp
})
return medition
except OSError as e:
return('Failed to read sensor.')
def connect_mqtt():
global client_id, mqtt_server
client = MQTTClient(client_id, mqtt_server)
client.set_callback(blink_led)
client.connect()
print('Connected to %s MQTT broker' % (mqtt_server))
client.subscribe(topic_led)
print('subscribed to %s topic' % (topic_led))
return client
def restart_and_reconnect():
print('Failed to connect to MQTT broker. Reconnecting...')
time.sleep(10)
machine.reset()
def blink_led(topic, msg):
print('Message from the topic to %s: %s ' % (topic.decode(), msg.decode()))
if msg.decode() == '1':
led.on()
elif msg.decode() == '0':
led.off()
try:
client = connect_mqtt()
except OSError as e:
restart_and_reconnect()
while True:
try:
client.check_msg()
if (time.time() - last_message) > message_interval:
message = read_sensor()
client.publish(topic_pub, message)
print("Reporting to MQTT topic {}: {}".format(topic_pub, message))
last_message = time.time()
except OSError as e:
restart_and_reconnect()