#------------------------------ [IMPORT]------------------------------------
import network
import time
from machine import Pin,Timer
import dht
import ujson
from umqtt.simple import MQTTClient
#--------------------------- [OBJETOS]---------------------------------------
temporiza=Timer(0) # se instancia un objeto de la clase Timer
prev_weather=0
led=Pin(2,Pin.OUT)
led2=Pin(13,Pin.OUT)
# MQTT Server Parameters
MQTT_CLIENT_ID = "estacion-temp-julian" #Esta parte es el identificador de la tarjeta, tiene que ser unico para evitar errores
MQTT_BROKER = "broker.hivemq.com"
MQTT_USER = ""
MQTT_PASSWORD = ""
topic_pub = "javi/clima"
topic_sub = 'UMB/javier'
topic_sub2 = 'javier/boton'
topic_pub2 ="UMB/temperatura"
sensor = dht.DHT22(Pin(15))
#----------------------[ CONECTAR WIFI ]---------------------------------------------------------#
print("Conectando al 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!")
#----------------------[ FUNCION RECEPCION EN EL SUB ]---------------------------------------------------------#
def sub_cb(topic, msg):
print(f"llego el topic: {topic} con el valor {msg}")
if topic== b'UMB/javier':
fun=int (msg.decode())
print(f'Luz Led :{fun}')
led.value(not fun)
led2.value(fun)
#----------------------[ CONECTAR BROKER ]---------------------------------------------------------#
print("Connecting to MQTT server... ", end="")
client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER, user=MQTT_USER, password=MQTT_PASSWORD)
client.set_callback(sub_cb)
client.connect()
client.subscribe(topic_sub)
client.subscribe(topic_sub2)
print('Connected to %s MQTT broker, subscribed to %s topic' % (MQTT_BROKER, topic_sub))
print("Connected!")
prev_weather = ""
#----------------------[ TIMER INTERUPCION ]---------------------------------------------------------#
def desborde (Timer):
global prev_weather
sensor.measure() #entrega error cuando el sensor esta desconectado
message = ujson.dumps({"temp": sensor.temperature(),"humidity": sensor.humidity(),})
tempe=sensor.temperature()
if message != prev_weather:
print("valor publicado en el topic {}: {}".format(topic_pub, message))
client.publish(topic_pub, message)
prev_weather = message
client.publish(topic_pub2, str(sensor.temperature()))
print("valor publicado en el topic {}: {}".format(topic_pub2, tempe))
#----------------------[ LLAMADO A LA INTERUPCION INTERNA ]---------------------------------------------------------#
temporiza.init(period=1000,mode=Timer.PERIODIC,callback=desborde)
#----------------------[ CICLO INFINITO ]---------------------------------------------------------#
while True:
print ("esperando")
client.wait_msg()