"""
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, ADC, RTC
import ntptime
import dht
import ujson
from umqtt.simple import MQTTClient
'''
Class for LDR sensor with required methods
'''
class LDR:
'''
Description: Initialiazing LDR sensor with given pin
Input: Pin
'''
def __init__(self, pin,):
self.ldr_pin = ADC(Pin(pin))
def get_raw_value(self):
return self.ldr_pin.read_u16()
def get_light_percentage(self):
raw_value = self.get_raw_value()
return 100 - round((raw_value/65535), 2) * 100
## Initializing LDR sensor
ldr = LDR(27)
## Testing LDR method
print(ldr.get_light_percentage())
time.sleep(0.5)
## MQTT Broker credentials
MQTT_CLIENT_ID = "clientId-RqJLZbS7c1"
MQTT_BROKER = "mqtt-dashboard.com"
MQTT_USER = ""
MQTT_PASSWORD = ""
MQTT_TOPIC = "testtopic"
## Connecting to WiFI
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("WiFi Connected!")
## Defining RTC Clock
rtc = RTC()
ntptime.settime()
## Connecting to MQTT server
print("Connecting to MQTT server... ")
client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER, user=MQTT_USER, password=MQTT_PASSWORD)
client.connect()
## Defining previous reading
prev_reading = None
while True:
print("Retrieving light percentage!")
## Getting the timestamp
dt = rtc.datetime()
try:
## Fetching new reading
reading = ldr.get_light_percentage()
## Publish if reading changed
if reading != prev_reading:
message = ujson.dumps({
"Time": f"{dt[3]}:{dt[4]} {dt[2]}-{dt[1]}-{dt[0]}",
"Reading": reading,
})
print(message)
print("Reporting to MQTT topic {}: {}".format(MQTT_TOPIC, message))
## Publishing message
client.publish(MQTT_TOPIC, message, retain=True, qos=1)
## Updating previous reading
prev_reading = reading
else:
print("No change")
except Exception as e:
print(f"Error reading: {e}")
time.sleep(1)