import network
import time
from machine import Pin
import dht
import ujson
from umqttsimple import MQTTClient
# WiFi Network Parameters
# SSID: Wokwi-GUEST
# Security: Open
print("Connecting to WiFi", end="")
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect("Wokwi-GUEST", "")
while not wlan.isconnected():
print(".", end="")
time.sleep(0.1)
print(wlan.ifconfig())
print("WiFi Connected!")
# MQTT Server Parameters
MQTT_CLIENT_ID = "mqttx_26ec0284"
MQTT_BROKER = "375305f9dc1e447e89ede913820a3620.s2.eu.hivemq.cloud"
MQTT_USER = "client-1"
MQTT_PASSWORD = "Jonathan2138"
MQTT_TOPIC = "wokwi-weather"
print("Connecting to MQTT server... ", end="")
client = MQTTClient(client_id=MQTT_CLIENT_ID,
server=MQTT_BROKER, user=MQTT_USER,
password=MQTT_PASSWORD,
keepalive=7200,
ssl=True,
ssl_params={'server_hostname':'375305f9dc1e447e89ede913820a3620.s2.eu.hivemq.cloud'})
# LED pin
led = Pin(0, Pin.OUT)
# The callback function
def sub_callback(topic, msg):
print("Received: {}:{}".format(topic.decode(), msg.decode()))
led.high() #turn the led ON
client.set_callback(sub_callback)
client.connect()
client.subscribe(topic = MQTT_TOPIC)
print("MQTT Connected!")
# Read data from the DHT22 sensor and publish to the MQTT brocker
prev_weather = ""
sensor = dht.DHT22(Pin(28))
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(".")
client.ping()
client.check_msg()
time.sleep(1)
led.low()