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("/myservo"): try: value = int(msg) print("Servo value:", value) # Add servo control here if needed except: print("Invalid servo 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 servo_feed = f"{username}/feeds/temperaturesetting" led_feed = f"{username}/feeds/led" # Subscribe to both feeds client.subscribe(servo_feed) client.subscribe(led_feed) print("Subscribed to:") print(" -", servo_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()