• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Copyright 2021-2022 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_packets_pb2 import HCIPacket
24from .emulated_bluetooth_vhci_pb2_grpc import VhciForwardingServiceStub
25
26
27# -----------------------------------------------------------------------------
28# Logging
29# -----------------------------------------------------------------------------
30logger = logging.getLogger(__name__)
31
32
33# -----------------------------------------------------------------------------
34async def open_android_emulator_transport(spec):
35    '''
36    Open a transport connection to an Android emulator via its gRPC interface.
37    The parameter string has this syntax:
38    [<remote-host>:<remote-port>][,mode=<host|controller>]
39    The <remote-host>:<remote-port> part is optional, it defaults to localhost:8554
40    The mode=<mode> part is optional, it defaults to mode=host
41    When the mode is set to 'controller', the connection is for a controller (i.e the
42    Android Bluetooth stack will use the connected endpoint as its controller). When
43    the mode is set to 'host', the connection is to the 'Root Canal' virtual controller
44    that runs as part of the emulator, and used by the Android Bluetooth stack.
45
46    Examples:
47    (empty string) --> connect as a host to the emulator on localhost:8554
48    localhost:8555 --> connect as a host to the emulator on localhost:8555
49    mode=controller --> connect as a controller to the emulator on localhost:8554
50    '''
51
52    # Wrapper for I/O operations
53    class HciDevice:
54        def __init__(self, hci_device):
55            self.hci_device = hci_device
56
57        async def read(self):
58            packet = await self.hci_device.read()
59            return bytes([packet.type]) + packet.packet
60
61        async def write(self, packet):
62            await self.hci_device.write(
63                HCIPacket(
64                    type   = packet[0],
65                    packet = packet[1:]
66                )
67            )
68
69    # Parse the parameters
70    mode        = 'host'
71    server_host = 'localhost'
72    server_port = 8554
73    if spec is not None:
74        params = spec.split(',')
75        for param in params:
76            if param.startswith('mode='):
77                mode = param.split('=')[1]
78            elif ':' in param:
79                server_host, server_port = param.split(':')
80            else:
81                raise ValueError('invalid parameter')
82
83    # Connect to the gRPC server
84    server_address = f'{server_host}:{server_port}'
85    logger.debug(f'connecting to gRPC server at {server_address}')
86    channel = grpc.aio.insecure_channel(server_address)
87
88    if mode == 'host':
89        # Connect as a host
90        service = EmulatedBluetoothServiceStub(channel)
91        hci_device = HciDevice(service.registerHCIDevice())
92    elif mode == 'controller':
93        # Connect as a controller
94        service = VhciForwardingServiceStub(channel)
95        hci_device = HciDevice(service.attachVhci())
96    else:
97        raise ValueError('invalid mode')
98
99    # Create the transport object
100    transport = PumpedTransport(
101        PumpedPacketSource(hci_device.read),
102        PumpedPacketSink(hci_device.write),
103        channel.close
104    )
105    transport.start()
106
107    return transport
108