import network
import time
from umqtt.simple import MQTTClient
import secrets

# WiFi setup
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):
    topic = topic.decode()
    msg = msg.decode()

    print("Received:", topic, msg)

    if topic.endswith("/mytemperaturesetting"):
        try:
            value = int(msg)
            print("temperaturesetting value:", value)
            # Add temperaturesetting control here if needed
        except:
            print("Invalid temperaturesetting value")

    elif topic.endswith("/led"):
        print("LED command:", msg)
        # Example: interpret ON/OFF
        if msg.upper() == "ON":
            print("Turn LED ON")
            # Add LED ON code here
        elif msg.upper() == "OFF":
            print("Turn LED OFF")
            # Add LED OFF code here
        else:
            print("Unknown LED command")

# 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
    temperaturesetting_feed = f"{username}/feeds/temperaturesetting"
    led_feed = f"{username}/feeds/led"

    # Subscribe to both feeds
    client.subscribe(temperaturesetting_feed)
    client.subscribe(led_feed)

    print("Subscribed to:")
    print(" -", temperaturesetting_feed)
    print(" -", led_feed)

    return client

# Main loop
def main():
    connect_wifi()
    client = connect_mqtt()

    print("Waiting for messages...")

    while True:
        client.check_msg()
        time.sleep(1)

# Run
main()
