from machine import Pin, I2C,PWM
import ssd1306,dht

key=Pin(27, Pin.OUT)
Buzzer= PWM(key)   #定义蜂鸣器
led = Pin(26, Pin.OUT)  #定义灯
Buzzer.duty(0)      #控制蜂鸣器初始关闭状态
global data
data = dht.DHT22(Pin(15))  #实例化15号管脚,21被占用了
# ESP32 Pin assignment 
i2c = I2C(0, scl=Pin(22), sda=Pin(21))

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

def Voice_On():   #开启调用
  Buzzer.duty(512)   #占空比
  Buzzer.freq(2000)    #频率
  time.sleep(0.5)
  Buzzer.duty(0)
  time.sleep(0.5)

def Voice_Off():     #关闭调用
  Buzzer.duty(0)   #蜂鸣器关闭

#报警灯
def led_on():
        led.value(0)
        time.sleep(0.3) # 等待0.3秒
        led.value(1)
        time.sleep(0.3) # 再等待0.3秒

def led_off():
    led.value(0)

oled.text('Hello, Wokwi!', 10, 10)   
oled.show()


"""
MicroPython IoT Weather Station Example for Wokwi.com

To view the data:

1. Go to http://www.hivemq.com/demos/websocket-client/
2. Click "Connect"
3. Under Subscriptions, click "Add New Topic Subscription"
4. In the Topic field, type "wokwi-weather" then click "Subscribe"

Now click on the DHT22 sensor in the simulation,
change the temperature/humidity, and you should see
the message appear on the MQTT Broker, in the "Messages" pane.

Copyright (C) 2022, Uri Shaked

https://wokwi.com/arduino/projects/322577683855704658
"""

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

# 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))

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() 
  message = ujson.dumps({
    "temp": sensor.temperature(),
    "humidity": sensor.humidity(),
  })
  if message != prev_weather:
    print("Updated!")
    print("Reporting to MQTT topic {}: {}".format(MQTT_TOPIC, message))
    client.publish(MQTT_TOPIC, message)
    prev_weather = message
  else:
    print("No change")
time.sleep(1)
"""

def Open_Test(t):
  data.measure()     #先调用测量函数,获取温湿度
  global temp
  temp=data.temperature()
  global humi
  humi=data.humidity()

Warn_tem_Max=29.0
Warn_tem_Min=20.0   
Warn_hum_Max=60.0
Warn_hum_Min=40.0

while True:   #循环获取温湿度
  if Warn_tem_Min<temp<Warn_tem_Max and Warn_hum_Min<humi<Warn_hum_Max:
    Voice_Off()
    led_off()
  else:
    Voice_On()
    led_on()
  max_or_min()
  Print()

"""
#include <Wire.h>         // I2C 通信库
#include <Adafruit_SSD1306.h> // OLED 屏幕库
#include "DHT.h"          // DHT 温湿度传感器库

#define OLED_RESET 4       // OLED 屏幕复位引脚,根据你的硬件可能需要修改
#define SCREEN_WIDTH 128   // OLED 屏幕宽度
#define SCREEN_HEIGHT 64   // OLED 屏幕高度
#define DHTPIN 2           // DHT22 传感器的数据引脚
#define DHTTYPE DHT22      // 使用 DHT22 传感器

Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
DHT dht(DHTPIN, DHTTYPE);

void setup() {
  // 初始化串口,用于调试
  Serial.begin(115200);
  // 初始化 OLED 屏幕
  if (!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) { // 0x3C 是 OLED 屏幕的地址
    Serial.println(F("SSD1306 allocation failed"));
    for(;;); // 不断循环等待
  }
  // 清除屏幕
  display.clearDisplay();
  // 初始化 DHT22 传感器
  dht.begin();
}

void loop() {
  // 读取 DHT22 的温度和湿度
  float temperature = dht.readTemperature();
  float humidity = dht.readHumidity();
  
  // 清除屏幕
  display.clearDisplay();
  
  // 设置字体大小
  display.setTextSize(1);
  // 设置字体颜色为白色
  display.setTextColor(WHITE);
  
  // 在屏幕上显示温度和湿度的字样
  display.setCursor(0, 0);
  display.print("温度: ");
  display.print(temperature);
  display.print(" C"); // C表示摄氏度
  
  display.setCursor(0, 10);
  display.print("湿度: ");
  display.print(humidity);
  display.print(" %"); // %表示百分比
  
  // 更新屏幕显示
  display.display();
  
  // 延迟一段时间再重新读取数据
  delay(2000);
}



# 定义温度阈值
TEMPERATURE_THRESHOLD = 30  # 例如,设定阈值为30摄氏度

# 假设这是从传感器读取到的当前温度值
current_temperature = 32  # 示例值,实际应从传感器读取

# 比较当前温度与阈值
if current_temperature > TEMPERATURE_THRESHOLD:
    # 发出警告,这里以打印到控制台为例
    print("警告:温度超过阈值!当前温度:", current_temperature, "°C")
    
    # 可以在这里添加更多的警告操作,例如发送邮件或短信
    # send_alert_email("温度警告", f"当前温度{current_temperature}°C,已超过阈值{TEMPERATURE_THRESHOLD}°C!")



#include <DHT.h>

#define DHTPIN 4         // DHT22的数据引脚连接到ESP32的GPIO 4
#define DHTTYPE DHT22    // DHT 22 (AM2302)
#define BEEPER_PIN 2     // 蜂鸣器连接到ESP32的GPIO 2
#define TEMPERATURE_THRESHOLD 30 // 温度阈值设置为30°C

DHT dht(DHTPIN, DHTTYPE);
unsigned long lastCheck = 0;

void setup() {
  Serial.begin(115200);
  pinMode(BEEPER_PIN, OUTPUT); // 设置蜂鸣器引脚为输出模式
  dht.begin();
}

void buzz(unsigned int duration) {
  digitalWrite(BEEPER_PIN, HIGH);
  delay(duration);
  digitalWrite(BEEPER_PIN, LOW);
}

void loop() {
  // 定期检查温度(例如每2秒检查一次)
  if (millis() - lastCheck >= 2000) {
    lastCheck = millis();
    float temperature = dht.readTemperature(); // 读取温度
    if (!isnan(temperature)) {
      Serial.print("Temperature: ");
      Serial.print(temperature);
      Serial.println("°C ");
      
      // 检查温度是否超过阈值
      if (temperature > TEMPERATURE_THRESHOLD) {
        Serial.println("Temperature is too high. Alarm!");
        // 蜂鸣器报警,例如响500毫秒停500毫秒,共响三次
        for(int i = 0; i < 3; i++) {
          buzz(500);
          delay(500);
        }
      }
    } else {
      Serial.println("Failed to read from DHT sensor!");
    }
  }
}
"""