import bluetooth, time

DTU_ADDR = bytes([0x24, 0x19, 0x72, 0x61, 0x9D, 0x62])
log = []
conn_handle = None
done = False
step = "idle"
read_handles = []

def bt_irq(event, data):
    global conn_handle, done, step, read_handles
    if event == 7:
        conn_handle = data[0]
        step = "connected"
        log.append(f"CONN {conn_handle}")
        ble.gattc_discover_services(conn_handle)
    elif event == 8:
        log.append(f"DISC err={data[2]}")
        done = True
    elif event == 9:
        conn, start, end, uuid = data
        log.append(f"SVC {uuid} {start}-{end}")
    elif event == 10:
        ble.gattc_discover_characteristics(conn_handle, 1, 65535)
    elif event == 11:
        conn, def_h, val_h, props, uuid = data
        log.append(f"CHAR {uuid} vh={val_h} props={props}")
        if props & 2:  # readable
            read_handles.append((val_h, str(uuid)))
    elif event == 12:
        step = "chars_done"
    elif event == 15:  # read result
        conn, val_h, char_data = data
        log.append(f"READ vh={val_h}: {bytes(char_data).hex()} | {bytes(char_data)}")
        if read_handles:
            h, u = read_handles.pop(0)
            try: ble.gattc_read(conn_handle, h)
            except: step = "read_done"
        else:
            step = "read_done"

ble = bluetooth.BLE()
ble.active(True)
ble.irq(bt_irq)
ble.gap_connect(0, DTU_ADDR)

for _ in range(15):
    if step == "chars_done": break
    time.sleep(1)

if step == "chars_done" and read_handles:
    h, u = read_handles.pop(0)
    ble.gattc_read(conn_handle, h)
    for _ in range(20):
        if step == "read_done": break
        time.sleep(1)

if conn_handle:
    try: ble.gap_disconnect(conn_handle)
    except: pass

with open("/dtu_read.txt","w") as f:
    f.write("\n".join(log))
print("READ_DONE")
