import network
import time
from machine import Pin, PWM, I2C
import dht
import ujson
from umqtt.simple import MQTTClient
import ssd1306

MQTT_CLIENT_ID = "liugejian2206054027"
MQTT_BROKER    = "broker.emqx.io"
MQTT_USER      = ""
MQTT_PASSWORD  = ""
MQTT_TOPIC_DATA = "liugejian/2206054027/weather"
MQTT_TOPIC_CTRL = "liugejian/2206054027/brightness"

sensor = dht.DHT22(Pin(15))

i2c = I2C(0, scl=Pin(22), sda=Pin(21)) 
oled_width = 128 
oled_height = 64 
oled = ssd1306.SSD1306_I2C(oled_width, oled_height, i2c) 
oled.text('liugejian', 10, 10)
oled.text('2206054027', 10, 20) 
oled.show()

led_pwm_pin = Pin(2, mode=Pin.OUT)
led_pwm = PWM(led_pwm_pin)


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.connect()

def on_message(topic, msg):
    global led_pwm
    if topic == MQTT_TOPIC_CTRL:
        cmd = msg.decode().lower()  # 将接收到的消息转换为小写字符串

        if cmd in ["on", "off"]:
            if cmd == "on":
                led_pwm.duty(1023)  # 设置 LED 全亮 (假设最大亮度值为1023)
            elif cmd == "off":
                led_pwm.duty(0)  # 关闭 LED
        else:  # 如果不是 "on" 或 "off" 命令,则尝试将其作为亮度值处理
            try:
                brightness = int(cmd)
                led_pwm.duty(brightness)
            except ValueError:
                print("Invalid command received: ", cmd)

client.set_callback(on_message)
client.subscribe(MQTT_TOPIC_CTRL)

prev_weather = ""
while True: 
    print("Measuring weather conditions... ", end="") 
    sensor.measure() 
    msg_data = { 
        "temp": sensor.temperature(), 
        "humidity": sensor.humidity(), 
    } 
    message = ujson.dumps(msg_data) 
    if message != prev_weather: 
        print("Updated!") 
        print("Reporting to MQTT topic {}: {}".format(MQTT_TOPIC_DATA, message))
        oled.fill(0) 
        oled.text("%.1f C" % (msg_data["temp"]), 10, 30) 
        oled.text("%.1f %%" % (msg_data["humidity"]), 10, 40)  
        oled.show() 
        client.publish(MQTT_TOPIC_DATA, message) 
        prev_weather = message 
    else: 
        print("No change")
    time.sleep(1)