1#!/usr/bin/env python3
2
3# Copyright 2015 The Android Open Source Project
4#
5# Licensed under the Apache License, Version 2.0 (the "License");
6# you may not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9# http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS,
13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
16"""Dump the configuration of a Bluetooth controller.
17
18The script expects to find the generated module hci_packets
19in PYTHONPATH.
20
21The controller is expected to be available through HCI over TCP
22at the port passed as parameter."""
23
24import argparse
25import asyncio
26import collections
27import sys
28
29import hci_packets as hci
30
31H4_IDC_CMD = 0x01
32H4_IDC_ACL = 0x02
33H4_IDC_SCO = 0x03
34H4_IDC_EVT = 0x04
35H4_IDC_ISO = 0x05
36
37HCI_HEADER_SIZES = dict([(H4_IDC_CMD, 3), (H4_IDC_ACL, 4), (H4_IDC_SCO, 3), (H4_IDC_EVT, 2), (H4_IDC_ISO, 4)])
38
39
40class Host:
41
42    def __init__(self):
43        self.evt_queue = collections.deque()
44        self.evt_queue_event = asyncio.Event()
45
46    async def connect(self, ip: str, port: int):
47        reader, writer = await asyncio.open_connection(ip, port)
48        self.reader = asyncio.create_task(self._read(reader))
49        self.writer = writer
50
51    async def _read(self, reader):
52        try:
53            while True:
54                idc = await reader.readexactly(1)
55
56                assert idc[0] in HCI_HEADER_SIZES
57                header = await reader.readexactly(HCI_HEADER_SIZES[idc[0]])
58
59                if idc[0] == H4_IDC_EVT:
60                    evt = hci.Event.parse_all(header + (await reader.readexactly(header[1])))
61                    #print(f"<< {evt.__class__.__name__}")
62                    self.evt_queue.append(evt)
63                    self.evt_queue_event.set()
64                else:
65                    assert False
66        except Exception as exn:
67            print(f"Reader interrupted: {exn}")
68            return
69
70    async def send_cmd(self, cmd: hci.Command):
71        #print(f">> {cmd.__class__.__name__}")
72        packet = bytes([H4_IDC_CMD]) + cmd.serialize()
73        self.writer.write(packet)
74
75    async def recv_evt(self) -> hci.Event:
76        while not self.evt_queue:
77            await self.evt_queue_event.wait()
78            self.evt_queue_event.clear()
79        return self.evt_queue.popleft()
80
81    async def expect_evt(self, expected_evt: type) -> hci.Event:
82        evt = await self.recv_evt()
83        assert isinstance(evt, expected_evt)
84        if not isinstance(evt, expected_evt):
85            print("Received unexpected event:")
86            evt.show()
87            print(f"Expected event of type {expected_evt.__name__}")
88            print(f"{list(evt.payload)}")
89        return evt
90
91
92async def br_edr_properties(host: Host):
93    await host.send_cmd(hci.ReadLocalSupportedFeatures())
94    page0 = await host.expect_evt(hci.ReadLocalSupportedFeaturesComplete)
95    await host.send_cmd(hci.ReadLocalExtendedFeatures(page_number=1))
96    page1 = await host.expect_evt(hci.ReadLocalExtendedFeaturesComplete)
97    await host.send_cmd(hci.ReadLocalExtendedFeatures(page_number=2))
98    page2 = await host.expect_evt(hci.ReadLocalExtendedFeaturesComplete)
99
100    print(
101        f"lmp_features: {{ 0x{page0.lmp_features:x}, 0x{page1.extended_lmp_features:x}, 0x{page2.extended_lmp_features:x} }}"
102    )
103
104    await host.send_cmd(hci.ReadBufferSize())
105    evt = await host.expect_evt(hci.ReadBufferSizeComplete)
106
107    print(f"acl_data_packet_length: {evt.acl_data_packet_length}")
108    print(f"total_num_acl_data_packets: {evt.total_num_acl_data_packets}")
109    print(f"sco_data_packet_length: {evt.synchronous_data_packet_length}")
110    print(f"total_num_sco_data_packets: {evt.total_num_synchronous_data_packets}")
111
112    await host.send_cmd(hci.ReadNumberOfSupportedIac())
113    evt = await host.expect_evt(hci.ReadNumberOfSupportedIacComplete)
114
115    print(f"num_supported_iac: {evt.num_support_iac}")
116
117
118async def le_properties(host: Host):
119    await host.send_cmd(hci.LeReadLocalSupportedFeatures())
120    evt = await host.expect_evt(hci.LeReadLocalSupportedFeaturesComplete)
121
122    print(f"le_features: 0x{evt.le_features:x}")
123
124    await host.send_cmd(hci.LeReadBufferSizeV2())
125    evt = await host.expect_evt(hci.LeReadBufferSizeV2Complete)
126
127    print(f"le_acl_data_packet_length: {evt.le_buffer_size.le_data_packet_length}")
128    print(f"total_num_le_acl_data_packets: {evt.le_buffer_size.total_num_le_packets}")
129    print(f"iso_data_packet_length: {evt.iso_buffer_size.le_data_packet_length}")
130    print(f"total_num_iso_data_packets: {evt.iso_buffer_size.total_num_le_packets}")
131
132    await host.send_cmd(hci.LeReadFilterAcceptListSize())
133    evt = await host.expect_evt(hci.LeReadFilterAcceptListSizeComplete)
134
135    print(f"le_filter_accept_list_size: {evt.filter_accept_list_size}")
136
137    await host.send_cmd(hci.LeReadResolvingListSize())
138    evt = await host.expect_evt(hci.LeReadResolvingListSizeComplete)
139
140    print(f"le_resolving_list_size: {evt.resolving_list_size}")
141
142    await host.send_cmd(hci.LeReadSupportedStates())
143    evt = await host.expect_evt(hci.LeReadSupportedStatesComplete)
144
145    print(f"le_supported_states: 0x{evt.le_states:x}")
146
147    await host.send_cmd(hci.LeReadMaximumAdvertisingDataLength())
148    evt = await host.expect_evt(hci.LeReadMaximumAdvertisingDataLengthComplete)
149
150    print(f"le_max_advertising_data_length: {evt.maximum_advertising_data_length}")
151
152    await host.send_cmd(hci.LeReadNumberOfSupportedAdvertisingSets())
153    evt = await host.expect_evt(hci.LeReadNumberOfSupportedAdvertisingSetsComplete)
154
155    print(f"le_num_supported_advertising_sets: {evt.number_supported_advertising_sets}")
156
157    await host.send_cmd(hci.LeReadPeriodicAdvertiserListSize())
158    evt = await host.expect_evt(hci.LeReadPeriodicAdvertiserListSizeComplete)
159
160    print(f"le_periodic_advertiser_list_size: {evt.periodic_advertiser_list_size}")
161
162
163async def run(tcp_port: int):
164    host = Host()
165    await host.connect('127.0.0.1', tcp_port)
166
167    await host.send_cmd(hci.Reset())
168    await host.expect_evt(hci.ResetComplete)
169
170    await host.send_cmd(hci.ReadLocalVersionInformation())
171    evt = await host.expect_evt(hci.ReadLocalVersionInformationComplete)
172
173    print(f"hci_version: {evt.local_version_information.hci_version}")
174    print(f"hci_subversion: 0x{evt.local_version_information.hci_revision:x}")
175    print(f"lmp_version: {evt.local_version_information.lmp_version}")
176    print(f"lmp_subversion: 0x{evt.local_version_information.lmp_subversion:x}")
177    print(f"company_identifier: 0x{evt.local_version_information.manufacturer_name:x}")
178
179    await host.send_cmd(hci.ReadLocalSupportedCommands())
180    evt = await host.expect_evt(hci.ReadLocalSupportedCommandsComplete)
181
182    print(f"supported_commands: {{ {', '.join([f'0x{b:x}' for b in evt.supported_commands])} }}")
183
184    try:
185        await br_edr_properties(host)
186    except Exception:
187        pass
188
189    try:
190        await le_properties(host)
191    except Exception:
192        pass
193
194
195def main() -> int:
196    """Generate cxx PDL backend."""
197    parser = argparse.ArgumentParser(description=__doc__)
198    parser.add_argument('tcp_port', type=int, help='HCI port')
199    return asyncio.run(run(**vars(parser.parse_args())))
200
201
202if __name__ == '__main__':
203    sys.exit(main())
204