# Complete project details at https://RandomNerdTutorials.com

import time
from umqttsimple import MQTTClient
import ubinascii
import machine
import micropython
import network
import esp
from machine import Pin
import dht
esp.osdebug(None)
import gc
gc.collect()

############### sensor #######################
sensor = dht.DHT22(machine.Pin(14))
############### sensor #######################

############### 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(" Connected!")
############### WIFI #######################

def connectMQTT():
    client = MQTTClient(client_id=b"hanafarm",
    server=b"09801199a93f4333ae24b951f40ab1db.s2.eu.hivemq.cloud",
    port=8883,
    user=b"astumasaru",
    password=b"Bb44012300",
    keepalive=7200,
    ssl=False,
    #ssl_params={'server_hostname':'09801199a93f4333ae24b951f40ab1db.s2.eu.hivemq.cloud'}
    )
    client.connect()
    return client

client = connectMQTT()

# Publishing Sensor Data to the MQTT broker 
def publish(topic, value):
    print(topic)
    print(value)
    client.publish(topic, value)
    print("publish Done")

def read_sensor():
    try:
        sensor.measure()
        temp = sensor.temperature()
        hum = sensor.humidity()
        if (isinstance(temp, float) and isinstance(hum, float)) or (isinstance(temp, int) and isinstance(hum, int)):
            temp = (b'{0:3.1f},'.format(temp))
            hum =  (b'{0:3.1f},'.format(hum))
            return temp, hum
        else:
            return('Invalid sensor readings.')
    except OSError as e:
        return('Failed to read sensor.')

def restart_and_reconnect():
    print('Failed to connect to MQTT broker. Reconnecting...')
    time.sleep(10)
    machine.reset()

try:
    client = connect_mqtt()
except OSError as e:
    restart_and_reconnect()

while True:
    try:
    #Read sensor data
        if (time.time() - last_message) > message_interval:
            temp, hum = read_sensor()
            print(temp)
            print(hum)
            #publish as MQTT payload
            publish('picow/temperature', temp)
            #publish('picow/pressure', pressure)
            publish('picow/humidity', hum)
            #delay 5 seconds
            utime.sleep(5)
    except OSError as e:
        restart_and_reconnect()
$abcdeabcde151015202530fghijfghij
NOCOMNCVCCGNDINLED1PWRRelay Module
NOCOMNCVCCGNDINLED1PWRRelay Module