import bluetooth, time

# Probe these MACs - read device name characteristic
TARGETS = [
    (0, bytes([0xEC,0xC9,0xFF,0xCD,0x83,0x2A])),
    (0, bytes([0x10,0xA5,0x62,0x18,0x9A,0x72])),
    (0, bytes([0xCC,0x8D,0xA2,0x11,0x09,0x8E])),
    (0, bytes([0xA4,0xC1,0x38,0x83,0xC4,0x93])),
    (0, bytes([0x98,0xDA,0x20,0x09,0x2D,0xB8])),
]

log = []
conn_handle = None
done = False
value_handle = None
pending_read = False

def bt_irq(event, data):
    global conn_handle, done, value_handle, pending_read
    if event == 7:  # connected
        conn_handle = data[0]
        log.append(f"CONN {conn_handle}")
        # Discover services
        ble.gattc_discover_services(conn_handle)
    elif event == 8:  # disconnected
        log.append(f"DISC")
        done = True
    elif event == 9:  # service result
        conn, start, end, uuid = data
        log.append(f"SVC {uuid} hdl={start}-{end}")
    elif event == 10:  # service done
        # Discover all chars
        if conn_handle is not None:
            ble.gattc_discover_characteristics(conn_handle, 1, 65535)
    elif event == 11:  # char result
        conn, def_handle, val_handle, props, uuid = data
        log.append(f"CHAR {uuid} vh={val_handle} props={props}")
        if str(uuid) == '0x2A00':  # Device Name
            value_handle = val_handle
    elif event == 12:  # char done
        if value_handle and conn_handle is not None:
            ble.gattc_read(conn_handle, value_handle)
        else:
            if conn_handle is not None:
                ble.gap_disconnect(conn_handle)
    elif event == 15:  # read result
        conn, val_handle, char_data = data
        log.append(f"NAME: {bytes(char_data)}")
        if conn_handle is not None:
            ble.gap_disconnect(conn_handle)

ble = bluetooth.BLE()
ble.active(True)
ble.irq(bt_irq)

with open("/probe_results.txt","w") as f:
    for addr_type, addr in TARGETS:
        mac = ":".join(f"{b:02X}" for b in addr)
        log = [f"=== {mac} ==="]
        conn_handle = None
        value_handle = None
        done = False
        try:
            ble.gap_connect(addr_type, addr)
            for _ in range(8):
                if done: break
                time.sleep(1)
            if not done and conn_handle:
                ble.gap_disconnect(conn_handle)
                time.sleep(1)
        except Exception as e:
            log.append(f"ERR: {e}")
        f.write("\n".join(log) + "\n\n")
        time.sleep(2)

print("PROBE_DONE")
