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 (runs when new message arrives)
def message_callback_temperaturesetting(topic, msg):
    print("Received from feed:", topic)
    print("Value:", msg)

    # Convert to int if needed (for servo control later)
    try:
        value = int(msg)
        print("Parsed value:", value)
        print(type(msg))
    except:
        print("Non-integer value")

# 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_temperaturesetting)
    client.connect()

    # Subscribe to your feed
    feed_path = f"{username}/feeds/temperaturesetting"
    client.subscribe(feed_path)

    print("Subscribed to:", feed_path)
    return client

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

    print("Waiting for messages...")

    while True:
        client.check_msg()  # Non-blocking
        time.sleep(1)

# Run
main()
