• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Lint as: python2, python3
2
3import asyncore
4import btsocket
5import struct
6import logging
7
8
9BT_ATT_DEFAULT_LE_MTU = 23
10
11BT_ATT_OP_MTU_REQ = 0x02
12BT_ATT_OP_MTU_RSP = 0x03
13
14
15class BluetoothGATTServerError(Exception):
16    """Error raised for GATT-related issues with BluetoothGATTServer."""
17    pass
18
19
20class BluetoothGATTServer(asyncore.dispatcher):
21    """Bluetooth GATT Server.
22
23    This class inherits asyncore.dispatcher to handle I/O on BLE socket.
24    It is essentially a socket service server. The class implements
25    initialization, read/write requests, notifications and indications.
26
27    Before creating an instance of this class, the machine must be set up
28    (with appropriate HCI commands) to be at least advertising, be powered,
29    and have LE turned on.
30
31    """
32
33    def __init__(self, mtu=BT_ATT_DEFAULT_LE_MTU):
34        self.mtu = max(mtu, BT_ATT_DEFAULT_LE_MTU)
35
36        sock, addr = btsocket.create_le_gatt_server_socket()
37        logging.debug('incoming connection from address %s', addr)
38
39        asyncore.dispatcher.__init__(self, sock=sock)
40        asyncore.loop()
41
42
43    def exchange_mtu(self, data):
44        """Handle exchange MTU request.
45
46        Exchange MTU request/response usually initiates client-server
47        communication. The method sends exchange MTU response back to client.
48        It also sets value for MTU attribute.
49
50        @param data: Raw data received from socket (without opcode).
51
52        """
53        if len(data) != 2:
54            raise BluetoothGATTServerError(
55                'Invalid MTU size: expected 2 bytes for Exchange MTU Request')
56
57        client_rx_mtu = struct.unpack('<H', data)
58        if client_rx_mtu < BT_ATT_DEFAULT_LE_MTU:
59            raise BluetoothGATTServerError('Invalid MTU size: %d < %d' %
60                                           client_rx_mtu, BT_ATT_DEFAULT_LE_MTU)
61
62        self.mtu = min(client_rx_mtu, self.mtu)
63
64        response = struct.pack('<BH', BT_ATT_OP_MTU_RSP, self.mtu)
65        self.send(response)
66
67
68    def handle_read(self):
69        """Receive and handle a single message from the socket.
70
71        This method gets called when the asynchronous loop detects that a read()
72        call on the channel's socket will succeed. It overrides handle_read()
73        from asyncore.dispatcher class.
74
75        """
76        data = self.recv(self.mtu)
77
78        opcode = ord(data[0])
79        data = data[1:]
80
81        func_map = {BT_ATT_OP_MTU_REQ: self.exchange_mtu}
82        if opcode not in func_map:
83            raise BluetoothGATTServerError('Invalid Opcode: %d' % opcode)
84
85        func_map[opcode](data)
86