• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Copyright 2021-2023 Google LLC
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7#      https://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14
15# -----------------------------------------------------------------------------
16# Imports
17# -----------------------------------------------------------------------------
18import logging
19import grpc
20
21from .common import PumpedTransport, PumpedPacketSource, PumpedPacketSink
22from .emulated_bluetooth_pb2_grpc import EmulatedBluetoothServiceStub
23from .emulated_bluetooth_vhci_pb2_grpc import VhciForwardingServiceStub
24
25# pylint: disable-next=no-name-in-module
26from .emulated_bluetooth_packets_pb2 import HCIPacket
27
28
29# -----------------------------------------------------------------------------
30# Logging
31# -----------------------------------------------------------------------------
32logger = logging.getLogger(__name__)
33
34
35# -----------------------------------------------------------------------------
36async def open_android_emulator_transport(spec):
37    '''
38    Open a transport connection to an Android emulator via its gRPC interface.
39    The parameter string has this syntax:
40    [<remote-host>:<remote-port>][,mode=<host|controller>]
41    The <remote-host>:<remote-port> part is optional, it defaults to localhost:8554
42    The mode=<mode> part is optional, it defaults to mode=host
43    When the mode is set to 'controller', the connection is for a controller (i.e the
44    Android Bluetooth stack will use the connected endpoint as its controller). When
45    the mode is set to 'host', the connection is to the 'Root Canal' virtual controller
46    that runs as part of the emulator, and used by the Android Bluetooth stack.
47
48    Examples:
49    (empty string) --> connect as a host to the emulator on localhost:8554
50    localhost:8555 --> connect as a host to the emulator on localhost:8555
51    mode=controller --> connect as a controller to the emulator on localhost:8554
52    '''
53
54    # Wrapper for I/O operations
55    class HciDevice:
56        def __init__(self, hci_device):
57            self.hci_device = hci_device
58
59        async def read(self):
60            packet = await self.hci_device.read()
61            return bytes([packet.type]) + packet.packet
62
63        async def write(self, packet):
64            await self.hci_device.write(HCIPacket(type=packet[0], packet=packet[1:]))
65
66    # Parse the parameters
67    mode = 'host'
68    server_host = 'localhost'
69    server_port = 8554
70    if spec is not None:
71        params = spec.split(',')
72        for param in params:
73            if param.startswith('mode='):
74                mode = param.split('=')[1]
75            elif ':' in param:
76                server_host, server_port = param.split(':')
77            else:
78                raise ValueError('invalid parameter')
79
80    # Connect to the gRPC server
81    server_address = f'{server_host}:{server_port}'
82    logger.debug(f'connecting to gRPC server at {server_address}')
83    channel = grpc.aio.insecure_channel(server_address)
84
85    if mode == 'host':
86        # Connect as a host
87        service = EmulatedBluetoothServiceStub(channel)
88        hci_device = HciDevice(service.registerHCIDevice())
89    elif mode == 'controller':
90        # Connect as a controller
91        service = VhciForwardingServiceStub(channel)
92        hci_device = HciDevice(service.attachVhci())
93    else:
94        raise ValueError('invalid mode')
95
96    # Create the transport object
97    transport = PumpedTransport(
98        PumpedPacketSource(hci_device.read),
99        PumpedPacketSink(hci_device.write),
100        channel.close,
101    )
102    transport.start()
103
104    return transport
105