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

# MQTT Server Parameters
MQTT_CLIENT_ID = "micropython-weather-demo"
MQTT_BROKER    = "broker.mqttdashboard.com"
MQTT_USER      = ""
MQTT_PASSWORD  = ""
MQTT_TOPIC     = "wokwi-weather"

sensor = dht.DHT22(Pin(15))

# ESP32 Pin assignment 
i2c = I2C(0, scl=Pin(22), sda=Pin(21))   #显示屏连接GPIIO 21 、22

buzzer_pin = Pin(5, Pin.OUT)  # 蜂鸣器连接到GPIO 5 
 
led_pin = Pin(0, Pin.OUT)  # LED连接到GPIO 0
led_pin.off()  # 初始时关闭LED  


# 设定温湿度报警阈值  
A=TEMP_THRESHOLD_HIGH = 30.0  # 高温报警阈值  
B=TEMP_THRESHOLD_LOW = 15.0   # 低温报警阈值  
C=HUMIDITY_THRESHOLD_HIGH = 80.0  # 高湿度报警阈值  
D=HUMIDITY_THRESHOLD_LOW = 30.0   # 低湿度报警阈值  

oled_width = 128
oled_height = 64
oled = ssd1306.SSD1306_I2C(oled_width, oled_height, i2c)

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

print("Connected!")

prev_weather = ""  
  
while True:  
  print("Measuring weather conditions... ", end="")  
  sensor.measure()   
  temp = sensor.temperature()  
  humidity = sensor.humidity() 
  
  if (temp >= A or temp <= B) or (humidity >= C or humidity <= D):  
        # 触发蜂鸣器报警          
    buzzer_pin.on()  # 蜂鸣器报警  
    time.sleep(1)

    led_pin.on()  # 点亮LED  
    time.sleep(0.5)  
    buzzer_pin.off() # 关闭蜂鸣器  
    led_pin.off()  #关灯

  message = ujson.dumps({  
    "temp": temp,  
    "humidity": humidity,  
  })  
  

  if message != prev_weather:  
    print("Updated!")  
    print("Reporting to MQTT topic {}: {}".format(MQTT_TOPIC, message))  
    try:  
      client.publish(MQTT_TOPIC, message)  

    except Exception as e:  
      print("MQTT publish failed:", e)  
    prev_weather = message  
  

    # 显示最新的温度和湿度  
    oled.fill(0)  # 清除屏幕  
    oled.text('temp: {:.1f}'.format(temp), 10, 10)  
    oled.text('humidity: {:.1f}'.format(humidity), 0, 0)  
    oled.show()  
  else:  
    print("No change")  
  time.sleep(1)