blob: 9549858b2c2e28229e97e709bd43675f87a6c65e [file] [log] [blame]
Myles Watson761dc492017-03-03 13:50:49 -08001//
2// Copyright 2017 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#include "hci_packetizer.h"
18
19#define LOG_TAG "android.hardware.bluetooth.hci_packetizer"
20#include <android-base/logging.h>
21#include <utils/Log.h>
22
23#include <dlfcn.h>
24#include <fcntl.h>
25
26namespace {
27
28const size_t preamble_size_for_type[] = {
29 0, HCI_COMMAND_PREAMBLE_SIZE, HCI_ACL_PREAMBLE_SIZE, HCI_SCO_PREAMBLE_SIZE,
30 HCI_EVENT_PREAMBLE_SIZE};
31const size_t packet_length_offset_for_type[] = {
32 0, HCI_LENGTH_OFFSET_CMD, HCI_LENGTH_OFFSET_ACL, HCI_LENGTH_OFFSET_SCO,
33 HCI_LENGTH_OFFSET_EVT};
34
35size_t HciGetPacketLengthForType(HciPacketType type, const uint8_t* preamble) {
36 size_t offset = packet_length_offset_for_type[type];
37 if (type != HCI_PACKET_TYPE_ACL_DATA) return preamble[offset];
38 return (((preamble[offset + 1]) << 8) | preamble[offset]);
39}
40
41} // namespace
42
43namespace android {
44namespace hardware {
45namespace bluetooth {
46namespace hci {
47
48const hidl_vec<uint8_t>& HciPacketizer::GetPacket() const { return packet_; }
49
50void HciPacketizer::OnDataReady(int fd, HciPacketType packet_type) {
51 switch (state_) {
52 case HCI_PREAMBLE: {
53 size_t bytes_read = TEMP_FAILURE_RETRY(
54 read(fd, preamble_ + bytes_read_,
55 preamble_size_for_type[packet_type] - bytes_read_));
56 CHECK(bytes_read > 0);
57 bytes_read_ += bytes_read;
58 if (bytes_read_ == preamble_size_for_type[packet_type]) {
59 size_t packet_length =
60 HciGetPacketLengthForType(packet_type, preamble_);
61 packet_.resize(preamble_size_for_type[packet_type] + packet_length);
62 memcpy(packet_.data(), preamble_, preamble_size_for_type[packet_type]);
63 bytes_remaining_ = packet_length;
64 state_ = HCI_PAYLOAD;
65 bytes_read_ = 0;
66 }
67 break;
68 }
69
70 case HCI_PAYLOAD: {
71 size_t bytes_read = TEMP_FAILURE_RETRY(read(
72 fd,
73 packet_.data() + preamble_size_for_type[packet_type] + bytes_read_,
74 bytes_remaining_));
75 CHECK(bytes_read > 0);
76 bytes_remaining_ -= bytes_read;
77 bytes_read_ += bytes_read;
78 if (bytes_remaining_ == 0) {
79 packet_ready_cb_();
80 state_ = HCI_PREAMBLE;
81 bytes_read_ = 0;
82 }
83 break;
84 }
85 }
86}
87
88} // namespace hci
89} // namespace bluetooth
90} // namespace hardware
91} // namespace android