1 /*
2  * Copyright (C) 2021-2022 Huawei Device Co., Ltd.
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  *     http://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 #include "bluetooth_hdi.h"
17 #include <v1_0/ihci_interface.h>
18 #include "bluetooth_hci_callbacks.h"
19 
20 using OHOS::HDI::Bluetooth::Hci::V1_0::IHciInterface;
21 
22 static OHOS::sptr<IHciInterface> g_iBtHci = nullptr;
23 static OHOS::sptr<BluetoothHciCallbacks> g_bluetoothHciCallbacks = nullptr;
24 
HdiInit(BtHciCallbacks * callbacks)25 int HdiInit(BtHciCallbacks *callbacks)
26 {
27     if (callbacks == nullptr) {
28         return INITIALIZATION_ERROR;
29     }
30 
31     OHOS::sptr<IHciInterface> iBtHci = IHciInterface::Get();
32     if (iBtHci == nullptr) {
33         return INITIALIZATION_ERROR;
34     }
35 
36     g_bluetoothHciCallbacks = new (std::nothrow) BluetoothHciCallbacks(callbacks);
37     if (g_bluetoothHciCallbacks == nullptr) {
38         return INITIALIZATION_ERROR;
39     }
40 
41     int32_t result = iBtHci->Init(g_bluetoothHciCallbacks);
42     if (result != BtStatus::SUCCESS) {
43         return INITIALIZATION_ERROR;
44     }
45 
46     g_iBtHci = iBtHci;
47 
48     return SUCCESS;
49 }
50 
HdiSendHciPacket(BtPacketType type,const BtPacket * packet)51 int HdiSendHciPacket(BtPacketType type, const BtPacket *packet)
52 {
53     if (packet == nullptr) {
54         return TRANSPORT_ERROR;
55     }
56     if (g_iBtHci == nullptr) {
57         return INITIALIZATION_ERROR;
58     }
59     BtType btType = BtType::ACL_DATA;
60     switch (type) {
61         case PACKET_TYPE_CMD:
62             btType = BtType::HCI_CMD;
63             break;
64         case PACKET_TYPE_ACL:
65             btType = BtType::ACL_DATA;
66             break;
67         case PACKET_TYPE_SCO:
68             btType = BtType::SCO_DATA;
69             break;
70         default:
71             break;
72     }
73     std::vector<uint8_t> data;
74     data.assign(packet->data, packet->data + packet->size);
75     int32_t result = g_iBtHci->SendHciPacket(btType, data);
76     if (result != BtStatus::SUCCESS) {
77         return TRANSPORT_ERROR;
78     }
79     return SUCCESS;
80 }
81 
HdiClose()82 void HdiClose()
83 {
84     if (g_bluetoothHciCallbacks != nullptr) {
85         g_bluetoothHciCallbacks = nullptr;
86     }
87 
88     if (g_iBtHci != nullptr) {
89         g_iBtHci->Close();
90         g_iBtHci = nullptr;
91     }
92 }
93