from machine import Pin, SoftI2C, PWM
import time
import dht
import ssd1306
import ujson
from umqtt.simple import MQTTClient
import network
# MQTT параметры
MQTT_CLIENT_ID = "micropython-weather"
MQTT_BROKER = "broker.mqttdashboard.com"
MQTT_USER = "111"
MQTT_PASSWORD = "132"
MQTT_TOPIC = "Hum"
MQTT_TOPIC1 = "Temp"
MQTT_TOPIC2 = "servo"
servo = PWM(Pin(18, mode=Pin.OUT))
servo.freq(50)
i2c = SoftI2C(scl=Pin(22), sda=Pin(21))
ledG = Pin(12, Pin.OUT)
ledR = Pin(13, Pin.OUT)
ledB = Pin(14, Pin.OUT)
ledG1 = Pin(26, Pin.OUT)
ledR1 = Pin(27, Pin.OUT)
ledB1 = Pin(25, Pin.OUT)
oled_width = 128
oled_height = 64
oled = ssd1306.SSD1306_I2C(oled_width, oled_height, i2c)
sensor = dht.DHT22(Pin(23))
sta_if = network.WLAN(network.STA_IF)
sta_if.active(True)
sta_if.connect('Wokwi-GUEST', '')
while not sta_if.isconnected():
time.sleep(0.1)
client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER, user=MQTT_USER, password=MQTT_PASSWORD)
client.connect()
prev_weather = ""
prev_weather1 = ""
def mqtt_message(topic, msg):
#msg=msg.decode()
#msg = ujson.loads(msg)
print("Incoming message:", msg)
try:
msg = ujson.loads(msg)
#msg=msg.decode()
servo.duty(int(msg))
except Exception as e:
print("Error:", e, msg)
print("Connecting to WiFi...", end="")
import network
wifi = network.WLAN(network.STA_IF)
wifi.active(True)
wifi.connect("Wokwi-GUEST", "")
while not wifi.isconnected():
sleep(0.5)
print(".", end="")
print("Done")
print("Connecting to MQTT...")
client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER, user=MQTT_USER, password=MQTT_PASSWORD)
client.set_callback(mqtt_message)
client.connect()
client.subscribe(MQTT_TOPIC2)
print("Connected!")
while True:
client.check_msg()
sensor.measure()
message = ujson.dumps(sensor.humidity())
if message != prev_weather:
client.publish(MQTT_TOPIC, message)
prev_weather = message
else:
time.sleep(1)
sensor.measure()
message1 = ujson.dumps(sensor.temperature())
if message1 != prev_weather1:
client.publish(MQTT_TOPIC1, message1)
prev_weather1 = message1
else:
time.sleep(1)
try:
time.sleep(1) # DHT22 возвращает не более 1 измерения каждые 2 секунды
sensor.measure() # Восстанавливает измерения с датчика
print(f"Temperature : {sensor.temperature():.1f}°C")
print(f"Humidity : {sensor.humidity():.1f}%")
except OSError as e:
print("Failed reception")
oled.fill(0)
oled.show()
oled.text(f"Temp. : {sensor.temperature()} C", 0, 0)
oled.text(f"Humidity : {sensor.humidity():.1f}%", 0, 10)
oled.show()
temp = (sensor.temperature())
tempmin = 15
tempmax = 40
humid = (sensor.humidity())
humidmin = 20
humidmax = 65
if (temp<tempmin):
ledG.off()
ledR.off()
ledB.on()
elif (temp>tempmax):
ledR.on()
ledG.off()
ledB.off()
else:
ledR.off()
ledG.on()
ledB.off()
if (humid<humidmin):
ledG1.on()
ledR1.on()
ledB1.off()
elif (humid>humidmax):
ledR1.on()
ledG1.off()
ledB1.on()
else:
ledR1.off()
ledG1.on()
ledB1.off()
#client.wait_msg()
#client.check_msg()