• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2022 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 #pragma once
18 
19 #include <memory>
20 #include <vector>
21 
22 #include "hci_internals.h"
23 #include "hci_packetizer.h"
24 
25 namespace android::hardware::bluetooth::hci {
26 
27 using PacketReadCallback = std::function<void(const std::vector<uint8_t>&)>;
28 using DisconnectCallback = std::function<void(void)>;
29 
30 class H4Protocol {
31  public:
32   H4Protocol(int fd, PacketReadCallback cmd_cb, PacketReadCallback acl_cb,
33              PacketReadCallback sco_cb, PacketReadCallback event_cb,
34              PacketReadCallback iso_cb, DisconnectCallback disconnect_cb);
35 
36   size_t Send(PacketType type, const uint8_t* data, size_t length);
37   size_t Send(PacketType type, const std::vector<uint8_t>& data);
38 
39   void OnDataReady();
40 
41  protected:
42   size_t OnPacketReady(const std::vector<uint8_t>& packet);
43   void SendDataToPacketizer(uint8_t* buffer, size_t length);
44 
45  private:
46   int uart_fd_;
47   bool disconnected_{false};
48 
49   PacketReadCallback cmd_cb_;
50   PacketReadCallback acl_cb_;
51   PacketReadCallback sco_cb_;
52   PacketReadCallback event_cb_;
53   PacketReadCallback iso_cb_;
54   DisconnectCallback disconnect_cb_;
55 
56   PacketType hci_packet_type_{PacketType::UNKNOWN};
57   HciPacketizer hci_packetizer_;
58 
59   /**
60    * Question : Why read in single chunk rather than multiple reads?
61    * Answer: Using multiple reads does not work with some BT USB dongles.
62    * Reading in single shot gives expected response.
63    * ACL max length is 2 bytes, so using 64K as the buffer length.
64    */
65   static constexpr size_t kMaxPacketLength = 64 * 1024;
66 };
67 
68 }  // namespace android::hardware::bluetooth::hci
69