import bluetooth, time

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

conn = None
services = []

def irq(ev, data):
    global conn
    print("IRQ:", ev, bytes(data[0]) if hasattr(data[0],'__len__') else data)
    if ev == 7:   # _IRQ_PERIPHERAL_CONNECT
        conn_h, addr_type, addr = data
        conn = conn_h
        print("CONNECTED! handle=", conn)
    elif ev == 8:  # _IRQ_PERIPHERAL_DISCONNECT
        print("DISCONNECTED")
        conn = None

ble.irq(irq)

# Addr as seen in scan (MSB-first byte iteration): 24:19:72:61:9D:62
addr = bytes([0x24, 0x19, 0x72, 0x61, 0x9D, 0x62])
print("Connecting to", ":".join("%02X"%b for b in addr))
ble.gap_connect(0, addr)

t = time.ticks_ms()
while conn is None:
    if time.ticks_diff(time.ticks_ms(), t) > 12000:
        print("TIMEOUT")
        break
    time.sleep_ms(100)

if conn is not None:
    print("SUCCESS conn=", conn)
    time.sleep(1)
    ble.gap_disconnect(conn)
