# Import modules ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Import your custom WiFi class from your WiFiConnector module.
from WiFiConnector import WiFi
# Import your custom DHT22 module
import dht22
# Import time module
import time
# Import mqtt
from umqtt.simple import MQTTClient
# Import ujson, to format the message to be published
import ujson
# Set up wifi ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#Set wifi data
ssid = "Wokwi-GUEST"
password = ""
# Connect to wifi
wifi = WiFi(ssid, password)
wifi.connect()
# Setup MQTT ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Set the client id. Change this to be specific to each room or get the id of the
# device
client_id = "living_room"
# client_id = ubinascii.hexlify(machine.unique_id())
# Set you MQTT broker (server) that's running on raspberry pi. 1883 is the default port
mqtt_server = 'test.mosquitto.org'
mqtt_port = 1883
mqtt_topic = 'flam_temperature_humidity'
# MQTT client setup
mqtt_client = MQTTClient(client_id, mqtt_server, port=mqtt_port)
mqtt_client.connect()
# Custom functions ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#Function to read temperature and humidity and return json
def publish_sensor_data():
# Read from DHT22 sensor on GPIO pin 15
temp_farenheit, temp_celsius, humidity = dht22.get_sensor_data(pin=15)
# Print the reading
print("Temperature: {}°F, Temperature: {}°C, Humidity: {}%".format(temp_farenheit, temp_celsius, humidity))
# If you get a complete reading, publish the data in json format
if temp_farenheit is not None and temp_celsius is not None and humidity is not None:
# Create a dictionary to store the data
data = {
"temperature_farenheit": temp_farenheit,
"temperature_celsius": temp_celsius,
"humidity": humidity
}
# Convert the dictionary to a JSON string
message = ujson.dumps(data)
# Publish the JSON message to the MQTT broker
mqtt_client.publish(mqtt_topic, message)
print("Data published:", message)
# Main Loop
while True:
# Publish the sensor data
publish_sensor_data()
# Wait before reading the sensor again (e.g., 2 seconds)
time.sleep(2)