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

# ====== Globals ======
tsetting = False
last_tsetting = None
temperatureSetting = 60

# DHT11 setup (GP14)
dht_sensor = dht.DHT11(Pin(14))
furnaceRelay = machine.Pin('GP16', machine.Pin.OUT) #configure LED Pin as an output pin and create and led object for Pin class


# ====== WiFi ======
def connect_wifi():
    wlan = network.WLAN(network.STA_IF)
    wlan.active(True)
    wlan.connect(secrets.WIFI_SSID, secrets.WIFI_PASSWORD)

    print("Connecting to WiFi...")
    while not wlan.isconnected():
        time.sleep(1)

    print("Connected:", wlan.ifconfig())

# ====== MQTT Callback ======
def message_callback(topic, msg):
    global tsetting, last_tsetting,temperatureSetting
    topic = topic.decode()
    msg = msg.decode()

    print("Received:", topic, msg)

    if topic.endswith("/temperaturesetting"):
        try:
            value = int(msg)
            print("temperaturesetting value::", value)
            temperatureSetting = value
            print("Temperature Setting == ",temperatureSetting)
        except:
            print("Invalid temperaturesetting value")

    if topic.endswith("/led"):
        print("LED command:", msg)

# ====== MQTT Setup ======
def connect_mqtt():
    client_id = "picoW-client"
    broker = "io.adafruit.com"
    port = 1883

    username = secrets.AIO_USERNAME
    password = secrets.AIO_KEY

    client = MQTTClient(client_id, broker, port=port,
                        user=username, password=password)

    client.set_callback(message_callback)
    client.connect()

    # Feed paths
    base = secrets.AIO_USERNAME + "/feeds/"
    temperaturesetting_feed = base + "temperaturesetting"
    led_feed = base + "led"
    humidity_feed = base + "humidity"
    temperature_feed = base + "temperature"

    # Subscribe
    client.subscribe(temperaturesetting_feed)
    client.subscribe(led_feed)

    print("Subscribed to feeds")

    return client, led_feed, humidity_feed, temperature_feed, temperaturesetting_feed

# ====== Publish helpers ======
def publish_led(client, led_feed, value):
    msg = "ON" if value else "OFF"
    client.publish(led_feed, msg)
    print("Published LED:", msg)

def publish_temp_humidity(client, humidity_feed, temperature_feed, humidity, temp_f):
    client.publish(humidity_feed, str(humidity))
    client.publish(temperature_feed, str(temp_f))

    print("Published Humidity:", humidity)
    print("Published Temp (F):", temp_f)

# ====== Read DHT11 ======
def read_dht():
    try:
        dht_sensor.measure()
        temp_c = dht_sensor.temperature()
        humidity = dht_sensor.humidity()

        # Convert to Fahrenheit
        temp_f = (temp_c * 9/5) + 32

        return temp_f, humidity

    except Exception as e:
        print("DHT read error:", e)
        return None, None

# ====== Main ======
def main():
    global tsetting, last_tsetting,temperatureSetting, furnaceRelay

    connect_wifi()
    client, led_feed, humidity_feed, temperature_feed, temperaturesetting_feed = connect_mqtt()

    last_dht_time = 0

    while True:
        client.check_msg()

        # ---- Example toggle logic (replace with real input) ----
#        if int(time.time()) % 10 == 0:
#            tsetting = not tsetting

        # ---- Publish LED state if changed ----
#        if tsetting != last_tsetting:
#            publish_led(client, led_feed, tsetting)
#            last_tsetting = tsetting

        # ---- Read DHT every 5 seconds ----
        if time.time() - last_dht_time > 15:
            temp_f, humidity = read_dht()

            if temp_f is not None:
                publish_temp_humidity(
                    client,
                    humidity_feed,
                    temperature_feed,
                    humidity,
                    temp_f
                )

            last_dht_time = time.time()


        if temperatureSetting > temp_f:
            tsetting = True
            furnaceRelay.value(True)
        else:
            tsetting = False
            furnaceRelay.value(False)
            
        print("Temperature Setting = ",temperatureSetting)
        publish_led(client, led_feed, tsetting)  


        time.sleep(5)

# Run
main()
