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

# I/O 設定
SW1 = Pin(14, Pin.IN, Pin.PULL_UP)
LED_R = Pin(32, Pin.OUT)
LED_Y = Pin(33, Pin.OUT)
LED_G = Pin(26, Pin.OUT)

adc = ADC(Pin(4))
adc.atten(ADC.ATTN_11DB)

# DHT22 設定
p0 = Pin(2, Pin.IN)
d = dht.DHT22(p0)

# ThingSpeak 設定
host = 'http://api.thingspeak.com'
api_key = 'NFKECOZHMQ8WC9D8'  # 改成你自己的 API Key

# WiFi 連線
sta = network.WLAN(network.STA_IF)
sta.active(True)
sta.connect('Wokwi-GUEST', '')
print("Connecting to WiFi...")
while not sta.isconnected():
    print(".", end="")
    time.sleep(0.1)
print(" Connected!")

# 控制變數
upload_count = 0
sw_pressed_count = 0

# 主迴圈
while upload_count < 10:
    try:
        d.measure()
        t = d.temperature()
        h = d.humidity()
        water_level = adc.read() / 4095 * 100

        # 上傳到 ThingSpeak
        url = '%s/update?api_key=%s&field1=%.2f&field2=%.2f&field3=%.2f' % (host, api_key, water_level, t, h)
        print('Sending to ThingSpeak: ', url)
        r = urequests.get(url)
        print(f"[{upload_count + 1}/10] Upload OK: Temp={t:.2f}°C, Hum={h:.2f}%, Water Level={water_level:.2f}%")
        r.close()
        upload_count += 1

        # 警示
        if water_level < 30:
            LED_R.value(1)
            print(f"Water level low! ({water_level:.2f}%)")
        else:
            LED_R.value(0)

        if t > 32:
            LED_Y.value(1)
            print("Temperature too high!")
        else:
            LED_Y.value(0)

        if h > 45:
            LED_G.value(1)
            print("Humidity too high!")
        else:
            LED_G.value(0)

    except Exception as e:
        print("Upload failed:", e)

    # 緊急按鈕處理
    if SW1.value() == 0:
        time.sleep(0.05)  # 防止按鈕彈跳
        if SW1.value() == 0:  # 確認按鈕仍被按下
            sw_pressed_count += 1
            if sw_pressed_count % 2 == 1:
                print("Emergency Mode On")
                LED_R.value(1)
                LED_G.value(1)
            else:
                print("Emergency Mode Off")
                LED_R.value(0)
                LED_G.value(0)
            while SW1.value() == 0:
                time.sleep(0.1)

    time.sleep(16)  # ThingSpeak 最快每 15 秒一次