• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Copyright 2021-2024 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 asyncio
19import logging
20
21from .common import Transport, StreamPacketSource, StreamPacketSink
22
23# -----------------------------------------------------------------------------
24# Logging
25# -----------------------------------------------------------------------------
26logger = logging.getLogger(__name__)
27
28
29# -----------------------------------------------------------------------------
30async def open_unix_client_transport(spec: str) -> Transport:
31    '''Open a UNIX socket client transport.
32
33    The parameter is the path of unix socket. For abstract socket, the first character
34    needs to be '@'.
35
36    Example:
37        * /tmp/hci.socket
38        * @hci_socket
39    '''
40
41    class UnixPacketSource(StreamPacketSource):
42        def connection_lost(self, exc):
43            logger.debug(f'connection lost: {exc}')
44            self.on_transport_lost()
45
46    # For abstract socket, the first character should be null character.
47    if spec.startswith('@'):
48        spec = '\0' + spec[1:]
49
50    (
51        unix_transport,
52        packet_source,
53    ) = await asyncio.get_running_loop().create_unix_connection(UnixPacketSource, spec)
54    packet_sink = StreamPacketSink(unix_transport)
55
56    return Transport(packet_source, packet_sink)
57