import network
import time
from machine import Pin
import dht
import ujson
from umqtt.simple import MQTTClient
DEVICE_ID = "weather_station"
BROKER_ADDRESS = "io.adafruit.com"
ADAFRUIT_USER = "Fileken"
ADAFRUIT_KEY = "aio_Bxpq41n6nYOanMF6FXrg4C0AxRuB"
TOPIC_TEMP = "Fileken/feeds/lab3-temperature"
TOPIC_HUMIDITY = "Fileken/feeds/lab3-humidity"
TOPIC_COMMANDS = "Fileken/feeds/lab3-commands"
weather_sensor = dht.DHT22(Pin(13))
led = Pin(2,Pin.OUT)
led.value(0)
def wifi_connect():
print("Подключение к Wi-Fi", end="")
wifi = network.WLAN(network.STA_IF)
wifi.active(True)
wifi.connect("Wokwi-GUEST", "")
while not wifi.isconnected():
print(".", end="")
time.sleep(0.5)
print(" Взломал!")
def process_incoming_message(topic, message):
print(f"Входящее сообщение из {topic}: {message.decode()}")
command = message.decode()
if command == "RESET":
print("Перезапуск...")
elif command == "PING":
print("Жив")
elif command == "STOP":
print("Отключаюсь...")
while True:
time.sleep(1)
elif command == "LEDON":
led.value(1)
print("Включил светодиод")
elif command == "LEDOFF":
led.value(0)
print("Выключил светодиод")
else:
print(f"Что?: {command}")
def mqtt_connect():
print("Подключаюсь к брокеру...", end="")
mqtt_client = MQTTClient(DEVICE_ID, BROKER_ADDRESS, user=ADAFRUIT_USER, password=ADAFRUIT_KEY)
mqtt_client.set_callback(process_incoming_message)
mqtt_client.connect()
print("Подключился")
mqtt_client.subscribe(TOPIC_COMMANDS)
return mqtt_client
def main():
wifi_connect()
client = mqtt_connect()
previous_data = ""
while True:
try:
print("Читаю данные...")
weather_sensor.measure()
temp = weather_sensor.temperature()
humidity = weather_sensor.humidity()
sensor_data = ujson.dumps({"temp": temp, "humidity": humidity})
if sensor_data != previous_data:
print("Что-то не так!")
print(f"Температура: {temp}C")
client.publish(TOPIC_TEMP, str(temp))
print(f"Влажность: {humidity}%")
client.publish(TOPIC_HUMIDITY, str(humidity))
previous_data = sensor_data
else:
print("Ничего не происходит")
client.check_msg()
time.sleep(2)
except Exception as e:
print(f"Ошибка: {e}")
if __name__ == "__main__":
main()