File: callback_connect.py

package info (click to toggle)
python-btsocket 0.3.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 232 kB
  • sloc: python: 1,687; sh: 20; makefile: 6
file content (57 lines) | stat: -rw-r--r-- 1,685 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import logging
from btsocket import btmgmt_callback
from btsocket import btmgmt_protocol

device_addr = 'E5:10:5E:37:11:2D'

# btmgmt_callback.logger.setLevel(logging.INFO)
# btmgmt_protocol.logger.setLevel(logging.DEBUG)


def connect(mgmt_class):
    mgmt_class.send('ReadManagementVersionInformation', 0xffff)
    mgmt_class.send('AddDevice', 0, device_addr,
                    [btmgmt_protocol.AddressType.LEPublic], 2)
    mgmt_class.send('StartDiscovery', 0,
                    [btmgmt_protocol.AddressType.LEPublic])


def disconnect(mgmt):
    mgmt.send('RemoveDevice', 0, device_addr,
              [btmgmt_protocol.AddressType.LEPublic])
    mgmt.send('Disconnect', 0, device_addr,
              [btmgmt_protocol.AddressType.LEPublic])


def on_connected(data, mgmt_class):
    if data.event_frame.address == device_addr:
        print('Connected...')
        mgmt_class.send('StopDiscovery', 0,
                        [btmgmt_protocol.AddressType.LEPublic])
    mgmt_class.loop.call_later(10, disconnect, mgmt_class)


def on_disconnect(data, mgmt_class):
    if data.event_frame.command_opcode == btmgmt_protocol.Commands.Disconnect:
        print('Disconnected...')
        mgmt_class.stop()
        print('Exiting...')


def app():
    mgmt = btmgmt_callback.Mgmt()
    mgmt.add_event_callback(btmgmt_protocol.Events.DeviceConnectedEvent,
                            on_connected)
    mgmt.add_event_callback(btmgmt_protocol.Events.CommandCompleteEvent,
                            on_disconnect)
    connect(mgmt)
    try:
        mgmt.start()
    except KeyboardInterrupt:
        mgmt.stop()
    finally:
        mgmt.close()


if __name__ == '__main__':
    app()