import asyncio
from bleak import BleakClient
import requests

# ---- CONFIG ----
CPB_ADDRESS   = "CA:98:08:04:13:33"  # CPB address
PICO_URL      = "http://192.168.4.1/swing"  # <== Pico's IP here
UART_RX_UUID  = "6e400003-b5a3-f393-e0a9-e50e24dcca9e"  # Nordic UART RX (CPB -> PC)


def handle_rx(_, data: bytearray):
    """Callback for BLE notifications from CPB UART RX characteristic."""
    try:
        msg = data.decode().strip()
    except UnicodeDecodeError:
        msg = repr(data)

    print("BLE:", msg)

    if msg == "SWING":
        try:
            print("Triggering Pico...")
            requests.post(PICO_URL, data={"event": "swing"})
        except Exception as e:
            print("Network error:", e)


async def main():
    print(f"Connecting to CPB at {CPB_ADDRESS}...")
    async with BleakClient(CPB_ADDRESS) as client:
        print("Connected to CPB!")

        # Start notifications directly on the RX characteristic UUID
        await client.start_notify(UART_RX_UUID, handle_rx)
        print("Notifications started. Listening for swing events… Ctrl+C to quit.")

        # Keep script alive - although it falls asleep every 30 min anyways if computer goes to sleep
        while True:
            await asyncio.sleep(1)


if __name__ == "__main__":
    asyncio.run(main())