import time
import ubinascii
import machine
import micropython
import network
import esp
from umqttsimple import MQTTClient
from machine import Pin, ADC
from dht import DHT22
esp.osdebug(None)
import gc
gc.collect()
# Wi-Fi credentials
ssid = 'Wokwi-GUEST'
password = ''
# MQTT server details
mqtt_server = 'broker.hivemq.com' # Replace with your MQTT server IP or domain name
client_id = ubinascii.hexlify(machine.unique_id())
topic_pub_temp = b'dht/temperature'
topic_pub_hum = b'dht/humidity'
topic_pub_light = b'ldr/light'
topic_sub_led = b'LED/light'
# Wi-Fi connection
station = network.WLAN(network.STA_IF)
station.active(True)
station.connect(ssid, password)
while not station.isconnected():
pass
print('Connection successful')
print(station.ifconfig())
# Initialize DHT22 sensor
dht22 = DHT22(Pin(13))
# LDR class definition
class LDR:
def __init__(self, pin, min_value=0, max_value=100):
if min_value >= max_value:
raise Exception('Min value is greater or equal to max value')
self.adc = ADC(Pin(pin))
self.adc.atten(ADC.ATTN_11DB)
self.min_value = min_value
self.max_value = max_value
def read(self):
return self.adc.read()
def value(self):
return (self.max_value - self.min_value) * self.read() / 4095
# Initialize LDR
ldr = LDR(34)
# LED initialization
led = Pin(2, Pin.OUT) # create output pin on GPIO2
# MQTT connection
def connect_mqtt():
global client_id, mqtt_server
client = MQTTClient(client_id, mqtt_server)
client.set_callback(mqtt_message)
client.connect()
client.subscribe(topic_sub_led)
print('Connected to %s MQTT broker' % (mqtt_server))
print('Subscribed to %s topic' % (topic_sub_led))
return client
def restart_and_reconnect():
print('Failed to connect to MQTT broker. Reconnecting...')
time.sleep(10)
machine.reset()
# Function to read DHT22 sensor
def read_dht():
dht22.measure()
return dht22.temperature(), dht22.humidity()
# Function to handle incoming MQTT messages
def mqtt_message(topic, msg):
print("Incoming message:", msg)
try:
if msg == b'off':
led.value(0)
print('LED is now OFF')
elif msg == b'on':
led.value(1)
print('LED is now ON')
except Exception as e:
print("Error:", e)
# Connect to MQTT broker
try:
client = connect_mqtt()
except OSError as e:
restart_and_reconnect()
# Main loop
last_message = 0
message_interval = 5
while True:
try:
if (time.time() - last_message) > message_interval:
temp, hum = read_dht()
light_intensity = 1 / ldr.value() * 20480
# Prepare sensor readings
temp = (b'{0:3.1f}'.format(temp))
hum = (b'{0:3.1f}'.format(hum))
light = (b'{0:3.1f}'.format(light_intensity))
# Publish sensor readings
client.publish(topic_pub_temp, temp)
client.publish(topic_pub_hum, hum)
client.publish(topic_pub_light, light)
# Print sensor readings to the console
print(f'Temperature: {temp.decode()}°C')
print(f'Humidity: {hum.decode()}%')
print(f'Luminous intensity: {light.decode()} lux')
print('********************************************')
last_message = time.time()
client.check_msg() # Check for incoming MQTT messages
except OSError as e:
restart_and_reconnect()