1#!/usr/bin/env python3
2#
3#   Copyright 2022 - 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
17import grpc
18
19from blueberry.facade.topshim import facade_pb2
20from blueberry.facade.topshim import facade_pb2_grpc
21from blueberry.tests.topshim.lib.async_closable import AsyncClosable
22from blueberry.tests.topshim.lib.async_closable import asyncSafeClose
23
24from google.protobuf import empty_pb2 as empty_proto
25
26
27class SecurityClient(AsyncClosable):
28    """
29    Wrapper gRPC interface to the GATT Service
30    """
31    # Timeout for async wait
32    __task_list = []
33    __channel = None
34    __security = None
35    __adapter = None
36
37    def __init__(self, adapter, port=8999):
38        self.__channel = grpc.aio.insecure_channel("localhost:%d" % port)
39        self.__security = facade_pb2_grpc.SecurityServiceStub(self.__channel)
40        self.__adapter = adapter
41
42    async def close(self):
43        """
44        Terminate the current tasks
45        """
46        for task in self.__task_list:
47            task.cancel()
48            task = None
49        self.__task_list.clear()
50        await self.__channel.close()
51
52    async def create_bond(self, address, transport):
53        """
54        Create a bonding entry for a given address with a particular transport type
55        """
56        await self.__security.CreateBond(facade_pb2.CreateBondRequest(address=address, transport=transport))
57        # State change to Bonding
58        await self.__adapter._listen_for_event(facade_pb2.EventType.BOND_STATE)
59        # State change to Bonded or None (based on success and failure)
60        return await self.__adapter._listen_for_event(facade_pb2.EventType.BOND_STATE)
61
62    async def remove_bond(self, address):
63        """
64        Removes a bonding entry for a given address
65        """
66        await self.__security.RemoveBond(facade_pb2.RemoveBondRequest(address=address))
67
68    async def generate_local_oob_data(self, transport):
69        await self.__security.GenerateLocalOobData(facade_pb2.GenerateOobDataRequest(transport=transport))
70        future = await self.__adapter._listen_for_event(facade_pb2.EventType.GENERATE_LOCAL_OOB_DATA)
71        return future
72