1# Copyright 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"""HID grpc interface."""
15
16import asyncio
17import logging
18
19from floss.pandora.floss import floss_enums
20from floss.pandora.floss import qa_client
21from floss.pandora.floss import utils
22from floss.pandora.server import bluetooth as bluetooth_module
23from google.protobuf import empty_pb2
24import grpc
25from pandora_experimental import hid_grpc_aio
26from pandora_experimental import hid_pb2
27
28
29class HIDService(hid_grpc_aio.HIDServicer):
30    """Service to trigger Bluetooth HID procedures.
31
32    This class implements the Pandora bluetooth test interfaces,
33    where the meta class definition is automatically generated by the protobuf.
34    The interface definition can be found in:
35    https://cs.android.com/android/platform/superproject/+/main:packages/modules/Bluetooth/pandora/interfaces/pandora_experimental/hid.proto
36    """
37
38    def __init__(self, bluetooth: bluetooth_module.Bluetooth):
39        self.bluetooth = bluetooth
40
41    async def SendHostReport(self, request: hid_pb2.SendHostReportRequest,
42                             context: grpc.ServicerContext) -> hid_pb2.SendHostReportResponse:
43
44        class HIDReportObserver(qa_client.BluetoothQACallbacks):
45            """Observer to observe the set HID report state."""
46
47            def __init__(self, task):
48                self.task = task
49
50            @utils.glib_callback()
51            def on_set_hid_report_completed(self, status):
52                if floss_enums.BtStatus(status) != floss_enums.BtStatus.SUCCESS:
53                    logging.error('Failed to set HID report. Status: %s', status)
54                future = self.task['set_hid_report']
55                future.get_loop().call_soon_threadsafe(future.set_result, None)
56
57        if not request.address:
58            await context.abort(grpc.StatusCode.INVALID_ARGUMENT, 'Request address field must be set.')
59
60        address = utils.address_from(request.address)
61
62        try:
63            set_hid_report = asyncio.get_running_loop().create_future()
64            observer = HIDReportObserver({'set_hid_report': set_hid_report})
65            name = utils.create_observer_name(observer)
66            self.bluetooth.qa_client.register_callback_observer(name, observer)
67            if request.report_type not in iter(floss_enums.BthhReportType):
68                await context.abort(grpc.StatusCode.INVALID_ARGUMENT, 'Invalid report type.')
69
70            if not self.bluetooth.set_hid_report(address, request.report_type, request.report):
71                await context.abort(grpc.StatusCode.UNKNOWN, 'Failed to call set_hid_report.')
72
73            await asyncio.wait_for(set_hid_report, timeout=5)
74
75        finally:
76            self.bluetooth.qa_client.unregister_callback_observer(name, observer)
77
78        return empty_pb2.Empty()
79