import network
import time
import json
from umqtt.simple import MQTTClient
#connecting the controller with internet
print("connecting to internet")
sta=network.WLAN(network.STA_IF)
sta.active(True)
sta.connect('Wokwi-GUEST','')
while not sta.isconnected():
print(".",end="")
time.sleep(0.2)
print("connected")
#declaring constant
mqtt_bro="broker.hivemq.com"
mqtt_port=1883
mqtt_topic="temp"
client_id="suga"
#mqtt instance
mqtt=MQTTClient(client_id,mqtt_bro,port=mqtt_port)
#function for connecting mqtt
def conn_mqtt():
try:
print("connecting MQTT")
mqtt.connect()
except Exception as e:
print("exception due to",str(e))
conn_mqtt()
def is_json(message):
try:
json.loads(message)
return True
except ValueError:
return False
def on_msg(topic,message):
print(f"received message with {topic}:{message.decode('utf-8')}")
data=json.loads(message.decode('utf-8'))
if is_json(decoded_message):
data=json.loads(decode_message)
print("parsed JSON data:",data)
else:
print("Non-JSON message received:",decoded_message)
mqtt.set_callback(on_msg)
mqtt.subscribe(mqtt_topic)
print("subscribed topic",mqtt_topic)
try:
while True:
mqtt.check_message()
time.sleep(1)
except KeyboardInterrupt:
print("disconnecting")
mqtt.disconnect()
from machine import Pin
from time import sleep
import dht
sensor_Data=dht.DHT22(Pin(0))
while True:
try:
sleep(2)
sensor_Data.measure()
Temperature_in_celsius=sensor_Data.temperature()
Temperature_in_Fahrenheit=Temperature_in_celsius*(1.8)+32.0
Humidity=sensor_Data.humidity()
print('Temperature_in_celsius: %0.3f C' %Temperature_in_Celsius)
print('Temperature_in_fahrenheit: %0.3f F' %Temperature_in_Fahrenheit )
print('Humidity: %0.3f %%'%Humidity)
except OSERROR as e:
print('failed to read sensor.')