import network
import ujson
import time
import dht
import machine
import umqtt.simple
from machine import Pin, I2C
from i2c_lcd import I2cLcd
from dht import DHT22
from neopixel import NeoPixel
#параметры
MQTT_CLIENT_ID = ""
MQTT_BROKER = "test.mosquitto.org"
MQTT_TOPIC = "top"
# Инициализация сенсоров и устройств
sensor = DHT22(Pin(12))
i2c = I2C(scl=Pin(22), sda=Pin(21), freq=400000)
lcd = I2cLcd(i2c, 0x27, 2, 16)
np = NeoPixel(Pin(27), 8) # 8 пикселей на пине 4
# Глобальные переменные для отслеживания запросов температуры и влажности
req_temp, req_hum = 0, 0
# Функция для установки цвета NeoPixels
def set_neopixel_color(color):
for i in range(np.n):
np[i] = color
np.write()
# Callback для обработки сообщений от MQTT
def sub_cb(topic, msg):
global req_temp, req_hum
print(topic, msg)
if topic == b'top' and '/humidity ' in msg:
req_hum = int(msg.split()[1])
print(req_temp, req_hum)
if topic == b'top' and '/red' in msg:
set_neopixel_color((255, 0, 0))
print(req_temp, req_hum)
if topic == b'top' and '/green' in msg:
set_neopixel_color((0, 255, 0))
print(req_temp, req_hum)
if topic == b'top' and '/blue' in msg:
set_neopixel_color((0, 0, 255))
print(req_temp, req_hum)
if topic == b'top' and '/off' in msg:
set_neopixel_color((0, 0, 0))
print(req_temp, req_hum)
if topic == b'top' and '/temperature ' in msg:
req_temp = int(msg.split()[1])
print(req_temp, req_hum)
if topic == b'top' and '/update' in msg:
update_data()
# Функция для публикации данных о температуре и влажности
def update_data():
temp, hum = read_sensor()
message = ujson.dumps({"temperature": temp, "humidity": hum})
client.publish(MQTT_TOPIC, message)
print("Data updated")
# Чтение данных с датчика DHT22
def read_sensor():
sensor.measure()
return sensor.temperature(), sensor.humidity()
# Подключение к WiFi
print("Connecting to WiFi...", end="")
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect('Wokwi-GUEST', '')
while not wlan.isconnected():
print(".", end="")
time.sleep(0.1)
print("\nConnected!")
# Подключение к MQTT
print("Connecting to MQTT server...", end="")
client = umqtt.simple.MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER)
client.set_callback(sub_cb)
client.connect()
client.subscribe(MQTT_TOPIC)
print("Connected!")
# Основной цикл программы
prev_weather = ""
while True:
client.check_msg()
temp, hum = read_sensor()
lcd.clear()
lcd.putstr("Temp: {}\nHum: {}".format(temp, hum))
# Обновление данных, если они изменились
weather_data = {"temperature": temp, "humidity": hum}
if weather_data != prev_weather:
update_data()
prev_weather = weather_data
# Управление светодиодами и NeoPixels
# Выключить, если температура ниже требуемой
time.sleep(2)