# main.py for CAGE PICO using MQTT (Publisher)
import time
import json
import machine
from umqtt.simple import MQTTClient
from SystemController import SystemController
from Net import Net
# --- CONFIGURATION ---
WIFI_SSID = "K2 Sweetwater FIU_Residents"
WIFI_PASSWORD = "4eiRdnZqjb88"
MQTT_BROKER = "test.mosquitto.org"
MQTT_TOPIC = b"smart_cage/status"  # The 'b' before the string is important
# Create a unique ID for this device so it doesn't conflict with others
CLIENT_ID = f"pico_cage_{machine.unique_id().hex()}"
# ---------------------
# 1. Connect to Wi-Fi
net = Net()
try:
    net.connect(WIFI_SSID, WIFI_PASSWORD)
except Exception as e:
    print(f"FATAL: Could not connect to WiFi: {e}")
    # Blink LED forever if Wi-Fi fails
    led = machine.Pin("LED", machine.Pin.OUT)
    while True:
        led.toggle()
        time.sleep(0.5)
# 2. Connect to the MQTT Broker
print(f"Connecting to MQTT Broker: {MQTT_BROKER}...")
mqtt_client = MQTTClient(CLIENT_ID, MQTT_BROKER, keepalive=60)
mqtt_client.connect()
print("Connected to MQTT Broker!")
# 3. Initialize the System Controller
controller = SystemController()
print("System Controller Initialized. Starting main loop...")
# 4. Main Loop
while True:
    try:
        # Run one cycle of the controller logic (door, fan, alarm, etc.)
        controller.run_once()
        
        # Get the latest status from the cage
        status_data = controller.cage.getStatus()
        
        # Publish the status as a JSON string to the MQTT topic
        print(f"Publishing to topic {MQTT_TOPIC}: {json.dumps(status_data)}")
        mqtt_client.publish(MQTT_TOPIC, json.dumps(status_data))
        
        # Wait 5 seconds before sending the next update
        time.sleep(5)
        
    except Exception as e:
        print(f"An error occurred in the main loop: {e}")
        print("Rebooting in 10 seconds...")
        time.sleep(10)
        machine.reset() # Reboot the pico if a major error occurs