from adafruit_ble import BLERadio
from adafruit_ble.advertising.standard import ProvideServicesAdvertisement
from adafruit_ble.services.nordic import UARTService
import time

ble = BLERadio()
uart_connection = None

UART_RX_CHAR_UUID = "6E400002-B5A3-F393-E0A9-E50E24DCCA9E"

while True:
    if not uart_connection:
        print("Trying to connect...")
        for adv in ble.start_scan(ProvideServicesAdvertisement, timeout=5):
            if UARTService in adv.services:
                uart_connection = ble.connect(adv)
                print("Connected")
                break
        ble.stop_scan()

    if uart_connection and uart_connection.connected:
        # Access the underlying bleak client directly
        bleak_client = uart_connection._bleio_connection._bleak_client

        data = bytes([1, 62])
        print(f"Writing directly to RX characteristic: {list(data)}")

        # Write directly to the correct characteristic
        import asyncio

        loop = asyncio.get_event_loop()
        loop.run_until_complete(
            bleak_client.write_gatt_char(UART_RX_CHAR_UUID, data)
        )

        print("Data written")
        time.sleep(2)
        uart_connection.disconnect()
        break