from machine import Pin, Timer
import network
import time
from umqtt.robust import MQTTClient
import sys
import dht
import random # Importa la librería random
sensor = dht.DHT22(Pin(15))
led = Pin(2, Pin.OUT)
mqtt_client_id = bytes('client_'+'12321', 'utf-8')
ADAFRUIT_IO_URL = 'io.adafruit.com'
ADAFRUIT_USERNAME = 'billyzm92'
ADAFRUIT_IO_KEY = 'aio_AxDx07gdal5NBLrWGmrAEmYnevkY'
TOGGLE_FEED_ID = 'led'
TEMP_FEED_ID = 'presion'
HUM_FEED_ID = 'hum'
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!")
client = MQTTClient(client_id=mqtt_client_id, server=ADAFRUIT_IO_URL, user=ADAFRUIT_USERNAME, password=ADAFRUIT_IO_KEY, ssl=False)
try:
client.connect()
except Exception as e:
print('could not connect to MQTT server {}{}'.format(type(e).__name__, e))
sys.exit()
def cb(topic, msg):
print('Received Data: Topic = {}, Msg = {}'.format(topic, msg))
received_data = str(msg, 'utf-8')
if received_data == "0":
led.value(0)
if received_data == "1":
led.value(1)
temp_feed = bytes('{:s}/feeds/{:s}'.format(ADAFRUIT_USERNAME, TEMP_FEED_ID), 'utf-8')
hum_feed = bytes('{:s}/feeds/{:s}'.format(ADAFRUIT_USERNAME, HUM_FEED_ID), 'utf-8')
toggle_feed = bytes('{:s}/feeds/{:s}'.format(ADAFRUIT_USERNAME, TOGGLE_FEED_ID), 'utf-8')
client.set_callback(cb)
client.subscribe(toggle_feed)
def sens_data(data):
sensor.measure()
temp = sensor.temperature()
hum = sensor.humidity()
client.publish(temp_feed, bytes(str(temp), 'utf-8'), qos=0)
client.publish(hum_feed, bytes(str(hum), 'utf-8'), qos=0)
print("Temp - ", str(temp))
print("Hum - ", str(hum))
print('Msg sent')
timer = Timer(0)
timer.init(period=10000, mode=Timer.PERIODIC, callback=sens_data)
# Definir función para generar valores aleatorios de latitud y longitud
def generate_random_location():
lat = random.uniform(-90, 90) # Latitud en el rango [-90, 90]
lon = random.uniform(-180, 180) # Longitud en el rango [-180, 180]
return lat, lon
# Definir función para publicar latitud y longitud simuladas
def publish_location():
lat, lon = generate_random_location()
lat_feed = bytes('{:s}/feeds/latitude'.format(ADAFRUIT_USERNAME), 'utf-8')
lon_feed = bytes('{:s}/feeds/longitude'.format(ADAFRUIT_USERNAME), 'utf-8')
client.publish(lat_feed, bytes(str(lat), 'utf-8'), qos=0)
client.publish(lon_feed, bytes(str(lon), 'utf-8'), qos=0)
print("Latitude:", lat)
print("Longitude:", lon)
while True:
try:
client.check_msg()
publish_location() # Llamar a la función para publicar latitud y longitud simuladas
time.sleep(10)
except:
client.disconnect()
sys.exit()