import bluetooth, time, struct

ble = bluetooth.BLE()
ble.active(True)
conn = None
notify_data = []
write_done_ev = False

def irq(ev, data):
    global conn, write_done_ev
    if ev == 7:
        c, at, addr = data; conn = c
    elif ev == 8:
        conn = None
    elif ev == 17:
        write_done_ev = True
    elif ev == 18:
        ch, vh, d = data
        notify_data.append((vh, bytes(d)))

ble.irq(irq)
ble.gap_connect(0, bytes([0x24,0x19,0x72,0x61,0x9D,0x62]))
t = time.ticks_ms()
while conn is None:
    if time.ticks_diff(time.ticks_ms(), t) > 10000: raise Exception("NO CONN")
    time.sleep_ms(50)
time.sleep_ms(600)

def wd(ms=4000):
    global write_done_ev; write_done_ev = False
    t = time.ticks_ms()
    while not write_done_ev:
        if time.ticks_diff(time.ticks_ms(), t) > ms: return
        time.sleep_ms(30)

# Enable both CCCDs
ble.gattc_write(conn, 21, struct.pack("<H",0x0001), 1); wd()
ble.gattc_write(conn, 24, struct.pack("<H",0x0001), 1); wd()

LOG = ["CONN OK, CCCDs enabled, waiting 30s..."]
t = time.ticks_ms()
while time.ticks_diff(time.ticks_ms(), t) < 30000:
    if len(notify_data) > 0:
        LOG.append("NOTIFY: vh={} {}b: {}".format(notify_data[-1][0], len(notify_data[-1][1]), notify_data[-1][1].hex()))
        notify_data.clear()
    time.sleep_ms(100)

LOG.append("DONE. passive timeout")
if conn: ble.gap_disconnect(conn)
with open("dtu_passive.txt","w") as f: f.write("\n".join(LOG)+"\n")
