1# Test BLE GAP connect/disconnect
2
3from micropython import const
4import time, machine, bluetooth
5
6TIMEOUT_MS = 4000
7
8_IRQ_CENTRAL_CONNECT = const(1)
9_IRQ_CENTRAL_DISCONNECT = const(2)
10_IRQ_PERIPHERAL_CONNECT = const(7)
11_IRQ_PERIPHERAL_DISCONNECT = const(8)
12
13waiting_events = {}
14
15
16def irq(event, data):
17    if event == _IRQ_CENTRAL_CONNECT:
18        print("_IRQ_CENTRAL_CONNECT")
19        waiting_events[event] = data[0]
20    elif event == _IRQ_CENTRAL_DISCONNECT:
21        print("_IRQ_CENTRAL_DISCONNECT")
22    elif event == _IRQ_PERIPHERAL_CONNECT:
23        print("_IRQ_PERIPHERAL_CONNECT")
24        waiting_events[event] = data[0]
25    elif event == _IRQ_PERIPHERAL_DISCONNECT:
26        print("_IRQ_PERIPHERAL_DISCONNECT")
27
28    if event not in waiting_events:
29        waiting_events[event] = None
30
31
32def wait_for_event(event, timeout_ms):
33    t0 = time.ticks_ms()
34    while time.ticks_diff(time.ticks_ms(), t0) < timeout_ms:
35        if event in waiting_events:
36            return waiting_events.pop(event)
37        machine.idle()
38    raise ValueError("Timeout waiting for {}".format(event))
39
40
41# Acting in peripheral role.
42def instance0():
43    multitest.globals(BDADDR=ble.config("mac"))
44    print("gap_advertise")
45    ble.gap_advertise(20_000, b"\x02\x01\x06\x04\xffMPY")
46    multitest.next()
47    try:
48        # Wait for central to connect, then wait for it to disconnect.
49        wait_for_event(_IRQ_CENTRAL_CONNECT, TIMEOUT_MS)
50        wait_for_event(_IRQ_CENTRAL_DISCONNECT, TIMEOUT_MS)
51
52        # Start advertising again.
53        print("gap_advertise")
54        ble.gap_advertise(20_000, b"\x02\x01\x06\x04\xffMPY")
55
56        # Wait for central to connect, then disconnect it.
57        conn_handle = wait_for_event(_IRQ_CENTRAL_CONNECT, TIMEOUT_MS)
58        print("gap_disconnect:", ble.gap_disconnect(conn_handle))
59        wait_for_event(_IRQ_CENTRAL_DISCONNECT, TIMEOUT_MS)
60    finally:
61        ble.active(0)
62
63
64# Acting in central role.
65def instance1():
66    multitest.next()
67    try:
68        # Connect to peripheral and then disconnect.
69        print("gap_connect")
70        ble.gap_connect(*BDADDR)
71        conn_handle = wait_for_event(_IRQ_PERIPHERAL_CONNECT, TIMEOUT_MS)
72        print("gap_disconnect:", ble.gap_disconnect(conn_handle))
73        wait_for_event(_IRQ_PERIPHERAL_DISCONNECT, TIMEOUT_MS)
74
75        # Connect to peripheral and then let the peripheral disconnect us.
76        # Extra scan timeout allows for the peripheral to receive the disconnect
77        # event and start advertising again.
78        print("gap_connect")
79        ble.gap_connect(BDADDR[0], BDADDR[1], 5000)
80        wait_for_event(_IRQ_PERIPHERAL_CONNECT, TIMEOUT_MS)
81        wait_for_event(_IRQ_PERIPHERAL_DISCONNECT, TIMEOUT_MS)
82    finally:
83        ble.active(0)
84
85
86ble = bluetooth.BLE()
87ble.active(1)
88ble.irq(irq)
89