2 // Copyright 2017 The Android Open Source Project
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
8 // http://www.apache.org/licenses/LICENSE-2.0
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.
17 #include "hci_packetizer.h"
19 #define LOG_TAG "android.hardware.bluetooth.hci_packetizer"
20 #include <android-base/logging.h>
21 #include <utils/Log.h>
28 const 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};
31 const 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};
35 size_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]);
48 const hidl_vec<uint8_t>& HciPacketizer::GetPacket() const { return packet_; }
50 void HciPacketizer::CbHciPacket(uint8_t *data, size_t len) {
51 packet_.setToExternal(data, len);
55 void HciPacketizer::OnDataReady(int fd, HciPacketType packet_type) {
58 size_t bytes_read = TEMP_FAILURE_RETRY(
59 read(fd, preamble_ + bytes_read_,
60 preamble_size_for_type[packet_type] - bytes_read_));
61 CHECK(bytes_read > 0);
62 bytes_read_ += bytes_read;
63 if (bytes_read_ == preamble_size_for_type[packet_type]) {
64 size_t packet_length =
65 HciGetPacketLengthForType(packet_type, preamble_);
66 packet_.resize(preamble_size_for_type[packet_type] + packet_length);
67 memcpy(packet_.data(), preamble_, preamble_size_for_type[packet_type]);
68 bytes_remaining_ = packet_length;
76 size_t bytes_read = TEMP_FAILURE_RETRY(read(
78 packet_.data() + preamble_size_for_type[packet_type] + bytes_read_,
80 CHECK(bytes_read > 0);
81 bytes_remaining_ -= bytes_read;
82 bytes_read_ += bytes_read;
83 if (bytes_remaining_ == 0) {
85 state_ = HCI_PREAMBLE;
94 } // namespace bluetooth
95 } // namespace hardware
96 } // namespace android