"""
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-ab1234"
MQTT_BROKER = "test.mosquitto.org"
MQTT_USER = ""
MQTT_PASSWORD = ""
MQTT_TOPIC = "wokwi-weather1"
MQTT_LED = b'settled'
#instanziamo l'oggetto sensore
sensor = dht.DHT22(Pin(15))
led = Pin(32, Pin.OUT)
led.off()
def subCallback(topic,msg):
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) #creiamo un oggetto interfaccia di rete WLAN
#le interfacce supportate sono network.STA_IF (station interface, permette al microcontrollore di connettersi agli access point)
#e network.AP_IF (access point, permette agli altri di connettersi al microcontrollore)
sta_if.active(True) #attiva l'interfaccia di rete quindi ci si può effettivamente connettere
sta_if.connect('Wokwi-GUEST', '') #i parametri che si passano sono ssid(nome della rete wifi) e la key(password?)
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) #istanziamo un client mqtt
#il client mqtt ha come parametri l'id del client, e il broker
client.set_callback(subCallback) #identifica una callback per i messaggi ricevuti
#la set_callback serve per definire cosa fare quando si riceve un messaggio, tramite la funzione subcallback
#sta a me verificare, per ogni messaggio che ricevo, qual è il topic e qual è il messaggio
#per ogni topic e per ogni messaggio, nella funzione subcallback definiamo un comportamento diverso
client.connect() #mi connetto al broker
client.subscribe(MQTT_LED) #mi sottoscrivo al topic led e posso comandare un'accensione o uno spegnimento
print("Connected!")
prev_weather = ""
while True:
print("Measuring weather conditions... ", end="")
sensor.measure()
message = ujson.dumps({
"temp": sensor.temperature(),
"humidity": sensor.humidity(),
})
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)