import network
import ujson
import time
import dht
import machine
import umqtt.simple
from machine import Pin
from time import sleep
from umqtt.simple import MQTTClient
from machine import I2C, Pin
from i2c_lcd import I2cLcd
from dht import DHT22

MQTT_CLIENT_ID = "micropython=weather-demo"
MQTT_BROKER = "test.mosquitto.org"
MQTT_USER = ""
MQTT_PASSWORD = ""
MQTT_angelina = "kurtka"

sensor = DHT22(Pin(12))
alm = 0x27
seting = I2C(scl=Pin(22), sda=Pin(21), freq=40000)
lcd = I2cLcd(seting, alm, 2, 16)
led1 = machine.Pin(2, machine.Pin.OUT)
led2 = machine.Pin(0, machine.Pin.OUT)

def sub_cb(topic, msg):
    global req_hum, req_temp
    print(topic, msg)
    if topic == b'kurtka' and '/humidity ' in msg:
        req_hum = int(msg.split()[1])
        print(req_temp, req_hum)
    if topic == b'kurtka' and '/temperature ' in msg:
        req_temp = int(msg.split()[1])
        print(req_temp, req_hum)
    if topic == b'kurtka' and '/update' in msg:
        message = ujson.dumps({
        "temperature": temperature,
        "humidity": humidity,
    })
        client.publish(MQT_angelina, message)
        print("Data updated")


req_temp, req_hum = 0, 0
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!")

print("Connecting to MQTT server... ", end="")
client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER, user=MQTT_USER, password=MQTT_PASSWORD)
client.set_callback(sub_cb)
client.connect()
client.subscribe(MQTT_angelina)

print("Connected!")
prev_weather = ""

while True:
    client.check_msg()
    sensor.measure()
    divan=sensor.temperature()
    krovat=sensor.humidity()
    lcd.move_to(0,0)
    lcd.clear()
    lcd.putstr("temp = "+ str(divan))
    lcd.move_to(0,1)
    lcd.putstr("hum = "+ str(krovat))
    message = ujson.dumps({
        "temperature": divan,
        "humidity": krovat,
    })
    if message != prev_weather:
        print("Updated")
        print("Reporting to MQTT topic {}: {}".format(MQTT_angelina, message))
        client.publish(MQTT_angelina, message)
        prev_weather = message
    if krovat >= req_hum:
        led1(1)
    else:
        led1(0)
    if divan >= req_temp:
        led2(1)
    else:
        led2(0)
    
    time.sleep(2)