1 /*
2  * Copyright (C) 2024 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package com.android.pandora
18 
19 import android.bluetooth.BluetoothHidHost
20 import android.bluetooth.BluetoothManager
21 import android.bluetooth.BluetoothProfile
22 import android.content.Context
23 import io.grpc.stub.StreamObserver
24 import java.io.Closeable
25 import kotlinx.coroutines.CoroutineScope
26 import kotlinx.coroutines.Dispatchers
27 import kotlinx.coroutines.cancel
28 import pandora.HIDGrpc.HIDImplBase
29 import pandora.HidProto.SendHostReportRequest
30 import pandora.HidProto.SendHostReportResponse
31 
32 @kotlinx.coroutines.ExperimentalCoroutinesApi
33 class Hid(val context: Context) : HIDImplBase(), Closeable {
34     private val TAG = "PandoraHid"
35 
36     private val scope: CoroutineScope = CoroutineScope(Dispatchers.Default.limitedParallelism(1))
37 
38     private val bluetoothManager =
39         context.getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager
40     private val bluetoothAdapter = bluetoothManager.adapter
41     private val bluetoothHidHost =
42         getProfileProxy<BluetoothHidHost>(context, BluetoothProfile.HID_HOST)
43 
closenull44     override fun close() {
45         // Deinit the CoroutineScope
46         scope.cancel()
47     }
48 
sendHostReportnull49     override fun sendHostReport(
50         request: SendHostReportRequest,
51         responseObserver: StreamObserver<SendHostReportResponse>,
52     ) {
53         grpcUnary(scope, responseObserver) {
54             bluetoothHidHost.setReport(
55                 request.address.toBluetoothDevice(bluetoothAdapter),
56                 request.reportType.number.toByte(),
57                 request.report
58             )
59             SendHostReportResponse.getDefaultInstance()
60         }
61     }
62 }
63