"""
MicroPython IoT Weather Station Example for Wokwi.com
To view the data:
1. Go to http://www.hivemq.com/demos/websocket-client/
2. Click "Connect"
3. Under Subscriptions, click "Add New Topic Subscription"
4. In the Topic field, type "wokwi-weather" then click "Subscribe"
Now click on the DHT22 sensor in the simulation,
change the temperature/humidity, and you should see
the message appear on the MQTT Broker, in the "Messages" pane.
Copyright (C) 2022, Uri Shaked
https://wokwi.com/arduino/projects/322577683855704658
"""
import network
import time
from machine import Pin
import dht
import ujson
from umqtt.simple import MQTTClient
# MQTT Server Parameters
MQTT_CLIENT_ID = "micropython-weather-demo-deety123"
MQTT_BROKER = "test.mosquitto.org"
MQTT_USER = ""
MQTT_PASSWORD = ""
MQTT_TOPIC = "wokwi-weather123" #su questo topic pubblicherà una rappresentazione json dei dati
MQTT_LED = b'unisa_iot/p01/wk-setLed' ### 3 asterischi relativi al led
sensor = dht.DHT22(Pin(15))
led = Pin(32, Pin.OUT) ###
led.off() ###
def subCallback(topic,msg): ###
#topic e msg nella callback vengono indicate in byte [b''], proprio per questo
#indichiamo MQTT_LED in byte, per permettere il confronto col parametro topic
#all'interno del if che troviamo qui sotto; questo tipo di problema non si pone
#quando pubblichi ma solo quando ricevi(come appunto in questo caso)
print(topic,msg)
if topic == MQTT_LED:
if msg == b'1':
led.on()
elif msg == b'0':
led.off()
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!")
print("Connecting to MQTT server... ", end="")
client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER, user=MQTT_USER, password=MQTT_PASSWORD)
client.set_callback(subCallback) ###serve impostarla prima di connetterci
#(probabilmente essendo possibile la presenza di messaggi persistenti su
#un certo topic, quindi disponibili già all'atto della connessione del client
#e alla sua conseguente sottoscrizione a quel topic)
#la callback è la funzione che verrà chiamata in corrispondenza della ricezione
#di un messaggio(includerà un identificazione del topic ed una gestione del msg)
#in umqtt si ha solo questa come callback, mentre in mqtt tradizionale ce
#ne sono varie di tipologie (on_connect, on_message, ecc)
client.connect()
client.subscribe(MQTT_LED) ###
print("Connected!")
prev_weather = ""
while True:
client.check_msg()
print("Measuring weather conditions... ", end="")
sensor.measure()
message = ujson.dumps({
"temp": sensor.temperature(),
"humidity": sensor.humidity(),
})
"""
dato strutturato e composto in json che sarà recuperato dal ricevente,
composto come dizionario chiave valore di temperatura ed umidità;
abbiamo una rappresentazione comunque topic-based, però stavolta il
topic è a sua volta strutturato, ovvero il topic "wokwi-weather" sarà
composto di due coppie chiave valore.
avremmo anche potuto avere due topic distinti per umidità e temperatura,
oppure avere un topic con addirittura ulteriori chiavi-valori
inoltre temp e humidity serviranno per accedere alla specifica parte
del payload (es: msg.payload.temp) (per esempio in Note-Red)
"""
if message != prev_weather:
print("Updated!")
print("Reporting to MQTT topic {}: {}".format(MQTT_TOPIC, message))
client.publish(MQTT_TOPIC, message)
prev_weather = message
else:
print("No change")
time.sleep(1)