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);
56 void HciPacketizer::OnDataReady(int fd, HciPacketType packet_type) {
59 size_t bytes_read = TEMP_FAILURE_RETRY(
60 read(fd, preamble_ + bytes_read_,
61 preamble_size_for_type[packet_type] - bytes_read_));
62 CHECK(bytes_read > 0);
63 bytes_read_ += bytes_read;
64 if (bytes_read_ == preamble_size_for_type[packet_type]) {
65 size_t packet_length =
66 HciGetPacketLengthForType(packet_type, preamble_);
67 packet_.resize(preamble_size_for_type[packet_type] + packet_length);
68 memcpy(packet_.data(), preamble_, preamble_size_for_type[packet_type]);
69 bytes_remaining_ = packet_length;
77 size_t bytes_read = TEMP_FAILURE_RETRY(read(
79 packet_.data() + preamble_size_for_type[packet_type] + bytes_read_,
81 CHECK(bytes_read > 0);
82 bytes_remaining_ -= bytes_read;
83 bytes_read_ += bytes_read;
84 if (bytes_remaining_ == 0) {
86 state_ = HCI_PREAMBLE;
96 } // namespace bluetooth
97 } // namespace hardware
98 } // namespace android