from machine import Pin, ADC
import network
import dht
import urequests
import time

# WiFi設定
sta = network.WLAN(network.STA_IF)
sta.active(True)
sta.connect('Wokwi-GUEST', '')
while not sta.isconnected():
    print('.', end='')
    time.sleep(0.2)
print('\nConnected to WiFi!')

# ThingSpeak設定
host = 'http://api.thingspeak.com'
api_key = 'R58N2MX9EZLR4XVK'

# 元件初始化
dht_sensor = dht.DHT22(Pin(15))
adc = ADC(Pin(34))
adc.atten(ADC.ATTN_11DB)

button = Pin(4, Pin.IN, Pin.PULL_UP)
red_led = Pin(25, Pin.OUT)
yellow_led = Pin(26, Pin.OUT)
green_led = Pin(27, Pin.OUT)

# 按鈕狀態控制
press_count = 0
last_press_time = 0
debounce_ms = 300

def handle_button(pin):
    global press_count, last_press_time
    now = time.ticks_ms()
    if time.ticks_diff(now, last_press_time) > debounce_ms:
        press_count += 1
        if press_count % 2 == 1:
            red_led.value(1)
            print("Warning! SW Touched!")
        else:
            red_led.value(0)
            print("Warning disable!!")
        last_press_time = now

button.irq(trigger=Pin.IRQ_FALLING, handler=handle_button)

# 感測器讀取
def read_sensors():
    dht_sensor.measure()
    temp = dht_sensor.temperature()
    hum = dht_sensor.humidity()
    water_raw = adc.read()
    water = round((water_raw / 4095) * 100)
    return temp, hum, water

# 警告檢查
def check_warnings(temp, hum, water):
    if temp < 22:
        green_led.value(1)
        print("Warning! Temp. too low!")
    else:
        green_led.value(0)
    if hum > 75:
        yellow_led.value(1)
        print("Warning! Hum. too High!")
    else:
        yellow_led.value(0)
    if water < 30:
        red_led.value(1)
        print("Warning! Water level too low!")
    else:
        if press_count % 2 == 0:
            red_led.value(0)

# 主迴圈:紀錄 10 次,每次取平均值
for i in range(10):
    temp_list = []
    hum_list = []
    water_list = []

    print(f"\n--- 第 {i+1} 次資料紀錄 ---")
    start = time.ticks_ms()
    while time.ticks_diff(time.ticks_ms(), start) < 15000:
        try:
            temp, hum, water = read_sensors()
            temp_list.append(temp)
            hum_list.append(hum)
            water_list.append(water)
            check_warnings(temp, hum, water)
        except Exception as e:
            print("讀取感測器錯誤:", e)
        time.sleep(1)

    avg_temp = sum(temp_list) / len(temp_list)
    avg_hum = sum(hum_list) / len(hum_list)
    avg_water = sum(water_list) / len(water_list)

    url = f"{host}/update?api_key={api_key}&field1={avg_temp:.1f}&field2={avg_hum:.1f}&field3={avg_water:.1f}"
    try:
        r = urequests.get(url)
        print("上傳成功:", r.text)
        r.close()
    except Exception as e:
        print("上傳失敗:", e)

    time.sleep(1)