Merge "Move ISecurityManagerListener out of internal namespace"
diff --git a/gd/Android.bp b/gd/Android.bp
index fc6461b..e7a389a 100644
--- a/gd/Android.bp
+++ b/gd/Android.bp
@@ -332,6 +332,14 @@
],
}
+filegroup {
+ name: "BluetoothHciClassSources",
+ srcs: [
+ "hci/address.cc",
+ "hci/class_of_device.cc",
+ ],
+}
+
genrule {
name: "BluetoothGeneratedPackets_h",
tools: [
diff --git a/gd/hci/acl_manager.cc b/gd/hci/acl_manager.cc
index 0e1ad45..2852b6c 100644
--- a/gd/hci/acl_manager.cc
+++ b/gd/hci/acl_manager.cc
@@ -56,7 +56,7 @@
};
struct AclManager::impl {
- impl(AclManager& acl_manager) : acl_manager_(acl_manager) {}
+ impl(const AclManager& acl_manager) : acl_manager_(acl_manager) {}
void Start() {
hci_layer_ = acl_manager_.GetDependency<HciLayer>();
@@ -1580,7 +1580,7 @@
handler_->Post(BindOnce(&impl::cleanup, common::Unretained(this), handle));
}
- AclManager& acl_manager_;
+ const AclManager& acl_manager_;
Controller* controller_ = nullptr;
uint16_t max_acl_packet_credits_ = 0;
diff --git a/gd/hci/acl_manager.h b/gd/hci/acl_manager.h
index 9a0b279..27c4fb3 100644
--- a/gd/hci/acl_manager.h
+++ b/gd/hci/acl_manager.h
@@ -150,11 +150,11 @@
private:
friend AclManager;
- AclConnection(AclManager* manager, uint16_t handle, Address address)
+ AclConnection(const AclManager* manager, uint16_t handle, Address address)
: manager_(manager), handle_(handle), address_(address) {}
- AclConnection(AclManager* manager, uint16_t handle, Address address, AddressType address_type, Role role)
+ AclConnection(const AclManager* manager, uint16_t handle, Address address, AddressType address_type, Role role)
: manager_(manager), handle_(handle), address_(address), address_type_(address_type), role_(role) {}
- AclManager* manager_;
+ const AclManager* manager_;
uint16_t handle_;
Address address_;
AddressType address_type_;
diff --git a/gd/l2cap/classic/internal/dynamic_channel_impl.cc b/gd/l2cap/classic/internal/dynamic_channel_impl.cc
index 3eaa42c..bd56187 100644
--- a/gd/l2cap/classic/internal/dynamic_channel_impl.cc
+++ b/gd/l2cap/classic/internal/dynamic_channel_impl.cc
@@ -105,11 +105,11 @@
incoming_mtu_ = mtu;
}
-RetransmissionAndFlowControlModeOption DynamicChannelImpl::GetMode() const {
+RetransmissionAndFlowControlModeOption DynamicChannelImpl::GetChannelMode() const {
return mode_;
}
-void DynamicChannelImpl::SetMode(RetransmissionAndFlowControlModeOption mode) {
+void DynamicChannelImpl::SetChannelMode(RetransmissionAndFlowControlModeOption mode) {
mode_ = mode;
}
diff --git a/gd/l2cap/classic/internal/dynamic_channel_impl.h b/gd/l2cap/classic/internal/dynamic_channel_impl.h
index d7e64f4..ba75814 100644
--- a/gd/l2cap/classic/internal/dynamic_channel_impl.h
+++ b/gd/l2cap/classic/internal/dynamic_channel_impl.h
@@ -20,6 +20,7 @@
#include "hci/address.h"
#include "l2cap/cid.h"
#include "l2cap/classic/dynamic_channel.h"
+#include "l2cap/internal/channel_impl.h"
#include "l2cap/l2cap_packets.h"
#include "l2cap/mtu.h"
#include "l2cap/psm.h"
@@ -33,7 +34,7 @@
class Link;
-class DynamicChannelImpl {
+class DynamicChannelImpl : public l2cap::internal::ChannelImpl {
public:
DynamicChannelImpl(Psm psm, Cid cid, Cid remote_cid, Link* link, os::Handler* l2cap_handler);
@@ -78,8 +79,8 @@
virtual Mtu GetIncomingMtu() const;
virtual void SetIncomingMtu(Mtu mtu);
- virtual RetransmissionAndFlowControlModeOption GetMode() const;
- virtual void SetMode(RetransmissionAndFlowControlModeOption mode);
+ virtual RetransmissionAndFlowControlModeOption GetChannelMode() const;
+ virtual void SetChannelMode(RetransmissionAndFlowControlModeOption mode);
virtual FcsType GetFcsType() const;
virtual void SetFcsType(FcsType fcs_type);
diff --git a/gd/l2cap/classic/internal/fixed_channel_impl.h b/gd/l2cap/classic/internal/fixed_channel_impl.h
index 80a86c5..563a770 100644
--- a/gd/l2cap/classic/internal/fixed_channel_impl.h
+++ b/gd/l2cap/classic/internal/fixed_channel_impl.h
@@ -19,6 +19,8 @@
#include "common/bidi_queue.h"
#include "l2cap/cid.h"
#include "l2cap/classic/fixed_channel.h"
+#include "l2cap/internal/channel_impl.h"
+#include "l2cap/l2cap_packets.h"
#include "os/handler.h"
#include "os/log.h"
@@ -29,7 +31,7 @@
class Link;
-class FixedChannelImpl {
+class FixedChannelImpl : public l2cap::internal::ChannelImpl {
public:
FixedChannelImpl(Cid cid, Link* link, os::Handler* l2cap_handler);
@@ -65,6 +67,22 @@
return channel_queue_.GetDownEnd();
}
+ Cid GetCid() const {
+ return cid_;
+ }
+
+ Cid GetRemoteCid() const {
+ return cid_;
+ }
+
+ RetransmissionAndFlowControlModeOption GetChannelMode() const {
+ return RetransmissionAndFlowControlModeOption::L2CAP_BASIC;
+ }
+
+ void SetChannelMode(RetransmissionAndFlowControlModeOption) {
+ LOG_ERROR("Setting channel mode on a fixed channel cid 0x%02hx", cid_);
+ }
+
private:
// Constructor states
// For logging purpose only
diff --git a/gd/l2cap/classic/internal/link.cc b/gd/l2cap/classic/internal/link.cc
index 0577784..286ab54 100644
--- a/gd/l2cap/classic/internal/link.cc
+++ b/gd/l2cap/classic/internal/link.cc
@@ -60,8 +60,8 @@
std::shared_ptr<FixedChannelImpl> Link::AllocateFixedChannel(Cid cid, SecurityPolicy security_policy) {
auto channel = fixed_channel_allocator_.AllocateChannel(cid, security_policy);
- scheduler_->AttachChannel(cid, channel->GetQueueDownEnd(), cid);
- reassembler_.AttachChannel(cid, channel->GetQueueDownEnd(), nullptr);
+ scheduler_->AttachChannel(cid, channel);
+ reassembler_.AttachChannel(cid, channel);
return channel;
}
@@ -95,8 +95,8 @@
SecurityPolicy security_policy) {
auto channel = dynamic_channel_allocator_.AllocateChannel(psm, remote_cid, security_policy);
if (channel != nullptr) {
- scheduler_->AttachChannel(channel->GetCid(), channel->GetQueueDownEnd(), channel->GetRemoteCid());
- reassembler_.AttachChannel(channel->GetCid(), channel->GetQueueDownEnd(), channel);
+ scheduler_->AttachChannel(channel->GetCid(), channel);
+ reassembler_.AttachChannel(channel->GetCid(), channel);
}
channel->local_initiated_ = false;
return channel;
@@ -106,8 +106,8 @@
SecurityPolicy security_policy) {
auto channel = dynamic_channel_allocator_.AllocateReservedChannel(reserved_cid, psm, remote_cid, security_policy);
if (channel != nullptr) {
- scheduler_->AttachChannel(channel->GetCid(), channel->GetQueueDownEnd(), channel->GetRemoteCid());
- reassembler_.AttachChannel(channel->GetCid(), channel->GetQueueDownEnd(), channel);
+ scheduler_->AttachChannel(channel->GetCid(), channel);
+ reassembler_.AttachChannel(channel->GetCid(), channel);
}
channel->local_initiated_ = true;
return channel;
diff --git a/gd/l2cap/classic/internal/link.h b/gd/l2cap/classic/internal/link.h
index 2ba7a9d..ea33b15 100644
--- a/gd/l2cap/classic/internal/link.h
+++ b/gd/l2cap/classic/internal/link.h
@@ -65,7 +65,7 @@
// FixedChannel methods
- virtual std::shared_ptr<FixedChannelImpl> AllocateFixedChannel(Cid cid, SecurityPolicy security_policy);
+ std::shared_ptr<FixedChannelImpl> AllocateFixedChannel(Cid cid, SecurityPolicy security_policy);
virtual bool IsFixedChannelAllocated(Cid cid);
diff --git a/gd/l2cap/classic/internal/link_manager.cc b/gd/l2cap/classic/internal/link_manager.cc
index d9961c2..ee93fd7 100644
--- a/gd/l2cap/classic/internal/link_manager.cc
+++ b/gd/l2cap/classic/internal/link_manager.cc
@@ -133,8 +133,8 @@
if (pending_dynamic_channels_.find(device) != pending_dynamic_channels_.end()) {
for (Psm psm : pending_dynamic_channels_[device]) {
auto& callbacks = pending_dynamic_channels_callbacks_[device].front();
- pending_dynamic_channels_callbacks_[device].pop_front();
link->SendConnectionRequest(psm, link->ReserveDynamicChannel(), std::move(callbacks));
+ pending_dynamic_channels_callbacks_[device].pop_front();
}
pending_dynamic_channels_.erase(device);
pending_dynamic_channels_callbacks_.erase(device);
diff --git a/gd/l2cap/classic/internal/link_mock.h b/gd/l2cap/classic/internal/link_mock.h
index 58dbd55..3e0e2a6 100644
--- a/gd/l2cap/classic/internal/link_mock.h
+++ b/gd/l2cap/classic/internal/link_mock.h
@@ -43,8 +43,6 @@
MOCK_METHOD(hci::Address, GetDevice, (), (override));
MOCK_METHOD(void, OnAclDisconnected, (hci::ErrorCode status), (override));
MOCK_METHOD(void, Disconnect, (), (override));
- MOCK_METHOD(std::shared_ptr<FixedChannelImpl>, AllocateFixedChannel, (Cid cid, SecurityPolicy security_policy),
- (override));
MOCK_METHOD(std::shared_ptr<DynamicChannelImpl>, AllocateDynamicChannel,
(Psm psm, Cid cid, SecurityPolicy security_policy), (override));
MOCK_METHOD(bool, IsFixedChannelAllocated, (Cid cid), (override));
diff --git a/gd/l2cap/classic/internal/signalling_manager.cc b/gd/l2cap/classic/internal/signalling_manager.cc
index bf2c8cd..147a571 100644
--- a/gd/l2cap/classic/internal/signalling_manager.cc
+++ b/gd/l2cap/classic/internal/signalling_manager.cc
@@ -202,7 +202,7 @@
}
case ConfigurationOptionType::RETRANSMISSION_AND_FLOW_CONTROL: {
auto config = RetransmissionAndFlowControlConfigurationOption::Specialize(option.get());
- channel->SetMode(config->mode_);
+ channel->SetChannelMode(config->mode_);
break;
}
case ConfigurationOptionType::FRAME_CHECK_SEQUENCE: {
diff --git a/gd/l2cap/classic/internal/signalling_manager_test.cc b/gd/l2cap/classic/internal/signalling_manager_test.cc
index 82aeca8..a89b445 100644
--- a/gd/l2cap/classic/internal/signalling_manager_test.cc
+++ b/gd/l2cap/classic/internal/signalling_manager_test.cc
@@ -58,36 +58,7 @@
os::Handler* l2cap_handler_ = nullptr;
};
-PacketView<kLittleEndian> GetPacketView(std::unique_ptr<packet::BasePacketBuilder> packet) {
- auto bytes = std::make_shared<std::vector<uint8_t>>();
- BitInserter i(*bytes);
- bytes->reserve(packet->size());
- packet->Serialize(i);
- return packet::PacketView<packet::kLittleEndian>(bytes);
-}
-
-TEST_F(L2capClassicSignallingManagerTest, handle_connection_request) {
- l2cap::internal::testing::MockParameterProvider parameter_provider;
- testing::MockDynamicChannelServiceManagerImpl dynamic_service_manager_;
- testing::MockFixedChannelServiceManagerImpl fixed_service_manager_;
- testing::MockLink link{l2cap_handler_, ¶meter_provider};
- std::shared_ptr<FixedChannelImpl> signalling_channel = std::make_shared<FixedChannelImpl>(1, &link, l2cap_handler_);
- EXPECT_CALL(link, AllocateFixedChannel(_, _)).WillRepeatedly(Return(signalling_channel));
- auto service_psm = 0x1;
- EXPECT_CALL(dynamic_service_manager_, IsServiceRegistered(service_psm)).WillRepeatedly(Return(true));
- DynamicChannelAllocator channel_allocator{&link, l2cap_handler_};
- ClassicSignallingManager signalling_manager{l2cap_handler_, &link, &dynamic_service_manager_, &channel_allocator,
- &fixed_service_manager_};
- auto* down_end = signalling_channel->GetQueueDownEnd();
- os::EnqueueBuffer<packet::PacketView<kLittleEndian>> enqueue_buffer{down_end};
- auto dcid = 0x101;
- auto builder = ConnectionRequestBuilder::Create(1, service_psm, dcid);
- enqueue_buffer.Enqueue(std::make_unique<PacketView<kLittleEndian>>(GetPacketView(std::move(builder))),
- l2cap_handler_);
- SyncHandler(l2cap_handler_);
- EXPECT_CALL(link, AllocateDynamicChannel(_, dcid, _));
- SyncHandler(l2cap_handler_);
-}
+TEST_F(L2capClassicSignallingManagerTest, precondition) {}
} // namespace
} // namespace internal
diff --git a/gd/l2cap/internal/channel_impl.h b/gd/l2cap/internal/channel_impl.h
new file mode 100644
index 0000000..c375b5f
--- /dev/null
+++ b/gd/l2cap/internal/channel_impl.h
@@ -0,0 +1,64 @@
+/*
+ * Copyright 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#pragma once
+
+#include "common/bidi_queue.h"
+#include "l2cap/cid.h"
+#include "l2cap/l2cap_packets.h"
+
+namespace bluetooth {
+namespace l2cap {
+namespace internal {
+
+/**
+ * Common interface for internal channel implementation
+ */
+class ChannelImpl {
+ public:
+ virtual ~ChannelImpl() = default;
+
+ /**
+ * Return the queue end for upper layer (L2CAP user)
+ */
+ virtual common::BidiQueueEnd<packet::BasePacketBuilder, packet::PacketView<packet::kLittleEndian>>*
+ GetQueueUpEnd() = 0;
+
+ /**
+ * Return the queue end for lower layer (segmenter and reassembler)
+ */
+ virtual common::BidiQueueEnd<packet::PacketView<packet::kLittleEndian>, packet::BasePacketBuilder>*
+ GetQueueDownEnd() = 0;
+
+ virtual Cid GetCid() const = 0;
+
+ virtual Cid GetRemoteCid() const = 0;
+
+ /**
+ * Return one of the supported channel mode as defined above
+ */
+ virtual RetransmissionAndFlowControlModeOption GetChannelMode() const = 0;
+
+ /**
+ * Invoked by the command signalling manager to update the channel mode. Does NOT apply to fixed channel, OR LE
+ * credit-based flow control channel
+ */
+ virtual void SetChannelMode(RetransmissionAndFlowControlModeOption) = 0;
+};
+
+} // namespace internal
+} // namespace l2cap
+} // namespace bluetooth
diff --git a/gd/l2cap/internal/channel_impl_mock.h b/gd/l2cap/internal/channel_impl_mock.h
new file mode 100644
index 0000000..0fe61e5
--- /dev/null
+++ b/gd/l2cap/internal/channel_impl_mock.h
@@ -0,0 +1,44 @@
+/*
+ * Copyright 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#pragma once
+
+#include "l2cap/internal/channel_impl.h"
+
+#include <gmock/gmock.h>
+
+// Unit test interfaces
+namespace bluetooth {
+namespace l2cap {
+namespace internal {
+namespace testing {
+
+class MockChannelImpl : public ChannelImpl {
+ public:
+ MOCK_METHOD((common::BidiQueueEnd<packet::BasePacketBuilder, packet::PacketView<packet::kLittleEndian>>*),
+ GetQueueUpEnd, (), (override));
+ MOCK_METHOD((common::BidiQueueEnd<packet::PacketView<packet::kLittleEndian>, packet::BasePacketBuilder>*),
+ GetQueueDownEnd, (), (override));
+ MOCK_METHOD(Cid, GetCid, (), (const, override));
+ MOCK_METHOD(Cid, GetRemoteCid, (), (const, override));
+ MOCK_METHOD(RetransmissionAndFlowControlModeOption, GetChannelMode, (), (const, override));
+ MOCK_METHOD(void, SetChannelMode, (RetransmissionAndFlowControlModeOption), (override));
+};
+
+} // namespace testing
+} // namespace internal
+} // namespace l2cap
+} // namespace bluetooth
diff --git a/gd/l2cap/internal/reassembler.cc b/gd/l2cap/internal/reassembler.cc
index 70f2be6..ede977c 100644
--- a/gd/l2cap/internal/reassembler.cc
+++ b/gd/l2cap/internal/reassembler.cc
@@ -18,7 +18,6 @@
#include "common/bidi_queue.h"
#include "l2cap/cid.h"
-#include "l2cap/classic/internal/dynamic_channel_impl.h"
#include "l2cap/l2cap_packets.h"
#include "packet/packet_view.h"
@@ -36,11 +35,10 @@
link_queue_up_end_->UnregisterDequeue();
}
-void Reassembler::AttachChannel(Cid cid, Reassembler::UpperQueueDownEnd* channel_down_end,
- std::shared_ptr<classic::internal::DynamicChannelImpl> channel) {
+void Reassembler::AttachChannel(Cid cid, std::shared_ptr<ChannelImpl> channel) {
ASSERT_LOG(channel_map_.find(cid) == channel_map_.end(), "Channel is already attached");
channel_map_.emplace(std::piecewise_construct, std::forward_as_tuple(cid),
- std::forward_as_tuple(channel_down_end, channel));
+ std::forward_as_tuple(channel->GetQueueDownEnd(), channel));
}
void Reassembler::DetachChannel(Cid cid) {
@@ -63,7 +61,7 @@
}
auto channel_mode = cid < kFirstDynamicChannel ? RetransmissionAndFlowControlModeOption::L2CAP_BASIC
- : channel->second.channel_->GetMode();
+ : channel->second.channel_->GetChannelMode();
switch (channel_mode) {
case RetransmissionAndFlowControlModeOption::L2CAP_BASIC:
handle_basic_mode_packet(cid, basic_frame_view);
diff --git a/gd/l2cap/internal/reassembler.h b/gd/l2cap/internal/reassembler.h
index a1cf903..30ae555 100644
--- a/gd/l2cap/internal/reassembler.h
+++ b/gd/l2cap/internal/reassembler.h
@@ -22,6 +22,7 @@
#include "common/bidi_queue.h"
#include "l2cap/cid.h"
+#include "l2cap/internal/channel_impl.h"
#include "l2cap/l2cap_packets.h"
#include "l2cap/mtu.h"
#include "os/queue.h"
@@ -31,12 +32,6 @@
namespace bluetooth {
namespace l2cap {
-namespace classic {
-namespace internal {
-class DynamicChannelImpl;
-}
-} // namespace classic
-
namespace internal {
/**
@@ -64,8 +59,7 @@
* config. If the channel is a fixed channel, use nullptr.
* TODO (b/144503952): Rethink about channel abstraction
*/
- void AttachChannel(Cid cid, UpperQueueDownEnd* channel_down_end,
- std::shared_ptr<classic::internal::DynamicChannelImpl> channel);
+ void AttachChannel(Cid cid, std::shared_ptr<ChannelImpl> channel);
/**
* Detach a channel for packet reassembly. Incoming packets won't be delivered to the specified cid.
@@ -74,10 +68,10 @@
private:
struct ChannelBuffer {
- ChannelBuffer(UpperQueueDownEnd* queue_end, std::shared_ptr<classic::internal::DynamicChannelImpl> channel)
+ ChannelBuffer(UpperQueueDownEnd* queue_end, std::shared_ptr<ChannelImpl> channel)
: enqueue_buffer_(queue_end), channel_(std::move(channel)) {}
os::EnqueueBuffer<UpperEnqueue> enqueue_buffer_;
- std::shared_ptr<classic::internal::DynamicChannelImpl> channel_;
+ std::shared_ptr<ChannelImpl> channel_;
};
LowerQueueUpEnd* link_queue_up_end_;
diff --git a/gd/l2cap/internal/reassembler_test.cc b/gd/l2cap/internal/reassembler_test.cc
index b3f5d9a..5db68e6 100644
--- a/gd/l2cap/internal/reassembler_test.cc
+++ b/gd/l2cap/internal/reassembler_test.cc
@@ -16,9 +16,11 @@
#include "l2cap/internal/reassembler.h"
+#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include <future>
+#include "l2cap/internal/channel_impl_mock.h"
#include "l2cap/l2cap_packets.h"
#include "os/handler.h"
#include "os/queue.h"
@@ -29,6 +31,9 @@
namespace l2cap {
namespace internal {
namespace {
+
+using ::testing::Return;
+
std::unique_ptr<BasicFrameBuilder> CreateSampleL2capPacket(Cid cid, std::vector<uint8_t> payload) {
auto raw_builder = std::make_unique<packet::RawBuilder>();
raw_builder->AddOctets(payload);
@@ -79,8 +84,13 @@
TEST_F(L2capClassicReassemblerTest, receive_basic_mode_packet_for_fixed_channel) {
common::BidiQueue<Reassembler::UpperEnqueue, Reassembler::UpperDequeue> channel_one_queue_{10};
common::BidiQueue<Reassembler::UpperEnqueue, Reassembler::UpperDequeue> channel_two_queue_{10};
- reassembler_->AttachChannel(1, channel_one_queue_.GetDownEnd(), nullptr);
- reassembler_->AttachChannel(2, channel_two_queue_.GetDownEnd(), nullptr);
+
+ auto mock_channel_1 = std::make_shared<testing::MockChannelImpl>();
+ ON_CALL(*mock_channel_1, GetQueueDownEnd()).WillByDefault(Return(channel_one_queue_.GetDownEnd()));
+ auto mock_channel_2 = std::make_shared<testing::MockChannelImpl>();
+ ON_CALL(*mock_channel_2, GetQueueDownEnd()).WillByDefault(Return(channel_two_queue_.GetDownEnd()));
+ reassembler_->AttachChannel(1, mock_channel_1);
+ reassembler_->AttachChannel(2, mock_channel_2);
os::EnqueueBuffer<Reassembler::UpperEnqueue> link_queue_enqueue_buffer{link_queue_.GetDownEnd()};
auto packet_one = CreateSampleL2capPacket(1, {1, 2, 3});
auto packet_two = CreateSampleL2capPacket(2, {4, 5, 6, 7});
diff --git a/gd/l2cap/internal/scheduler.h b/gd/l2cap/internal/scheduler.h
index ba4f384..65094c7 100644
--- a/gd/l2cap/internal/scheduler.h
+++ b/gd/l2cap/internal/scheduler.h
@@ -18,6 +18,7 @@
#include "common/bidi_queue.h"
#include "l2cap/cid.h"
+#include "l2cap/internal/channel_impl.h"
#include "l2cap/l2cap_packets.h"
#include "packet/base_packet_builder.h"
#include "packet/packet_view.h"
@@ -47,10 +48,10 @@
* Attach the channel with the specified ChannelQueueDownEnd into the scheduler.
*
* @param cid The channel to attach to the scheduler.
- * @param channel_down_end The ChannelQueueDownEnd associated with the channel to attach to the scheduler.
- * @param remote_cid The destination endpoint of the packet.
+ * @param channel The reference to a DynamicChannelImpl object. Use nullptr for fixed channel.
+ * TODO (b/144503952): Rethink about channel abstraction. Currently channel contains duplicated info as remote_cid
*/
- virtual void AttachChannel(Cid cid, UpperQueueDownEnd* channel_down_end, Cid remote_cid) {}
+ virtual void AttachChannel(Cid cid, std::shared_ptr<ChannelImpl> channel) {}
/**
* Detach the channel from the scheduler.
diff --git a/gd/l2cap/internal/scheduler_fifo.cc b/gd/l2cap/internal/scheduler_fifo.cc
index cc9cca7..c77e937 100644
--- a/gd/l2cap/internal/scheduler_fifo.cc
+++ b/gd/l2cap/internal/scheduler_fifo.cc
@@ -15,6 +15,8 @@
*/
#include "l2cap/internal/scheduler_fifo.h"
+
+#include "l2cap/classic/internal/dynamic_channel_impl.h"
#include "l2cap/l2cap_packets.h"
#include "os/log.h"
@@ -34,10 +36,10 @@
}
}
-void Fifo::AttachChannel(Cid cid, UpperQueueDownEnd* channel_down_end, Cid remote_cid) {
+void Fifo::AttachChannel(Cid cid, std::shared_ptr<ChannelImpl> channel) {
ASSERT(segmenter_map_.find(cid) == segmenter_map_.end());
segmenter_map_.emplace(std::piecewise_construct, std::forward_as_tuple(cid),
- std::forward_as_tuple(handler_, channel_down_end, this, cid, remote_cid));
+ std::forward_as_tuple(handler_, this, channel));
}
void Fifo::DetachChannel(Cid cid) {
diff --git a/gd/l2cap/internal/scheduler_fifo.h b/gd/l2cap/internal/scheduler_fifo.h
index b5264b6..a2921fa 100644
--- a/gd/l2cap/internal/scheduler_fifo.h
+++ b/gd/l2cap/internal/scheduler_fifo.h
@@ -22,6 +22,7 @@
#include "common/bidi_queue.h"
#include "common/bind.h"
#include "l2cap/cid.h"
+#include "l2cap/internal/channel_impl.h"
#include "l2cap/internal/scheduler.h"
#include "l2cap/internal/segmenter.h"
#include "os/handler.h"
@@ -29,13 +30,14 @@
namespace bluetooth {
namespace l2cap {
+
namespace internal {
class Fifo : public Scheduler {
public:
Fifo(LowerQueueUpEnd* link_queue_up_end, os::Handler* handler);
~Fifo() override;
- void AttachChannel(Cid cid, UpperQueueDownEnd* channel_down_end, Cid remote_cid) override;
+ void AttachChannel(Cid cid, std::shared_ptr<ChannelImpl> channel) override;
void DetachChannel(Cid cid) override;
void NotifyPacketsReady(Cid cid, int number_packets) override;
diff --git a/gd/l2cap/internal/scheduler_fifo_test.cc b/gd/l2cap/internal/scheduler_fifo_test.cc
index e6d4f78..3a53a36 100644
--- a/gd/l2cap/internal/scheduler_fifo_test.cc
+++ b/gd/l2cap/internal/scheduler_fifo_test.cc
@@ -16,9 +16,11 @@
#include "l2cap/internal/scheduler_fifo.h"
+#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include <future>
+#include "l2cap/internal/channel_impl_mock.h"
#include "os/handler.h"
#include "os/queue.h"
#include "os/thread.h"
@@ -29,11 +31,13 @@
namespace internal {
namespace {
+using ::testing::Return;
+
void sync_handler(os::Handler* handler) {
std::promise<void> promise;
auto future = promise.get_future();
handler->Post(common::BindOnce(&std::promise<void>::set_value, common::Unretained(&promise)));
- auto status = future.wait_for(std::chrono::milliseconds(3));
+ auto status = future.wait_for(std::chrono::milliseconds(300));
EXPECT_EQ(status, std::future_status::ready);
}
@@ -65,8 +69,21 @@
TEST_F(L2capSchedulerFifoTest, send_packet) {
common::BidiQueue<Scheduler::UpperEnqueue, Scheduler::UpperDequeue> channel_one_queue_{10};
common::BidiQueue<Scheduler::UpperEnqueue, Scheduler::UpperDequeue> channel_two_queue_{10};
- fifo_->AttachChannel(1, channel_one_queue_.GetDownEnd(), 1);
- fifo_->AttachChannel(2, channel_two_queue_.GetDownEnd(), 2);
+
+ auto mock_channel_1 = std::make_shared<testing::MockChannelImpl>();
+ EXPECT_CALL(*mock_channel_1, GetQueueDownEnd()).WillRepeatedly(Return(channel_one_queue_.GetDownEnd()));
+ EXPECT_CALL(*mock_channel_1, GetChannelMode())
+ .WillRepeatedly(Return(RetransmissionAndFlowControlModeOption::L2CAP_BASIC));
+ EXPECT_CALL(*mock_channel_1, GetCid()).WillRepeatedly(Return(1));
+ EXPECT_CALL(*mock_channel_1, GetRemoteCid()).WillRepeatedly(Return(1));
+ auto mock_channel_2 = std::make_shared<testing::MockChannelImpl>();
+ EXPECT_CALL(*mock_channel_2, GetQueueDownEnd()).WillRepeatedly(Return(channel_two_queue_.GetDownEnd()));
+ EXPECT_CALL(*mock_channel_2, GetChannelMode())
+ .WillRepeatedly(Return(RetransmissionAndFlowControlModeOption::L2CAP_BASIC));
+ EXPECT_CALL(*mock_channel_2, GetCid()).WillRepeatedly(Return(2));
+ EXPECT_CALL(*mock_channel_2, GetRemoteCid()).WillRepeatedly(Return(2));
+ fifo_->AttachChannel(1, mock_channel_1);
+ fifo_->AttachChannel(2, mock_channel_2);
os::EnqueueBuffer<Scheduler::UpperDequeue> channel_one_enqueue_buffer{channel_one_queue_.GetUpEnd()};
os::EnqueueBuffer<Scheduler::UpperDequeue> channel_two_enqueue_buffer{channel_two_queue_.GetUpEnd()};
auto packet_one = std::make_unique<packet::RawBuilder>();
diff --git a/gd/l2cap/internal/scheduler_mock.h b/gd/l2cap/internal/scheduler_mock.h
index be7dedb..82e35a3 100644
--- a/gd/l2cap/internal/scheduler_mock.h
+++ b/gd/l2cap/internal/scheduler_mock.h
@@ -15,6 +15,7 @@
*/
#pragma once
+#include "l2cap/internal/channel_impl.h"
#include "l2cap/internal/scheduler.h"
#include <gmock/gmock.h>
@@ -27,7 +28,7 @@
class MockScheduler : public Scheduler {
public:
- MOCK_METHOD(void, AttachChannel, (Cid cid, UpperQueueDownEnd* channel_down_end, Cid remote_cid), (override));
+ MOCK_METHOD(void, AttachChannel, (Cid cid, std::shared_ptr<l2cap::internal::ChannelImpl> channel), (override));
MOCK_METHOD(void, DetachChannel, (Cid cid), (override));
MOCK_METHOD(void, NotifyPacketsReady, (Cid cid, int number_packet), (override));
};
diff --git a/gd/l2cap/internal/segmenter.cc b/gd/l2cap/internal/segmenter.cc
index 3b658db..e1f4c10 100644
--- a/gd/l2cap/internal/segmenter.cc
+++ b/gd/l2cap/internal/segmenter.cc
@@ -19,6 +19,7 @@
#include "common/bind.h"
#include "l2cap/cid.h"
+#include "l2cap/classic/internal/dynamic_channel_impl.h"
#include "l2cap/internal/scheduler.h"
#include "l2cap/internal/segmenter.h"
#include "os/handler.h"
@@ -30,10 +31,9 @@
namespace l2cap {
namespace internal {
-Segmenter::Segmenter(os::Handler* handler, UpperQueueDownEnd* queue_end, Scheduler* scheduler, Cid channel_id,
- Cid remote_channel_id)
- : handler_(handler), queue_end_(queue_end), scheduler_(scheduler), channel_id_(channel_id),
- remote_channel_id_(remote_channel_id) {
+Segmenter::Segmenter(os::Handler* handler, Scheduler* scheduler, std::shared_ptr<ChannelImpl> channel)
+ : handler_(handler), queue_end_(channel->GetQueueDownEnd()), scheduler_(scheduler), channel_id_(channel->GetCid()),
+ remote_channel_id_(channel->GetRemoteCid()), channel_(channel) {
try_register_dequeue();
}
@@ -66,6 +66,16 @@
auto packet = queue_end_->TryDequeue();
ASSERT(packet != nullptr);
// TODO(hsz): Construct PDU(s) according to channel mode.
+ if (channel_ == nullptr || channel_->GetChannelMode() == RetransmissionAndFlowControlModeOption::L2CAP_BASIC) {
+ handle_basic_mode_sdu(std::move(packet));
+ }
+ if (channel_ != nullptr &&
+ channel_->GetChannelMode() == RetransmissionAndFlowControlModeOption::ENHANCED_RETRANSMISSION) {
+ handle_enhanced_retransmission_mode_sdu(std::move(packet));
+ }
+}
+
+void Segmenter::handle_basic_mode_sdu(std::unique_ptr<UpperDequeue> packet) {
auto pdu = BasicFrameBuilder::Create(remote_channel_id_, std::move(packet));
pdu_buffer_.emplace(std::move(pdu));
queue_end_->UnregisterDequeue();
@@ -73,6 +83,10 @@
scheduler_->NotifyPacketsReady(channel_id_, 1);
}
+void Segmenter::handle_enhanced_retransmission_mode_sdu(std::unique_ptr<UpperDequeue> packet) {
+ LOG_ERROR("Not implemented");
+}
+
} // namespace internal
} // namespace l2cap
} // namespace bluetooth
diff --git a/gd/l2cap/internal/segmenter.h b/gd/l2cap/internal/segmenter.h
index e04c49a..dd4a420 100644
--- a/gd/l2cap/internal/segmenter.h
+++ b/gd/l2cap/internal/segmenter.h
@@ -22,6 +22,7 @@
#include "common/bidi_queue.h"
#include "common/bind.h"
#include "l2cap/cid.h"
+#include "l2cap/internal/channel_impl.h"
#include "os/handler.h"
#include "os/queue.h"
#include "packet/base_packet_builder.h"
@@ -30,7 +31,6 @@
namespace bluetooth {
namespace l2cap {
namespace internal {
-
class Scheduler;
/**
@@ -43,7 +43,7 @@
using UpperDequeue = packet::BasePacketBuilder;
using UpperQueueDownEnd = common::BidiQueueEnd<UpperEnqueue, UpperDequeue>;
- Segmenter(os::Handler* handler, UpperQueueDownEnd* queue_end, Scheduler* scheduler, Cid cid, Cid remote_cid);
+ Segmenter(os::Handler* handler, Scheduler* scheduler, std::shared_ptr<ChannelImpl> channel);
~Segmenter();
/**
@@ -64,10 +64,13 @@
Scheduler* scheduler_;
const Cid channel_id_;
const Cid remote_channel_id_;
+ std::shared_ptr<ChannelImpl> channel_;
bool is_dequeue_registered_ = false;
void try_register_dequeue();
void dequeue_callback();
+ void handle_basic_mode_sdu(std::unique_ptr<UpperDequeue> packet);
+ void handle_enhanced_retransmission_mode_sdu(std::unique_ptr<UpperDequeue> packet);
};
} // namespace internal
} // namespace l2cap
diff --git a/gd/l2cap/internal/segmenter_test.cc b/gd/l2cap/internal/segmenter_test.cc
index bf12c60..a1c1b24 100644
--- a/gd/l2cap/internal/segmenter_test.cc
+++ b/gd/l2cap/internal/segmenter_test.cc
@@ -16,9 +16,11 @@
#include "l2cap/internal/segmenter.h"
+#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include <future>
+#include "l2cap/internal/channel_impl_mock.h"
#include "l2cap/internal/scheduler.h"
#include "os/handler.h"
#include "os/queue.h"
@@ -29,6 +31,9 @@
namespace l2cap {
namespace internal {
namespace {
+
+using ::testing::Return;
+
std::unique_ptr<packet::BasePacketBuilder> CreateSdu(std::vector<uint8_t> payload) {
auto raw_builder = std::make_unique<packet::RawBuilder>();
raw_builder->AddOctets(payload);
@@ -60,7 +65,13 @@
thread_ = new os::Thread("test_thread", os::Thread::Priority::NORMAL);
user_handler_ = new os::Handler(thread_);
queue_handler_ = new os::Handler(thread_);
- segmenter_ = new Segmenter(queue_handler_, channel_queue_.GetDownEnd(), &scheduler_, 0x41, 0x41);
+ mock_channel_ = std::make_shared<testing::MockChannelImpl>();
+ EXPECT_CALL(*mock_channel_, GetQueueDownEnd()).WillRepeatedly(Return(channel_queue_.GetDownEnd()));
+ EXPECT_CALL(*mock_channel_, GetChannelMode())
+ .WillRepeatedly(Return(RetransmissionAndFlowControlModeOption::L2CAP_BASIC));
+ EXPECT_CALL(*mock_channel_, GetCid()).WillRepeatedly(Return(0x41));
+ EXPECT_CALL(*mock_channel_, GetRemoteCid()).WillRepeatedly(Return(0x41));
+ segmenter_ = new Segmenter(queue_handler_, &scheduler_, mock_channel_);
}
void TearDown() override {
@@ -76,6 +87,7 @@
os::Handler* user_handler_ = nullptr;
os::Handler* queue_handler_ = nullptr;
common::BidiQueue<Segmenter::UpperEnqueue, Segmenter::UpperDequeue> channel_queue_{10};
+ std::shared_ptr<testing::MockChannelImpl> mock_channel_;
Segmenter* segmenter_ = nullptr;
FakeScheduler scheduler_;
};
diff --git a/gd/l2cap/le/internal/fixed_channel_impl.cc b/gd/l2cap/le/internal/fixed_channel_impl.cc
index 4833ae0..5f85139 100644
--- a/gd/l2cap/le/internal/fixed_channel_impl.cc
+++ b/gd/l2cap/le/internal/fixed_channel_impl.cc
@@ -99,6 +99,20 @@
link_->RefreshRefCount();
}
+Cid FixedChannelImpl::GetCid() const {
+ return cid_;
+}
+
+Cid FixedChannelImpl::GetRemoteCid() const {
+ return cid_;
+}
+
+RetransmissionAndFlowControlModeOption FixedChannelImpl::GetChannelMode() const {
+ return RetransmissionAndFlowControlModeOption::L2CAP_BASIC;
+}
+
+void FixedChannelImpl::SetChannelMode(RetransmissionAndFlowControlModeOption option) {}
+
} // namespace internal
} // namespace le
} // namespace l2cap
diff --git a/gd/l2cap/le/internal/fixed_channel_impl.h b/gd/l2cap/le/internal/fixed_channel_impl.h
index b75afb5..972640e 100644
--- a/gd/l2cap/le/internal/fixed_channel_impl.h
+++ b/gd/l2cap/le/internal/fixed_channel_impl.h
@@ -18,6 +18,7 @@
#include "common/bidi_queue.h"
#include "l2cap/cid.h"
+#include "l2cap/internal/channel_impl.h"
#include "l2cap/le/fixed_channel.h"
#include "os/handler.h"
#include "os/log.h"
@@ -29,7 +30,7 @@
class Link;
-class FixedChannelImpl {
+class FixedChannelImpl : public l2cap::internal::ChannelImpl {
public:
FixedChannelImpl(Cid cid, Link* link, os::Handler* l2cap_handler);
@@ -52,6 +53,11 @@
return acquired_;
}
+ Cid GetCid() const override;
+ Cid GetRemoteCid() const override;
+ RetransmissionAndFlowControlModeOption GetChannelMode() const override;
+ void SetChannelMode(RetransmissionAndFlowControlModeOption option) override;
+
virtual void OnClosed(hci::ErrorCode status);
virtual std::string ToString() {
diff --git a/gd/l2cap/le/internal/link.h b/gd/l2cap/le/internal/link.h
index 85f0280..5dc8ae4 100644
--- a/gd/l2cap/le/internal/link.h
+++ b/gd/l2cap/le/internal/link.h
@@ -69,7 +69,7 @@
virtual std::shared_ptr<FixedChannelImpl> AllocateFixedChannel(Cid cid, SecurityPolicy security_policy) {
auto channel = fixed_channel_allocator_.AllocateChannel(cid, security_policy);
- scheduler_->AttachChannel(cid, channel->GetQueueDownEnd(), cid);
+ scheduler_->AttachChannel(cid, channel);
return channel;
}
diff --git a/gd/neighbor/Android.bp b/gd/neighbor/Android.bp
index 0b8b4da..bd69a3e 100644
--- a/gd/neighbor/Android.bp
+++ b/gd/neighbor/Android.bp
@@ -4,6 +4,7 @@
"connectability.cc",
"discoverability.cc",
"inquiry.cc",
+ "name.cc",
"page.cc",
"scan.cc",
],
diff --git a/gd/neighbor/name.cc b/gd/neighbor/name.cc
new file mode 100644
index 0000000..34fa86b
--- /dev/null
+++ b/gd/neighbor/name.cc
@@ -0,0 +1,225 @@
+/*
+ * Copyright 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+#define LOG_TAG "bt_gd_neigh"
+
+#include "neighbor/name.h"
+
+#include <memory>
+#include <unordered_map>
+#include <utility>
+
+#include "common/bind.h"
+#include "hci/hci_layer.h"
+#include "hci/hci_packets.h"
+#include "module.h"
+#include "os/handler.h"
+#include "os/log.h"
+
+namespace bluetooth {
+namespace neighbor {
+
+struct ReadCallbackHandler {
+ ReadRemoteNameCallback callback;
+ os::Handler* handler;
+};
+
+struct CancelCallbackHandler {
+ CancelRemoteNameCallback callback;
+ os::Handler* handler;
+};
+
+constexpr std::array<uint8_t, 248> kEmptyName{};
+
+struct NameModule::impl {
+ void ReadRemoteNameRequest(hci::Address address, hci::PageScanRepetitionMode page_scan_repetition_mode,
+ uint16_t clock_offset, hci::ClockOffsetValid clock_offset_valid,
+ ReadRemoteNameCallback callback, os::Handler* handler);
+ void CancelRemoteNameRequest(hci::Address address, CancelRemoteNameCallback, os::Handler* handler);
+
+ void Start();
+ void Stop();
+
+ impl(const NameModule& name_module);
+
+ private:
+ const NameModule& module_;
+
+ void EnqueueCommandComplete(std::unique_ptr<hci::CommandPacketBuilder> command);
+ void EnqueueCommandStatus(std::unique_ptr<hci::CommandPacketBuilder> command);
+
+ void OnCommandComplete(hci::CommandCompleteView view);
+ void OnCommandStatus(hci::CommandStatusView status);
+ void OnEvent(hci::EventPacketView view);
+
+ std::unordered_map<hci::Address, std::unique_ptr<ReadCallbackHandler>> read_callback_handler_map_;
+ std::unordered_map<hci::Address, std::unique_ptr<CancelCallbackHandler>> cancel_callback_handler_map_;
+
+ hci::HciLayer* hci_layer_;
+ os::Handler* handler_;
+};
+
+const ModuleFactory neighbor::NameModule::Factory = ModuleFactory([]() { return new neighbor::NameModule(); });
+
+neighbor::NameModule::impl::impl(const neighbor::NameModule& module) : module_(module) {}
+
+void neighbor::NameModule::impl::EnqueueCommandComplete(std::unique_ptr<hci::CommandPacketBuilder> command) {
+ hci_layer_->EnqueueCommand(std::move(command), common::BindOnce(&impl::OnCommandComplete, common::Unretained(this)),
+ handler_);
+}
+
+void neighbor::NameModule::impl::EnqueueCommandStatus(std::unique_ptr<hci::CommandPacketBuilder> command) {
+ hci_layer_->EnqueueCommand(std::move(command), common::BindOnce(&impl::OnCommandStatus, common::Unretained(this)),
+ handler_);
+}
+
+void neighbor::NameModule::impl::OnCommandComplete(hci::CommandCompleteView view) {
+ switch (view.GetCommandOpCode()) {
+ case hci::OpCode::REMOTE_NAME_REQUEST_CANCEL: {
+ auto packet = hci::RemoteNameRequestCancelCompleteView::Create(view);
+ ASSERT(packet.IsValid());
+ ASSERT(packet.GetStatus() == hci::ErrorCode::SUCCESS);
+ hci::Address address = packet.GetBdAddr();
+ ASSERT(cancel_callback_handler_map_.find(address) != cancel_callback_handler_map_.end());
+ cancel_callback_handler_map_.erase(address);
+ } break;
+ default:
+ LOG_WARN("Unhandled command:%s", hci::OpCodeText(view.GetCommandOpCode()).c_str());
+ break;
+ }
+}
+
+void neighbor::NameModule::impl::OnCommandStatus(hci::CommandStatusView status) {
+ ASSERT(status.GetStatus() == hci::ErrorCode::SUCCESS);
+
+ switch (status.GetCommandOpCode()) {
+ case hci::OpCode::REMOTE_NAME_REQUEST: {
+ auto packet = hci::RemoteNameRequestStatusView::Create(status);
+ ASSERT(packet.IsValid());
+ } break;
+
+ default:
+ LOG_WARN("Unhandled command:%s", hci::OpCodeText(status.GetCommandOpCode()).c_str());
+ break;
+ }
+}
+
+void neighbor::NameModule::impl::OnEvent(hci::EventPacketView view) {
+ switch (view.GetEventCode()) {
+ case hci::EventCode::REMOTE_NAME_REQUEST_COMPLETE: {
+ auto packet = hci::RemoteNameRequestCompleteView::Create(view);
+ ASSERT(packet.IsValid());
+ hci::Address address = packet.GetBdAddr();
+ ASSERT(read_callback_handler_map_.find(address) != read_callback_handler_map_.end());
+ auto read_callback_handler = std::move(read_callback_handler_map_[address]);
+ read_callback_handler->handler->Post(common::BindOnce(std::move(read_callback_handler->callback),
+ packet.GetStatus(), address, packet.GetRemoteName()));
+ read_callback_handler_map_.erase(address);
+ } break;
+ default:
+ LOG_ERROR("Unhandled event:%s", hci::EventCodeText(view.GetEventCode()).c_str());
+ break;
+ }
+}
+
+void neighbor::NameModule::impl::Start() {
+ hci_layer_ = module_.GetDependency<hci::HciLayer>();
+ handler_ = module_.GetHandler();
+
+ hci_layer_->RegisterEventHandler(hci::EventCode::REMOTE_NAME_REQUEST_COMPLETE,
+ common::Bind(&NameModule::impl::OnEvent, common::Unretained(this)), handler_);
+}
+
+void neighbor::NameModule::impl::Stop() {
+ hci_layer_->UnregisterEventHandler(hci::EventCode::REMOTE_NAME_REQUEST_COMPLETE);
+}
+
+void neighbor::NameModule::impl::ReadRemoteNameRequest(hci::Address address,
+ hci::PageScanRepetitionMode page_scan_repetition_mode,
+ uint16_t clock_offset, hci::ClockOffsetValid clock_offset_valid,
+ ReadRemoteNameCallback callback, os::Handler* handler) {
+ LOG_DEBUG("%s Start read remote name request for %s", __func__, address.ToString().c_str());
+
+ if (read_callback_handler_map_.find(address) != read_callback_handler_map_.end()) {
+ LOG_WARN("Ignoring duplicate read remote name request to:%s", address.ToString().c_str());
+ handler->Post(common::BindOnce(std::move(callback), hci::ErrorCode::UNSPECIFIED_ERROR, address, kEmptyName));
+ return;
+ }
+ read_callback_handler_map_[address] = std::unique_ptr<ReadCallbackHandler>(new ReadCallbackHandler{
+ .callback = std::move(callback),
+ .handler = handler,
+ });
+
+ EnqueueCommandStatus(
+ hci::RemoteNameRequestBuilder::Create(address, page_scan_repetition_mode, clock_offset, clock_offset_valid));
+}
+
+void neighbor::NameModule::impl::CancelRemoteNameRequest(hci::Address address, CancelRemoteNameCallback callback,
+ os::Handler* handler) {
+ LOG_DEBUG("%s Cancel remote name request for %s", __func__, address.ToString().c_str());
+
+ if (cancel_callback_handler_map_.find(address) != cancel_callback_handler_map_.end()) {
+ LOG_WARN("Ignoring duplicate cancel remote name request to:%s", address.ToString().c_str());
+ handler->Post(common::BindOnce(std::move(callback), hci::ErrorCode::UNSPECIFIED_ERROR, address));
+ return;
+ }
+ cancel_callback_handler_map_[address] = std::unique_ptr<CancelCallbackHandler>(new CancelCallbackHandler{
+ .callback = std::move(callback),
+ .handler = handler,
+ });
+ EnqueueCommandComplete(hci::RemoteNameRequestCancelBuilder::Create(address));
+}
+
+/**
+ * General API here
+ */
+neighbor::NameModule::NameModule() : pimpl_(std::make_unique<impl>(*this)) {}
+
+neighbor::NameModule::~NameModule() {
+ pimpl_.reset();
+}
+
+void neighbor::NameModule::ReadRemoteNameRequest(hci::Address address,
+ hci::PageScanRepetitionMode page_scan_repetition_mode,
+ uint16_t clock_offset, hci::ClockOffsetValid clock_offset_valid,
+ ReadRemoteNameCallback callback, os::Handler* handler) {
+ GetHandler()->Post(common::BindOnce(&NameModule::impl::ReadRemoteNameRequest, common::Unretained(pimpl_.get()),
+ address, page_scan_repetition_mode, clock_offset, clock_offset_valid,
+ std::move(callback), handler));
+}
+
+void neighbor::NameModule::CancelRemoteNameRequest(hci::Address address, CancelRemoteNameCallback callback,
+ os::Handler* handler) {
+ GetHandler()->Post(common::BindOnce(&NameModule::impl::CancelRemoteNameRequest, common::Unretained(pimpl_.get()),
+ address, std::move(callback), handler));
+}
+
+/**
+ * Module methods here
+ */
+void neighbor::NameModule::ListDependencies(ModuleList* list) {
+ list->add<hci::HciLayer>();
+}
+
+void neighbor::NameModule::Start() {
+ pimpl_->Start();
+}
+
+void neighbor::NameModule::Stop() {
+ pimpl_->Stop();
+}
+
+} // namespace neighbor
+} // namespace bluetooth
diff --git a/gd/neighbor/name.h b/gd/neighbor/name.h
new file mode 100644
index 0000000..291e1de
--- /dev/null
+++ b/gd/neighbor/name.h
@@ -0,0 +1,59 @@
+/*
+ * Copyright 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+#pragma once
+
+#include <array>
+#include <cstdint>
+#include <memory>
+
+#include "common/bind.h"
+#include "hci/address.h"
+#include "hci/hci_packets.h"
+#include "module.h"
+
+namespace bluetooth {
+namespace neighbor {
+
+using ReadRemoteNameCallback =
+ common::OnceCallback<void(hci::ErrorCode status, hci::Address address, std::array<uint8_t, 248> name)>;
+using CancelRemoteNameCallback = common::OnceCallback<void(hci::ErrorCode status, hci::Address address)>;
+
+class NameModule : public bluetooth::Module {
+ public:
+ void ReadRemoteNameRequest(hci::Address address, hci::PageScanRepetitionMode page_scan_repetition_mode,
+ uint16_t clock_offset, hci::ClockOffsetValid clock_offset_valid,
+ ReadRemoteNameCallback on_read_name, os::Handler* handler);
+ void CancelRemoteNameRequest(hci::Address address, CancelRemoteNameCallback on_cancel, os::Handler* handler);
+
+ static const ModuleFactory Factory;
+
+ NameModule();
+ ~NameModule();
+
+ protected:
+ void ListDependencies(ModuleList* list) override;
+ void Start() override;
+ void Stop() override;
+
+ private:
+ struct impl;
+ std::unique_ptr<impl> pimpl_;
+
+ DISALLOW_COPY_AND_ASSIGN(NameModule);
+};
+
+} // namespace neighbor
+} // namespace bluetooth
diff --git a/gd/os/linux_generic/reactive_semaphore.cc b/gd/os/linux_generic/reactive_semaphore.cc
index 4cc0b4c..df0050a 100644
--- a/gd/os/linux_generic/reactive_semaphore.cc
+++ b/gd/os/linux_generic/reactive_semaphore.cc
@@ -16,6 +16,7 @@
#include "reactive_semaphore.h"
+#include <error.h>
#include <sys/eventfd.h>
#include <unistd.h>
#include <functional>
@@ -33,19 +34,19 @@
ReactiveSemaphore::~ReactiveSemaphore() {
int close_status;
RUN_NO_INTR(close_status = close(fd_));
- ASSERT(close_status != -1);
+ ASSERT_LOG(close_status != -1, "close failed: %s", strerror(errno));
}
void ReactiveSemaphore::Decrease() {
uint64_t val = 0;
auto read_result = eventfd_read(fd_, &val);
- ASSERT(read_result != -1);
+ ASSERT_LOG(read_result != -1, "decrease failed: %s", strerror(errno));
}
void ReactiveSemaphore::Increase() {
uint64_t val = 1;
auto write_result = eventfd_write(fd_, val);
- ASSERT(write_result != -1);
+ ASSERT_LOG(write_result != -1, "increase failed: %s", strerror(errno));
}
int ReactiveSemaphore::GetFd() {
diff --git a/gd/shim/Android.bp b/gd/shim/Android.bp
index 4ef329d..33c9b65 100644
--- a/gd/shim/Android.bp
+++ b/gd/shim/Android.bp
@@ -1,13 +1,16 @@
filegroup {
name: "BluetoothShimSources",
srcs: [
+ "advertising.cc",
"controller.cc",
"connectability.cc",
"discoverability.cc",
"hci_layer.cc",
"inquiry.cc",
"l2cap.cc",
+ "name.cc",
"page.cc",
+ "scanning.cc",
"stack.cc",
],
}
diff --git a/gd/shim/advertising.cc b/gd/shim/advertising.cc
new file mode 100644
index 0000000..b7e0b4e
--- /dev/null
+++ b/gd/shim/advertising.cc
@@ -0,0 +1,61 @@
+/*
+ * Copyright 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+#define LOG_TAG "bt_gd_shim"
+
+#include <functional>
+#include <memory>
+
+#include "hci/address.h"
+#include "hci/hci_packets.h"
+#include "hci/le_advertising_manager.h"
+#include "module.h"
+#include "os/handler.h"
+#include "os/log.h"
+#include "shim/advertising.h"
+
+namespace bluetooth {
+namespace shim {
+
+struct Advertising::impl {
+ hci::LeAdvertisingManager* module_{nullptr};
+
+ impl(hci::LeAdvertisingManager* module);
+ ~impl();
+};
+
+const ModuleFactory Advertising::Factory = ModuleFactory([]() { return new Advertising(); });
+
+Advertising::impl::impl(hci::LeAdvertisingManager* advertising_manager) : module_(advertising_manager) {}
+
+Advertising::impl::~impl() {}
+
+/**
+ * Module methods
+ */
+void Advertising::ListDependencies(ModuleList* list) {
+ list->add<hci::LeAdvertisingManager>();
+}
+
+void Advertising::Start() {
+ pimpl_ = std::make_unique<impl>(GetDependency<hci::LeAdvertisingManager>());
+}
+
+void Advertising::Stop() {
+ pimpl_.reset();
+}
+
+} // namespace shim
+} // namespace bluetooth
diff --git a/gd/shim/advertising.h b/gd/shim/advertising.h
new file mode 100644
index 0000000..17c094a
--- /dev/null
+++ b/gd/shim/advertising.h
@@ -0,0 +1,46 @@
+/*
+ * Copyright 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+#pragma once
+
+#include <memory>
+#include <string>
+
+#include "module.h"
+#include "shim/iadvertising.h"
+
+namespace bluetooth {
+namespace shim {
+
+class Advertising : public bluetooth::Module, public bluetooth::shim::IAdvertising {
+ public:
+ Advertising() = default;
+ ~Advertising() = default;
+
+ static const ModuleFactory Factory;
+
+ protected:
+ void ListDependencies(ModuleList* list) override; // Module
+ void Start() override; // Module
+ void Stop() override; // Module
+
+ private:
+ struct impl;
+ std::unique_ptr<impl> pimpl_;
+ DISALLOW_COPY_AND_ASSIGN(Advertising);
+};
+
+} // namespace shim
+} // namespace bluetooth
diff --git a/gd/shim/iadvertising.h b/gd/shim/iadvertising.h
new file mode 100644
index 0000000..85a75c6
--- /dev/null
+++ b/gd/shim/iadvertising.h
@@ -0,0 +1,29 @@
+/*
+ * Copyright 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+#pragma once
+
+/**
+ * The gd API exported to the legacy api
+ */
+namespace bluetooth {
+namespace shim {
+
+struct IAdvertising {
+ virtual ~IAdvertising() {}
+};
+
+} // namespace shim
+} // namespace bluetooth
diff --git a/gd/shim/il2cap.h b/gd/shim/il2cap.h
index c4e7463..994953e 100644
--- a/gd/shim/il2cap.h
+++ b/gd/shim/il2cap.h
@@ -28,25 +28,25 @@
namespace shim {
using ConnectionClosedCallback = std::function<void(uint16_t cid, int error_code)>;
-using Postable = std::function<void(std::function<void(uint16_t cid)>)>;
-using ConnectionOpenCallback = std::function<void(uint16_t psm, uint16_t cid, Postable postable)>;
+using ConnectionOpenCallback = std::function<void(std::string string_address, uint16_t psm, uint16_t cid)>;
using ReadDataReadyCallback = std::function<void(uint16_t cid, std::vector<const uint8_t> data)>;
struct IL2cap {
virtual void RegisterService(uint16_t psm, ConnectionOpenCallback on_open, std::promise<void> completed) = 0;
virtual void UnregisterService(uint16_t psm) = 0;
- virtual void CreateConnection(uint16_t psm, const std::string address, std::promise<uint16_t> completed) = 0;
+ virtual void CreateConnection(uint16_t psm, const std::string address, ConnectionOpenCallback on_open,
+ std::promise<uint16_t> completed) = 0;
virtual void CloseConnection(uint16_t cid) = 0;
virtual void SetReadDataReadyCallback(uint16_t cid, ReadDataReadyCallback on_data_ready) = 0;
virtual void SetConnectionClosedCallback(uint16_t cid, ConnectionClosedCallback on_closed) = 0;
- virtual bool Write(uint16_t cid, const uint8_t* data, size_t len) = 0;
- virtual bool WriteFlushable(uint16_t cid, const uint8_t* data, size_t len) = 0;
- virtual bool WriteNonFlushable(uint16_t cid, const uint8_t* data, size_t len) = 0;
+ virtual void Write(uint16_t cid, const uint8_t* data, size_t len) = 0;
+ virtual void WriteFlushable(uint16_t cid, const uint8_t* data, size_t len) = 0;
+ virtual void WriteNonFlushable(uint16_t cid, const uint8_t* data, size_t len) = 0;
- virtual bool IsCongested(uint16_t cid) = 0;
+ virtual void SendLoopbackResponse(std::function<void()>) = 0;
virtual ~IL2cap() {}
};
diff --git a/gd/shim/iname.h b/gd/shim/iname.h
new file mode 100644
index 0000000..c99ba37
--- /dev/null
+++ b/gd/shim/iname.h
@@ -0,0 +1,40 @@
+/*
+ * Copyright 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+#pragma once
+
+#include <cstdint>
+#include <functional>
+#include <string>
+
+/**
+ * The gd API exported to the legacy api
+ */
+using ReadRemoteNameCallback =
+ std::function<void(std::string address_string, uint8_t hci_status, std::array<uint8_t, 248> remote_name)>;
+using CancelRemoteNameCallback = std::function<void(std::string address_string, uint8_t hci_status)>;
+
+namespace bluetooth {
+namespace shim {
+
+struct IName {
+ virtual void ReadRemoteNameRequest(std::string remote_address, ReadRemoteNameCallback callback) = 0;
+ virtual void CancelRemoteNameRequest(std::string remote_address, CancelRemoteNameCallback callback) = 0;
+
+ virtual ~IName() {}
+};
+
+} // namespace shim
+} // namespace bluetooth
diff --git a/gd/shim/iscanning.h b/gd/shim/iscanning.h
new file mode 100644
index 0000000..ddaabb6
--- /dev/null
+++ b/gd/shim/iscanning.h
@@ -0,0 +1,29 @@
+/*
+ * Copyright 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+#pragma once
+
+/**
+ * The gd API exported to the legacy api
+ */
+namespace bluetooth {
+namespace shim {
+
+struct IScanning {
+ virtual ~IScanning() {}
+};
+
+} // namespace shim
+} // namespace bluetooth
diff --git a/gd/shim/istack.h b/gd/shim/istack.h
index af2b62d..f432dac 100644
--- a/gd/shim/istack.h
+++ b/gd/shim/istack.h
@@ -23,25 +23,31 @@
namespace bluetooth {
namespace shim {
+struct IAdvertising;
struct IController;
struct IConnectability;
struct IDiscoverability;
struct IHciLayer;
struct IInquiry;
+struct IName;
struct IL2cap;
struct IPage;
+struct IScanning;
struct IStack {
virtual void Start() = 0;
virtual void Stop() = 0;
+ virtual IAdvertising* GetAdvertising() = 0;
virtual IController* GetController() = 0;
virtual IConnectability* GetConnectability() = 0;
virtual IDiscoverability* GetDiscoverability() = 0;
virtual IHciLayer* GetHciLayer() = 0;
virtual IInquiry* GetInquiry() = 0;
+ virtual IName* GetName() = 0;
virtual IL2cap* GetL2cap() = 0;
virtual IPage* GetPage() = 0;
+ virtual IScanning* GetScanning() = 0;
virtual ~IStack() {}
};
diff --git a/gd/shim/l2cap.cc b/gd/shim/l2cap.cc
index 118b1cf..6177272 100644
--- a/gd/shim/l2cap.cc
+++ b/gd/shim/l2cap.cc
@@ -163,28 +163,46 @@
bool Write(ConnectionInterfaceDescriptor cid, std::unique_ptr<packet::RawBuilder> packet);
- void SetHandler(os::Handler* handler) {
- handler_ = handler;
- }
-
size_t NumberOfActiveConnections() const {
return cid_to_interface_map_.size();
}
- ConnectionInterfaceManager();
+ void GeneralCallback(ConnectionOpenCallback on_open, hci::Address address, l2cap::Psm psm,
+ ConnectionInterfaceDescriptor cid) {
+ on_open(address.ToString(), static_cast<uint16_t>(psm), static_cast<uint16_t>(cid));
+ }
+
+ void ConnectionOpened(ConnectionOpenCallback on_open, hci::Address address, l2cap::Psm psm,
+ ConnectionInterfaceDescriptor cid) {
+ LOG_DEBUG("%s address:%s psm:%hd cid:%hd", __func__, address.ToString().c_str(), psm, cid);
+ handler_->Post(common::BindOnce(&ConnectionInterfaceManager::GeneralCallback, common::Unretained(this), on_open,
+ address, psm, cid));
+ // TODO(cmanton) queue this pending connection address/psm tuple up for deletion
+ // There may be multiple, so only remove one
+ }
+
+ void ConnectionFailed(hci::Address address, l2cap::Psm psm) {
+ LOG_DEBUG("%s Connection Failed", __func__);
+ // TODO(cmanton) queue this pending connection address/psm tuple up for deletion
+ // There may be multiple, so only remove one
+ }
+
+ ConnectionInterfaceManager(os::Handler* handler);
private:
- std::unordered_map<ConnectionInterfaceDescriptor, std::unique_ptr<ConnectionInterface>> cid_to_interface_map_;
- ConnectionInterfaceDescriptor current_connection_interface_descriptor_;
os::Handler* handler_;
+ ConnectionInterfaceDescriptor current_connection_interface_descriptor_;
bool HasResources() const;
bool Exists(ConnectionInterfaceDescriptor id) const;
+
+ std::unordered_map<ConnectionInterfaceDescriptor, std::unique_ptr<ConnectionInterface>> cid_to_interface_map_;
ConnectionInterfaceDescriptor AllocateConnectionInterfaceDescriptor();
+ ConnectionInterfaceManager() = delete;
};
-ConnectionInterfaceManager::ConnectionInterfaceManager()
- : current_connection_interface_descriptor_(kStartConnectionInterfaceDescriptor) {}
+ConnectionInterfaceManager::ConnectionInterfaceManager(os::Handler* handler)
+ : handler_(handler), current_connection_interface_descriptor_(kStartConnectionInterfaceDescriptor) {}
bool ConnectionInterfaceManager::Exists(ConnectionInterfaceDescriptor cid) const {
return cid_to_interface_map_.find(cid) != cid_to_interface_map_.end();
@@ -242,11 +260,58 @@
return true;
}
+class PendingConnection {
+ public:
+ PendingConnection(ConnectionInterfaceManager* connection_interface_manager, l2cap::Psm psm, hci::Address address,
+ ConnectionOpenCallback on_open, std::promise<uint16_t> completed)
+ : connection_interface_manager_(connection_interface_manager), psm_(psm), address_(address),
+ on_open_(std::move(on_open)), completed_(std::move(completed)) {}
+
+ void OnConnectionOpen(std::unique_ptr<l2cap::classic::DynamicChannel> channel) {
+ LOG_DEBUG("Local initiated connection is open to device:%s for psm:%hd", address_.ToString().c_str(), psm_);
+ ConnectionInterfaceDescriptor cid = connection_interface_manager_->AddChannel(std::move(channel));
+ completed_.set_value(cid);
+ // Attempt to avoid async race condition with upper stack
+ std::this_thread::yield();
+ connection_interface_manager_->ConnectionOpened(std::move(on_open_), address_, psm_, cid);
+ }
+
+ void OnConnectionFailure(l2cap::classic::DynamicChannelManager::ConnectionResult result) {
+ LOG_DEBUG("Connection failed to device:%s for psm:%hd", address_.ToString().c_str(), psm_);
+ switch (result.connection_result_code) {
+ case l2cap::classic::DynamicChannelManager::ConnectionResultCode::SUCCESS:
+ LOG_WARN("Connection failed result:success hci:%s", hci::ErrorCodeText(result.hci_error).c_str());
+ break;
+ case l2cap::classic::DynamicChannelManager::ConnectionResultCode::FAIL_NO_SERVICE_REGISTERED:
+ LOG_DEBUG("Connection failed result:no service registered hci:%s",
+ hci::ErrorCodeText(result.hci_error).c_str());
+ break;
+ case l2cap::classic::DynamicChannelManager::ConnectionResultCode::FAIL_HCI_ERROR:
+ LOG_DEBUG("Connection failed result:hci error hci:%s", hci::ErrorCodeText(result.hci_error).c_str());
+ break;
+ case l2cap::classic::DynamicChannelManager::ConnectionResultCode::FAIL_L2CAP_ERROR:
+ LOG_DEBUG("Connection failed result:l2cap error hci:%s l2cap:%s", hci::ErrorCodeText(result.hci_error).c_str(),
+ l2cap::ConnectionResponseResultText(result.l2cap_connection_response_result).c_str());
+ break;
+ }
+ completed_.set_value(kInvalidConnectionInterfaceDescriptor);
+ connection_interface_manager_->ConnectionFailed(address_, psm_);
+ }
+
+ private:
+ ConnectionInterfaceManager* connection_interface_manager_;
+ const l2cap::Psm psm_;
+ const hci::Address address_;
+ ConnectionOpenCallback on_open_;
+ std::promise<uint16_t> completed_;
+};
+
class ServiceInterface {
public:
- ServiceInterface(uint16_t psm, ServiceInterfaceCallback register_callback,
- ConnectionInterfaceCallback connection_callback)
- : psm_(psm), register_callback_(register_callback), connection_callback_(connection_callback) {}
+ ServiceInterface(ConnectionInterfaceManager* connection_interface_manager, l2cap::Psm psm,
+ ConnectionOpenCallback on_open, std::promise<void> completed)
+ : connection_interface_manager_(connection_interface_manager), psm_(psm), on_open_(on_open),
+ completed_(std::move(completed)) {}
void OnRegistrationComplete(l2cap::classic::DynamicChannelManager::RegistrationResult result,
std::unique_ptr<l2cap::classic::DynamicChannelService> service) {
@@ -254,12 +319,15 @@
ASSERT(psm_ == service->GetPsm());
LOG_DEBUG("Registration is complete for psm:%hd", psm_);
service_ = std::move(service);
- register_callback_(psm_, result);
+ completed_.set_value();
}
void OnConnectionOpen(std::unique_ptr<l2cap::classic::DynamicChannel> channel) {
- LOG_DEBUG("Connection is open to device:%s for psm:%hd", channel->GetDevice().ToString().c_str(), psm_);
- connection_callback_(psm_, std::move(channel));
+ LOG_DEBUG("Remote initiated connection is open from device:%s for psm:%hd", channel->GetDevice().ToString().c_str(),
+ psm_);
+ hci::Address address = channel->GetDevice();
+ ConnectionInterfaceDescriptor cid = connection_interface_manager_->AddChannel(std::move(channel));
+ connection_interface_manager_->ConnectionOpened(on_open_, address, psm_, cid);
}
l2cap::SecurityPolicy GetSecurityPolicy() const {
@@ -276,133 +344,59 @@
}
private:
+ ConnectionInterfaceManager* connection_interface_manager_;
const l2cap::Psm psm_;
+ ConnectionOpenCallback on_open_;
+ std::promise<void> completed_;
+
std::unique_ptr<l2cap::classic::DynamicChannelService> service_;
+
const l2cap::SecurityPolicy security_policy_;
- ServiceInterfaceCallback register_callback_;
- ConnectionInterfaceCallback connection_callback_;
};
struct L2cap::impl {
void RegisterService(l2cap::Psm psm, ConnectionOpenCallback on_open, std::promise<void> completed);
void UnregisterService(l2cap::Psm psm);
- void CreateConnection(l2cap::Psm psm, hci::Address address, std::promise<uint16_t> completed);
+ void CreateConnection(l2cap::Psm psm, hci::Address address, ConnectionOpenCallback on_open,
+ std::promise<uint16_t> completed);
void CloseConnection(ConnectionInterfaceDescriptor cid);
- void OnConnectionOpenNever(std::unique_ptr<l2cap::classic::DynamicChannel> channel);
- void OnConnectionFailureNever(l2cap::classic::DynamicChannelManager::ConnectionResult result);
+ void SetReadDataReadyCallback(ConnectionInterfaceDescriptor cid, ReadDataReadyCallback on_data_ready);
+ void SetConnectionClosedCallback(ConnectionInterfaceDescriptor cid, ConnectionClosedCallback on_closed);
- bool Write(ConnectionInterfaceDescriptor cid, std::unique_ptr<packet::RawBuilder> packet);
+ void Write(ConnectionInterfaceDescriptor cid, std::unique_ptr<packet::RawBuilder> packet);
+
+ void SendLoopbackResponse(std::function<void()> function);
impl(L2cap& module, l2cap::classic::L2capClassicModule* l2cap_module);
- ConnectionInterfaceManager connection_interface_manager_;
-
- void OpenConnection(l2cap::Psm psm, ConnectionInterfaceDescriptor cid);
private:
L2cap& module_;
- l2cap::classic::L2capClassicModule* l2cap_module_{nullptr};
+ l2cap::classic::L2capClassicModule* l2cap_module_;
+ os::Handler* handler_;
+ ConnectionInterfaceManager connection_interface_manager_;
+
std::unique_ptr<l2cap::classic::DynamicChannelManager> dynamic_channel_manager_;
std::unordered_map<l2cap::Psm, std::shared_ptr<ServiceInterface>> psm_to_service_interface_map_;
- std::unordered_map<l2cap::Psm, ConnectionOpenCallback> psm_to_on_open_map_;
-
- std::mutex mutex_;
- std::unordered_map<l2cap::Psm, std::promise<void>> psm_to_register_complete_map_;
- std::unordered_map<l2cap::Psm, std::queue<std::promise<uint16_t>>> psm_to_connect_completed_queue_;
-
- os::Handler* handler_;
+ std::unordered_map<l2cap::Psm, std::shared_ptr<PendingConnection>> psm_to_pending_connection_map_;
};
L2cap::impl::impl(L2cap& module, l2cap::classic::L2capClassicModule* l2cap_module)
- : module_(module), l2cap_module_(l2cap_module) {
- handler_ = module_.GetHandler();
+ : module_(module), l2cap_module_(l2cap_module), handler_(module_.GetHandler()),
+ connection_interface_manager_(handler_) {
dynamic_channel_manager_ = l2cap_module_->GetDynamicChannelManager();
- connection_interface_manager_.SetHandler(handler_);
-}
-
-void L2cap::impl::OnConnectionOpenNever(std::unique_ptr<l2cap::classic::DynamicChannel> channel) {
- ASSERT(false);
-}
-
-void L2cap::impl::OnConnectionFailureNever(l2cap::classic::DynamicChannelManager::ConnectionResult result) {
- ASSERT(false);
- switch (result.connection_result_code) {
- case l2cap::classic::DynamicChannelManager::ConnectionResultCode::SUCCESS:
- LOG_WARN("Connection failed result:success hci:%s", hci::ErrorCodeText(result.hci_error).c_str());
- break;
- case l2cap::classic::DynamicChannelManager::ConnectionResultCode::FAIL_NO_SERVICE_REGISTERED:
- LOG_DEBUG("Connection failed result:no service registered hci:%s", hci::ErrorCodeText(result.hci_error).c_str());
- break;
- case l2cap::classic::DynamicChannelManager::ConnectionResultCode::FAIL_HCI_ERROR:
- LOG_DEBUG("Connection failed result:hci error hci:%s", hci::ErrorCodeText(result.hci_error).c_str());
- break;
- case l2cap::classic::DynamicChannelManager::ConnectionResultCode::FAIL_L2CAP_ERROR:
- LOG_DEBUG("Connection failed result:l2cap error hci:%s l2cap:%s", hci::ErrorCodeText(result.hci_error).c_str(),
- l2cap::ConnectionResponseResultText(result.l2cap_connection_response_result).c_str());
- break;
- }
-}
-
-void L2cap::impl::OpenConnection(l2cap::Psm psm, ConnectionInterfaceDescriptor cid) {
- LOG_INFO("About to call back to client indicating open connection psm:%hd cid:%hd", psm, cid);
- psm_to_on_open_map_[psm](psm, cid, [cid](std::function<void(uint16_t cid)> func) {
- LOG_DEBUG("About to run postable on this thread and inform sdp that connection is open");
- func(cid);
- });
}
void L2cap::impl::RegisterService(l2cap::Psm psm, ConnectionOpenCallback on_open, std::promise<void> completed) {
ASSERT(psm_to_service_interface_map_.find(psm) == psm_to_service_interface_map_.end());
- ASSERT(psm_to_register_complete_map_.find(psm) == psm_to_register_complete_map_.end());
- ASSERT(psm_to_on_open_map_.find(psm) == psm_to_on_open_map_.end());
- {
- std::unique_lock<std::mutex> lock(mutex_);
- psm_to_on_open_map_[psm] = on_open;
- psm_to_register_complete_map_[psm] = std::move(completed);
- }
+ auto service_interface =
+ std::make_shared<ServiceInterface>(&connection_interface_manager_, psm, on_open, std::move(completed));
+ psm_to_service_interface_map_.emplace(psm, service_interface);
- psm_to_service_interface_map_.emplace(
- psm, std::make_shared<ServiceInterface>(
- psm,
- [this](l2cap::Psm psm, l2cap::classic::DynamicChannelManager::RegistrationResult result) {
- LOG_DEBUG("Service has been registered");
- ASSERT(psm_to_register_complete_map_.find(psm) != psm_to_register_complete_map_.end());
- {
- std::unique_lock<std::mutex> lock(mutex_);
- auto completed = std::move(psm_to_register_complete_map_[psm]);
- psm_to_register_complete_map_.erase(psm);
- completed.set_value();
- }
- },
-
- [this](l2cap::Psm psm, std::unique_ptr<l2cap::classic::DynamicChannel> channel) {
- ConnectionInterfaceDescriptor cid = connection_interface_manager_.AddChannel(std::move(channel));
- LOG_DEBUG("Connection has been opened cid:%hd psm:%hd", cid, psm);
- {
- // If initiated locally unblock requestor that
- // we now have a connection by providing the
- // cid.
- std::unique_lock<std::mutex> lock(mutex_);
- if (psm_to_connect_completed_queue_.find(psm) != psm_to_connect_completed_queue_.end()) {
- if (!psm_to_connect_completed_queue_[psm].empty()) {
- LOG_DEBUG("Locally initiated, so inform waiting client of the cid %hd", cid);
- auto completed = std::move(psm_to_connect_completed_queue_[psm].front());
- psm_to_connect_completed_queue_[psm].pop();
- completed.set_value(cid);
- }
- }
- std::this_thread::yield();
- }
- if (cid != kInvalidConnectionInterfaceDescriptor) {
- handler_->Post(common::BindOnce(&L2cap::impl::OpenConnection, common::Unretained(this), psm, cid));
- }
- usleep(10);
- }));
-
- psm_to_service_interface_map_.find(psm)->second->RegisterService(
+ service_interface->RegisterService(
[this](l2cap::Psm psm, l2cap::SecurityPolicy security_policy,
l2cap::classic::DynamicChannelManager::OnRegistrationCompleteCallback on_registration_complete,
l2cap::classic::DynamicChannelManager::OnConnectionOpenCallback on_connection_open) {
@@ -416,24 +410,40 @@
psm_to_service_interface_map_.erase(psm);
}
-void L2cap::impl::CreateConnection(l2cap::Psm psm, hci::Address address, std::promise<uint16_t> completed) {
- LOG_INFO("Creating connection to psm:%hd device:%s", psm, address.ToString().c_str());
- {
- std::unique_lock<std::mutex> lock(mutex_);
- psm_to_connect_completed_queue_[psm].push(std::move(completed));
- }
+void L2cap::impl::CreateConnection(l2cap::Psm psm, hci::Address address, ConnectionOpenCallback on_open,
+ std::promise<uint16_t> completed) {
+ LOG_DEBUG("Initiating classic connection to psm:%hd device:%s", psm, address.ToString().c_str());
+ auto pending_connection = std::make_shared<PendingConnection>(&connection_interface_manager_, psm, address,
+ std::move(on_open), std::move(completed));
+ // TODO(cmanton) hash psm/address pair into unordered map for pending_connection
+ // This is ok for now
+ psm_to_pending_connection_map_[psm] = pending_connection;
+
bool rc = dynamic_channel_manager_->ConnectChannel(
- address, psm, common::Bind(&L2cap::impl::OnConnectionOpenNever, common::Unretained(this)),
- common::Bind(&L2cap::impl::OnConnectionFailureNever, common::Unretained(this)), handler_);
- ASSERT_LOG(rc == true, "Failed to create classic connection channel");
+ address, psm, common::Bind(&PendingConnection::OnConnectionOpen, common::Unretained(pending_connection.get())),
+ common::BindOnce(&PendingConnection::OnConnectionFailure, common::Unretained(pending_connection.get())),
+ handler_);
+ ASSERT_LOG(rc == true, "Failed to create classic connection");
}
void L2cap::impl::CloseConnection(ConnectionInterfaceDescriptor cid) {
connection_interface_manager_.RemoveConnection(cid);
}
-bool L2cap::impl::Write(ConnectionInterfaceDescriptor cid, std::unique_ptr<packet::RawBuilder> packet) {
- return connection_interface_manager_.Write(cid, std::move(packet));
+void L2cap::impl::SetReadDataReadyCallback(ConnectionInterfaceDescriptor cid, ReadDataReadyCallback on_data_ready) {
+ connection_interface_manager_.SetReadDataReadyCallback(cid, on_data_ready);
+}
+
+void L2cap::impl::SetConnectionClosedCallback(ConnectionInterfaceDescriptor cid, ConnectionClosedCallback on_closed) {
+ connection_interface_manager_.SetConnectionClosedCallback(cid, std::move(on_closed));
+}
+
+void L2cap::impl::Write(ConnectionInterfaceDescriptor cid, std::unique_ptr<packet::RawBuilder> packet) {
+ connection_interface_manager_.Write(cid, std::move(packet));
+}
+
+void L2cap::impl::SendLoopbackResponse(std::function<void()> function) {
+ function();
}
void L2cap::RegisterService(uint16_t raw_psm, ConnectionOpenCallback on_open, std::promise<void> completed) {
@@ -444,51 +454,54 @@
void L2cap::UnregisterService(uint16_t raw_psm) {
l2cap::Psm psm{raw_psm};
- pimpl_->UnregisterService(psm);
+ GetHandler()->Post(common::Bind(&L2cap::impl::UnregisterService, common::Unretained(pimpl_.get()), psm));
}
-void L2cap::CreateConnection(uint16_t raw_psm, const std::string address_string, std::promise<uint16_t> completed) {
+void L2cap::CreateConnection(uint16_t raw_psm, const std::string address_string, ConnectionOpenCallback on_open,
+ std::promise<uint16_t> completed) {
l2cap::Psm psm{raw_psm};
hci::Address address;
hci::Address::FromString(address_string, address);
GetHandler()->Post(common::BindOnce(&L2cap::impl::CreateConnection, common::Unretained(pimpl_.get()), psm, address,
- std::move(completed)));
+ on_open, std::move(completed)));
}
void L2cap::CloseConnection(uint16_t raw_cid) {
ConnectionInterfaceDescriptor cid(raw_cid);
- return pimpl_->CloseConnection(cid);
+ GetHandler()->Post(common::Bind(&L2cap::impl::CloseConnection, common::Unretained(pimpl_.get()), cid));
}
-void L2cap::SetReadDataReadyCallback(uint16_t cid, ReadDataReadyCallback on_data_ready) {
- pimpl_->connection_interface_manager_.SetReadDataReadyCallback(static_cast<ConnectionInterfaceDescriptor>(cid),
- on_data_ready);
+void L2cap::SetReadDataReadyCallback(uint16_t raw_cid, ReadDataReadyCallback on_data_ready) {
+ ConnectionInterfaceDescriptor cid(raw_cid);
+ GetHandler()->Post(
+ common::Bind(&L2cap::impl::SetReadDataReadyCallback, common::Unretained(pimpl_.get()), cid, on_data_ready));
}
-void L2cap::SetConnectionClosedCallback(uint16_t cid, ConnectionClosedCallback on_closed) {
- pimpl_->connection_interface_manager_.SetConnectionClosedCallback(static_cast<ConnectionInterfaceDescriptor>(cid),
- on_closed);
+void L2cap::SetConnectionClosedCallback(uint16_t raw_cid, ConnectionClosedCallback on_closed) {
+ ConnectionInterfaceDescriptor cid(raw_cid);
+ GetHandler()->Post(common::Bind(&L2cap::impl::SetConnectionClosedCallback, common::Unretained(pimpl_.get()), cid,
+ std::move(on_closed)));
}
-bool L2cap::Write(uint16_t cid, const uint8_t* data, size_t len) {
+void L2cap::Write(uint16_t raw_cid, const uint8_t* data, size_t len) {
+ ConnectionInterfaceDescriptor cid(raw_cid);
auto packet = MakeUniquePacket(data, len);
- return pimpl_->Write(static_cast<ConnectionInterfaceDescriptor>(cid), std::move(packet));
+ GetHandler()->Post(common::BindOnce(&L2cap::impl::Write, common::Unretained(pimpl_.get()), cid, std::move(packet)));
}
-bool L2cap::WriteFlushable(uint16_t cid, const uint8_t* data, size_t len) {
+void L2cap::WriteFlushable(uint16_t raw_cid, const uint8_t* data, size_t len) {
LOG_WARN("UNIMPLEMENTED Write flushable");
- return false;
+ return Write(raw_cid, data, len);
}
-bool L2cap::WriteNonFlushable(uint16_t cid, const uint8_t* data, size_t len) {
+void L2cap::WriteNonFlushable(uint16_t raw_cid, const uint8_t* data, size_t len) {
LOG_WARN("UNIMPLEMENTED Write non flushable");
- return false;
+ return Write(raw_cid, data, len);
}
-bool L2cap::IsCongested(ConnectionInterfaceDescriptor cid) {
- LOG_WARN("UNIMPLEMENTED Congestion check on channels or links");
- return false;
+void L2cap::SendLoopbackResponse(std::function<void()> function) {
+ GetHandler()->Post(common::BindOnce(&L2cap::impl::SendLoopbackResponse, common::Unretained(pimpl_.get()), function));
}
/**
diff --git a/gd/shim/l2cap.h b/gd/shim/l2cap.h
index 67a75d9..955d20c 100644
--- a/gd/shim/l2cap.h
+++ b/gd/shim/l2cap.h
@@ -32,17 +32,18 @@
void RegisterService(uint16_t psm, ConnectionOpenCallback on_open, std::promise<void> completed) override;
void UnregisterService(uint16_t psm) override;
- void CreateConnection(uint16_t psm, const std::string address, std::promise<uint16_t> completed) override;
+ void CreateConnection(uint16_t psm, const std::string address_string, ConnectionOpenCallback on_open,
+ std::promise<uint16_t> completed) override;
void CloseConnection(uint16_t cid) override;
void SetReadDataReadyCallback(uint16_t cid, ReadDataReadyCallback on_data_ready) override;
void SetConnectionClosedCallback(uint16_t cid, ConnectionClosedCallback on_closed) override;
- bool Write(uint16_t cid, const uint8_t* data, size_t len) override;
- bool WriteFlushable(uint16_t cid, const uint8_t* data, size_t len) override;
- bool WriteNonFlushable(uint16_t cid, const uint8_t* data, size_t len) override;
+ void Write(uint16_t cid, const uint8_t* data, size_t len) override;
+ void WriteFlushable(uint16_t cid, const uint8_t* data, size_t len) override;
+ void WriteNonFlushable(uint16_t cid, const uint8_t* data, size_t len) override;
- bool IsCongested(uint16_t cid) override;
+ void SendLoopbackResponse(std::function<void()>) override;
L2cap() = default;
~L2cap() = default;
diff --git a/gd/shim/name.cc b/gd/shim/name.cc
new file mode 100644
index 0000000..582d1ed
--- /dev/null
+++ b/gd/shim/name.cc
@@ -0,0 +1,125 @@
+/*
+ * Copyright 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+#define LOG_TAG "bt_gd_shim"
+
+#include <functional>
+#include <memory>
+#include <string>
+#include <unordered_map>
+
+#include "hci/address.h"
+#include "hci/hci_packets.h"
+#include "module.h"
+#include "neighbor/name.h"
+#include "os/handler.h"
+#include "os/log.h"
+#include "shim/name.h"
+
+namespace bluetooth {
+namespace shim {
+
+struct Name::impl {
+ void ReadRemoteNameRequest(const hci::Address address, hci::PageScanRepetitionMode page_scan_repetition_mode,
+ uint16_t clock_offset, hci::ClockOffsetValid clock_offset_valid,
+ ReadRemoteNameCallback callback);
+ void CancelRemoteNameRequest(const hci::Address address, CancelRemoteNameCallback callback);
+
+ void OnReadRemoteName(hci::ErrorCode status, hci::Address address, std::array<uint8_t, 248> name);
+ void OnCancelRemoteName(hci::ErrorCode status, hci::Address address);
+
+ impl(neighbor::NameModule* module, os::Handler* handler);
+ ~impl();
+
+ private:
+ std::unordered_map<hci::Address, ReadRemoteNameCallback> address_to_read_remote_callback_map_;
+ std::unordered_map<hci::Address, CancelRemoteNameCallback> address_to_cancel_remote_callback_map_;
+
+ neighbor::NameModule* module_{nullptr};
+ os::Handler* handler_;
+};
+
+const ModuleFactory Name::Factory = ModuleFactory([]() { return new Name(); });
+
+void Name::impl::OnReadRemoteName(hci::ErrorCode status, hci::Address address, std::array<uint8_t, 248> name) {
+ LOG_DEBUG("%s from %s", __func__, address.ToString().c_str());
+ ASSERT(address_to_read_remote_callback_map_.find(address) != address_to_read_remote_callback_map_.end());
+ ReadRemoteNameCallback callback = address_to_read_remote_callback_map_[address];
+ address_to_read_remote_callback_map_.erase(address);
+ callback(address.ToString(), static_cast<uint8_t>(status), name);
+}
+
+void Name::impl::OnCancelRemoteName(hci::ErrorCode status, hci::Address address) {
+ LOG_DEBUG("%s from %s", __func__, address.ToString().c_str());
+ ASSERT(address_to_cancel_remote_callback_map_.find(address) != address_to_cancel_remote_callback_map_.end());
+ CancelRemoteNameCallback callback = address_to_cancel_remote_callback_map_[address];
+ address_to_cancel_remote_callback_map_.erase(address);
+ callback(address.ToString(), static_cast<uint8_t>(status));
+}
+
+void Name::impl::ReadRemoteNameRequest(const hci::Address address,
+ hci::PageScanRepetitionMode page_scan_repetition_mode, uint16_t clock_offset,
+ hci::ClockOffsetValid clock_offset_valid, ReadRemoteNameCallback callback) {
+ ASSERT(address_to_read_remote_callback_map_.find(address) == address_to_read_remote_callback_map_.end());
+ address_to_read_remote_callback_map_[address] = callback;
+ module_->ReadRemoteNameRequest(address, page_scan_repetition_mode, clock_offset, clock_offset_valid,
+ common::BindOnce(&Name::impl::OnReadRemoteName, common::Unretained(this)), handler_);
+}
+
+void Name::impl::CancelRemoteNameRequest(const hci::Address address, CancelRemoteNameCallback callback) {
+ ASSERT(address_to_cancel_remote_callback_map_.find(address) == address_to_cancel_remote_callback_map_.end());
+ address_to_cancel_remote_callback_map_[address] = callback;
+ module_->CancelRemoteNameRequest(address, common::BindOnce(&Name::impl::OnCancelRemoteName, common::Unretained(this)),
+ handler_);
+}
+
+Name::impl::impl(neighbor::NameModule* module, os::Handler* handler) : module_(module), handler_(handler) {}
+
+Name::impl::~impl() {}
+
+void Name::ReadRemoteNameRequest(std::string remote_address, ReadRemoteNameCallback callback) {
+ hci::Address address;
+ hci::Address::FromString(remote_address, address);
+
+ // TODO(cmanton) Use remote name request defaults for now
+ hci::PageScanRepetitionMode page_scan_repetition_mode = hci::PageScanRepetitionMode::R1;
+ uint16_t clock_offset = 0;
+ hci::ClockOffsetValid clock_offset_valid = hci::ClockOffsetValid::INVALID;
+ pimpl_->ReadRemoteNameRequest(address, page_scan_repetition_mode, clock_offset, clock_offset_valid, callback);
+}
+
+void Name::CancelRemoteNameRequest(std::string remote_address, CancelRemoteNameCallback callback) {
+ hci::Address address;
+ hci::Address::FromString(remote_address, address);
+ pimpl_->CancelRemoteNameRequest(address, callback);
+}
+
+/**
+ * Module methods
+ */
+void Name::ListDependencies(ModuleList* list) {
+ list->add<neighbor::NameModule>();
+}
+
+void Name::Start() {
+ pimpl_ = std::make_unique<impl>(GetDependency<neighbor::NameModule>(), GetHandler());
+}
+
+void Name::Stop() {
+ pimpl_.reset();
+}
+
+} // namespace shim
+} // namespace bluetooth
diff --git a/gd/shim/name.h b/gd/shim/name.h
new file mode 100644
index 0000000..7d8233f
--- /dev/null
+++ b/gd/shim/name.h
@@ -0,0 +1,48 @@
+/*
+ * Copyright 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+#pragma once
+
+#include <memory>
+
+#include "module.h"
+#include "shim/iname.h"
+
+namespace bluetooth {
+namespace shim {
+
+class Name : public bluetooth::Module, public bluetooth::shim::IName {
+ public:
+ void ReadRemoteNameRequest(std::string remote_address, ReadRemoteNameCallback callback) override;
+ void CancelRemoteNameRequest(std::string remote_address, CancelRemoteNameCallback callback) override;
+
+ Name() = default;
+ ~Name() = default;
+
+ static const ModuleFactory Factory;
+
+ protected:
+ void ListDependencies(ModuleList* list) override; // Module
+ void Start() override; // Module
+ void Stop() override; // Module
+
+ private:
+ struct impl;
+ std::unique_ptr<impl> pimpl_;
+ DISALLOW_COPY_AND_ASSIGN(Name);
+};
+
+} // namespace shim
+} // namespace bluetooth
diff --git a/gd/shim/only_include_this_file_into_legacy_stack___ever.h b/gd/shim/only_include_this_file_into_legacy_stack___ever.h
index bce2a66..335778a 100644
--- a/gd/shim/only_include_this_file_into_legacy_stack___ever.h
+++ b/gd/shim/only_include_this_file_into_legacy_stack___ever.h
@@ -24,11 +24,14 @@
* Only common data structures should be used to pass data between the stacks.
*
*/
+#include "gd/shim/iadvertising.h"
#include "gd/shim/iconnectability.h"
#include "gd/shim/icontroller.h"
#include "gd/shim/idiscoverability.h"
#include "gd/shim/ihci_layer.h"
#include "gd/shim/iinquiry.h"
#include "gd/shim/il2cap.h"
+#include "gd/shim/iname.h"
#include "gd/shim/ipage.h"
+#include "gd/shim/iscanning.h"
#include "gd/shim/istack.h"
diff --git a/gd/shim/scanning.cc b/gd/shim/scanning.cc
new file mode 100644
index 0000000..5216937
--- /dev/null
+++ b/gd/shim/scanning.cc
@@ -0,0 +1,61 @@
+/*
+ * Copyright 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+#define LOG_TAG "bt_gd_shim"
+
+#include <functional>
+#include <memory>
+
+#include "hci/address.h"
+#include "hci/hci_packets.h"
+#include "hci/le_scanning_manager.h"
+#include "module.h"
+#include "os/handler.h"
+#include "os/log.h"
+#include "shim/scanning.h"
+
+namespace bluetooth {
+namespace shim {
+
+struct Scanning::impl {
+ hci::LeScanningManager* module_{nullptr};
+
+ impl(hci::LeScanningManager* module);
+ ~impl();
+};
+
+const ModuleFactory Scanning::Factory = ModuleFactory([]() { return new Scanning(); });
+
+Scanning::impl::impl(hci::LeScanningManager* scanning_manager) : module_(scanning_manager) {}
+
+Scanning::impl::~impl() {}
+
+/**
+ * Module methods
+ */
+void Scanning::ListDependencies(ModuleList* list) {
+ list->add<hci::LeScanningManager>();
+}
+
+void Scanning::Start() {
+ pimpl_ = std::make_unique<impl>(GetDependency<hci::LeScanningManager>());
+}
+
+void Scanning::Stop() {
+ pimpl_.reset();
+}
+
+} // namespace shim
+} // namespace bluetooth
diff --git a/gd/shim/scanning.h b/gd/shim/scanning.h
new file mode 100644
index 0000000..8768ead
--- /dev/null
+++ b/gd/shim/scanning.h
@@ -0,0 +1,46 @@
+/*
+ * Copyright 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+#pragma once
+
+#include <memory>
+#include <string>
+
+#include "module.h"
+#include "shim/iscanning.h"
+
+namespace bluetooth {
+namespace shim {
+
+class Scanning : public bluetooth::Module, public bluetooth::shim::IScanning {
+ public:
+ Scanning() = default;
+ ~Scanning() = default;
+
+ static const ModuleFactory Factory;
+
+ protected:
+ void ListDependencies(ModuleList* list) override; // Module
+ void Start() override; // Module
+ void Stop() override; // Module
+
+ private:
+ struct impl;
+ std::unique_ptr<impl> pimpl_;
+ DISALLOW_COPY_AND_ASSIGN(Scanning);
+};
+
+} // namespace shim
+} // namespace bluetooth
diff --git a/gd/shim/stack.cc b/gd/shim/stack.cc
index 8b02e6b..7822a35 100644
--- a/gd/shim/stack.cc
+++ b/gd/shim/stack.cc
@@ -20,23 +20,29 @@
#include "hal/hci_hal.h"
#include "hci/acl_manager.h"
#include "hci/classic_security_manager.h"
+#include "hci/le_advertising_manager.h"
+#include "hci/le_scanning_manager.h"
#include "l2cap/classic/l2cap_classic_module.h"
#include "l2cap/le/l2cap_le_module.h"
#include "neighbor/connectability.h"
#include "neighbor/discoverability.h"
#include "neighbor/inquiry.h"
+#include "neighbor/name.h"
#include "neighbor/page.h"
#include "neighbor/scan.h"
#include "os/log.h"
#include "os/thread.h"
#include "security/security_module.h"
+#include "shim/advertising.h"
#include "shim/connectability.h"
#include "shim/controller.h"
#include "shim/discoverability.h"
#include "shim/hci_layer.h"
#include "shim/inquiry.h"
#include "shim/l2cap.h"
+#include "shim/name.h"
#include "shim/page.h"
+#include "shim/scanning.h"
#include "stack_manager.h"
using ::bluetooth::os::Thread;
@@ -52,21 +58,27 @@
ModuleList modules;
modules.add<::bluetooth::hal::HciHal>();
modules.add<::bluetooth::hci::AclManager>();
+ modules.add<::bluetooth::hci::LeAdvertisingManager>();
+ modules.add<::bluetooth::hci::LeScanningManager>();
modules.add<::bluetooth::l2cap::classic::L2capClassicModule>();
modules.add<::bluetooth::l2cap::le::L2capLeModule>();
modules.add<::bluetooth::neighbor::ConnectabilityModule>();
modules.add<::bluetooth::neighbor::DiscoverabilityModule>();
modules.add<::bluetooth::neighbor::InquiryModule>();
+ modules.add<::bluetooth::neighbor::NameModule>();
modules.add<::bluetooth::neighbor::PageModule>();
modules.add<::bluetooth::neighbor::ScanModule>();
modules.add<::bluetooth::shim::Controller>();
modules.add<::bluetooth::shim::HciLayer>();
modules.add<::bluetooth::security::SecurityModule>();
+ modules.add<::bluetooth::shim::Advertising>();
modules.add<::bluetooth::shim::Connectability>();
modules.add<::bluetooth::shim::Discoverability>();
modules.add<::bluetooth::shim::Inquiry>();
+ modules.add<::bluetooth::shim::Name>();
modules.add<::bluetooth::shim::L2cap>();
modules.add<::bluetooth::shim::Page>();
+ modules.add<::bluetooth::shim::Scanning>();
stack_thread_ = new Thread("gd_stack_thread", Thread::Priority::NORMAL);
stack_manager_.StartUp(&modules, stack_thread_);
@@ -88,6 +100,10 @@
LOG_INFO("%s Successfully shut down Gd stack", __func__);
}
+ IAdvertising* GetAdvertising() {
+ return stack_manager_.GetInstance<bluetooth::shim::Advertising>();
+ }
+
IController* GetController() {
return stack_manager_.GetInstance<bluetooth::shim::Controller>();
}
@@ -112,10 +128,18 @@
return stack_manager_.GetInstance<bluetooth::shim::L2cap>();
}
+ IName* GetName() {
+ return stack_manager_.GetInstance<bluetooth::shim::Name>();
+ }
+
IPage* GetPage() {
return stack_manager_.GetInstance<bluetooth::shim::Page>();
}
+ IScanning* GetScanning() {
+ return stack_manager_.GetInstance<bluetooth::shim::Scanning>();
+ }
+
private:
os::Thread* stack_thread_ = nullptr;
bool is_running_ = false;
@@ -135,6 +159,10 @@
pimpl_->Stop();
}
+bluetooth::shim::IAdvertising* bluetooth::shim::Stack::GetAdvertising() {
+ return pimpl_->GetAdvertising();
+}
+
bluetooth::shim::IConnectability* bluetooth::shim::Stack::GetConnectability() {
return pimpl_->GetConnectability();
}
@@ -159,10 +187,18 @@
return pimpl_->GetL2cap();
}
+bluetooth::shim::IName* bluetooth::shim::Stack::GetName() {
+ return pimpl_->GetName();
+}
+
bluetooth::shim::IPage* bluetooth::shim::Stack::GetPage() {
return pimpl_->GetPage();
}
+bluetooth::shim::IScanning* bluetooth::shim::Stack::GetScanning() {
+ return pimpl_->GetScanning();
+}
+
bluetooth::shim::IStack* bluetooth::shim::GetGabeldorscheStack() {
static IStack* instance = new Stack();
return instance;
diff --git a/gd/shim/stack.h b/gd/shim/stack.h
index f56852a..f4a51fc 100644
--- a/gd/shim/stack.h
+++ b/gd/shim/stack.h
@@ -18,13 +18,16 @@
#include <memory>
+#include "shim/iadvertising.h"
#include "shim/iconnectability.h"
#include "shim/icontroller.h"
#include "shim/idiscoverability.h"
#include "shim/ihci_layer.h"
#include "shim/iinquiry.h"
#include "shim/il2cap.h"
+#include "shim/iname.h"
#include "shim/ipage.h"
+#include "shim/iscanning.h"
#include "shim/istack.h"
/**
@@ -41,13 +44,16 @@
void Start() override; // IStack
void Stop() override; // IStack
+ IAdvertising* GetAdvertising() override; // IStack
IController* GetController() override; // IStack
IConnectability* GetConnectability() override; // IStack
IHciLayer* GetHciLayer() override; // IStack
IDiscoverability* GetDiscoverability() override; // IStack
IInquiry* GetInquiry() override; // IStack
+ IName* GetName() override; // IStack
IL2cap* GetL2cap() override; // IStack
IPage* GetPage() override; // IStack
+ IScanning* GetScanning() override; // IStack
private:
struct impl;
diff --git a/main/shim/btm.cc b/main/shim/btm.cc
index 35f5f43..7ebbf90 100644
--- a/main/shim/btm.cc
+++ b/main/shim/btm.cc
@@ -17,6 +17,7 @@
#define LOG_TAG "bt_shim_btm"
#include <algorithm>
+#include <cstring>
#include "main/shim/btm.h"
#include "main/shim/entry.h"
@@ -34,12 +35,16 @@
static constexpr uint8_t kInquiryResultWithRssiMode = 1;
static constexpr uint8_t kExtendedInquiryResultMode = 2;
+static constexpr size_t kRemoteDeviceNameLength = 248;
+
extern void btm_process_cancel_complete(uint8_t status, uint8_t mode);
extern void btm_process_inq_complete(uint8_t status, uint8_t result_type);
extern void btm_process_inq_results(uint8_t* p, uint8_t result_mode);
+using BtmRemoteDeviceName = tBTM_REMOTE_DEV_NAME;
+
/**
- * Inquiry
+ *
*/
void bluetooth::shim::Btm::OnInquiryResult(std::vector<const uint8_t> result) {
CHECK(result.size() < kMaxInquiryResultSize);
@@ -194,7 +199,7 @@
}
/**
- * Periodic Inquiry
+ * Periodic
*/
bool bluetooth::shim::Btm::StartPeriodicInquiry(
uint8_t mode, uint8_t duration, uint8_t max_responses, uint16_t max_delay,
@@ -343,3 +348,85 @@
LOG_WARN(LOG_TAG, "UNIMPLEMENTED %s", __func__);
return state;
}
+
+bool bluetooth::shim::Btm::IsLeAclConnected(
+ const RawAddress& raw_address) const {
+ // TODO(cmanton) Check current acl's for this address and indicate if there is
+ // an LE option. For now ignore and default to classic.
+ LOG_INFO(LOG_TAG, "%s Le acl connection check is temporarily unsupported",
+ __func__);
+ return false;
+}
+
+bluetooth::shim::BtmStatus bluetooth::shim::Btm::ReadClassicRemoteDeviceName(
+ const RawAddress& raw_address, tBTM_CMPL_CB* callback) {
+ if (!CheckClassicAclLink(raw_address)) {
+ return bluetooth::shim::BTM_UNKNOWN_ADDR;
+ }
+
+ if (!classic_read_remote_name_.Start(raw_address)) {
+ LOG_INFO(LOG_TAG, "%s Read remote name is currently busy address:%s",
+ __func__, raw_address.ToString().c_str());
+ return bluetooth::shim::BTM_BUSY;
+ }
+
+ LOG_DEBUG(LOG_TAG, "%s Start read name from address:%s", __func__,
+ raw_address.ToString().c_str());
+ bluetooth::shim::GetName()->ReadRemoteNameRequest(
+ classic_read_remote_name_.AddressString(),
+ [this, callback](
+ std::string address_string, uint8_t hci_status,
+ std::array<uint8_t, kRemoteDeviceNameLength> remote_name) {
+ RawAddress raw_address;
+ RawAddress::FromString(address_string, raw_address);
+
+ BtmRemoteDeviceName name{
+ .status = (hci_status == 0) ? (BTM_SUCCESS) : (BTM_BAD_VALUE_RET),
+ .bd_addr = raw_address,
+ .length = kRemoteDeviceNameLength,
+ };
+ std::copy(remote_name.begin(), remote_name.end(), name.remote_bd_name);
+ LOG_DEBUG(LOG_TAG, "%s Finish read name from address:%s name:%s",
+ __func__, address_string.c_str(), name.remote_bd_name);
+ callback(&name);
+ classic_read_remote_name_.Stop();
+ });
+ return bluetooth::shim::BTM_CMD_STARTED;
+}
+
+bluetooth::shim::BtmStatus bluetooth::shim::Btm::ReadLeRemoteDeviceName(
+ const RawAddress& raw_address, tBTM_CMPL_CB* callback) {
+ if (!CheckLeAclLink(raw_address)) {
+ return bluetooth::shim::BTM_UNKNOWN_ADDR;
+ }
+
+ if (!le_read_remote_name_.Start(raw_address)) {
+ return bluetooth::shim::BTM_BUSY;
+ }
+
+ LOG_INFO(LOG_TAG, "UNIMPLEMENTED %s need access to GATT module", __func__);
+ return bluetooth::shim::BTM_UNKNOWN_ADDR;
+}
+
+bluetooth::shim::BtmStatus
+bluetooth::shim::Btm::CancelAllReadRemoteDeviceName() {
+ if (classic_read_remote_name_.IsInProgress() ||
+ le_read_remote_name_.IsInProgress()) {
+ if (classic_read_remote_name_.IsInProgress()) {
+ bluetooth::shim::GetName()->CancelRemoteNameRequest(
+ classic_read_remote_name_.AddressString(),
+ [this](std::string address_string, uint8_t status) {
+ classic_read_remote_name_.Stop();
+ });
+ }
+ if (le_read_remote_name_.IsInProgress()) {
+ LOG_INFO(LOG_TAG, "UNIMPLEMENTED %s need access to GATT module",
+ __func__);
+ }
+ return bluetooth::shim::BTM_UNKNOWN_ADDR;
+ }
+ LOG_INFO(LOG_TAG,
+ "%s Cancelling classic remote device name without one in progress",
+ __func__);
+ return bluetooth::shim::BTM_WRONG_MODE;
+}
diff --git a/main/shim/btm.h b/main/shim/btm.h
index aa92bf6..6f9c00b 100644
--- a/main/shim/btm.h
+++ b/main/shim/btm.h
@@ -17,6 +17,7 @@
#pragma once
#include <cstdint>
+#include <mutex>
#include <unordered_map>
#include <vector>
@@ -62,6 +63,62 @@
namespace bluetooth {
namespace shim {
+using BtmStatus = enum : uint16_t {
+ BTM_SUCCESS = 0, /* 0 Command succeeded */
+ BTM_CMD_STARTED, /* 1 Command started OK. */
+ BTM_BUSY, /* 2 Device busy with another command */
+ BTM_NO_RESOURCES, /* 3 No resources to issue command */
+ BTM_MODE_UNSUPPORTED, /* 4 Request for 1 or more unsupported modes */
+ BTM_ILLEGAL_VALUE, /* 5 Illegal parameter value */
+ BTM_WRONG_MODE, /* 6 Device in wrong mode for request */
+ BTM_UNKNOWN_ADDR, /* 7 Unknown remote BD address */
+ BTM_DEVICE_TIMEOUT, /* 8 Device timeout */
+ BTM_BAD_VALUE_RET, /* 9 A bad value was received from HCI */
+ BTM_ERR_PROCESSING, /* 10 Generic error */
+ BTM_NOT_AUTHORIZED, /* 11 Authorization failed */
+ BTM_DEV_RESET, /* 12 Device has been reset */
+ BTM_CMD_STORED, /* 13 request is stored in control block */
+ BTM_ILLEGAL_ACTION, /* 14 state machine gets illegal command */
+ BTM_DELAY_CHECK, /* 15 delay the check on encryption */
+ BTM_SCO_BAD_LENGTH, /* 16 Bad SCO over HCI data length */
+ BTM_SUCCESS_NO_SECURITY, /* 17 security passed, no security set */
+ BTM_FAILED_ON_SECURITY, /* 18 security failed */
+ BTM_REPEATED_ATTEMPTS, /* 19 repeated attempts for LE security requests */
+ BTM_MODE4_LEVEL4_NOT_SUPPORTED, /* 20 Secure Connections Only Mode can't be
+ supported */
+ BTM_DEV_BLACKLISTED /* 21 The device is Blacklisted */
+};
+
+class ReadRemoteName {
+ public:
+ bool Start(RawAddress raw_address) {
+ std::unique_lock<std::mutex> lock(mutex_);
+ if (in_progress_) {
+ return false;
+ }
+ raw_address_ = raw_address;
+ in_progress_ = true;
+ return true;
+ }
+
+ void Stop() {
+ std::unique_lock<std::mutex> lock(mutex_);
+ raw_address_ = RawAddress::kEmpty;
+ in_progress_ = false;
+ }
+
+ bool IsInProgress() const { return in_progress_; }
+
+ std::string AddressString() const { return raw_address_.ToString(); }
+
+ ReadRemoteName() : in_progress_{false}, raw_address_(RawAddress::kEmpty) {}
+
+ private:
+ bool in_progress_;
+ RawAddress raw_address_;
+ std::mutex mutex_;
+};
+
class Btm {
public:
Btm();
@@ -120,16 +177,21 @@
void SetLeConnectibleOff();
ConnectabilityState GetLeConnectabilityState() const;
+ bool IsLeAclConnected(const RawAddress& raw_address) const;
+
+ // Remote device name
+ BtmStatus ReadClassicRemoteDeviceName(const RawAddress& raw_address,
+ tBTM_CMPL_CB* callback);
+ BtmStatus ReadLeRemoteDeviceName(const RawAddress& raw_address,
+ tBTM_CMPL_CB* callback);
+ BtmStatus CancelAllReadRemoteDeviceName();
+
private:
- // DiscoverabilityState classic_;
- // DiscoverabilityState le_;
-
- // ConnectabilityState classic_connectibility_state_;
- // ConnectabilityState le_connectibility_state_;
-
- // bool DoSetEventFilter();
- // void DoSetDiscoverability();
- // bool DoSetInquiryMode();
+ ReadRemoteName le_read_remote_name_;
+ ReadRemoteName classic_read_remote_name_;
+ // TODO(cmanton) abort if there is no classic acl link up
+ bool CheckClassicAclLink(const RawAddress& raw_address) { return true; }
+ bool CheckLeAclLink(const RawAddress& raw_address) { return true; }
};
} // namespace shim
diff --git a/main/shim/btm_api.cc b/main/shim/btm_api.cc
index ee3b0cf..a8adee8 100644
--- a/main/shim/btm_api.cc
+++ b/main/shim/btm_api.cc
@@ -493,15 +493,23 @@
*
******************************************************************************/
tBTM_STATUS bluetooth::shim::BTM_ReadRemoteDeviceName(
- const RawAddress& remote_bda, tBTM_CMPL_CB* p_cb, tBT_TRANSPORT transport) {
- if (transport == BT_TRANSPORT_LE) {
- LOG_INFO(LOG_TAG, "UNIMPLEMENTED %s", __func__);
- return BTM_NO_RESOURCES;
- }
+ const RawAddress& raw_address, tBTM_CMPL_CB* callback,
+ tBT_TRANSPORT transport) {
+ CHECK(callback != nullptr);
+ tBTM_STATUS status = BTM_NO_RESOURCES;
- LOG_INFO(LOG_TAG, "UNIMPLEMENTED %s", __func__);
- return BTM_NO_RESOURCES;
- CHECK(p_cb != nullptr);
+ switch (transport) {
+ case BT_TRANSPORT_LE:
+ status = shim_btm.ReadLeRemoteDeviceName(raw_address, callback);
+ break;
+ case BT_TRANSPORT_BR_EDR:
+ status = shim_btm.ReadClassicRemoteDeviceName(raw_address, callback);
+ break;
+ default:
+ LOG_WARN(LOG_TAG, "%s Unspecified transport:%d", __func__, transport);
+ break;
+ }
+ return status;
}
/*******************************************************************************
@@ -523,8 +531,7 @@
*
******************************************************************************/
tBTM_STATUS bluetooth::shim::BTM_CancelRemoteDeviceName(void) {
- LOG_INFO(LOG_TAG, "UNIMPLEMENTED %s", __func__);
- return BTM_NO_RESOURCES;
+ return shim_btm.CancelAllReadRemoteDeviceName();
}
/*******************************************************************************
@@ -1155,9 +1162,8 @@
* Returns true to use LE, false use BR/EDR.
*
******************************************************************************/
-bool bluetooth::shim::BTM_UseLeLink(const RawAddress& bd_addr) {
- LOG_INFO(LOG_TAG, "UNIMPLEMENTED %s", __func__);
- return false;
+bool bluetooth::shim::BTM_UseLeLink(const RawAddress& raw_address) {
+ return shim_btm.IsLeAclConnected(raw_address);
}
/*******************************************************************************
diff --git a/main/shim/entry.cc b/main/shim/entry.cc
index 8768818..4655219 100644
--- a/main/shim/entry.cc
+++ b/main/shim/entry.cc
@@ -54,6 +54,10 @@
return GetGabeldorscheStack()->GetL2cap();
}
+bluetooth::shim::IName* bluetooth::shim::GetName() {
+ return GetGabeldorscheStack()->GetName();
+}
+
bluetooth::shim::IPage* bluetooth::shim::GetPage() {
return GetGabeldorscheStack()->GetPage();
}
diff --git a/main/shim/entry.h b/main/shim/entry.h
index a4d4cf4..2ffd2e5 100644
--- a/main/shim/entry.h
+++ b/main/shim/entry.h
@@ -44,6 +44,7 @@
bluetooth::shim::IInquiry* GetInquiry();
bluetooth::shim::IHciLayer* GetHciLayer();
bluetooth::shim::IL2cap* GetL2cap();
+bluetooth::shim::IName* GetName();
bluetooth::shim::IPage* GetPage();
} // namespace shim
diff --git a/main/shim/l2cap.cc b/main/shim/l2cap.cc
index 4fa6127..98db9cb 100644
--- a/main/shim/l2cap.cc
+++ b/main/shim/l2cap.cc
@@ -26,6 +26,7 @@
constexpr size_t kBtHdrSize = sizeof(BT_HDR);
constexpr uint16_t kInvalidConnectionInterfaceDescriptor = 0;
constexpr bool kDisconnectResponseRequired = false;
+constexpr uint16_t kConnectionSuccess = 0;
bool bluetooth::legacy::shim::PsmData::IsPsmAllocated(uint16_t psm) const {
return psm_to_callback_map_.find(psm) != psm_to_callback_map_.end();
@@ -159,14 +160,34 @@
auto completed = register_completed.get_future();
bluetooth::shim::GetL2cap()->RegisterService(
psm,
- std::bind(&bluetooth::legacy::shim::L2cap::OnConnectionReady, this,
- std::placeholders::_1, std::placeholders::_2,
- std::placeholders::_3),
+ std::bind(
+ &bluetooth::legacy::shim::L2cap::OnRemoteInitiatedConnectionCreated,
+ this, std::placeholders::_1, std::placeholders::_2,
+ std::placeholders::_3),
std::move(register_completed));
completed.wait();
LOG_DEBUG(LOG_TAG, "Successfully registered service on psm:%hd", psm);
}
+void bluetooth::legacy::shim::L2cap::OnRemoteInitiatedConnectionCreated(
+ std::string string_address, uint16_t psm, uint16_t cid) {
+ RawAddress raw_address;
+ RawAddress::FromString(string_address, raw_address);
+
+ LOG_DEBUG(LOG_TAG,
+ "Sending connection indicator to upper stack from device:%s "
+ "psm:%hd cid:%hd",
+ string_address.c_str(), psm, cid);
+
+ CHECK(!ConnectionExists(cid));
+ cid_to_psm_map_[cid] = psm;
+ SetCallbacks(cid, Classic().Callbacks(psm));
+ const tL2CAP_APPL_INFO* callbacks = Classic().Callbacks(psm);
+ CHECK(callbacks != nullptr);
+ callbacks->pL2CA_ConnectInd_Cb(raw_address, cid, psm /* UNUSED */,
+ 0 /* UNUSED */);
+}
+
void bluetooth::legacy::shim::L2cap::UnregisterService(uint16_t psm) {
if (!Classic().IsPsmRegistered(psm)) {
LOG_WARN(LOG_TAG,
@@ -182,9 +203,6 @@
uint16_t bluetooth::legacy::shim::L2cap::CreateConnection(
uint16_t psm, const RawAddress& raw_address) {
- LOG_DEBUG(LOG_TAG, "Requesting connection to psm:%hd address:%s", psm,
- raw_address.ToString().c_str());
-
if (!Classic().IsPsmRegistered(psm)) {
LOG_WARN(LOG_TAG, "Service must be registered in order to connect psm:%hd",
psm);
@@ -193,8 +211,18 @@
std::promise<uint16_t> connect_completed;
auto completed = connect_completed.get_future();
- bluetooth::shim::GetL2cap()->CreateConnection(psm, raw_address.ToString(),
- std::move(connect_completed));
+ LOG_DEBUG(LOG_TAG,
+ "Starting local initiated connection to psm:%hd address:%s", psm,
+ raw_address.ToString().c_str());
+
+ bluetooth::shim::GetL2cap()->CreateConnection(
+ psm, raw_address.ToString(),
+ std::bind(
+ &bluetooth::legacy::shim::L2cap::OnLocalInitiatedConnectionCreated,
+ this, std::placeholders::_1, std::placeholders::_2,
+ std::placeholders::_3),
+ std::move(connect_completed));
+
uint16_t cid = completed.get();
if (cid == kInvalidConnectionInterfaceDescriptor) {
LOG_WARN(LOG_TAG,
@@ -205,62 +233,59 @@
"Successfully started connection to psm:%hd address:%s"
" connection_interface_descriptor:%hd",
psm, raw_address.ToString().c_str(), cid);
- CHECK(cid_to_psm_map_.find(cid) == cid_to_psm_map_.end());
+ CHECK(!ConnectionExists(cid));
cid_to_psm_map_[cid] = psm;
SetCallbacks(cid, Classic().Callbacks(psm));
- const tL2CAP_APPL_INFO* callbacks = Classic().Callbacks(psm);
- CHECK(callbacks != nullptr);
}
return cid;
}
-void bluetooth::legacy::shim::L2cap::OnConnectionReady(
- uint16_t psm, uint16_t cid,
- std::function<void(std::function<void(uint16_t c)>)> func) {
- LOG_DEBUG(
- LOG_TAG,
- "l2cap got new connection psm:%hd connection_interface_descriptor:%hd",
- psm, cid);
+void bluetooth::legacy::shim::L2cap::OnLocalInitiatedConnectionCreated(
+ std::string string_address, uint16_t psm, uint16_t cid) {
+ LOG_DEBUG(LOG_TAG,
+ "Sending connection confirm to the upper stack but really "
+ "a connection to %s has already been done cid:%hd",
+ string_address.c_str(), cid);
+ // TODO(cmanton) Make sure the device is correct for locally initiated
const tL2CAP_APPL_INFO* callbacks = Classic().Callbacks(psm);
- if (callbacks == nullptr) {
- return;
- }
- LOG_DEBUG(LOG_TAG, "%s Setting postable map for cid:%d", __func__, cid);
- cid_to_postable_map_[cid] = func;
- func([&cid, &callbacks](uint16_t cid2) {
- LOG_WARN(LOG_TAG,
- "Queuing up the connection confirm to the upper stack but really "
- "a connection has already been done Cid:%hd Cid2:%hd",
- cid, cid2);
- callbacks->pL2CA_ConnectCfm_Cb(cid2, 0);
- });
-}
+ CHECK(callbacks != nullptr);
+ callbacks->pL2CA_ConnectCfm_Cb(cid, kConnectionSuccess);
+};
bool bluetooth::legacy::shim::L2cap::Write(uint16_t cid, BT_HDR* bt_hdr) {
- CHECK(ConnectionExists(cid));
CHECK(bt_hdr != nullptr);
const uint8_t* data = bt_hdr->data + bt_hdr->offset;
size_t len = bt_hdr->len;
+ if (!ConnectionExists(cid) || len == 0) {
+ return false;
+ }
LOG_DEBUG(LOG_TAG, "Writing data cid:%hd len:%zd", cid, len);
- return bluetooth::shim::GetL2cap()->Write(cid, data, len);
+ bluetooth::shim::GetL2cap()->Write(cid, data, len);
+ return true;
}
bool bluetooth::legacy::shim::L2cap::WriteFlushable(uint16_t cid,
BT_HDR* bt_hdr) {
- CHECK(ConnectionExists(cid));
CHECK(bt_hdr != nullptr);
const uint8_t* data = bt_hdr->data + bt_hdr->offset;
size_t len = bt_hdr->len;
- return bluetooth::shim::GetL2cap()->WriteFlushable(cid, data, len);
+ if (!ConnectionExists(cid) || len == 0) {
+ return false;
+ }
+ bluetooth::shim::GetL2cap()->WriteFlushable(cid, data, len);
+ return true;
}
bool bluetooth::legacy::shim::L2cap::WriteNonFlushable(uint16_t cid,
BT_HDR* bt_hdr) {
- CHECK(ConnectionExists(cid));
CHECK(bt_hdr != nullptr);
const uint8_t* data = bt_hdr->data + bt_hdr->offset;
size_t len = bt_hdr->len;
- return bluetooth::shim::GetL2cap()->WriteNonFlushable(cid, data, len);
+ if (!ConnectionExists(cid) || len == 0) {
+ return false;
+ }
+ bluetooth::shim::GetL2cap()->WriteNonFlushable(cid, data, len);
+ return true;
}
bool bluetooth::legacy::shim::L2cap::SetCallbacks(
@@ -280,6 +305,7 @@
static_cast<BT_HDR*>(osi_calloc(data.size() + kBtHdrSize));
std::copy(data.begin(), data.end(), bt_hdr->data);
bt_hdr->len = data.size();
+ CHECK(cid_to_callback_map_.find(cid) != cid_to_callback_map_.end());
cid_to_callback_map_[cid]->pL2CA_DataInd_Cb(cid, bt_hdr);
});
@@ -309,14 +335,12 @@
bool bluetooth::legacy::shim::L2cap::ConfigRequest(
uint16_t cid, const tL2CAP_CFG_INFO* config_info) {
CHECK(ConnectionExists(cid));
- LOG_INFO(LOG_TAG, "Received config request from upper layer");
- CHECK(cid_to_psm_map_.find(cid) != cid_to_psm_map_.end());
- const tL2CAP_APPL_INFO* callbacks = Classic().Callbacks(cid_to_psm_map_[cid]);
- CHECK(callbacks != nullptr);
- CHECK(cid_to_postable_map_.count(cid) == 1);
+ LOG_INFO(LOG_TAG, "Received config request from upper layer cid:%hd", cid);
- auto func = cid_to_postable_map_[cid];
- func([&cid, &callbacks](uint16_t cid2) {
+ bluetooth::shim::GetL2cap()->SendLoopbackResponse([this, cid]() {
+ CHECK(ConnectionExists(cid));
+ const tL2CAP_APPL_INFO* callbacks = cid_to_callback_map_[cid];
+ CHECK(callbacks != nullptr);
tL2CAP_CFG_INFO cfg_info{
.result = L2CAP_CFG_OK,
.mtu_present = false,
@@ -327,7 +351,6 @@
.ext_flow_spec_present = false,
.flags = 0,
};
- LOG_INFO(LOG_TAG, "Config request lambda");
callbacks->pL2CA_ConfigCfm_Cb(cid, &cfg_info);
callbacks->pL2CA_ConfigInd_Cb(cid, &cfg_info);
});
@@ -346,8 +369,8 @@
bool bluetooth::legacy::shim::L2cap::DisconnectRequest(uint16_t cid) {
CHECK(ConnectionExists(cid));
- bluetooth::shim::GetL2cap()->CloseConnection(cid);
cid_to_callback_map_.erase(cid);
+ bluetooth::shim::GetL2cap()->CloseConnection(cid);
return true;
}
diff --git a/main/shim/l2cap.h b/main/shim/l2cap.h
index da9852a..2fbe0d6 100644
--- a/main/shim/l2cap.h
+++ b/main/shim/l2cap.h
@@ -53,15 +53,18 @@
void RegisterService(uint16_t psm, const tL2CAP_APPL_INFO* callbacks,
bool enable_snoop);
void UnregisterService(uint16_t psm);
+
uint16_t CreateConnection(uint16_t psm, const RawAddress& raw_address);
- void OnConnectionReady(
- uint16_t psm, uint16_t cid,
- std::function<void(std::function<void(uint16_t cid)>)> func);
bool Write(uint16_t cid, BT_HDR* bt_hdr);
bool WriteFlushable(uint16_t cid, BT_HDR* bt_hdr);
bool WriteNonFlushable(uint16_t cid, BT_HDR* bt_hdr);
+ void OnLocalInitiatedConnectionCreated(std::string string_address,
+ uint16_t psm, uint16_t cid);
+ void OnRemoteInitiatedConnectionCreated(std::string string_addresss,
+ uint16_t psm, uint16_t cid);
+
uint16_t GetNextDynamicClassicPsm();
uint16_t GetNextDynamicLePsm();
@@ -79,9 +82,6 @@
bool DisconnectRequest(uint16_t cid);
bool DisconnectResponse(uint16_t cid);
- void Test(void* context);
- void Test2();
-
L2cap();
PsmData& Classic();
diff --git a/main/shim/l2cap_test.cc b/main/shim/l2cap_test.cc
index 1f67de6..bf28f3c 100644
--- a/main/shim/l2cap_test.cc
+++ b/main/shim/l2cap_test.cc
@@ -232,14 +232,10 @@
uint16_t cid = l2cap_->CreateConnection(kPsm, raw_address);
CHECK(cid != 0);
- {
- // Simulate a successful connection response
- l2cap_->OnConnectionReady(kPsm, kCid,
- [&cid](std::function<void(uint16_t)> func) {
- LOG_INFO(LOG_TAG, "In closure cid:%d", cid);
- func(cid);
- });
- }
+ // Simulate a successful connection response
+ l2cap_->OnLocalInitiatedConnectionCreated("11:22:33:44:55:66", kPsm, kCid);
+ CHECK(cnt_.L2caConnectCfmCb == 1);
+
CHECK(l2cap_->ConfigRequest(cid, nullptr));
}
@@ -253,14 +249,10 @@
uint16_t cid = l2cap_->CreateConnection(kPsm, raw_address);
CHECK(cid != 0);
- {
- // Simulate a successful connection response
- l2cap_->OnConnectionReady(kPsm, kCid,
- [&cid](std::function<void(uint16_t)> func) {
- LOG_INFO(LOG_TAG, "In closure cid:%d", cid);
- func(cid);
- });
- }
+ // Simulate a successful connection response
+ l2cap_->OnLocalInitiatedConnectionCreated("11:22:33:44:55:66", kPsm, kCid);
+ CHECK(cnt_.L2caConnectCfmCb == 1);
+
CHECK(l2cap_->ConfigResponse(cid, nullptr));
}
@@ -274,14 +266,10 @@
uint16_t cid = l2cap_->CreateConnection(kPsm, raw_address);
CHECK(cid != 0);
- {
- // Simulate a successful connection response
- l2cap_->OnConnectionReady(kPsm, kCid,
- [&cid](std::function<void(uint16_t)> func) {
- LOG_INFO(LOG_TAG, "In closure cid:%d", cid);
- func(cid);
- });
- }
+ // Simulate a successful connection response
+ l2cap_->OnLocalInitiatedConnectionCreated("11:22:33:44:55:66", kPsm, kCid);
+ CHECK(cnt_.L2caConnectCfmCb == 1);
+
CHECK(l2cap_->DisconnectRequest(cid));
}
@@ -295,14 +283,10 @@
uint16_t cid = l2cap_->CreateConnection(kPsm, raw_address);
CHECK(cid != 0);
- {
- // Simulate a successful connection response
- l2cap_->OnConnectionReady(kPsm, kCid,
- [&cid](std::function<void(uint16_t)> func) {
- LOG_INFO(LOG_TAG, "In closure cid:%d", cid);
- func(cid);
- });
- }
+ // Simulate a successful connection response
+ l2cap_->OnLocalInitiatedConnectionCreated("11:22:33:44:55:66", kPsm, kCid);
+ CHECK(cnt_.L2caConnectCfmCb == 1);
+
CHECK(l2cap_->DisconnectResponse(cid));
}
@@ -316,18 +300,13 @@
uint16_t cid = l2cap_->CreateConnection(kPsm, raw_address);
CHECK(cid != 0);
- {
- // Simulate a successful connection response
- l2cap_->OnConnectionReady(kPsm, kCid,
- [&cid](std::function<void(uint16_t)> func) {
- LOG_INFO(LOG_TAG, "In closure cid:%d", cid);
- func(cid);
- });
- }
+ // Simulate a successful connection response
+ l2cap_->OnLocalInitiatedConnectionCreated("11:22:33:44:55:66", kPsm, kCid);
CHECK(cnt_.L2caConnectCfmCb == 1);
CHECK(l2cap_->ConfigRequest(cid, nullptr) == true);
CHECK(cnt_.L2caConfigCfmCb == 1);
+ CHECK(cnt_.L2caConfigIndCb == 1);
BT_HDR* bt_hdr = (BT_HDR*)bt_hdr_data;
diff --git a/main/shim/test_stack.cc b/main/shim/test_stack.cc
index e475d49..9d38541 100644
--- a/main/shim/test_stack.cc
+++ b/main/shim/test_stack.cc
@@ -39,8 +39,10 @@
registered_service_.erase(psm);
}
-void TestGdShimL2cap::CreateConnection(uint16_t psm, const std::string address,
- std::promise<uint16_t> completed) {
+void TestGdShimL2cap::CreateConnection(
+ uint16_t psm, const std::string address,
+ bluetooth::shim::ConnectionOpenCallback on_open,
+ std::promise<uint16_t> completed) {
completed.set_value(cid_);
}
@@ -52,29 +54,28 @@
void TestGdShimL2cap::SetConnectionClosedCallback(
uint16_t cid, bluetooth::shim::ConnectionClosedCallback on_closed) {}
-bool TestGdShimL2cap::Write(uint16_t cid, const uint8_t* data, size_t len) {
+void TestGdShimL2cap::Write(uint16_t cid, const uint8_t* data, size_t len) {
ASSERT(data_buffer_ != nullptr);
ASSERT(data_buffer_size_ > len);
memcpy(data_buffer_, data, len);
- return write_success_;
}
-bool TestGdShimL2cap::WriteFlushable(uint16_t cid, const uint8_t* data,
- size_t len) {
- return write_success_;
-}
+void TestGdShimL2cap::WriteFlushable(uint16_t cid, const uint8_t* data,
+ size_t len) {}
-bool TestGdShimL2cap::WriteNonFlushable(uint16_t cid, const uint8_t* data,
- size_t len) {
- return write_success_;
-}
+void TestGdShimL2cap::WriteNonFlushable(uint16_t cid, const uint8_t* data,
+ size_t len) {}
-bool TestGdShimL2cap::IsCongested(uint16_t cid) { return is_congested_; }
+void TestGdShimL2cap::SendLoopbackResponse(std::function<void()> function) {
+ function();
+}
void TestStack::Start() {}
void TestStack::Stop() {}
+bluetooth::shim::IAdvertising* TestStack::GetAdvertising() { return nullptr; }
+
bluetooth::shim::IController* TestStack::GetController() { return nullptr; }
bluetooth::shim::IConnectability* TestStack::GetConnectability() {
@@ -91,4 +92,8 @@
bluetooth::shim::IL2cap* TestStack::GetL2cap() { return &test_l2cap_; }
+bluetooth::shim::IName* TestStack::GetName() { return nullptr; }
+
bluetooth::shim::IPage* TestStack::GetPage() { return nullptr; }
+
+bluetooth::shim::IScanning* TestStack::GetScanning() { return nullptr; }
diff --git a/main/shim/test_stack.h b/main/shim/test_stack.h
index e8bdc13..92027b1 100644
--- a/main/shim/test_stack.h
+++ b/main/shim/test_stack.h
@@ -34,6 +34,7 @@
std::promise<void> completed) override;
void UnregisterService(uint16_t psm);
void CreateConnection(uint16_t psm, const std::string address,
+ bluetooth::shim::ConnectionOpenCallback on_open,
std::promise<uint16_t> completed) override;
void CloseConnection(uint16_t cid);
void SetReadDataReadyCallback(
@@ -42,24 +43,27 @@
void SetConnectionClosedCallback(
uint16_t cid,
bluetooth::shim::ConnectionClosedCallback on_closed) override;
- bool Write(uint16_t cid, const uint8_t* data, size_t len) override;
- bool WriteFlushable(uint16_t cid, const uint8_t* data, size_t len) override;
- bool WriteNonFlushable(uint16_t cid, const uint8_t* data,
+ void Write(uint16_t cid, const uint8_t* data, size_t len) override;
+ void WriteFlushable(uint16_t cid, const uint8_t* data, size_t len) override;
+ void WriteNonFlushable(uint16_t cid, const uint8_t* data,
size_t len) override;
- bool IsCongested(uint16_t cid) override;
+ void SendLoopbackResponse(std::function<void()>) override;
};
class TestStack : public bluetooth::shim::IStack {
public:
TestStack() = default;
+ bluetooth::shim::IAdvertising* GetAdvertising();
bluetooth::shim::IController* GetController();
bluetooth::shim::IConnectability* GetConnectability();
bluetooth::shim::IDiscoverability* GetDiscoverability();
bluetooth::shim::IHciLayer* GetHciLayer();
bluetooth::shim::IInquiry* GetInquiry();
bluetooth::shim::IL2cap* GetL2cap();
+ bluetooth::shim::IName* GetName();
bluetooth::shim::IPage* GetPage();
+ bluetooth::shim::IScanning* GetScanning();
TestGdShimL2cap test_l2cap_;
diff --git a/test/rootcanal/Android.bp b/test/rootcanal/Android.bp
index 3a1871b..f2d3293 100644
--- a/test/rootcanal/Android.bp
+++ b/test/rootcanal/Android.bp
@@ -41,6 +41,7 @@
],
generated_headers: [
"RootCanalGeneratedPackets_h",
+ "BluetoothGeneratedPackets_h",
],
static_libs: [
"android.hardware.bluetooth-async",
@@ -84,6 +85,7 @@
],
generated_headers: [
"RootCanalGeneratedPackets_h",
+ "BluetoothGeneratedPackets_h",
],
static_libs: [
"android.hardware.bluetooth-async",
diff --git a/vendor_libs/test_vendor_lib/Android.bp b/vendor_libs/test_vendor_lib/Android.bp
index d53f201..7d20b25 100644
--- a/vendor_libs/test_vendor_lib/Android.bp
+++ b/vendor_libs/test_vendor_lib/Android.bp
@@ -36,6 +36,7 @@
"model/setup/test_command_handler.cc",
"model/setup/test_model.cc",
":BluetoothPacketSources",
+ ":BluetoothHciClassSources",
],
cflags: [
"-fvisibility=hidden",
@@ -50,6 +51,7 @@
],
generated_headers: [
"RootCanalGeneratedPackets_h",
+ "BluetoothGeneratedPackets_h",
],
include_dirs: [
"system/bt",
@@ -126,6 +128,7 @@
],
generated_headers: [
"RootCanalGeneratedPackets_h",
+ "BluetoothGeneratedPackets_h",
],
shared_libs: [
"liblog",
diff --git a/vendor_libs/test_vendor_lib/model/controller/acl_connection.h b/vendor_libs/test_vendor_lib/model/controller/acl_connection.h
index 8c27f04..cc33c13 100644
--- a/vendor_libs/test_vendor_lib/model/controller/acl_connection.h
+++ b/vendor_libs/test_vendor_lib/model/controller/acl_connection.h
@@ -18,10 +18,12 @@
#include <cstdint>
-#include "types/address.h"
+#include "hci/address.h"
namespace test_vendor_lib {
+using ::bluetooth::hci::Address;
+
// Model the connection of a device to the controller.
class AclConnection {
public:
diff --git a/vendor_libs/test_vendor_lib/model/controller/acl_connection_handler.cc b/vendor_libs/test_vendor_lib/model/controller/acl_connection_handler.cc
index 6ad54ff..c1fcd84 100644
--- a/vendor_libs/test_vendor_lib/model/controller/acl_connection_handler.cc
+++ b/vendor_libs/test_vendor_lib/model/controller/acl_connection_handler.cc
@@ -18,12 +18,14 @@
#include "os/log.h"
-#include "types/address.h"
+#include "hci/address.h"
using std::shared_ptr;
namespace test_vendor_lib {
+using ::bluetooth::hci::Address;
+
bool AclConnectionHandler::HasHandle(uint16_t handle) const {
if (acl_connections_.count(handle) == 0) {
return false;
diff --git a/vendor_libs/test_vendor_lib/model/controller/acl_connection_handler.h b/vendor_libs/test_vendor_lib/model/controller/acl_connection_handler.h
index 447aac6..6b32952 100644
--- a/vendor_libs/test_vendor_lib/model/controller/acl_connection_handler.h
+++ b/vendor_libs/test_vendor_lib/model/controller/acl_connection_handler.h
@@ -21,11 +21,13 @@
#include <unordered_map>
#include "acl_connection.h"
+#include "hci/address.h"
#include "include/acl.h"
-#include "types/address.h"
namespace test_vendor_lib {
+using ::bluetooth::hci::Address;
+
class AclConnectionHandler {
public:
AclConnectionHandler() = default;
diff --git a/vendor_libs/test_vendor_lib/model/controller/dual_mode_controller.cc b/vendor_libs/test_vendor_lib/model/controller/dual_mode_controller.cc
index 9730a21..961eae7 100644
--- a/vendor_libs/test_vendor_lib/model/controller/dual_mode_controller.cc
+++ b/vendor_libs/test_vendor_lib/model/controller/dual_mode_controller.cc
@@ -23,11 +23,11 @@
#include <base/values.h>
#include "os/log.h"
+#include "packet/raw_builder.h"
#include "hci.h"
#include "packets/hci/acl_packet_view.h"
#include "packets/hci/command_packet_view.h"
-#include "packets/hci/event_packet_builder.h"
#include "packets/hci/sco_packet_view.h"
using std::vector;
@@ -76,31 +76,49 @@
link_layer_controller_.TimerTick();
}
-void DualModeController::SendCommandCompleteSuccess(OpCode command_opcode) const {
- send_event_(packets::EventPacketBuilder::CreateCommandCompleteOnlyStatusEvent(command_opcode, hci::Status::SUCCESS)
- ->ToVector());
+void DualModeController::SendCommandCompleteSuccess(
+ bluetooth::hci::OpCode command_opcode) const {
+ SendCommandCompleteOnlyStatus(command_opcode,
+ bluetooth::hci::ErrorCode::SUCCESS);
}
void DualModeController::SendCommandCompleteUnknownOpCodeEvent(uint16_t command_opcode) const {
- send_event_(packets::EventPacketBuilder::CreateCommandCompleteUnknownOpCodeEvent(command_opcode)->ToVector());
+ std::unique_ptr<bluetooth::packet::RawBuilder> raw_builder_ptr =
+ std::make_unique<bluetooth::packet::RawBuilder>();
+ raw_builder_ptr->AddOctets1(0x01); // num_responses
+ raw_builder_ptr->AddOctets2(command_opcode);
+ raw_builder_ptr->AddOctets1(
+ static_cast<uint8_t>(bluetooth::hci::ErrorCode::UNKNOWN_HCI_COMMAND));
+
+ auto packet = bluetooth::hci::EventPacketBuilder::Create(
+ bluetooth::hci::EventCode::COMMAND_COMPLETE, std::move(raw_builder_ptr));
+ send_event_(std::move(packet));
}
-void DualModeController::SendCommandCompleteOnlyStatus(OpCode command_opcode, hci::Status status) const {
- send_event_(packets::EventPacketBuilder::CreateCommandCompleteOnlyStatusEvent(command_opcode, status)->ToVector());
+void DualModeController::SendCommandCompleteOnlyStatus(
+ bluetooth::hci::OpCode command_opcode,
+ bluetooth::hci::ErrorCode status) const {
+ std::unique_ptr<bluetooth::packet::RawBuilder> raw_builder_ptr =
+ std::make_unique<bluetooth::packet::RawBuilder>();
+ raw_builder_ptr->AddOctets1(static_cast<uint8_t>(status));
+ auto packet = bluetooth::hci::CommandCompleteBuilder::Create(
+ 0x01, command_opcode, std::move(raw_builder_ptr));
+ send_event_(std::move(packet));
}
-void DualModeController::SendCommandCompleteStatusAndAddress(OpCode command_opcode, hci::Status status,
- const Address& address) const {
- send_event_(packets::EventPacketBuilder::CreateCommandCompleteStatusAndAddressEvent(command_opcode, status, address)
- ->ToVector());
+void DualModeController::SendCommandStatus(
+ bluetooth::hci::ErrorCode status,
+ bluetooth::hci::OpCode command_opcode) const {
+ std::unique_ptr<bluetooth::packet::RawBuilder> raw_builder_ptr =
+ std::make_unique<bluetooth::packet::RawBuilder>();
+ auto packet = bluetooth::hci::CommandStatusBuilder::Create(
+ status, 0x01, command_opcode, std::move(raw_builder_ptr));
+ send_event_(std::move(packet));
}
-void DualModeController::SendCommandStatus(hci::Status status, OpCode command_opcode) const {
- send_event_(packets::EventPacketBuilder::CreateCommandStatusEvent(status, command_opcode)->ToVector());
-}
-
-void DualModeController::SendCommandStatusSuccess(OpCode command_opcode) const {
- SendCommandStatus(hci::Status::SUCCESS, command_opcode);
+void DualModeController::SendCommandStatusSuccess(
+ bluetooth::hci::OpCode command_opcode) const {
+ SendCommandStatus(bluetooth::hci::ErrorCode::SUCCESS, command_opcode);
}
DualModeController::DualModeController(const std::string& properties_filename, uint16_t num_keys)
@@ -226,7 +244,9 @@
uint16_t handle = args.begin().extract<uint16_t>();
- send_event_(packets::EventPacketBuilder::CreateSniffSubratingEvent(hci::Status::SUCCESS, handle)->ToVector());
+ auto packet = bluetooth::hci::SniffSubratingCompleteBuilder::Create(
+ 0x01, bluetooth::hci::ErrorCode::SUCCESS, handle);
+ send_event_(std::move(packet));
}
void DualModeController::RegisterTaskScheduler(
@@ -248,8 +268,17 @@
auto acl_packet = packets::AclPacketView::Create(packet);
if (loopback_mode_ == hci::LoopbackMode::LOCAL) {
uint16_t handle = acl_packet.GetHandle();
- send_acl_(packet);
- send_event_(packets::EventPacketBuilder::CreateNumberOfCompletedPacketsEvent(handle, 1)->ToVector());
+
+ std::unique_ptr<bluetooth::packet::RawBuilder> raw_builder_ptr =
+ std::make_unique<bluetooth::packet::RawBuilder>();
+ raw_builder_ptr->AddOctets1(0x01);
+ raw_builder_ptr->AddOctets2(handle);
+ raw_builder_ptr->AddOctets2(0x01);
+
+ auto packet = bluetooth::hci::EventPacketBuilder::Create(
+ bluetooth::hci::EventCode::NUMBER_OF_COMPLETED_PACKETS,
+ std::move(raw_builder_ptr));
+ send_event_(std::move(packet));
return;
}
@@ -261,7 +290,16 @@
if (loopback_mode_ == hci::LoopbackMode::LOCAL) {
uint16_t handle = sco_packet.GetHandle();
send_sco_(packet);
- send_event_(packets::EventPacketBuilder::CreateNumberOfCompletedPacketsEvent(handle, 1)->ToVector());
+ std::unique_ptr<bluetooth::packet::RawBuilder> raw_builder_ptr =
+ std::make_unique<bluetooth::packet::RawBuilder>();
+ raw_builder_ptr->AddOctets1(0x01);
+ raw_builder_ptr->AddOctets2(handle);
+ raw_builder_ptr->AddOctets2(0x01);
+
+ auto packet = bluetooth::hci::EventPacketBuilder::Create(
+ bluetooth::hci::EventCode::NUMBER_OF_COMPLETED_PACKETS,
+ std::move(raw_builder_ptr));
+ send_event_(std::move(packet));
return;
}
}
@@ -276,19 +314,32 @@
op != OpCode::RESET && op != OpCode::SET_CONTROLLER_TO_HOST_FLOW_CONTROL && op != OpCode::HOST_BUFFER_SIZE &&
op != OpCode::HOST_NUM_COMPLETED_PACKETS && op != OpCode::READ_BUFFER_SIZE && op != OpCode::READ_LOOPBACK_MODE &&
op != OpCode::WRITE_LOOPBACK_MODE) {
- send_event_(packets::EventPacketBuilder::CreateLoopbackCommandEvent(op, command_packet.GetPayload())->ToVector());
+ std::unique_ptr<bluetooth::packet::RawBuilder> raw_builder_ptr =
+ std::make_unique<bluetooth::packet::RawBuilder>();
+ raw_builder_ptr->AddOctets(*packet);
+ auto packet = bluetooth::hci::LoopbackCommandBuilder::Create(
+ std::move(raw_builder_ptr));
+ send_event_(std::move(packet));
} else if (active_hci_commands_.count(opcode) > 0) {
active_hci_commands_[opcode](command_packet.GetPayload());
} else {
SendCommandCompleteUnknownOpCodeEvent(opcode);
- LOG_INFO("Command opcode: 0x%04X, OGF: 0x%04X, OCF: 0x%04X", opcode, (opcode & 0xFC00) >> 10, opcode & 0x03FF);
+ LOG_INFO("Unknown command, opcode: 0x%04X, OGF: 0x%04X, OCF: 0x%04X",
+ opcode, (opcode & 0xFC00) >> 10, opcode & 0x03FF);
}
}
void DualModeController::RegisterEventChannel(
const std::function<void(std::shared_ptr<std::vector<uint8_t>>)>& callback) {
- link_layer_controller_.RegisterEventChannel(callback);
- send_event_ = callback;
+ send_event_ =
+ [callback](std::shared_ptr<bluetooth::hci::EventPacketBuilder> event) {
+ auto bytes = std::make_shared<std::vector<uint8_t>>();
+ bluetooth::packet::BitInserter bit_inserter(*bytes);
+ bytes->reserve(event->size());
+ event->Serialize(bit_inserter);
+ callback(std::move(bytes));
+ };
+ link_layer_controller_.RegisterEventChannel(send_event_);
}
void DualModeController::RegisterAclChannel(
@@ -310,17 +361,19 @@
loopback_mode_ = hci::LoopbackMode::NO;
}
- SendCommandCompleteSuccess(OpCode::RESET);
+ SendCommandCompleteSuccess(bluetooth::hci::OpCode::RESET);
}
void DualModeController::HciReadBufferSize(packets::PacketView<true> args) {
ASSERT_LOG(args.size() == 0, "%s size=%zu", __func__, args.size());
- std::shared_ptr<packets::EventPacketBuilder> command_complete =
- packets::EventPacketBuilder::CreateCommandCompleteReadBufferSize(
- hci::Status::SUCCESS, properties_.GetAclDataPacketSize(), properties_.GetSynchronousDataPacketSize(),
- properties_.GetTotalNumAclDataPackets(), properties_.GetTotalNumSynchronousDataPackets());
- send_event_(command_complete->ToVector());
+ auto packet = bluetooth::hci::ReadBufferSizeCompleteBuilder::Create(
+ 0x01, bluetooth::hci::ErrorCode::SUCCESS,
+ properties_.GetAclDataPacketSize(),
+ properties_.GetSynchronousDataPacketSize(),
+ properties_.GetTotalNumAclDataPackets(),
+ properties_.GetTotalNumSynchronousDataPackets());
+ send_event_(std::move(packet));
}
void DualModeController::HciReadEncryptionKeySize(
@@ -329,25 +382,34 @@
uint16_t handle = args.begin().extract<uint16_t>();
- std::shared_ptr<packets::EventPacketBuilder> command_complete =
- packets::EventPacketBuilder::CreateCommandCompleteReadEncryptionKeySize(
- hci::Status::SUCCESS, handle, properties_.GetEncryptionKeySize());
-
- send_event_(command_complete->ToVector());
+ auto packet = bluetooth::hci::ReadEncryptionKeySizeCompleteBuilder::Create(
+ 0x01, bluetooth::hci::ErrorCode::SUCCESS, handle,
+ properties_.GetEncryptionKeySize());
+ send_event_(std::move(packet));
}
void DualModeController::HciHostBufferSize(packets::PacketView<true> args) {
ASSERT_LOG(args.size() == 7, "%s size=%zu", __func__, args.size());
- SendCommandCompleteSuccess(OpCode::HOST_BUFFER_SIZE);
+ SendCommandCompleteSuccess(bluetooth::hci::OpCode::HOST_BUFFER_SIZE);
}
void DualModeController::HciReadLocalVersionInformation(packets::PacketView<true> args) {
ASSERT_LOG(args.size() == 0, "%s size=%zu", __func__, args.size());
- std::shared_ptr<packets::EventPacketBuilder> command_complete =
- packets::EventPacketBuilder::CreateCommandCompleteReadLocalVersionInformation(
- hci::Status::SUCCESS, properties_.GetVersion(), properties_.GetRevision(), properties_.GetLmpPalVersion(),
- properties_.GetManufacturerName(), properties_.GetLmpPalSubversion());
- send_event_(command_complete->ToVector());
+
+ std::unique_ptr<bluetooth::packet::RawBuilder> raw_builder_ptr =
+ std::make_unique<bluetooth::packet::RawBuilder>();
+ raw_builder_ptr->AddOctets1(
+ static_cast<uint8_t>(bluetooth::hci::ErrorCode::SUCCESS));
+ raw_builder_ptr->AddOctets1(properties_.GetVersion());
+ raw_builder_ptr->AddOctets2(properties_.GetRevision());
+ raw_builder_ptr->AddOctets1(properties_.GetLmpPalVersion());
+ raw_builder_ptr->AddOctets2(properties_.GetManufacturerName());
+ raw_builder_ptr->AddOctets2(properties_.GetLmpPalSubversion());
+
+ auto packet = bluetooth::hci::CommandCompleteBuilder::Create(
+ 0x01, bluetooth::hci::OpCode::READ_LOCAL_VERSION_INFORMATION,
+ std::move(raw_builder_ptr));
+ send_event_(std::move(packet));
}
void DualModeController::HciReadRemoteVersionInformation(packets::PacketView<true> args) {
@@ -355,50 +417,65 @@
uint16_t handle = args.begin().extract<uint16_t>();
- hci::Status status =
- link_layer_controller_.SendCommandToRemoteByHandle(OpCode::READ_REMOTE_VERSION_INFORMATION, args, handle);
+ auto status = link_layer_controller_.SendCommandToRemoteByHandle(
+ bluetooth::hci::OpCode::READ_REMOTE_VERSION_INFORMATION, args, handle);
- SendCommandStatus(status, OpCode::READ_REMOTE_VERSION_INFORMATION);
+ SendCommandStatus(status,
+ bluetooth::hci::OpCode::READ_REMOTE_VERSION_INFORMATION);
}
void DualModeController::HciReadBdAddr(packets::PacketView<true> args) {
ASSERT_LOG(args.size() == 0, "%s size=%zu", __func__, args.size());
- std::shared_ptr<packets::EventPacketBuilder> command_complete =
- packets::EventPacketBuilder::CreateCommandCompleteReadBdAddr(hci::Status::SUCCESS, properties_.GetAddress());
- send_event_(command_complete->ToVector());
+ auto packet = bluetooth::hci::ReadBdAddrCompleteBuilder::Create(
+ 0x01, bluetooth::hci::ErrorCode::SUCCESS, properties_.GetAddress());
+ send_event_(std::move(packet));
}
void DualModeController::HciReadLocalSupportedCommands(packets::PacketView<true> args) {
ASSERT_LOG(args.size() == 0, "%s size=%zu", __func__, args.size());
- std::shared_ptr<packets::EventPacketBuilder> command_complete =
- packets::EventPacketBuilder::CreateCommandCompleteReadLocalSupportedCommands(hci::Status::SUCCESS,
- properties_.GetSupportedCommands());
- send_event_(command_complete->ToVector());
+
+ std::array<uint8_t, 64> supported_commands;
+ supported_commands.fill(0x00);
+ size_t len = properties_.GetSupportedCommands().size();
+ if (len > 64) {
+ len = 64;
+ }
+ std::copy_n(properties_.GetSupportedCommands().begin(), len,
+ supported_commands.begin());
+
+ auto packet =
+ bluetooth::hci::ReadLocalSupportedCommandsCompleteBuilder::Create(
+ 0x01, bluetooth::hci::ErrorCode::SUCCESS, supported_commands);
+ send_event_(std::move(packet));
}
void DualModeController::HciReadLocalSupportedFeatures(packets::PacketView<true> args) {
ASSERT_LOG(args.size() == 0, "%s size=%zu", __func__, args.size());
- std::shared_ptr<packets::EventPacketBuilder> command_complete =
- packets::EventPacketBuilder::CreateCommandCompleteReadLocalSupportedFeatures(hci::Status::SUCCESS,
- properties_.GetSupportedFeatures());
- send_event_(command_complete->ToVector());
+ auto packet =
+ bluetooth::hci::ReadLocalSupportedFeaturesCompleteBuilder::Create(
+ 0x01, bluetooth::hci::ErrorCode::SUCCESS,
+ properties_.GetSupportedFeatures());
+ send_event_(std::move(packet));
}
void DualModeController::HciReadLocalSupportedCodecs(packets::PacketView<true> args) {
ASSERT_LOG(args.size() == 0, "%s size=%zu", __func__, args.size());
- std::shared_ptr<packets::EventPacketBuilder> command_complete =
- packets::EventPacketBuilder::CreateCommandCompleteReadLocalSupportedCodecs(
- hci::Status::SUCCESS, properties_.GetSupportedCodecs(), properties_.GetVendorSpecificCodecs());
- send_event_(command_complete->ToVector());
+ auto packet = bluetooth::hci::ReadLocalSupportedCodecsCompleteBuilder::Create(
+ 0x01, bluetooth::hci::ErrorCode::SUCCESS,
+ properties_.GetSupportedCodecs(), properties_.GetVendorSpecificCodecs());
+ send_event_(std::move(packet));
}
void DualModeController::HciReadLocalExtendedFeatures(packets::PacketView<true> args) {
ASSERT_LOG(args.size() == 1, "%s size=%zu", __func__, args.size());
uint8_t page_number = args.begin().extract<uint8_t>();
- send_event_(packets::EventPacketBuilder::CreateCommandCompleteReadLocalExtendedFeatures(
- hci::Status::SUCCESS, page_number, properties_.GetExtendedFeaturesMaximumPageNumber(),
- properties_.GetExtendedFeatures(page_number))
- ->ToVector());
+
+ auto pakcet =
+ bluetooth::hci::ReadLocalExtendedFeaturesCompleteBuilder::Create(
+ 0x01, bluetooth::hci::ErrorCode::SUCCESS, page_number,
+ properties_.GetExtendedFeaturesMaximumPageNumber(),
+ properties_.GetExtendedFeatures(page_number));
+ send_event_(std::move(pakcet));
}
void DualModeController::HciReadRemoteExtendedFeatures(packets::PacketView<true> args) {
@@ -406,10 +483,11 @@
uint16_t handle = args.begin().extract<uint16_t>();
- hci::Status status =
- link_layer_controller_.SendCommandToRemoteByHandle(OpCode::READ_REMOTE_EXTENDED_FEATURES, args, handle);
+ auto status = link_layer_controller_.SendCommandToRemoteByHandle(
+ bluetooth::hci::OpCode::READ_REMOTE_EXTENDED_FEATURES, args, handle);
- SendCommandStatus(status, OpCode::READ_REMOTE_EXTENDED_FEATURES);
+ SendCommandStatus(status,
+ bluetooth::hci::OpCode::READ_REMOTE_EXTENDED_FEATURES);
}
void DualModeController::HciSwitchRole(packets::PacketView<true> args) {
@@ -418,9 +496,9 @@
Address address = args.begin().extract<Address>();
uint8_t role = args.begin().extract<uint8_t>();
- hci::Status status = link_layer_controller_.SwitchRole(address, role);
+ auto status = link_layer_controller_.SwitchRole(address, role);
- SendCommandStatus(status, OpCode::SWITCH_ROLE);
+ SendCommandStatus(status, bluetooth::hci::OpCode::SWITCH_ROLE);
}
void DualModeController::HciReadRemoteSupportedFeatures(packets::PacketView<true> args) {
@@ -428,10 +506,11 @@
uint16_t handle = args.begin().extract<uint16_t>();
- hci::Status status =
- link_layer_controller_.SendCommandToRemoteByHandle(OpCode::READ_REMOTE_SUPPORTED_FEATURES, args, handle);
+ auto status = link_layer_controller_.SendCommandToRemoteByHandle(
+ bluetooth::hci::OpCode::READ_REMOTE_SUPPORTED_FEATURES, args, handle);
- SendCommandStatus(status, OpCode::READ_REMOTE_SUPPORTED_FEATURES);
+ SendCommandStatus(status,
+ bluetooth::hci::OpCode::READ_REMOTE_SUPPORTED_FEATURES);
}
void DualModeController::HciReadClockOffset(packets::PacketView<true> args) {
@@ -439,9 +518,10 @@
uint16_t handle = args.begin().extract<uint16_t>();
- hci::Status status = link_layer_controller_.SendCommandToRemoteByHandle(OpCode::READ_CLOCK_OFFSET, args, handle);
+ auto status = link_layer_controller_.SendCommandToRemoteByHandle(
+ bluetooth::hci::OpCode::READ_CLOCK_OFFSET, args, handle);
- SendCommandStatus(status, OpCode::READ_CLOCK_OFFSET);
+ SendCommandStatus(status, bluetooth::hci::OpCode::READ_CLOCK_OFFSET);
}
void DualModeController::HciIoCapabilityRequestReply(packets::PacketView<true> args) {
@@ -453,10 +533,12 @@
uint8_t oob_data_present_flag = args_itr.extract<uint8_t>();
uint8_t authentication_requirements = args_itr.extract<uint8_t>();
- hci::Status status = link_layer_controller_.IoCapabilityRequestReply(peer, io_capability, oob_data_present_flag,
- authentication_requirements);
+ auto status = link_layer_controller_.IoCapabilityRequestReply(
+ peer, io_capability, oob_data_present_flag, authentication_requirements);
+ auto packet = bluetooth::hci::IoCapabilityRequestReplyCompleteBuilder::Create(
+ 0x01, status, peer);
- SendCommandCompleteStatusAndAddress(OpCode::IO_CAPABILITY_REQUEST_REPLY, status, peer);
+ send_event_(std::move(packet));
}
void DualModeController::HciUserConfirmationRequestReply(packets::PacketView<true> args) {
@@ -464,9 +546,12 @@
Address peer = args.begin().extract<Address>();
- hci::Status status = link_layer_controller_.UserConfirmationRequestReply(peer);
+ auto status = link_layer_controller_.UserConfirmationRequestReply(peer);
+ auto packet =
+ bluetooth::hci::UserConfirmationRequestReplyCompleteBuilder::Create(
+ 0x01, status, peer);
- SendCommandCompleteStatusAndAddress(OpCode::USER_CONFIRMATION_REQUEST_REPLY, status, peer);
+ send_event_(std::move(packet));
}
void DualModeController::HciUserConfirmationRequestNegativeReply(packets::PacketView<true> args) {
@@ -474,9 +559,13 @@
Address peer = args.begin().extract<Address>();
- hci::Status status = link_layer_controller_.UserConfirmationRequestNegativeReply(peer);
+ auto status =
+ link_layer_controller_.UserConfirmationRequestNegativeReply(peer);
+ auto packet =
+ bluetooth::hci::UserConfirmationRequestNegativeReplyCompleteBuilder::
+ Create(0x01, status, peer);
- SendCommandCompleteStatusAndAddress(OpCode::USER_CONFIRMATION_REQUEST_NEGATIVE_REPLY, status, peer);
+ send_event_(std::move(packet));
}
void DualModeController::HciUserPasskeyRequestReply(packets::PacketView<true> args) {
@@ -486,9 +575,12 @@
Address peer = args_itr.extract<Address>();
uint32_t numeric_value = args_itr.extract<uint32_t>();
- hci::Status status = link_layer_controller_.UserPasskeyRequestReply(peer, numeric_value);
+ auto status =
+ link_layer_controller_.UserPasskeyRequestReply(peer, numeric_value);
+ auto packet = bluetooth::hci::UserPasskeyRequestReplyCompleteBuilder::Create(
+ 0x01, status, peer);
- SendCommandCompleteStatusAndAddress(OpCode::USER_PASSKEY_REQUEST_REPLY, status, peer);
+ send_event_(std::move(packet));
}
void DualModeController::HciUserPasskeyRequestNegativeReply(packets::PacketView<true> args) {
@@ -496,9 +588,12 @@
Address peer = args.begin().extract<Address>();
- hci::Status status = link_layer_controller_.UserPasskeyRequestNegativeReply(peer);
+ auto status = link_layer_controller_.UserPasskeyRequestNegativeReply(peer);
+ auto packet =
+ bluetooth::hci::UserPasskeyRequestNegativeReplyCompleteBuilder::Create(
+ 0x01, status, peer);
- SendCommandCompleteStatusAndAddress(OpCode::USER_PASSKEY_REQUEST_NEGATIVE_REPLY, status, peer);
+ send_event_(std::move(packet));
}
void DualModeController::HciRemoteOobDataRequestReply(packets::PacketView<true> args) {
@@ -514,9 +609,12 @@
for (size_t i = 0; i < 16; i++) {
r.push_back(args_itr.extract<uint8_t>());
}
- hci::Status status = link_layer_controller_.RemoteOobDataRequestReply(peer, c, r);
+ auto status = link_layer_controller_.RemoteOobDataRequestReply(peer, c, r);
+ auto packet =
+ bluetooth::hci::RemoteOobDataRequestReplyCompleteBuilder::Create(
+ 0x01, status, peer);
- SendCommandCompleteStatusAndAddress(OpCode::REMOTE_OOB_DATA_REQUEST_REPLY, status, peer);
+ send_event_(std::move(packet));
}
void DualModeController::HciRemoteOobDataRequestNegativeReply(packets::PacketView<true> args) {
@@ -524,9 +622,12 @@
Address peer = args.begin().extract<Address>();
- hci::Status status = link_layer_controller_.RemoteOobDataRequestNegativeReply(peer);
+ auto status = link_layer_controller_.RemoteOobDataRequestNegativeReply(peer);
+ auto packet =
+ bluetooth::hci::RemoteOobDataRequestNegativeReplyCompleteBuilder::Create(
+ 0x01, status, peer);
- SendCommandCompleteStatusAndAddress(OpCode::REMOTE_OOB_DATA_REQUEST_NEGATIVE_REPLY, status, peer);
+ send_event_(std::move(packet));
}
void DualModeController::HciIoCapabilityRequestNegativeReply(packets::PacketView<true> args) {
@@ -536,16 +637,20 @@
Address peer = args_itr.extract<Address>();
hci::Status reason = args_itr.extract<hci::Status>();
- hci::Status status = link_layer_controller_.IoCapabilityRequestNegativeReply(peer, reason);
+ auto status =
+ link_layer_controller_.IoCapabilityRequestNegativeReply(peer, reason);
+ auto packet =
+ bluetooth::hci::IoCapabilityRequestNegativeReplyCompleteBuilder::Create(
+ 0x01, status, peer);
- SendCommandCompleteStatusAndAddress(OpCode::IO_CAPABILITY_REQUEST_NEGATIVE_REPLY, status, peer);
+ send_event_(std::move(packet));
}
void DualModeController::HciWriteSimplePairingMode(packets::PacketView<true> args) {
ASSERT_LOG(args.size() == 1, "%s size=%zu", __func__, args.size());
ASSERT(args[0] == 1 || args[0] == 0);
link_layer_controller_.WriteSimplePairingMode(args[0] == 1);
- SendCommandCompleteSuccess(OpCode::WRITE_SIMPLE_PAIRING_MODE);
+ SendCommandCompleteSuccess(bluetooth::hci::OpCode::WRITE_SIMPLE_PAIRING_MODE);
}
void DualModeController::HciChangeConnectionPacketType(packets::PacketView<true> args) {
@@ -554,49 +659,52 @@
uint16_t handle = args_itr.extract<uint16_t>();
uint16_t packet_type = args_itr.extract<uint16_t>();
- hci::Status status = link_layer_controller_.ChangeConnectionPacketType(handle, packet_type);
+ auto status =
+ link_layer_controller_.ChangeConnectionPacketType(handle, packet_type);
- SendCommandStatus(status, OpCode::CHANGE_CONNECTION_PACKET_TYPE);
+ SendCommandStatus(status,
+ bluetooth::hci::OpCode::CHANGE_CONNECTION_PACKET_TYPE);
}
void DualModeController::HciWriteLeHostSupport(packets::PacketView<true> args) {
ASSERT_LOG(args.size() == 2, "%s size=%zu", __func__, args.size());
- SendCommandCompleteSuccess(OpCode::WRITE_LE_HOST_SUPPORT);
+ SendCommandCompleteSuccess(bluetooth::hci::OpCode::WRITE_LE_HOST_SUPPORT);
}
void DualModeController::HciWriteSecureConnectionHostSupport(
packets::PacketView<true> args) {
ASSERT_LOG(args.size() == 1, "%s size=%zu", __func__, args.size());
- SendCommandCompleteSuccess(OpCode::WRITE_SECURE_CONNECTIONS_HOST_SUPPORT);
+ SendCommandCompleteSuccess(
+ bluetooth::hci::OpCode::WRITE_SECURE_CONNECTIONS_HOST_SUPPORT);
}
void DualModeController::HciSetEventMask(packets::PacketView<true> args) {
ASSERT_LOG(args.size() == 8, "%s size=%zu", __func__, args.size());
- SendCommandCompleteSuccess(OpCode::SET_EVENT_MASK);
+ SendCommandCompleteSuccess(bluetooth::hci::OpCode::SET_EVENT_MASK);
}
void DualModeController::HciWriteInquiryMode(packets::PacketView<true> args) {
ASSERT_LOG(args.size() == 1, "%s size=%zu", __func__, args.size());
link_layer_controller_.SetInquiryMode(args[0]);
- SendCommandCompleteSuccess(OpCode::WRITE_INQUIRY_MODE);
+ SendCommandCompleteSuccess(bluetooth::hci::OpCode::WRITE_INQUIRY_MODE);
}
void DualModeController::HciWritePageScanType(packets::PacketView<true> args) {
ASSERT_LOG(args.size() == 1, "%s size=%zu", __func__, args.size());
- SendCommandCompleteSuccess(OpCode::WRITE_PAGE_SCAN_TYPE);
+ SendCommandCompleteSuccess(bluetooth::hci::OpCode::WRITE_PAGE_SCAN_TYPE);
}
void DualModeController::HciWriteInquiryScanType(packets::PacketView<true> args) {
ASSERT_LOG(args.size() == 1, "%s size=%zu", __func__, args.size());
- SendCommandCompleteSuccess(OpCode::WRITE_INQUIRY_SCAN_TYPE);
+ SendCommandCompleteSuccess(bluetooth::hci::OpCode::WRITE_INQUIRY_SCAN_TYPE);
}
void DualModeController::HciAuthenticationRequested(packets::PacketView<true> args) {
ASSERT_LOG(args.size() == 2, "%s size=%zu", __func__, args.size());
uint16_t handle = args.begin().extract<uint16_t>();
- hci::Status status = link_layer_controller_.AuthenticationRequested(handle);
+ auto status = link_layer_controller_.AuthenticationRequested(handle);
- SendCommandStatus(status, OpCode::AUTHENTICATION_REQUESTED);
+ SendCommandStatus(status, bluetooth::hci::OpCode::AUTHENTICATION_REQUESTED);
}
void DualModeController::HciSetConnectionEncryption(packets::PacketView<true> args) {
@@ -604,9 +712,10 @@
auto args_itr = args.begin();
uint16_t handle = args_itr.extract<uint16_t>();
uint8_t encryption_enable = args_itr.extract<uint8_t>();
- hci::Status status = link_layer_controller_.SetConnectionEncryption(handle, encryption_enable);
+ auto status =
+ link_layer_controller_.SetConnectionEncryption(handle, encryption_enable);
- SendCommandStatus(status, OpCode::SET_CONNECTION_ENCRYPTION);
+ SendCommandStatus(status, bluetooth::hci::OpCode::SET_CONNECTION_ENCRYPTION);
}
void DualModeController::HciChangeConnectionLinkKey(packets::PacketView<true> args) {
@@ -614,9 +723,9 @@
auto args_itr = args.begin();
uint16_t handle = args_itr.extract<uint16_t>();
- hci::Status status = link_layer_controller_.ChangeConnectionLinkKey(handle);
+ auto status = link_layer_controller_.ChangeConnectionLinkKey(handle);
- SendCommandStatus(status, OpCode::CHANGE_CONNECTION_LINK_KEY);
+ SendCommandStatus(status, bluetooth::hci::OpCode::CHANGE_CONNECTION_LINK_KEY);
}
void DualModeController::HciMasterLinkKey(packets::PacketView<true> args) {
@@ -624,34 +733,36 @@
auto args_itr = args.begin();
uint8_t key_flag = args_itr.extract<uint8_t>();
- hci::Status status = link_layer_controller_.MasterLinkKey(key_flag);
+ auto status = link_layer_controller_.MasterLinkKey(key_flag);
- SendCommandStatus(status, OpCode::MASTER_LINK_KEY);
+ SendCommandStatus(status, bluetooth::hci::OpCode::MASTER_LINK_KEY);
}
void DualModeController::HciWriteAuthenticationEnable(packets::PacketView<true> args) {
ASSERT_LOG(args.size() == 1, "%s size=%zu", __func__, args.size());
properties_.SetAuthenticationEnable(args[0]);
- SendCommandCompleteSuccess(OpCode::WRITE_AUTHENTICATION_ENABLE);
+ SendCommandCompleteSuccess(
+ bluetooth::hci::OpCode::WRITE_AUTHENTICATION_ENABLE);
}
void DualModeController::HciReadAuthenticationEnable(packets::PacketView<true> args) {
ASSERT_LOG(args.size() == 0, "%s size=%zu", __func__, args.size());
- std::shared_ptr<packets::EventPacketBuilder> command_complete =
- packets::EventPacketBuilder::CreateCommandCompleteReadAuthenticationEnable(hci::Status::SUCCESS,
- properties_.GetAuthenticationEnable());
- send_event_(command_complete->ToVector());
+ auto packet = bluetooth::hci::ReadAuthenticationEnableCompleteBuilder::Create(
+ 0x01, bluetooth::hci::ErrorCode::SUCCESS,
+ static_cast<bluetooth::hci::AuthenticationEnable>(
+ properties_.GetAuthenticationEnable()));
+ send_event_(std::move(packet));
}
void DualModeController::HciWriteClassOfDevice(packets::PacketView<true> args) {
ASSERT_LOG(args.size() == 3, "%s size=%zu", __func__, args.size());
properties_.SetClassOfDevice(args[0], args[1], args[2]);
- SendCommandCompleteSuccess(OpCode::WRITE_CLASS_OF_DEVICE);
+ SendCommandCompleteSuccess(bluetooth::hci::OpCode::WRITE_CLASS_OF_DEVICE);
}
void DualModeController::HciWritePageTimeout(packets::PacketView<true> args) {
ASSERT_LOG(args.size() == 2, "%s size=%zu", __func__, args.size());
- SendCommandCompleteSuccess(OpCode::WRITE_PAGE_TIMEOUT);
+ SendCommandCompleteSuccess(bluetooth::hci::OpCode::WRITE_PAGE_TIMEOUT);
}
void DualModeController::HciHoldMode(packets::PacketView<true> args) {
@@ -661,9 +772,10 @@
uint16_t hold_mode_max_interval = args_itr.extract<uint16_t>();
uint16_t hold_mode_min_interval = args_itr.extract<uint16_t>();
- hci::Status status = link_layer_controller_.HoldMode(handle, hold_mode_max_interval, hold_mode_min_interval);
+ auto status = link_layer_controller_.HoldMode(handle, hold_mode_max_interval,
+ hold_mode_min_interval);
- SendCommandStatus(status, OpCode::HOLD_MODE);
+ SendCommandStatus(status, bluetooth::hci::OpCode::HOLD_MODE);
}
void DualModeController::HciSniffMode(packets::PacketView<true> args) {
@@ -675,10 +787,11 @@
uint16_t sniff_attempt = args_itr.extract<uint16_t>();
uint16_t sniff_timeout = args_itr.extract<uint16_t>();
- hci::Status status =
- link_layer_controller_.SniffMode(handle, sniff_max_interval, sniff_min_interval, sniff_attempt, sniff_timeout);
+ auto status = link_layer_controller_.SniffMode(handle, sniff_max_interval,
+ sniff_min_interval,
+ sniff_attempt, sniff_timeout);
- SendCommandStatus(status, OpCode::SNIFF_MODE);
+ SendCommandStatus(status, bluetooth::hci::OpCode::SNIFF_MODE);
}
void DualModeController::HciExitSniffMode(packets::PacketView<true> args) {
@@ -686,9 +799,9 @@
auto args_itr = args.begin();
uint16_t handle = args_itr.extract<uint16_t>();
- hci::Status status = link_layer_controller_.ExitSniffMode(handle);
+ auto status = link_layer_controller_.ExitSniffMode(handle);
- SendCommandStatus(status, OpCode::EXIT_SNIFF_MODE);
+ SendCommandStatus(status, bluetooth::hci::OpCode::EXIT_SNIFF_MODE);
}
void DualModeController::HciQosSetup(packets::PacketView<true> args) {
@@ -702,15 +815,17 @@
uint32_t latency = args_itr.extract<uint32_t>();
uint32_t delay_variation = args_itr.extract<uint32_t>();
- hci::Status status =
- link_layer_controller_.QosSetup(handle, service_type, token_rate, peak_bandwidth, latency, delay_variation);
+ auto status =
+ link_layer_controller_.QosSetup(handle, service_type, token_rate,
+ peak_bandwidth, latency, delay_variation);
- SendCommandStatus(status, OpCode::QOS_SETUP);
+ SendCommandStatus(status, bluetooth::hci::OpCode::QOS_SETUP);
}
void DualModeController::HciWriteDefaultLinkPolicySettings(packets::PacketView<true> args) {
ASSERT_LOG(args.size() == 2, "%s size=%zu", __func__, args.size());
- SendCommandCompleteSuccess(OpCode::WRITE_DEFAULT_LINK_POLICY_SETTINGS);
+ SendCommandCompleteSuccess(
+ bluetooth::hci::OpCode::WRITE_DEFAULT_LINK_POLICY_SETTINGS);
}
void DualModeController::HciFlowSpecification(packets::PacketView<true> args) {
@@ -725,10 +840,11 @@
uint32_t peak_bandwidth = args_itr.extract<uint32_t>();
uint32_t access_latency = args_itr.extract<uint32_t>();
- hci::Status status = link_layer_controller_.FlowSpecification(handle, flow_direction, service_type, token_rate,
- token_bucket_size, peak_bandwidth, access_latency);
+ auto status = link_layer_controller_.FlowSpecification(
+ handle, flow_direction, service_type, token_rate, token_bucket_size,
+ peak_bandwidth, access_latency);
- SendCommandStatus(status, OpCode::FLOW_SPECIFICATION);
+ SendCommandStatus(status, bluetooth::hci::OpCode::FLOW_SPECIFICATION);
}
void DualModeController::HciWriteLinkPolicySettings(packets::PacketView<true> args) {
@@ -738,9 +854,12 @@
uint16_t handle = args_itr.extract<uint16_t>();
uint16_t settings = args_itr.extract<uint16_t>();
- hci::Status status = link_layer_controller_.WriteLinkPolicySettings(handle, settings);
+ auto status =
+ link_layer_controller_.WriteLinkPolicySettings(handle, settings);
- send_event_(packets::EventPacketBuilder::CreateCommandCompleteWriteLinkPolicySettings(status, handle)->ToVector());
+ auto packet = bluetooth::hci::WriteLinkPolicySettingsCompleteBuilder::Create(
+ 0x01, status, handle);
+ send_event_(std::move(packet));
}
void DualModeController::HciWriteLinkSupervisionTimeout(packets::PacketView<true> args) {
@@ -750,24 +869,35 @@
uint16_t handle = args_itr.extract<uint16_t>();
uint16_t timeout = args_itr.extract<uint16_t>();
- hci::Status status = link_layer_controller_.WriteLinkSupervisionTimeout(handle, timeout);
-
- send_event_(
- packets::EventPacketBuilder::CreateCommandCompleteWriteLinkSupervisionTimeout(status, handle)->ToVector());
+ auto status =
+ link_layer_controller_.WriteLinkSupervisionTimeout(handle, timeout);
+ auto packet =
+ bluetooth::hci::WriteLinkSupervisionTimeoutCompleteBuilder::Create(
+ 0x01, status, handle);
+ send_event_(std::move(packet));
}
void DualModeController::HciReadLocalName(packets::PacketView<true> args) {
ASSERT_LOG(args.size() == 0, "%s size=%zu", __func__, args.size());
- std::shared_ptr<packets::EventPacketBuilder> command_complete =
- packets::EventPacketBuilder::CreateCommandCompleteReadLocalName(hci::Status::SUCCESS, properties_.GetName());
- send_event_(command_complete->ToVector());
+
+ std::array<uint8_t, 248> local_name;
+ local_name.fill(0x00);
+ size_t len = properties_.GetName().size();
+ if (len > 247) {
+ len = 247; // one byte for NULL octet (0x00)
+ }
+ std::copy_n(properties_.GetName().begin(), len, local_name.begin());
+
+ auto packet = bluetooth::hci::ReadLocalNameCompleteBuilder::Create(
+ 0x01, bluetooth::hci::ErrorCode::SUCCESS, local_name);
+ send_event_(std::move(packet));
}
void DualModeController::HciWriteLocalName(packets::PacketView<true> args) {
ASSERT_LOG(args.size() == 248, "%s size=%zu", __func__, args.size());
std::vector<uint8_t> clipped(args.begin(), args.begin() + LastNonZero(args) + 1);
properties_.SetName(clipped);
- SendCommandCompleteSuccess(OpCode::WRITE_LOCAL_NAME);
+ SendCommandCompleteSuccess(bluetooth::hci::OpCode::WRITE_LOCAL_NAME);
}
void DualModeController::HciWriteExtendedInquiryResponse(packets::PacketView<true> args) {
@@ -777,46 +907,49 @@
properties_.SetExtendedInquiryData(clipped);
LOG_WARN("Write EIR Inquiry - Size = %d (%d)", static_cast<int>(properties_.GetExtendedInquiryData().size()),
static_cast<int>(clipped.size()));
- SendCommandCompleteSuccess(OpCode::WRITE_EXTENDED_INQUIRY_RESPONSE);
+ SendCommandCompleteSuccess(
+ bluetooth::hci::OpCode::WRITE_EXTENDED_INQUIRY_RESPONSE);
}
void DualModeController::HciRefreshEncryptionKey(packets::PacketView<true> args) {
ASSERT_LOG(args.size() == 2, "%s size=%zu", __func__, args.size());
auto args_itr = args.begin();
uint16_t handle = args_itr.extract<uint16_t>();
- SendCommandStatusSuccess(OpCode::REFRESH_ENCRYPTION_KEY);
+ SendCommandStatusSuccess(bluetooth::hci::OpCode::REFRESH_ENCRYPTION_KEY);
// TODO: Support this in the link layer
- hci::Status status = hci::Status::SUCCESS;
- send_event_(packets::EventPacketBuilder::CreateEncryptionKeyRefreshCompleteEvent(status, handle)->ToVector());
+ auto packet = bluetooth::hci::EncryptionKeyRefreshCompleteBuilder::Create(
+ bluetooth::hci::ErrorCode::SUCCESS, handle);
+ send_event_(std::move(packet));
}
void DualModeController::HciWriteVoiceSetting(packets::PacketView<true> args) {
ASSERT_LOG(args.size() == 2, "%s size=%zu", __func__, args.size());
- SendCommandCompleteSuccess(OpCode::WRITE_VOICE_SETTING);
+ SendCommandCompleteSuccess(bluetooth::hci::OpCode::WRITE_VOICE_SETTING);
}
void DualModeController::HciWriteCurrentIacLap(packets::PacketView<true> args) {
ASSERT(args.size() > 0);
ASSERT(args.size() == 1 + (3 * args[0])); // count + 3-byte IACs
- SendCommandCompleteSuccess(OpCode::WRITE_CURRENT_IAC_LAP);
+ SendCommandCompleteSuccess(bluetooth::hci::OpCode::WRITE_CURRENT_IAC_LAP);
}
void DualModeController::HciWriteInquiryScanActivity(packets::PacketView<true> args) {
ASSERT_LOG(args.size() == 4, "%s size=%zu", __func__, args.size());
- SendCommandCompleteSuccess(OpCode::WRITE_INQUIRY_SCAN_ACTIVITY);
+ SendCommandCompleteSuccess(
+ bluetooth::hci::OpCode::WRITE_INQUIRY_SCAN_ACTIVITY);
}
void DualModeController::HciWriteScanEnable(packets::PacketView<true> args) {
ASSERT_LOG(args.size() == 1, "%s size=%zu", __func__, args.size());
link_layer_controller_.SetInquiryScanEnable(args[0] & 0x1);
link_layer_controller_.SetPageScanEnable(args[0] & 0x2);
- SendCommandCompleteSuccess(OpCode::WRITE_SCAN_ENABLE);
+ SendCommandCompleteSuccess(bluetooth::hci::OpCode::WRITE_SCAN_ENABLE);
}
void DualModeController::HciSetEventFilter(packets::PacketView<true> args) {
ASSERT(args.size() > 0);
- SendCommandCompleteSuccess(OpCode::SET_EVENT_FILTER);
+ SendCommandCompleteSuccess(bluetooth::hci::OpCode::SET_EVENT_FILTER);
}
void DualModeController::HciInquiry(packets::PacketView<true> args) {
@@ -825,21 +958,22 @@
link_layer_controller_.SetInquiryMaxResponses(args[4]);
link_layer_controller_.StartInquiry(std::chrono::milliseconds(args[3] * 1280));
- SendCommandStatusSuccess(OpCode::INQUIRY);
+ SendCommandStatusSuccess(bluetooth::hci::OpCode::INQUIRY);
}
void DualModeController::HciInquiryCancel(packets::PacketView<true> args) {
ASSERT_LOG(args.size() == 0, "%s size=%zu", __func__, args.size());
link_layer_controller_.InquiryCancel();
- SendCommandCompleteSuccess(OpCode::INQUIRY_CANCEL);
+ SendCommandCompleteSuccess(bluetooth::hci::OpCode::INQUIRY_CANCEL);
}
void DualModeController::HciAcceptConnectionRequest(packets::PacketView<true> args) {
ASSERT_LOG(args.size() == 7, "%s size=%zu", __func__, args.size());
Address addr = args.begin().extract<Address>();
bool try_role_switch = args[6] == 0;
- hci::Status status = link_layer_controller_.AcceptConnectionRequest(addr, try_role_switch);
- SendCommandStatus(status, OpCode::ACCEPT_CONNECTION_REQUEST);
+ auto status =
+ link_layer_controller_.AcceptConnectionRequest(addr, try_role_switch);
+ SendCommandStatus(status, bluetooth::hci::OpCode::ACCEPT_CONNECTION_REQUEST);
}
void DualModeController::HciRejectConnectionRequest(packets::PacketView<true> args) {
@@ -847,23 +981,28 @@
auto args_itr = args.begin();
Address addr = args_itr.extract<Address>();
uint8_t reason = args_itr.extract<uint8_t>();
- hci::Status status = link_layer_controller_.RejectConnectionRequest(addr, reason);
- SendCommandStatus(status, OpCode::REJECT_CONNECTION_REQUEST);
+ auto status = link_layer_controller_.RejectConnectionRequest(addr, reason);
+ SendCommandStatus(status, bluetooth::hci::OpCode::REJECT_CONNECTION_REQUEST);
}
void DualModeController::HciLinkKeyRequestReply(packets::PacketView<true> args) {
ASSERT_LOG(args.size() == 22, "%s size=%zu", __func__, args.size());
Address addr = args.begin().extract<Address>();
packets::PacketView<true> key = args.SubViewLittleEndian(6, 22);
- hci::Status status = link_layer_controller_.LinkKeyRequestReply(addr, key);
- send_event_(packets::EventPacketBuilder::CreateCommandCompleteLinkKeyRequestReply(status, addr)->ToVector());
+ auto status = link_layer_controller_.LinkKeyRequestReply(addr, key);
+ auto packet =
+ bluetooth::hci::LinkKeyRequestReplyCompleteBuilder::Create(0x01, status);
+ send_event_(std::move(packet));
}
void DualModeController::HciLinkKeyRequestNegativeReply(packets::PacketView<true> args) {
ASSERT_LOG(args.size() == 6, "%s size=%zu", __func__, args.size());
Address addr = args.begin().extract<Address>();
- hci::Status status = link_layer_controller_.LinkKeyRequestNegativeReply(addr);
- send_event_(packets::EventPacketBuilder::CreateCommandCompleteLinkKeyRequestNegativeReply(status, addr)->ToVector());
+ auto status = link_layer_controller_.LinkKeyRequestNegativeReply(addr);
+ auto packet =
+ bluetooth::hci::LinkKeyRequestNegativeReplyCompleteBuilder::Create(
+ 0x01, status, addr);
+ send_event_(std::move(packet));
}
void DualModeController::HciDeleteStoredLinkKey(packets::PacketView<true> args) {
@@ -880,8 +1019,10 @@
security_manager_.DeleteAllKeys();
}
- send_event_(packets::EventPacketBuilder::CreateCommandCompleteDeleteStoredLinkKey(hci::Status::SUCCESS, deleted_keys)
- ->ToVector());
+ auto packet = bluetooth::hci::DeleteStoredLinkKeyCompleteBuilder::Create(
+ 0x01, bluetooth::hci::ErrorCode::SUCCESS, deleted_keys);
+
+ send_event_(std::move(packet));
}
void DualModeController::HciRemoteNameRequest(packets::PacketView<true> args) {
@@ -889,10 +1030,10 @@
Address remote_addr = args.begin().extract<Address>();
- hci::Status status =
- link_layer_controller_.SendCommandToRemoteByAddress(OpCode::REMOTE_NAME_REQUEST, args, remote_addr, false);
+ auto status = link_layer_controller_.SendCommandToRemoteByAddress(
+ bluetooth::hci::OpCode::REMOTE_NAME_REQUEST, args, remote_addr, false);
- SendCommandStatus(status, OpCode::REMOTE_NAME_REQUEST);
+ SendCommandStatus(status, bluetooth::hci::OpCode::REMOTE_NAME_REQUEST);
}
void DualModeController::HciLeSetEventMask(packets::PacketView<true> args) {
@@ -901,29 +1042,38 @@
uint64_t mask = args.begin().extract<uint64_t>();
link_layer_controller_.SetLeEventMask(mask);
*/
- SendCommandCompleteSuccess(OpCode::LE_SET_EVENT_MASK);
+ SendCommandCompleteSuccess(bluetooth::hci::OpCode::LE_SET_EVENT_MASK);
}
void DualModeController::HciLeReadBufferSize(packets::PacketView<true> args) {
ASSERT_LOG(args.size() == 0, "%s size=%zu", __func__, args.size());
- std::shared_ptr<packets::EventPacketBuilder> command_complete =
- packets::EventPacketBuilder::CreateCommandCompleteLeReadBufferSize(
- hci::Status::SUCCESS, properties_.GetLeDataPacketLength(), properties_.GetTotalNumLeDataPackets());
- send_event_(command_complete->ToVector());
+
+ std::unique_ptr<bluetooth::packet::RawBuilder> raw_builder_ptr =
+ std::make_unique<bluetooth::packet::RawBuilder>();
+ raw_builder_ptr->AddOctets1(
+ static_cast<uint8_t>(bluetooth::hci::ErrorCode::SUCCESS));
+ raw_builder_ptr->AddOctets2(properties_.GetLeDataPacketLength());
+ raw_builder_ptr->AddOctets1(properties_.GetTotalNumLeDataPackets());
+
+ auto packet = bluetooth::hci::CommandCompleteBuilder::Create(
+ 0x01, bluetooth::hci::OpCode::LE_READ_BUFFER_SIZE,
+ std::move(raw_builder_ptr));
+ send_event_(std::move(packet));
}
void DualModeController::HciLeReadLocalSupportedFeatures(packets::PacketView<true> args) {
ASSERT_LOG(args.size() == 0, "%s size=%zu", __func__, args.size());
- std::shared_ptr<packets::EventPacketBuilder> command_complete =
- packets::EventPacketBuilder::CreateCommandCompleteLeReadLocalSupportedFeatures(
- hci::Status::SUCCESS, properties_.GetLeSupportedFeatures());
- send_event_(command_complete->ToVector());
+ auto packet =
+ bluetooth::hci::LeReadLocalSupportedFeaturesCompleteBuilder::Create(
+ 0x01, bluetooth::hci::ErrorCode::SUCCESS,
+ properties_.GetLeSupportedFeatures());
+ send_event_(std::move(packet));
}
void DualModeController::HciLeSetRandomAddress(packets::PacketView<true> args) {
ASSERT_LOG(args.size() == 6, "%s size=%zu", __func__, args.size());
properties_.SetLeAddress(args.begin().extract<Address>());
- SendCommandCompleteSuccess(OpCode::LE_SET_RANDOM_ADDRESS);
+ SendCommandCompleteSuccess(bluetooth::hci::OpCode::LE_SET_RANDOM_ADDRESS);
}
void DualModeController::HciLeSetAdvertisingParameters(packets::PacketView<true> args) {
@@ -937,25 +1087,28 @@
args_itr.extract<uint8_t>() /* AdvertisingFilterPolicy */
);
- SendCommandCompleteSuccess(OpCode::LE_SET_ADVERTISING_PARAMETERS);
+ SendCommandCompleteSuccess(
+ bluetooth::hci::OpCode::LE_SET_ADVERTISING_PARAMETERS);
}
void DualModeController::HciLeSetAdvertisingData(packets::PacketView<true> args) {
ASSERT_LOG(args.size() == 32, "%s size=%zu", __func__, args.size());
properties_.SetLeAdvertisement(std::vector<uint8_t>(args.begin() + 1, args.end()));
- SendCommandCompleteSuccess(OpCode::LE_SET_ADVERTISING_DATA);
+ SendCommandCompleteSuccess(bluetooth::hci::OpCode::LE_SET_ADVERTISING_DATA);
}
void DualModeController::HciLeSetScanResponseData(packets::PacketView<true> args) {
ASSERT_LOG(args.size() == 32, "%s size=%zu", __func__, args.size());
properties_.SetLeScanResponse(std::vector<uint8_t>(args.begin() + 1, args.end()));
- SendCommandCompleteSuccess(OpCode::LE_SET_SCAN_RESPONSE_DATA);
+ SendCommandCompleteSuccess(bluetooth::hci::OpCode::LE_SET_SCAN_RESPONSE_DATA);
}
void DualModeController::HciLeSetAdvertisingEnable(packets::PacketView<true> args) {
ASSERT_LOG(args.size() == 1, "%s size=%zu", __func__, args.size());
- hci::Status status = link_layer_controller_.SetLeAdvertisingEnable(args.begin().extract<uint8_t>());
- SendCommandCompleteOnlyStatus(OpCode::LE_SET_ADVERTISING_ENABLE, status);
+ auto status = link_layer_controller_.SetLeAdvertisingEnable(
+ args.begin().extract<uint8_t>());
+ SendCommandCompleteOnlyStatus(
+ bluetooth::hci::OpCode::LE_SET_ADVERTISING_ENABLE, status);
}
void DualModeController::HciLeSetScanParameters(packets::PacketView<true> args) {
@@ -965,7 +1118,7 @@
link_layer_controller_.SetLeScanWindow(args[3] | (args[4], 8));
link_layer_controller_.SetLeAddressType(args[5]);
link_layer_controller_.SetLeScanFilterPolicy(args[6]);
- SendCommandCompleteSuccess(OpCode::LE_SET_SCAN_PARAMETERS);
+ SendCommandCompleteSuccess(bluetooth::hci::OpCode::LE_SET_SCAN_PARAMETERS);
}
void DualModeController::HciLeSetScanEnable(packets::PacketView<true> args) {
@@ -973,7 +1126,7 @@
LOG_INFO("SetScanEnable: %d %d", args[0], args[1]);
link_layer_controller_.SetLeScanEnable(args[0]);
link_layer_controller_.SetLeFilterDuplicates(args[1]);
- SendCommandCompleteSuccess(OpCode::LE_SET_SCAN_ENABLE);
+ SendCommandCompleteSuccess(bluetooth::hci::OpCode::LE_SET_SCAN_ENABLE);
}
void DualModeController::HciLeCreateConnection(packets::PacketView<true> args) {
@@ -998,19 +1151,20 @@
link_layer_controller_.SetLeMinimumCeLength(args_itr.extract<uint16_t>());
link_layer_controller_.SetLeMaximumCeLength(args_itr.extract<uint16_t>());
- hci::Status status = link_layer_controller_.SetLeConnect(true);
+ auto status = link_layer_controller_.SetLeConnect(true);
- SendCommandStatus(status, OpCode::LE_CREATE_CONNECTION);
+ SendCommandStatus(status, bluetooth::hci::OpCode::LE_CREATE_CONNECTION);
}
void DualModeController::HciLeConnectionUpdate(packets::PacketView<true> args) {
ASSERT_LOG(args.size() == 14, "%s size=%zu", __func__, args.size());
- SendCommandStatus(hci::Status::CONNECTION_REJECTED_UNACCEPTABLE_BD_ADDR, OpCode::LE_CONNECTION_UPDATE);
+ SendCommandStatus(
+ bluetooth::hci::ErrorCode::CONNECTION_REJECTED_UNACCEPTABLE_BD_ADDR,
+ bluetooth::hci::OpCode::LE_CONNECTION_UPDATE);
- send_event_(packets::EventPacketBuilder::CreateLeConnectionUpdateCompleteEvent(hci::Status::SUCCESS, 0x0002, 0x0006,
- 0x0000, 0x01f4)
- ->ToVector());
+ auto packet = bluetooth::hci::LeConnectionUpdateCompleteBuilder::Create(
+ bluetooth::hci::ErrorCode::SUCCESS, 0x0002, 0x0006, 0x0000, 0x01f4);
}
void DualModeController::HciCreateConnection(packets::PacketView<true> args) {
@@ -1023,10 +1177,10 @@
uint16_t clock_offset = args_itr.extract<uint16_t>();
uint8_t allow_role_switch = args_itr.extract<uint8_t>();
- hci::Status status =
- link_layer_controller_.CreateConnection(address, packet_type, page_scan_mode, clock_offset, allow_role_switch);
+ auto status = link_layer_controller_.CreateConnection(
+ address, packet_type, page_scan_mode, clock_offset, allow_role_switch);
- SendCommandStatus(status, OpCode::CREATE_CONNECTION);
+ SendCommandStatus(status, bluetooth::hci::OpCode::CREATE_CONNECTION);
}
void DualModeController::HciDisconnect(packets::PacketView<true> args) {
@@ -1036,49 +1190,52 @@
uint16_t handle = args_itr.extract<uint16_t>();
uint8_t reason = args_itr.extract<uint8_t>();
- hci::Status status = link_layer_controller_.Disconnect(handle, reason);
+ auto status = link_layer_controller_.Disconnect(handle, reason);
- SendCommandStatus(status, OpCode::DISCONNECT);
+ SendCommandStatus(status, bluetooth::hci::OpCode::DISCONNECT);
}
void DualModeController::HciLeConnectionCancel(packets::PacketView<true> args) {
ASSERT_LOG(args.size() == 0, "%s size=%zu", __func__, args.size());
link_layer_controller_.SetLeConnect(false);
- SendCommandStatusSuccess(OpCode::LE_CREATE_CONNECTION_CANCEL);
+ SendCommandStatusSuccess(bluetooth::hci::OpCode::LE_CREATE_CONNECTION_CANCEL);
/* For testing Jakub's patch: Figure out a neat way to call this without
recompiling. I'm thinking about a bad device. */
/*
SendCommandCompleteOnlyStatus(OpCode::LE_CREATE_CONNECTION_CANCEL,
- Status::ERR_COMMAND_DISALLOWED);
+ bluetooth::hci::ErrorCode::COMMAND_DISALLOWED);
*/
}
void DualModeController::HciLeReadWhiteListSize(packets::PacketView<true> args) {
ASSERT_LOG(args.size() == 0, "%s size=%zu", __func__, args.size());
- std::shared_ptr<packets::EventPacketBuilder> command_complete =
- packets::EventPacketBuilder::CreateCommandCompleteLeReadWhiteListSize(hci::Status::SUCCESS,
- properties_.GetLeWhiteListSize());
- send_event_(command_complete->ToVector());
+ auto packet = bluetooth::hci::LeReadWhiteListSizeCompleteBuilder::Create(
+ 0x01, bluetooth::hci::ErrorCode::SUCCESS,
+ properties_.GetLeWhiteListSize());
+ send_event_(std::move(packet));
}
void DualModeController::HciLeClearWhiteList(packets::PacketView<true> args) {
ASSERT_LOG(args.size() == 0, "%s size=%zu", __func__, args.size());
link_layer_controller_.LeWhiteListClear();
- SendCommandCompleteSuccess(OpCode::LE_CLEAR_WHITE_LIST);
+ SendCommandCompleteSuccess(bluetooth::hci::OpCode::LE_CLEAR_WHITE_LIST);
}
void DualModeController::HciLeAddDeviceToWhiteList(packets::PacketView<true> args) {
ASSERT_LOG(args.size() == 7, "%s size=%zu", __func__, args.size());
if (link_layer_controller_.LeWhiteListFull()) {
- SendCommandCompleteOnlyStatus(OpCode::LE_ADD_DEVICE_TO_WHITE_LIST, hci::Status::MEMORY_CAPACITY_EXCEEDED);
+ SendCommandCompleteOnlyStatus(
+ bluetooth::hci::OpCode::LE_ADD_DEVICE_TO_WHITE_LIST,
+ bluetooth::hci::ErrorCode::MEMORY_CAPACITY_EXCEEDED);
return;
}
auto args_itr = args.begin();
uint8_t addr_type = args_itr.extract<uint8_t>();
Address address = args_itr.extract<Address>();
link_layer_controller_.LeWhiteListAddDevice(address, addr_type);
- SendCommandCompleteSuccess(OpCode::LE_ADD_DEVICE_TO_WHITE_LIST);
+ SendCommandCompleteSuccess(
+ bluetooth::hci::OpCode::LE_ADD_DEVICE_TO_WHITE_LIST);
}
void DualModeController::HciLeRemoveDeviceFromWhiteList(packets::PacketView<true> args) {
@@ -1088,14 +1245,15 @@
uint8_t addr_type = args_itr.extract<uint8_t>();
Address address = args_itr.extract<Address>();
link_layer_controller_.LeWhiteListRemoveDevice(address, addr_type);
- SendCommandCompleteSuccess(OpCode::LE_REMOVE_DEVICE_FROM_WHITE_LIST);
+ SendCommandCompleteSuccess(
+ bluetooth::hci::OpCode::LE_REMOVE_DEVICE_FROM_WHITE_LIST);
}
void DualModeController::HciLeClearResolvingList(
packets::PacketView<true> args) {
ASSERT_LOG(args.size() == 0, "%s size=%zu", __func__, args.size());
link_layer_controller_.LeResolvingListClear();
- SendCommandCompleteSuccess(OpCode::LE_CLEAR_RESOLVING_LIST);
+ SendCommandCompleteSuccess(bluetooth::hci::OpCode::LE_CLEAR_RESOLVING_LIST);
}
void DualModeController::HciLeAddDeviceToResolvingList(
@@ -1103,8 +1261,9 @@
ASSERT_LOG(args.size() == 39, "%s size=%zu", __func__, args.size());
if (link_layer_controller_.LeResolvingListFull()) {
- SendCommandCompleteOnlyStatus(OpCode::LE_ADD_DEVICE_TO_RESOLVING_LIST,
- hci::Status::MEMORY_CAPACITY_EXCEEDED);
+ SendCommandCompleteOnlyStatus(
+ bluetooth::hci::OpCode::LE_ADD_DEVICE_TO_RESOLVING_LIST,
+ bluetooth::hci::ErrorCode::MEMORY_CAPACITY_EXCEEDED);
return;
}
auto args_itr = args.begin();
@@ -1124,7 +1283,8 @@
link_layer_controller_.LeResolvingListAddDevice(address, addr_type, peerIrk,
localIrk);
- SendCommandCompleteSuccess(OpCode::LE_ADD_DEVICE_TO_RESOLVING_LIST);
+ SendCommandCompleteSuccess(
+ bluetooth::hci::OpCode::LE_ADD_DEVICE_TO_RESOLVING_LIST);
}
void DualModeController::HciLeRemoveDeviceFromResolvingList(
@@ -1135,7 +1295,8 @@
uint8_t addr_type = args_itr.extract<uint8_t>();
Address address = args_itr.extract<Address>();
link_layer_controller_.LeResolvingListRemoveDevice(address, addr_type);
- SendCommandCompleteSuccess(OpCode::LE_REMOVE_DEVICE_FROM_RESOLVING_LIST);
+ SendCommandCompleteSuccess(
+ bluetooth::hci::OpCode::LE_REMOVE_DEVICE_FROM_RESOLVING_LIST);
}
void DualModeController::HciLeSetPrivacyMode(packets::PacketView<true> args) {
@@ -1152,28 +1313,18 @@
peer_identity_address_type, peer_identity_address, privacy_mode);
}
- SendCommandCompleteSuccess(OpCode::LE_SET_PRIVACY_MODE);
+ SendCommandCompleteSuccess(bluetooth::hci::OpCode::LE_SET_PRIVACY_MODE);
}
-/*
-void DualModeController::HciLeReadRemoteUsedFeaturesRsp(uint16_t handle,
- uint64_t features) {
- std::shared_ptr<packets::EventPacketBuilder> event =
- packets::EventPacketBuilder::CreateLeRemoteUsedFeaturesEvent(
- hci::Status::SUCCESS, handle, features);
- send_event_(event->ToVector());
-}
-*/
-
void DualModeController::HciLeReadRemoteFeatures(packets::PacketView<true> args) {
ASSERT_LOG(args.size() == 2, "%s size=%zu", __func__, args.size());
uint16_t handle = args.begin().extract<uint16_t>();
- hci::Status status =
- link_layer_controller_.SendCommandToRemoteByHandle(OpCode::LE_READ_REMOTE_FEATURES, args, handle);
+ auto status = link_layer_controller_.SendCommandToRemoteByHandle(
+ bluetooth::hci::OpCode::LE_READ_REMOTE_FEATURES, args, handle);
- SendCommandStatus(status, OpCode::LE_READ_REMOTE_FEATURES);
+ SendCommandStatus(status, bluetooth::hci::OpCode::LE_READ_REMOTE_FEATURES);
}
void DualModeController::HciLeRand(packets::PacketView<true> args) {
@@ -1182,51 +1333,64 @@
for (size_t rand_bytes = 0; rand_bytes < sizeof(uint64_t); rand_bytes += sizeof(RAND_MAX)) {
random_val = (random_val << (8 * sizeof(RAND_MAX))) | random();
}
- std::shared_ptr<packets::EventPacketBuilder> command_complete =
- packets::EventPacketBuilder::CreateCommandCompleteLeRand(hci::Status::SUCCESS, random_val);
- send_event_(command_complete->ToVector());
+
+ auto packet = bluetooth::hci::LeRandCompleteBuilder::Create(
+ 0x01, bluetooth::hci::ErrorCode::SUCCESS, random_val);
+ send_event_(std::move(packet));
}
void DualModeController::HciLeReadSupportedStates(packets::PacketView<true> args) {
ASSERT_LOG(args.size() == 0, "%s size=%zu", __func__, args.size());
- std::shared_ptr<packets::EventPacketBuilder> command_complete =
- packets::EventPacketBuilder::CreateCommandCompleteLeReadSupportedStates(hci::Status::SUCCESS,
- properties_.GetLeSupportedStates());
- send_event_(command_complete->ToVector());
+ auto packet = bluetooth::hci::LeReadSupportedStatesCompleteBuilder::Create(
+ 0x01, bluetooth::hci::ErrorCode::SUCCESS,
+ properties_.GetLeSupportedStates());
+ send_event_(std::move(packet));
}
void DualModeController::HciLeVendorCap(packets::PacketView<true> args) {
ASSERT_LOG(args.size() == 0, "%s size=%zu", __func__, args.size());
vector<uint8_t> caps = properties_.GetLeVendorCap();
if (caps.size() == 0) {
- SendCommandCompleteOnlyStatus(OpCode::LE_GET_VENDOR_CAPABILITIES, hci::Status::UNKNOWN_COMMAND);
+ SendCommandCompleteOnlyStatus(
+ bluetooth::hci::OpCode::LE_GET_VENDOR_CAPABILITIES,
+ bluetooth::hci::ErrorCode::UNKNOWN_HCI_COMMAND);
return;
}
- std::shared_ptr<packets::EventPacketBuilder> command_complete =
- packets::EventPacketBuilder::CreateCommandCompleteLeGetVendorCapabilities(hci::Status::SUCCESS,
- properties_.GetLeVendorCap());
- send_event_(command_complete->ToVector());
+ std::unique_ptr<bluetooth::packet::RawBuilder> raw_builder_ptr =
+ std::make_unique<bluetooth::packet::RawBuilder>();
+ raw_builder_ptr->AddOctets1(
+ static_cast<uint8_t>(bluetooth::hci::ErrorCode::SUCCESS));
+ raw_builder_ptr->AddOctets(properties_.GetLeVendorCap());
+
+ auto packet = bluetooth::hci::CommandCompleteBuilder::Create(
+ 0x01, bluetooth::hci::OpCode::LE_GET_VENDOR_CAPABILITIES,
+ std::move(raw_builder_ptr));
+ send_event_(std::move(packet));
}
void DualModeController::HciLeVendorMultiAdv(packets::PacketView<true> args) {
ASSERT(args.size() > 0);
- SendCommandCompleteOnlyStatus(OpCode::LE_MULTI_ADVT, hci::Status::UNKNOWN_COMMAND);
+ SendCommandCompleteOnlyStatus(bluetooth::hci::OpCode::LE_MULTI_ADVT,
+ bluetooth::hci::ErrorCode::UNKNOWN_HCI_COMMAND);
}
void DualModeController::HciLeAdvertisingFilter(packets::PacketView<true> args) {
ASSERT(args.size() > 0);
- SendCommandCompleteOnlyStatus(OpCode::LE_ADV_FILTER, hci::Status::UNKNOWN_COMMAND);
+ SendCommandCompleteOnlyStatus(bluetooth::hci::OpCode::LE_ADV_FILTER,
+ bluetooth::hci::ErrorCode::UNKNOWN_HCI_COMMAND);
}
void DualModeController::HciLeEnergyInfo(packets::PacketView<true> args) {
ASSERT(args.size() > 0);
- SendCommandCompleteOnlyStatus(OpCode::LE_ENERGY_INFO, hci::Status::UNKNOWN_COMMAND);
+ SendCommandCompleteOnlyStatus(bluetooth::hci::OpCode::LE_ENERGY_INFO,
+ bluetooth::hci::ErrorCode::UNKNOWN_HCI_COMMAND);
}
void DualModeController::HciLeExtendedScanParams(packets::PacketView<true> args) {
ASSERT(args.size() > 0);
- SendCommandCompleteOnlyStatus(OpCode::LE_EXTENDED_SCAN_PARAMS, hci::Status::UNKNOWN_COMMAND);
+ SendCommandCompleteOnlyStatus(bluetooth::hci::OpCode::LE_EXTENDED_SCAN_PARAMS,
+ bluetooth::hci::ErrorCode::UNKNOWN_HCI_COMMAND);
}
void DualModeController::HciLeStartEncryption(packets::PacketView<true> args) {
@@ -1240,9 +1404,13 @@
// for (size_t i = 0; i < 16; i++) {
// long_term_key.push_back(args_itr.extract<uint18_t>();
// }
- SendCommandStatus(hci::Status::SUCCESS, OpCode::LE_START_ENCRYPTION);
+ SendCommandStatus(bluetooth::hci::ErrorCode::SUCCESS,
+ bluetooth::hci::OpCode::LE_START_ENCRYPTION);
- send_event_(packets::EventPacketBuilder::CreateEncryptionChange(hci::Status::SUCCESS, handle, 0x01)->ToVector());
+ auto packet = bluetooth::hci::EncryptionChangeBuilder::Create(
+ bluetooth::hci::ErrorCode::SUCCESS, handle,
+ bluetooth::hci::EncryptionEnabled::OFF);
+ send_event_(std::move(packet));
#if 0
std::shared_ptr<packets::AclPacketBuilder> encryption_information =
@@ -1299,8 +1467,10 @@
void DualModeController::HciReadLoopbackMode(packets::PacketView<true> args) {
ASSERT_LOG(args.size() == 0, "%s size=%zu", __func__, args.size());
- send_event_(packets::EventPacketBuilder::CreateCommandCompleteReadLoopbackMode(hci::Status::SUCCESS, loopback_mode_)
- ->ToVector());
+ auto packet = bluetooth::hci::ReadLoopbackModeCompleteBuilder::Create(
+ 0x01, bluetooth::hci::ErrorCode::SUCCESS,
+ static_cast<bluetooth::hci::LoopbackMode>(loopback_mode_));
+ send_event_(std::move(packet));
}
void DualModeController::HciWriteLoopbackMode(packets::PacketView<true> args) {
@@ -1308,15 +1478,17 @@
loopback_mode_ = static_cast<hci::LoopbackMode>(args[0]);
// ACL channel
uint16_t acl_handle = 0x123;
- send_event_(packets::EventPacketBuilder::CreateConnectionCompleteEvent(
- hci::Status::SUCCESS, acl_handle, properties_.GetAddress(), hci::LinkType::ACL, false)
- ->ToVector());
+ auto packet_acl = bluetooth::hci::ConnectionCompleteBuilder::Create(
+ bluetooth::hci::ErrorCode::SUCCESS, acl_handle, properties_.GetAddress(),
+ bluetooth::hci::LinkType::ACL, bluetooth::hci::Enable::DISABLED);
+ send_event_(std::move(packet_acl));
// SCO channel
uint16_t sco_handle = 0x345;
- send_event_(packets::EventPacketBuilder::CreateConnectionCompleteEvent(
- hci::Status::SUCCESS, sco_handle, properties_.GetAddress(), hci::LinkType::SCO, false)
- ->ToVector());
- SendCommandCompleteSuccess(OpCode::WRITE_LOOPBACK_MODE);
+ auto packet_sco = bluetooth::hci::ConnectionCompleteBuilder::Create(
+ bluetooth::hci::ErrorCode::SUCCESS, sco_handle, properties_.GetAddress(),
+ bluetooth::hci::LinkType::SCO, bluetooth::hci::Enable::DISABLED);
+ send_event_(std::move(packet_sco));
+ SendCommandCompleteSuccess(bluetooth::hci::OpCode::WRITE_LOOPBACK_MODE);
}
void DualModeController::SetAddress(Address address) {
diff --git a/vendor_libs/test_vendor_lib/model/controller/dual_mode_controller.h b/vendor_libs/test_vendor_lib/model/controller/dual_mode_controller.h
index 4ee9d12..d22e6b7 100644
--- a/vendor_libs/test_vendor_lib/model/controller/dual_mode_controller.h
+++ b/vendor_libs/test_vendor_lib/model/controller/dual_mode_controller.h
@@ -24,14 +24,17 @@
#include <vector>
#include "base/time/time.h"
+#include "hci/address.h"
+#include "hci/hci_packets.h"
#include "link_layer_controller.h"
#include "model/devices/device.h"
#include "model/setup/async_manager.h"
#include "security_manager.h"
-#include "types/address.h"
namespace test_vendor_lib {
+using ::bluetooth::hci::Address;
+
// Emulates a dual mode BR/EDR + LE controller by maintaining the link layer
// state machine detailed in the Bluetooth Core Specification Version 4.2,
// Volume 6, Part B, Section 1.1 (page 30). Provides methods corresponding to
@@ -80,7 +83,9 @@
void RegisterTaskCancel(std::function<void(AsyncTaskId)> cancel);
// Set the callbacks for sending packets to the HCI.
- void RegisterEventChannel(const std::function<void(std::shared_ptr<std::vector<uint8_t>>)>& send_event);
+ void RegisterEventChannel(
+ const std::function<void(std::shared_ptr<std::vector<uint8_t>>)>&
+ send_event);
void RegisterAclChannel(const std::function<void(std::shared_ptr<std::vector<uint8_t>>)>& send_acl);
@@ -423,25 +428,25 @@
void SendCommandComplete(hci::OpCode command_opcode, const std::vector<uint8_t>& return_parameters) const;
// Sends a command complete event with no return parameters.
- void SendCommandCompleteSuccess(hci::OpCode command_opcode) const;
+ void SendCommandCompleteSuccess(bluetooth::hci::OpCode command_opcode) const;
void SendCommandCompleteUnknownOpCodeEvent(uint16_t command_opcode) const;
// Sends a command complete event with no return parameters.
- void SendCommandCompleteOnlyStatus(hci::OpCode command_opcode, hci::Status status) const;
-
- void SendCommandCompleteStatusAndAddress(hci::OpCode command_opcode, hci::Status status,
- const Address& address) const;
+ void SendCommandCompleteOnlyStatus(bluetooth::hci::OpCode command_opcode,
+ bluetooth::hci::ErrorCode status) const;
// Creates a command status event and sends it back to the HCI.
- void SendCommandStatus(hci::Status status, hci::OpCode command_opcode) const;
+ void SendCommandStatus(bluetooth::hci::ErrorCode status,
+ bluetooth::hci::OpCode command_opcode) const;
// Sends a command status event with default event parameters.
- void SendCommandStatusSuccess(hci::OpCode command_opcode) const;
+ void SendCommandStatusSuccess(bluetooth::hci::OpCode command_opcode) const;
// Callbacks to send packets back to the HCI.
std::function<void(std::shared_ptr<std::vector<uint8_t>>)> send_acl_;
- std::function<void(std::shared_ptr<std::vector<uint8_t>>)> send_event_;
+ std::function<void(std::shared_ptr<bluetooth::hci::EventPacketBuilder>)>
+ send_event_;
std::function<void(std::shared_ptr<std::vector<uint8_t>>)> send_sco_;
// Maintains the commands to be registered and used in the HciHandler object.
diff --git a/vendor_libs/test_vendor_lib/model/controller/link_layer_controller.cc b/vendor_libs/test_vendor_lib/model/controller/link_layer_controller.cc
index 0feba95..61563c0 100644
--- a/vendor_libs/test_vendor_lib/model/controller/link_layer_controller.cc
+++ b/vendor_libs/test_vendor_lib/model/controller/link_layer_controller.cc
@@ -17,14 +17,14 @@
#include "link_layer_controller.h"
#include "hci.h"
+#include "include/le_advertisement.h"
#include "os/log.h"
#include "packets/hci/acl_packet_builder.h"
#include "packets/hci/command_packet_view.h"
-#include "packets/hci/event_packet_builder.h"
#include "packets/hci/sco_packet_builder.h"
+#include "packets/raw_builder.h"
#include "packet/raw_builder.h"
-#include "packets/link_layer_packets.h"
using std::vector;
using namespace std::chrono;
@@ -60,8 +60,9 @@
});
}
-hci::Status LinkLayerController::SendCommandToRemoteByAddress(hci::OpCode opcode, PacketView<true> args,
- const Address& remote, bool use_public_address) {
+bluetooth::hci::ErrorCode LinkLayerController::SendCommandToRemoteByAddress(
+ bluetooth::hci::OpCode opcode, PacketView<true> args, const Address& remote,
+ bool use_public_address) {
Address local_address;
if (use_public_address) {
local_address = properties_.GetAddress();
@@ -79,15 +80,15 @@
local_address, remote, std::move(raw_builder_ptr));
SendLinkLayerPacket(std::move(command));
- return hci::Status::SUCCESS;
+ return bluetooth::hci::ErrorCode::SUCCESS;
}
-hci::Status LinkLayerController::SendCommandToRemoteByHandle(hci::OpCode opcode, PacketView<true> args,
- uint16_t handle) {
+bluetooth::hci::ErrorCode LinkLayerController::SendCommandToRemoteByHandle(
+ bluetooth::hci::OpCode opcode, PacketView<true> args, uint16_t handle) {
// TODO: Handle LE connections
bool use_public_address = true;
if (!connections_.HasHandle(handle)) {
- return hci::Status::UNKNOWN_CONNECTION;
+ return bluetooth::hci::ErrorCode::UNKNOWN_CONNECTION;
}
return SendCommandToRemoteByAddress(opcode, args, connections_.GetAddress(handle), use_public_address);
}
@@ -108,7 +109,16 @@
static_cast<int>(acl_packet.size()));
ScheduleTask(milliseconds(5), [this, handle]() {
- send_event_(EventPacketBuilder::CreateNumberOfCompletedPacketsEvent(handle, 1)->ToVector());
+ std::unique_ptr<bluetooth::packet::RawBuilder> raw_builder_ptr =
+ std::make_unique<bluetooth::packet::RawBuilder>();
+ raw_builder_ptr->AddOctets1(0x01);
+ raw_builder_ptr->AddOctets2(handle);
+ raw_builder_ptr->AddOctets2(0x01);
+
+ auto packet = bluetooth::hci::EventPacketBuilder::Create(
+ bluetooth::hci::EventCode::NUMBER_OF_COMPLETED_PACKETS,
+ std::move(raw_builder_ptr));
+ send_event_(std::move(packet));
});
auto acl_payload = acl_packet.GetPayload();
@@ -247,29 +257,25 @@
auto args = command.GetPayload().begin();
std::vector<uint64_t> response_data;
hci::OpCode opcode = static_cast<hci::OpCode>(args.extract<uint16_t>());
+ std::unique_ptr<bluetooth::packet::RawBuilder> raw_builder_ptr =
+ std::make_unique<bluetooth::packet::RawBuilder>();
switch (opcode) {
case (hci::OpCode::REMOTE_NAME_REQUEST): {
std::vector<uint8_t> name = properties_.GetName();
LOG_INFO("Remote Name (Local Name) %d", static_cast<int>(name.size()));
- response_data.push_back(static_cast<uint8_t>(hci::Status::SUCCESS));
- response_data.push_back(name.size());
- uint64_t word = 0;
- for (size_t i = 0; i < name.size(); i++) {
- if (i > 0 && (i % 8 == 0)) {
- response_data.push_back(word);
- word = 0;
- }
- word |= static_cast<uint64_t>(name[i]) << (8 * (i % 8));
- }
- response_data.push_back(word);
+ raw_builder_ptr->AddOctets1(
+ static_cast<uint8_t>(bluetooth::hci::ErrorCode::SUCCESS));
+ raw_builder_ptr->AddOctets8(name.size());
+ raw_builder_ptr->AddOctets(name);
} break;
case (hci::OpCode::READ_REMOTE_SUPPORTED_FEATURES):
LOG_INFO("(%s) Remote Supported Features Requested by: %s %x",
incoming.GetDestinationAddress().ToString().c_str(), incoming.GetSourceAddress().ToString().c_str(),
static_cast<int>(properties_.GetSupportedFeatures()));
- response_data.push_back(static_cast<uint8_t>(hci::Status::SUCCESS));
- response_data.push_back(properties_.GetSupportedFeatures());
+ raw_builder_ptr->AddOctets1(
+ static_cast<uint8_t>(bluetooth::hci::ErrorCode::SUCCESS));
+ raw_builder_ptr->AddOctets8(properties_.GetSupportedFeatures());
break;
case (hci::OpCode::READ_REMOTE_EXTENDED_FEATURES): {
uint8_t page_number = (args + 2).extract<uint8_t>(); // skip the handle
@@ -277,34 +283,37 @@
page_number, incoming.GetSourceAddress().ToString().c_str());
uint8_t max_page_number = properties_.GetExtendedFeaturesMaximumPageNumber();
if (page_number > max_page_number) {
- response_data.push_back(static_cast<uint8_t>(hci::Status::INVALID_HCI_COMMAND_PARAMETERS));
- response_data.push_back(page_number);
- response_data.push_back(max_page_number);
- response_data.push_back(0);
+ raw_builder_ptr->AddOctets1(static_cast<uint8_t>(
+ bluetooth::hci::ErrorCode::INVALID_HCI_COMMAND_PARAMETERS));
+ raw_builder_ptr->AddOctets1(page_number);
+ raw_builder_ptr->AddOctets1(max_page_number);
+ raw_builder_ptr->AddOctets8(0);
} else {
- response_data.push_back(static_cast<uint8_t>(hci::Status::SUCCESS));
- response_data.push_back(page_number);
- response_data.push_back(max_page_number);
- response_data.push_back(properties_.GetExtendedFeatures(page_number));
+ raw_builder_ptr->AddOctets1(
+ static_cast<uint8_t>(bluetooth::hci::ErrorCode::SUCCESS));
+ raw_builder_ptr->AddOctets1(page_number);
+ raw_builder_ptr->AddOctets1(max_page_number);
+ raw_builder_ptr->AddOctets8(
+ properties_.GetExtendedFeatures(page_number));
}
} break;
case (hci::OpCode::READ_REMOTE_VERSION_INFORMATION):
- response_data.push_back(static_cast<uint8_t>(hci::Status::SUCCESS));
- response_data.push_back(properties_.GetLmpPalVersion());
- response_data.push_back(properties_.GetManufacturerName());
- response_data.push_back(properties_.GetLmpPalSubversion());
+ raw_builder_ptr->AddOctets1(
+ static_cast<uint8_t>(bluetooth::hci::ErrorCode::SUCCESS));
+ raw_builder_ptr->AddOctets1(properties_.GetLmpPalVersion());
+ raw_builder_ptr->AddOctets2(properties_.GetManufacturerName());
+ raw_builder_ptr->AddOctets2(properties_.GetLmpPalSubversion());
break;
case (hci::OpCode::READ_CLOCK_OFFSET):
- response_data.push_back(static_cast<uint8_t>(hci::Status::SUCCESS));
- response_data.push_back(properties_.GetClockOffset());
+ raw_builder_ptr->AddOctets1(
+ static_cast<uint8_t>(bluetooth::hci::ErrorCode::SUCCESS));
+ raw_builder_ptr->AddOctets2(properties_.GetClockOffset());
break;
default:
LOG_INFO("Dropping unhandled command 0x%04x", static_cast<uint16_t>(opcode));
return;
}
- std::unique_ptr<bluetooth::packet::RawBuilder> raw_builder_ptr =
- std::make_unique<bluetooth::packet::RawBuilder>();
for (uint64_t data : response_data) {
raw_builder_ptr->AddOctets8(data);
}
@@ -345,7 +354,10 @@
LOG_INFO("%s: Unknown connection @%s", __func__, peer.ToString().c_str());
return;
}
- send_event_(EventPacketBuilder::CreateEncryptionChange(hci::Status::SUCCESS, handle, 1)->ToVector());
+ auto packet = bluetooth::hci::EncryptionChangeBuilder::Create(
+ bluetooth::hci::ErrorCode::SUCCESS, handle,
+ bluetooth::hci::EncryptionEnabled::ON);
+ send_event_(std::move(packet));
auto response = model::packets::EncryptConnectionResponseBuilder::Create(
properties_.GetAddress(), peer, security_manager_.GetKey(peer));
SendLinkLayerPacket(std::move(response));
@@ -360,7 +372,10 @@
LOG_INFO("%s: Unknown connection @%s", __func__, incoming.GetSourceAddress().ToString().c_str());
return;
}
- send_event_(EventPacketBuilder::CreateEncryptionChange(hci::Status::SUCCESS, handle, 1)->ToVector());
+ auto packet = bluetooth::hci::EncryptionChangeBuilder::Create(
+ bluetooth::hci::ErrorCode::SUCCESS, handle,
+ bluetooth::hci::EncryptionEnabled::ON);
+ send_event_(std::move(packet));
}
void LinkLayerController::IncomingInquiryPacket(
@@ -418,15 +433,17 @@
auto inquiry_response =
model::packets::InquiryResponseView::Create(basic_inquiry_response);
ASSERT(inquiry_response.IsValid());
- std::unique_ptr<EventPacketBuilder> inquiry_result =
- EventPacketBuilder::CreateInquiryResultEvent();
- bool result_added = inquiry_result->AddInquiryResult(
- inquiry_response.GetSourceAddress(),
- inquiry_response.GetPageScanRepetitionMode(),
+
+ auto page_scan_repetition_mode =
+ (bluetooth::hci::PageScanRepetitionMode)
+ inquiry_response.GetPageScanRepetitionMode();
+
+ auto packet = bluetooth::hci::InquiryResultBuilder::Create(
+ 0x01, inquiry_response.GetSourceAddress(), page_scan_repetition_mode,
inquiry_response.GetClassOfDevice(),
inquiry_response.GetClockOffset());
- CHECK(result_added);
- send_event_(inquiry_result->ToVector());
+
+ send_event_(std::move(packet));
} break;
case (model::packets::InquiryType::RSSI): {
@@ -435,13 +452,16 @@
model::packets::InquiryResponseWithRssiView::Create(
basic_inquiry_response);
ASSERT(inquiry_response.IsValid());
- send_event_(EventPacketBuilder::CreateExtendedInquiryResultEvent(
- incoming.GetSourceAddress(),
- inquiry_response.GetPageScanRepetitionMode(),
- inquiry_response.GetClassOfDevice(),
- inquiry_response.GetClockOffset(),
- inquiry_response.GetRssi(), eir)
- ->ToVector());
+
+ auto page_scan_repetition_mode =
+ (bluetooth::hci::PageScanRepetitionMode)
+ inquiry_response.GetPageScanRepetitionMode();
+
+ auto packet = bluetooth::hci::InquiryResultWithRssiBuilder::Create(
+ 0x01, inquiry_response.GetSourceAddress(), page_scan_repetition_mode,
+ inquiry_response.GetClassOfDevice(),
+ inquiry_response.GetClockOffset(), inquiry_response.GetRssi());
+ send_event_(std::move(packet));
} break;
case (model::packets::InquiryType::EXTENDED): {
@@ -450,13 +470,25 @@
model::packets::ExtendedInquiryResponseView::Create(
basic_inquiry_response);
ASSERT(inquiry_response.IsValid());
- eir = inquiry_response.GetExtendedData();
- send_event_(EventPacketBuilder::CreateExtendedInquiryResultEvent(
- incoming.GetSourceAddress(),
- inquiry_response.GetPageScanRepetitionMode(),
- inquiry_response.GetClassOfDevice(),
- inquiry_response.GetClockOffset(), GetRssi(), eir)
- ->ToVector());
+
+ std::unique_ptr<bluetooth::packet::RawBuilder> raw_builder_ptr =
+ std::make_unique<bluetooth::packet::RawBuilder>();
+ raw_builder_ptr->AddOctets1(0x01); // num_responses
+ raw_builder_ptr->AddAddress(inquiry_response.GetSourceAddress());
+ raw_builder_ptr->AddOctets1(inquiry_response.GetPageScanRepetitionMode());
+ raw_builder_ptr->AddOctets1(0x00); // _reserved_
+ auto class_of_device = inquiry_response.GetClassOfDevice();
+ for (unsigned int i = 0; i < class_of_device.kLength; i++) {
+ raw_builder_ptr->AddOctets1(class_of_device.cod[i]);
+ }
+ raw_builder_ptr->AddOctets2(inquiry_response.GetClockOffset());
+ raw_builder_ptr->AddOctets1(inquiry_response.GetRssi());
+ raw_builder_ptr->AddOctets(inquiry_response.GetExtendedData());
+
+ auto packet = bluetooth::hci::EventPacketBuilder::Create(
+ bluetooth::hci::EventCode::EXTENDED_INQUIRY_RESULT,
+ std::move(raw_builder_ptr));
+ send_event_(std::move(packet));
} break;
default:
LOG_WARN("Unhandled Incoming Inquiry Response of type %d",
@@ -490,9 +522,12 @@
security_manager_.SetPeerIoCapability(peer, io_capability, oob_data_present, authentication_requirements);
- send_event_(EventPacketBuilder::CreateIoCapabilityResponseEvent(peer, io_capability, oob_data_present,
- authentication_requirements)
- ->ToVector());
+ auto packet = bluetooth::hci::IoCapabilityResponseBuilder::Create(
+ peer, static_cast<bluetooth::hci::IoCapability>(io_capability),
+ static_cast<bluetooth::hci::OobDataPresent>(oob_data_present),
+ static_cast<bluetooth::hci::AuthenticationRequirements>(
+ authentication_requirements));
+ send_event_(std::move(packet));
StartSimplePairing(peer);
}
@@ -512,10 +547,12 @@
security_manager_.SetPeerIoCapability(peer, io_capability, oob_data_present,
authentication_requirements);
- send_event_(
- EventPacketBuilder::CreateIoCapabilityResponseEvent(
- peer, io_capability, oob_data_present, authentication_requirements)
- ->ToVector());
+ auto packet = bluetooth::hci::IoCapabilityResponseBuilder::Create(
+ peer, static_cast<bluetooth::hci::IoCapability>(io_capability),
+ static_cast<bluetooth::hci::OobDataPresent>(oob_data_present),
+ static_cast<bluetooth::hci::AuthenticationRequirements>(
+ authentication_requirements));
+ send_event_(std::move(packet));
PairingType pairing_type = security_manager_.GetSimplePairingType();
if (pairing_type != PairingType::INVALID) {
@@ -552,13 +589,20 @@
if (le_scan_enable_) {
vector<uint8_t> ad = advertisement.GetData();
- std::unique_ptr<EventPacketBuilder> le_adverts = EventPacketBuilder::CreateLeAdvertisingReportEvent();
-
- if (!le_adverts->AddLeAdvertisingReport(adv_type, address_type, address, ad, GetRssi())) {
- LOG_INFO("Couldn't add the advertising report.");
- } else {
- send_event_(le_adverts->ToVector());
- }
+ std::unique_ptr<bluetooth::packet::RawBuilder> raw_builder_ptr =
+ std::make_unique<bluetooth::packet::RawBuilder>();
+ raw_builder_ptr->AddOctets1(
+ static_cast<uint8_t>(bluetooth::hci::SubeventCode::ADVERTISING_REPORT));
+ raw_builder_ptr->AddOctets1(0x01); // num reports
+ raw_builder_ptr->AddOctets1(static_cast<uint8_t>(adv_type));
+ raw_builder_ptr->AddOctets1(static_cast<uint8_t>(address_type));
+ raw_builder_ptr->AddAddress(address);
+ raw_builder_ptr->AddOctets1(ad.size());
+ raw_builder_ptr->AddOctets(ad);
+ raw_builder_ptr->AddOctets1(GetRssi());
+ auto packet = bluetooth::hci::EventPacketBuilder::Create(
+ bluetooth::hci::EventCode::LE_META_EVENT, std::move(raw_builder_ptr));
+ send_event_(std::move(packet));
}
// Active scanning
@@ -602,10 +646,13 @@
address_type);
return;
}
- send_event_(EventPacketBuilder::CreateLeConnectionCompleteEvent(
- hci::Status::SUCCESS, handle, role, static_cast<uint8_t>(address_type), address, connection_interval,
- connection_latency, supervision_timeout)
- ->ToVector());
+ auto packet = bluetooth::hci::LeConnectionCompleteBuilder::Create(
+ bluetooth::hci::ErrorCode::SUCCESS, handle,
+ static_cast<bluetooth::hci::Role>(role),
+ static_cast<bluetooth::hci::AddressType>(address_type), address,
+ connection_interval, connection_latency, supervision_timeout,
+ static_cast<bluetooth::hci::MasterClockAccuracy>(0x00));
+ send_event_(std::move(packet));
}
void LinkLayerController::IncomingLeConnectPacket(
@@ -666,14 +713,20 @@
auto address_type =
static_cast<LeAdvertisement::AddressType>(scan_response.GetAddressType());
- std::unique_ptr<EventPacketBuilder> le_adverts = EventPacketBuilder::CreateLeAdvertisingReportEvent();
-
- if (!le_adverts->AddLeAdvertisingReport(
- adv_type, address_type, incoming.GetSourceAddress(), ad, GetRssi())) {
- LOG_INFO("Couldn't add the scan response.");
- } else {
- send_event_(le_adverts->ToVector());
- }
+ std::unique_ptr<bluetooth::packet::RawBuilder> raw_builder_ptr =
+ std::make_unique<bluetooth::packet::RawBuilder>();
+ raw_builder_ptr->AddOctets1(
+ static_cast<uint8_t>(bluetooth::hci::SubeventCode::ADVERTISING_REPORT));
+ raw_builder_ptr->AddOctets1(0x01); // num reports
+ raw_builder_ptr->AddOctets1(static_cast<uint8_t>(adv_type));
+ raw_builder_ptr->AddOctets1(static_cast<uint8_t>(address_type));
+ raw_builder_ptr->AddAddress(incoming.GetSourceAddress());
+ raw_builder_ptr->AddOctets1(ad.size());
+ raw_builder_ptr->AddOctets(ad);
+ raw_builder_ptr->AddOctets1(GetRssi());
+ auto packet = bluetooth::hci::EventPacketBuilder::Create(
+ bluetooth::hci::EventCode::LE_META_EVENT, std::move(raw_builder_ptr));
+ send_event_(std::move(packet));
}
void LinkLayerController::IncomingPagePacket(
@@ -688,9 +741,15 @@
incoming.GetSourceAddress().ToString().c_str());
}
- send_event_(EventPacketBuilder::CreateConnectionRequestEvent(incoming.GetSourceAddress(), page.GetClassOfDevice(),
- hci::LinkType::ACL)
- ->ToVector());
+ bluetooth::hci::Address source_address;
+ bluetooth::hci::Address::FromString(page.GetSourceAddress().ToString(),
+ source_address);
+
+ auto packet = bluetooth::hci::ConnectionRequestBuilder::Create(
+ source_address, page.GetClassOfDevice(),
+ bluetooth::hci::ConnectionRequestLinkType::ACL);
+
+ send_event_(std::move(packet));
}
void LinkLayerController::IncomingPageRejectPacket(
@@ -699,9 +758,11 @@
auto reject = model::packets::PageRejectView::Create(incoming);
ASSERT(reject.IsValid());
LOG_INFO("%s: Sending CreateConnectionComplete", __func__);
- send_event_(EventPacketBuilder::CreateConnectionCompleteEvent(static_cast<hci::Status>(reject.GetReason()), 0x0eff,
- incoming.GetSourceAddress(), hci::LinkType::ACL, false)
- ->ToVector());
+ auto packet = bluetooth::hci::ConnectionCompleteBuilder::Create(
+ static_cast<bluetooth::hci::ErrorCode>(reject.GetReason()), 0x0eff,
+ incoming.GetSourceAddress(), bluetooth::hci::LinkType::ACL,
+ bluetooth::hci::Enable::DISABLED);
+ send_event_(std::move(packet));
}
void LinkLayerController::IncomingPageResponsePacket(
@@ -712,9 +773,10 @@
LOG_WARN("%s: No free handles", __func__);
return;
}
- send_event_(EventPacketBuilder::CreateConnectionCompleteEvent(hci::Status::SUCCESS, handle,
- incoming.GetSourceAddress(), hci::LinkType::ACL, false)
- ->ToVector());
+ auto packet = bluetooth::hci::ConnectionCompleteBuilder::Create(
+ bluetooth::hci::ErrorCode::SUCCESS, handle, incoming.GetSourceAddress(),
+ bluetooth::hci::LinkType::ACL, bluetooth::hci::Enable::DISABLED);
+ send_event_(std::move(packet));
}
void LinkLayerController::IncomingResponsePacket(
@@ -726,47 +788,57 @@
hci::OpCode opcode = static_cast<hci::OpCode>(response.GetOpcode());
auto args = response.GetPayload().begin();
- hci::Status status = static_cast<hci::Status>(args.extract<uint64_t>());
+ auto status = static_cast<bluetooth::hci::ErrorCode>(args.extract<uint8_t>());
uint16_t handle = connections_.GetHandle(incoming.GetSourceAddress());
switch (opcode) {
case (hci::OpCode::REMOTE_NAME_REQUEST): {
- std::string remote_name = "";
- size_t length = args.extract<uint64_t>();
- uint64_t word = 0;
- for (size_t b = 0; b < length; b++) {
- size_t byte = b % 8;
- if (byte == 0) {
- word = args.extract<uint64_t>();
- }
- remote_name += static_cast<uint8_t>(word >> (byte * 8));
+ std::array<uint8_t, 248> remote_name;
+ remote_name.fill(0x00);
+ uint64_t len = args.extract<uint64_t>();
+ if (len > 247) {
+ len = 247; // one byte for NULL octet (0x00)
}
- send_event_(
- EventPacketBuilder::CreateRemoteNameRequestCompleteEvent(status, incoming.GetSourceAddress(), remote_name)
- ->ToVector());
+ for (uint64_t i = 0; i < len; i++) {
+ remote_name[i] = args.extract<uint8_t>();
+ }
+ auto packet = bluetooth::hci::RemoteNameRequestCompleteBuilder::Create(
+ status, incoming.GetSourceAddress(), remote_name);
+ send_event_(std::move(packet));
} break;
case (hci::OpCode::READ_REMOTE_SUPPORTED_FEATURES): {
- send_event_(
- EventPacketBuilder::CreateRemoteSupportedFeaturesEvent(status, handle, args.extract<uint64_t>())->ToVector());
+ auto packet =
+ bluetooth::hci::ReadRemoteSupportedFeaturesCompleteBuilder::Create(
+ status, handle, args.extract<uint64_t>());
+ send_event_(std::move(packet));
} break;
case (hci::OpCode::READ_REMOTE_EXTENDED_FEATURES): {
- if (status == hci::Status::SUCCESS) {
- send_event_(EventPacketBuilder::CreateReadRemoteExtendedFeaturesEvent(
- status, handle, args.extract<uint64_t>(), args.extract<uint64_t>(), args.extract<uint64_t>())
- ->ToVector());
+ if (status == bluetooth::hci::ErrorCode::SUCCESS) {
+ auto packet =
+ bluetooth::hci::ReadRemoteExtendedFeaturesCompleteBuilder::Create(
+ status, handle, args.extract<uint8_t>(),
+ args.extract<uint8_t>(), args.extract<uint64_t>());
+ send_event_(std::move(packet));
} else {
- send_event_(EventPacketBuilder::CreateReadRemoteExtendedFeaturesEvent(status, handle, 0, 0, 0)->ToVector());
+ auto packet =
+ bluetooth::hci::ReadRemoteExtendedFeaturesCompleteBuilder::Create(
+ status, handle, 0, 0, 0);
+ send_event_(std::move(packet));
}
} break;
case (hci::OpCode::READ_REMOTE_VERSION_INFORMATION): {
- send_event_(EventPacketBuilder::CreateReadRemoteVersionInformationEvent(
- status, handle, args.extract<uint64_t>(), args.extract<uint64_t>(), args.extract<uint64_t>())
- ->ToVector());
+ auto packet =
+ bluetooth::hci::ReadRemoteVersionInformationCompleteBuilder::Create(
+ status, handle, args.extract<uint8_t>(), args.extract<uint16_t>(),
+ args.extract<uint16_t>());
+ send_event_(std::move(packet));
LOG_INFO("Read remote version handle 0x%04x", handle);
} break;
case (hci::OpCode::READ_CLOCK_OFFSET): {
- send_event_(EventPacketBuilder::CreateReadClockOffsetEvent(status, handle, args.extract<uint64_t>())->ToVector());
+ auto packet = bluetooth::hci::ReadClockOffsetCompleteBuilder::Create(
+ status, handle, args.extract<uint16_t>());
+ send_event_(std::move(packet));
} break;
default:
LOG_INFO("Unhandled response to command 0x%04x", static_cast<uint16_t>(opcode));
@@ -811,7 +883,8 @@
}
void LinkLayerController::RegisterEventChannel(
- const std::function<void(std::shared_ptr<std::vector<uint8_t>>)>& callback) {
+ const std::function<
+ void(std::shared_ptr<bluetooth::hci::EventPacketBuilder>)>& callback) {
send_event_ = callback;
}
@@ -872,7 +945,8 @@
void LinkLayerController::StartSimplePairing(const Address& address) {
// IO Capability Exchange (See the Diagram in the Spec)
- send_event_(EventPacketBuilder::CreateIoCapabilityRequestEvent(address)->ToVector());
+ auto packet = bluetooth::hci::IoCapabilityRequestBuilder::Create(address);
+ send_event_(std::move(packet));
// Get a Key, then authenticate
// PublicKeyExchange(address);
@@ -884,9 +958,11 @@
ASSERT(security_manager_.GetAuthenticationAddress() == peer);
// TODO: Public key exchange first?
switch (pairing_type) {
- case PairingType::AUTO_CONFIRMATION:
- send_event_(EventPacketBuilder::CreateUserConfirmationRequestEvent(peer, 123456)->ToVector());
- break;
+ case PairingType::AUTO_CONFIRMATION: {
+ auto packet =
+ bluetooth::hci::UserConfirmationRequestBuilder::Create(peer, 123456);
+ send_event_(std::move(packet));
+ } break;
case PairingType::CONFIRM_Y_N:
LOG_ALWAYS_FATAL("Unimplemented PairingType %d", static_cast<int>(pairing_type));
break;
@@ -911,37 +987,41 @@
uint16_t handle = security_manager_.GetAuthenticationHandle();
ASSERT(security_manager_.GetAuthenticationAddress() == peer);
// Check key in security_manager_ ?
- send_event_(EventPacketBuilder::CreateAuthenticationCompleteEvent(hci::Status::SUCCESS, handle)->ToVector());
+ auto packet = bluetooth::hci::AuthenticationCompleteBuilder::Create(
+ bluetooth::hci::ErrorCode::SUCCESS, handle);
+ send_event_(std::move(packet));
}
-hci::Status LinkLayerController::LinkKeyRequestReply(const Address& peer, PacketView<true> key) {
+bluetooth::hci::ErrorCode LinkLayerController::LinkKeyRequestReply(
+ const Address& peer, PacketView<true> key) {
std::vector<uint8_t> key_vec(key.begin(), key.end());
security_manager_.WriteKey(peer, key_vec);
security_manager_.AuthenticationRequestFinished();
ScheduleTask(milliseconds(5), [this, peer]() { AuthenticateRemoteStage2(peer); });
- return hci::Status::SUCCESS;
+ return bluetooth::hci::ErrorCode::SUCCESS;
}
-hci::Status LinkLayerController::LinkKeyRequestNegativeReply(const Address& address) {
+bluetooth::hci::ErrorCode LinkLayerController::LinkKeyRequestNegativeReply(
+ const Address& address) {
security_manager_.DeleteKey(address);
// Simple pairing to get a key
uint16_t handle = connections_.GetHandle(address);
if (handle == acl::kReservedHandle) {
LOG_INFO("%s: Device not connected %s", __func__, address.ToString().c_str());
- return hci::Status::UNKNOWN_CONNECTION;
+ return bluetooth::hci::ErrorCode::UNKNOWN_CONNECTION;
}
security_manager_.AuthenticationRequest(address, handle);
ScheduleTask(milliseconds(5), [this, address]() { StartSimplePairing(address); });
- return hci::Status::SUCCESS;
+ return bluetooth::hci::ErrorCode::SUCCESS;
}
-hci::Status LinkLayerController::IoCapabilityRequestReply(const Address& peer, uint8_t io_capability,
- uint8_t oob_data_present_flag,
- uint8_t authentication_requirements) {
+bluetooth::hci::ErrorCode LinkLayerController::IoCapabilityRequestReply(
+ const Address& peer, uint8_t io_capability, uint8_t oob_data_present_flag,
+ uint8_t authentication_requirements) {
security_manager_.SetLocalIoCapability(peer, io_capability, oob_data_present_flag, authentication_requirements);
PairingType pairing_type = security_manager_.GetSimplePairingType();
@@ -962,12 +1042,13 @@
SendLinkLayerPacket(std::move(packet));
}
- return hci::Status::SUCCESS;
+ return bluetooth::hci::ErrorCode::SUCCESS;
}
-hci::Status LinkLayerController::IoCapabilityRequestNegativeReply(const Address& peer, hci::Status reason) {
+bluetooth::hci::ErrorCode LinkLayerController::IoCapabilityRequestNegativeReply(
+ const Address& peer, hci::Status reason) {
if (security_manager_.GetAuthenticationAddress() != peer) {
- return hci::Status::AUTHENTICATION_FAILURE;
+ return bluetooth::hci::ErrorCode::AUTHENTICATION_FAILURE;
}
security_manager_.InvalidateIoCapabilities();
@@ -976,12 +1057,13 @@
properties_.GetAddress(), peer, static_cast<uint8_t>(reason));
SendLinkLayerPacket(std::move(packet));
- return hci::Status::SUCCESS;
+ return bluetooth::hci::ErrorCode::SUCCESS;
}
-hci::Status LinkLayerController::UserConfirmationRequestReply(const Address& peer) {
+bluetooth::hci::ErrorCode LinkLayerController::UserConfirmationRequestReply(
+ const Address& peer) {
if (security_manager_.GetAuthenticationAddress() != peer) {
- return hci::Status::AUTHENTICATION_FAILURE;
+ return bluetooth::hci::ErrorCode::AUTHENTICATION_FAILURE;
}
// TODO: Key could be calculated here.
std::vector<uint8_t> key_vec{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16};
@@ -990,69 +1072,77 @@
security_manager_.AuthenticationRequestFinished();
ScheduleTask(milliseconds(5), [this, peer]() { AuthenticateRemoteStage2(peer); });
- return hci::Status::SUCCESS;
+ return bluetooth::hci::ErrorCode::SUCCESS;
}
-hci::Status LinkLayerController::UserConfirmationRequestNegativeReply(const Address& peer) {
+bluetooth::hci::ErrorCode
+LinkLayerController::UserConfirmationRequestNegativeReply(const Address& peer) {
if (security_manager_.GetAuthenticationAddress() != peer) {
- return hci::Status::AUTHENTICATION_FAILURE;
+ return bluetooth::hci::ErrorCode::AUTHENTICATION_FAILURE;
}
- return hci::Status::SUCCESS;
+ return bluetooth::hci::ErrorCode::SUCCESS;
}
-hci::Status LinkLayerController::UserPasskeyRequestReply(const Address& peer, uint32_t numeric_value) {
+bluetooth::hci::ErrorCode LinkLayerController::UserPasskeyRequestReply(
+ const Address& peer, uint32_t numeric_value) {
if (security_manager_.GetAuthenticationAddress() != peer) {
- return hci::Status::AUTHENTICATION_FAILURE;
+ return bluetooth::hci::ErrorCode::AUTHENTICATION_FAILURE;
}
LOG_INFO("TODO:Do something with the passkey %06d", numeric_value);
- return hci::Status::SUCCESS;
+ return bluetooth::hci::ErrorCode::SUCCESS;
}
-hci::Status LinkLayerController::UserPasskeyRequestNegativeReply(const Address& peer) {
+bluetooth::hci::ErrorCode LinkLayerController::UserPasskeyRequestNegativeReply(
+ const Address& peer) {
if (security_manager_.GetAuthenticationAddress() != peer) {
- return hci::Status::AUTHENTICATION_FAILURE;
+ return bluetooth::hci::ErrorCode::AUTHENTICATION_FAILURE;
}
- return hci::Status::SUCCESS;
+ return bluetooth::hci::ErrorCode::SUCCESS;
}
-hci::Status LinkLayerController::RemoteOobDataRequestReply(const Address& peer, const std::vector<uint8_t>& c,
- const std::vector<uint8_t>& r) {
+bluetooth::hci::ErrorCode LinkLayerController::RemoteOobDataRequestReply(
+ const Address& peer, const std::vector<uint8_t>& c,
+ const std::vector<uint8_t>& r) {
if (security_manager_.GetAuthenticationAddress() != peer) {
- return hci::Status::AUTHENTICATION_FAILURE;
+ return bluetooth::hci::ErrorCode::AUTHENTICATION_FAILURE;
}
LOG_INFO("TODO:Do something with the OOB data c=%d r=%d", c[0], r[0]);
- return hci::Status::SUCCESS;
+ return bluetooth::hci::ErrorCode::SUCCESS;
}
-hci::Status LinkLayerController::RemoteOobDataRequestNegativeReply(const Address& peer) {
+bluetooth::hci::ErrorCode
+LinkLayerController::RemoteOobDataRequestNegativeReply(const Address& peer) {
if (security_manager_.GetAuthenticationAddress() != peer) {
- return hci::Status::AUTHENTICATION_FAILURE;
+ return bluetooth::hci::ErrorCode::AUTHENTICATION_FAILURE;
}
- return hci::Status::SUCCESS;
+ return bluetooth::hci::ErrorCode::SUCCESS;
}
void LinkLayerController::HandleAuthenticationRequest(const Address& address, uint16_t handle) {
if (simple_pairing_mode_enabled_ == true) {
security_manager_.AuthenticationRequest(address, handle);
- send_event_(EventPacketBuilder::CreateLinkKeyRequestEvent(address)->ToVector());
+ auto packet = bluetooth::hci::LinkKeyRequestBuilder::Create(address);
+ send_event_(std::move(packet));
} else { // Should never happen for our phones
// Check for a key, try to authenticate, ask for a PIN.
- send_event_(
- EventPacketBuilder::CreateAuthenticationCompleteEvent(hci::Status::AUTHENTICATION_FAILURE, handle)->ToVector());
+ auto packet = bluetooth::hci::AuthenticationCompleteBuilder::Create(
+ bluetooth::hci::ErrorCode::AUTHENTICATION_FAILURE, handle);
+ send_event_(std::move(packet));
}
}
-hci::Status LinkLayerController::AuthenticationRequested(uint16_t handle) {
+bluetooth::hci::ErrorCode LinkLayerController::AuthenticationRequested(
+ uint16_t handle) {
if (!connections_.HasHandle(handle)) {
LOG_INFO("Authentication Requested for unknown handle %04x", handle);
- return hci::Status::UNKNOWN_CONNECTION;
+ return bluetooth::hci::ErrorCode::UNKNOWN_CONNECTION;
}
Address remote = connections_.GetAddress(handle);
ScheduleTask(milliseconds(5), [this, remote, handle]() { HandleAuthenticationRequest(remote, handle); });
- return hci::Status::SUCCESS;
+ return bluetooth::hci::ErrorCode::SUCCESS;
}
void LinkLayerController::HandleSetConnectionEncryption(const Address& peer, uint16_t handle,
@@ -1060,8 +1150,10 @@
// TODO: Block ACL traffic or at least guard against it
if (connections_.IsEncrypted(handle) && encryption_enable) {
- send_event_(
- EventPacketBuilder::CreateEncryptionChange(hci::Status::SUCCESS, handle, encryption_enable)->ToVector());
+ auto packet = bluetooth::hci::EncryptionChangeBuilder::Create(
+ bluetooth::hci::ErrorCode::SUCCESS, handle,
+ static_cast<bluetooth::hci::EncryptionEnabled>(encryption_enable));
+ send_event_(std::move(packet));
return;
}
@@ -1070,31 +1162,33 @@
SendLinkLayerPacket(std::move(packet));
}
-hci::Status LinkLayerController::SetConnectionEncryption(uint16_t handle, uint8_t encryption_enable) {
+bluetooth::hci::ErrorCode LinkLayerController::SetConnectionEncryption(
+ uint16_t handle, uint8_t encryption_enable) {
if (!connections_.HasHandle(handle)) {
LOG_INFO("Set Connection Encryption for unknown handle %04x", handle);
- return hci::Status::UNKNOWN_CONNECTION;
+ return bluetooth::hci::ErrorCode::UNKNOWN_CONNECTION;
}
if (connections_.IsEncrypted(handle) && !encryption_enable) {
- return hci::Status::ENCRYPTION_MODE_NOT_ACCEPTABLE;
+ return bluetooth::hci::ErrorCode::ENCRYPTION_MODE_NOT_ACCEPTABLE;
}
Address remote = connections_.GetAddress(handle);
if (security_manager_.ReadKey(remote) == 0) {
- return hci::Status::PIN_OR_KEY_MISSING;
+ return bluetooth::hci::ErrorCode::PIN_OR_KEY_MISSING;
}
ScheduleTask(milliseconds(5), [this, remote, handle, encryption_enable]() {
HandleSetConnectionEncryption(remote, handle, encryption_enable);
});
- return hci::Status::SUCCESS;
+ return bluetooth::hci::ErrorCode::SUCCESS;
}
-hci::Status LinkLayerController::AcceptConnectionRequest(const Address& addr, bool try_role_switch) {
+bluetooth::hci::ErrorCode LinkLayerController::AcceptConnectionRequest(
+ const Address& addr, bool try_role_switch) {
if (!connections_.HasPendingConnection(addr)) {
LOG_INFO("%s: No pending connection for %s", __func__, addr.ToString().c_str());
- return hci::Status::UNKNOWN_CONNECTION;
+ return bluetooth::hci::ErrorCode::UNKNOWN_CONNECTION;
}
LOG_INFO("%s: Accept in 200ms", __func__);
@@ -1103,7 +1197,7 @@
MakeSlaveConnection(addr, try_role_switch);
});
- return hci::Status::SUCCESS;
+ return bluetooth::hci::ErrorCode::SUCCESS;
}
void LinkLayerController::MakeSlaveConnection(const Address& addr, bool try_role_switch) {
@@ -1118,15 +1212,17 @@
return;
}
LOG_INFO("%s CreateConnection returned handle 0x%x", __func__, handle);
- send_event_(
- EventPacketBuilder::CreateConnectionCompleteEvent(hci::Status::SUCCESS, handle, addr, hci::LinkType::ACL, false)
- ->ToVector());
+ auto packet = bluetooth::hci::ConnectionCompleteBuilder::Create(
+ bluetooth::hci::ErrorCode::SUCCESS, handle, addr,
+ bluetooth::hci::LinkType::ACL, bluetooth::hci::Enable::DISABLED);
+ send_event_(std::move(packet));
}
-hci::Status LinkLayerController::RejectConnectionRequest(const Address& addr, uint8_t reason) {
+bluetooth::hci::ErrorCode LinkLayerController::RejectConnectionRequest(
+ const Address& addr, uint8_t reason) {
if (!connections_.HasPendingConnection(addr)) {
LOG_INFO("%s: No pending connection for %s", __func__, addr.ToString().c_str());
- return hci::Status::UNKNOWN_CONNECTION;
+ return bluetooth::hci::ErrorCode::UNKNOWN_CONNECTION;
}
LOG_INFO("%s: Reject in 200ms", __func__);
@@ -1135,7 +1231,7 @@
RejectSlaveConnection(addr, reason);
});
- return hci::Status::SUCCESS;
+ return bluetooth::hci::ErrorCode::SUCCESS;
}
void LinkLayerController::RejectSlaveConnection(const Address& addr, uint8_t reason) {
@@ -1145,15 +1241,17 @@
SendLinkLayerPacket(std::move(to_send));
ASSERT(reason >= 0x0d && reason <= 0x0f);
- send_event_(EventPacketBuilder::CreateConnectionCompleteEvent(static_cast<hci::Status>(reason), 0xeff, addr,
- hci::LinkType::ACL, false)
- ->ToVector());
+ auto packet = bluetooth::hci::ConnectionCompleteBuilder::Create(
+ static_cast<bluetooth::hci::ErrorCode>(reason), 0xeff, addr,
+ bluetooth::hci::LinkType::ACL, bluetooth::hci::Enable::DISABLED);
+ send_event_(std::move(packet));
}
-hci::Status LinkLayerController::CreateConnection(const Address& addr, uint16_t, uint8_t, uint16_t,
- uint8_t allow_role_switch) {
+bluetooth::hci::ErrorCode LinkLayerController::CreateConnection(
+ const Address& addr, uint16_t, uint8_t, uint16_t,
+ uint8_t allow_role_switch) {
if (!connections_.CreatePendingConnection(addr)) {
- return hci::Status::CONTROLLER_BUSY;
+ return bluetooth::hci::ErrorCode::CONTROLLER_BUSY;
}
auto page = model::packets::PageBuilder::Create(
@@ -1161,20 +1259,22 @@
allow_role_switch);
SendLinkLayerPacket(std::move(page));
- return hci::Status::SUCCESS;
+ return bluetooth::hci::ErrorCode::SUCCESS;
}
-hci::Status LinkLayerController::CreateConnectionCancel(const Address& addr) {
+bluetooth::hci::ErrorCode LinkLayerController::CreateConnectionCancel(
+ const Address& addr) {
if (!connections_.CancelPendingConnection(addr)) {
- return hci::Status::UNKNOWN_CONNECTION;
+ return bluetooth::hci::ErrorCode::UNKNOWN_CONNECTION;
}
- return hci::Status::SUCCESS;
+ return bluetooth::hci::ErrorCode::SUCCESS;
}
-hci::Status LinkLayerController::Disconnect(uint16_t handle, uint8_t reason) {
+bluetooth::hci::ErrorCode LinkLayerController::Disconnect(uint16_t handle,
+ uint8_t reason) {
// TODO: Handle LE
if (!connections_.HasHandle(handle)) {
- return hci::Status::UNKNOWN_CONNECTION;
+ return bluetooth::hci::ErrorCode::UNKNOWN_CONNECTION;
}
const Address& remote = connections_.GetAddress(handle);
@@ -1187,125 +1287,141 @@
DisconnectCleanup(handle, static_cast<uint8_t>(hci::Status::CONNECTION_TERMINATED_BY_LOCAL_HOST));
});
- return hci::Status::SUCCESS;
+ return bluetooth::hci::ErrorCode::SUCCESS;
}
void LinkLayerController::DisconnectCleanup(uint16_t handle, uint8_t reason) {
// TODO: Clean up other connection state.
- send_event_(EventPacketBuilder::CreateDisconnectionCompleteEvent(hci::Status::SUCCESS, handle, reason)->ToVector());
+ auto packet = bluetooth::hci::DisconnectionCompleteBuilder::Create(
+ bluetooth::hci::ErrorCode::SUCCESS, handle,
+ static_cast<bluetooth::hci::ErrorCode>(reason));
+ send_event_(std::move(packet));
}
-hci::Status LinkLayerController::ChangeConnectionPacketType(uint16_t handle, uint16_t types) {
+bluetooth::hci::ErrorCode LinkLayerController::ChangeConnectionPacketType(
+ uint16_t handle, uint16_t types) {
if (!connections_.HasHandle(handle)) {
- return hci::Status::UNKNOWN_CONNECTION;
+ return bluetooth::hci::ErrorCode::UNKNOWN_CONNECTION;
}
- std::unique_ptr<EventPacketBuilder> packet =
- EventPacketBuilder::CreateConnectionPacketTypeChangedEvent(hci::Status::SUCCESS, handle, types);
- std::shared_ptr<std::vector<uint8_t>> raw_packet = packet->ToVector();
- ScheduleTask(milliseconds(20), [this, raw_packet]() { send_event_(raw_packet); });
+ auto packet = bluetooth::hci::ConnectionPacketTypeChangedBuilder::Create(
+ bluetooth::hci::ErrorCode::SUCCESS, handle, types);
+ std::shared_ptr<bluetooth::hci::ConnectionPacketTypeChangedBuilder>
+ shared_packet = std::move(packet);
+ ScheduleTask(milliseconds(20), [this, shared_packet]() {
+ send_event_(std::move(shared_packet));
+ });
- return hci::Status::SUCCESS;
+ return bluetooth::hci::ErrorCode::SUCCESS;
}
-hci::Status LinkLayerController::ChangeConnectionLinkKey(uint16_t handle) {
+bluetooth::hci::ErrorCode LinkLayerController::ChangeConnectionLinkKey(
+ uint16_t handle) {
if (!connections_.HasHandle(handle)) {
- return hci::Status::UNKNOWN_CONNECTION;
+ return bluetooth::hci::ErrorCode::UNKNOWN_CONNECTION;
}
// TODO: implement real logic
- return hci::Status::COMMAND_DISALLOWED;
+ return bluetooth::hci::ErrorCode::COMMAND_DISALLOWED;
}
-hci::Status LinkLayerController::MasterLinkKey(uint8_t /* key_flag */) {
+bluetooth::hci::ErrorCode LinkLayerController::MasterLinkKey(
+ uint8_t /* key_flag */) {
// TODO: implement real logic
- return hci::Status::COMMAND_DISALLOWED;
+ return bluetooth::hci::ErrorCode::COMMAND_DISALLOWED;
}
-hci::Status LinkLayerController::HoldMode(uint16_t handle, uint16_t hold_mode_max_interval,
- uint16_t hold_mode_min_interval) {
+bluetooth::hci::ErrorCode LinkLayerController::HoldMode(
+ uint16_t handle, uint16_t hold_mode_max_interval,
+ uint16_t hold_mode_min_interval) {
if (!connections_.HasHandle(handle)) {
- return hci::Status::UNKNOWN_CONNECTION;
+ return bluetooth::hci::ErrorCode::UNKNOWN_CONNECTION;
}
if (hold_mode_max_interval < hold_mode_min_interval) {
- return hci::Status::INVALID_HCI_COMMAND_PARAMETERS;
+ return bluetooth::hci::ErrorCode::INVALID_HCI_COMMAND_PARAMETERS;
}
// TODO: implement real logic
- return hci::Status::COMMAND_DISALLOWED;
+ return bluetooth::hci::ErrorCode::COMMAND_DISALLOWED;
}
-hci::Status LinkLayerController::SniffMode(uint16_t handle, uint16_t sniff_max_interval, uint16_t sniff_min_interval,
- uint16_t sniff_attempt, uint16_t sniff_timeout) {
+bluetooth::hci::ErrorCode LinkLayerController::SniffMode(
+ uint16_t handle, uint16_t sniff_max_interval, uint16_t sniff_min_interval,
+ uint16_t sniff_attempt, uint16_t sniff_timeout) {
if (!connections_.HasHandle(handle)) {
- return hci::Status::UNKNOWN_CONNECTION;
+ return bluetooth::hci::ErrorCode::UNKNOWN_CONNECTION;
}
if (sniff_max_interval < sniff_min_interval || sniff_attempt < 0x0001 || sniff_attempt > 0x7FFF ||
sniff_timeout > 0x7FFF) {
- return hci::Status::INVALID_HCI_COMMAND_PARAMETERS;
+ return bluetooth::hci::ErrorCode::INVALID_HCI_COMMAND_PARAMETERS;
}
// TODO: implement real logic
- return hci::Status::COMMAND_DISALLOWED;
+ return bluetooth::hci::ErrorCode::COMMAND_DISALLOWED;
}
-hci::Status LinkLayerController::ExitSniffMode(uint16_t handle) {
+bluetooth::hci::ErrorCode LinkLayerController::ExitSniffMode(uint16_t handle) {
if (!connections_.HasHandle(handle)) {
- return hci::Status::UNKNOWN_CONNECTION;
+ return bluetooth::hci::ErrorCode::UNKNOWN_CONNECTION;
}
// TODO: implement real logic
- return hci::Status::COMMAND_DISALLOWED;
+ return bluetooth::hci::ErrorCode::COMMAND_DISALLOWED;
}
-hci::Status LinkLayerController::QosSetup(uint16_t handle, uint8_t service_type, uint32_t /* token_rate */,
- uint32_t /* peak_bandwidth */, uint32_t /* latency */,
- uint32_t /* delay_variation */) {
+bluetooth::hci::ErrorCode LinkLayerController::QosSetup(
+ uint16_t handle, uint8_t service_type, uint32_t /* token_rate */,
+ uint32_t /* peak_bandwidth */, uint32_t /* latency */,
+ uint32_t /* delay_variation */) {
if (!connections_.HasHandle(handle)) {
- return hci::Status::UNKNOWN_CONNECTION;
+ return bluetooth::hci::ErrorCode::UNKNOWN_CONNECTION;
}
if (service_type > 0x02) {
- return hci::Status::INVALID_HCI_COMMAND_PARAMETERS;
+ return bluetooth::hci::ErrorCode::INVALID_HCI_COMMAND_PARAMETERS;
}
// TODO: implement real logic
- return hci::Status::COMMAND_DISALLOWED;
+ return bluetooth::hci::ErrorCode::COMMAND_DISALLOWED;
}
-hci::Status LinkLayerController::SwitchRole(Address /* bd_addr */, uint8_t /* role */) {
+bluetooth::hci::ErrorCode LinkLayerController::SwitchRole(Address /* bd_addr */,
+ uint8_t /* role */) {
// TODO: implement real logic
- return hci::Status::COMMAND_DISALLOWED;
+ return bluetooth::hci::ErrorCode::COMMAND_DISALLOWED;
}
-hci::Status LinkLayerController::WriteLinkPolicySettings(uint16_t handle, uint16_t) {
+bluetooth::hci::ErrorCode LinkLayerController::WriteLinkPolicySettings(
+ uint16_t handle, uint16_t) {
if (!connections_.HasHandle(handle)) {
- return hci::Status::UNKNOWN_CONNECTION;
+ return bluetooth::hci::ErrorCode::UNKNOWN_CONNECTION;
}
- return hci::Status::SUCCESS;
+ return bluetooth::hci::ErrorCode::SUCCESS;
}
-hci::Status LinkLayerController::FlowSpecification(uint16_t handle, uint8_t flow_direction, uint8_t service_type,
- uint32_t /* token_rate */, uint32_t /* token_bucket_size */,
- uint32_t /* peak_bandwidth */, uint32_t /* access_latency */) {
+bluetooth::hci::ErrorCode LinkLayerController::FlowSpecification(
+ uint16_t handle, uint8_t flow_direction, uint8_t service_type,
+ uint32_t /* token_rate */, uint32_t /* token_bucket_size */,
+ uint32_t /* peak_bandwidth */, uint32_t /* access_latency */) {
if (!connections_.HasHandle(handle)) {
- return hci::Status::UNKNOWN_CONNECTION;
+ return bluetooth::hci::ErrorCode::UNKNOWN_CONNECTION;
}
if (flow_direction > 0x01 || service_type > 0x02) {
- return hci::Status::INVALID_HCI_COMMAND_PARAMETERS;
+ return bluetooth::hci::ErrorCode::INVALID_HCI_COMMAND_PARAMETERS;
}
// TODO: implement real logic
- return hci::Status::COMMAND_DISALLOWED;
+ return bluetooth::hci::ErrorCode::COMMAND_DISALLOWED;
}
-hci::Status LinkLayerController::WriteLinkSupervisionTimeout(uint16_t handle, uint16_t) {
+bluetooth::hci::ErrorCode LinkLayerController::WriteLinkSupervisionTimeout(
+ uint16_t handle, uint16_t) {
if (!connections_.HasHandle(handle)) {
- return hci::Status::UNKNOWN_CONNECTION;
+ return bluetooth::hci::ErrorCode::UNKNOWN_CONNECTION;
}
- return hci::Status::SUCCESS;
+ return bluetooth::hci::ErrorCode::SUCCESS;
}
void LinkLayerController::LeWhiteListClear() {
@@ -1424,7 +1540,9 @@
void LinkLayerController::InquiryTimeout() {
if (inquiry_state_ == Inquiry::InquiryState::INQUIRY) {
inquiry_state_ = Inquiry::InquiryState::STANDBY;
- send_event_(EventPacketBuilder::CreateInquiryCompleteEvent(hci::Status::SUCCESS)->ToVector());
+ auto packet = bluetooth::hci::InquiryCompleteBuilder::Create(
+ bluetooth::hci::ErrorCode::SUCCESS);
+ send_event_(std::move(packet));
}
}
diff --git a/vendor_libs/test_vendor_lib/model/controller/link_layer_controller.h b/vendor_libs/test_vendor_lib/model/controller/link_layer_controller.h
index 659093b..36aa671 100644
--- a/vendor_libs/test_vendor_lib/model/controller/link_layer_controller.h
+++ b/vendor_libs/test_vendor_lib/model/controller/link_layer_controller.h
@@ -17,6 +17,8 @@
#pragma once
#include "acl_connection_handler.h"
+#include "hci/address.h"
+#include "hci/hci_packets.h"
#include "include/hci.h"
#include "include/inquiry.h"
#include "include/phy.h"
@@ -26,18 +28,22 @@
#include "packets/hci/sco_packet_view.h"
#include "packets/link_layer_packets.h"
#include "security_manager.h"
-#include "types/address.h"
namespace test_vendor_lib {
+using ::bluetooth::hci::Address;
+
class LinkLayerController {
public:
static constexpr size_t kIrk_size = 16;
LinkLayerController(const DeviceProperties& properties) : properties_(properties) {}
- hci::Status SendCommandToRemoteByAddress(hci::OpCode opcode, packets::PacketView<true> args, const Address& remote,
- bool use_public_address);
- hci::Status SendCommandToRemoteByHandle(hci::OpCode opcode, packets::PacketView<true> args, uint16_t handle);
+ bluetooth::hci::ErrorCode SendCommandToRemoteByAddress(
+ bluetooth::hci::OpCode opcode, packets::PacketView<true> args,
+ const Address& remote, bool use_public_address);
+ bluetooth::hci::ErrorCode SendCommandToRemoteByHandle(
+ bluetooth::hci::OpCode opcode, packets::PacketView<true> args,
+ uint16_t handle);
hci::Status SendScoToRemote(packets::ScoPacketView sco_packet);
hci::Status SendAclToRemote(packets::AclPacketView acl_packet);
@@ -45,31 +51,45 @@
void StartSimplePairing(const Address& address);
void AuthenticateRemoteStage1(const Address& address, PairingType pairing_type);
void AuthenticateRemoteStage2(const Address& address);
- hci::Status LinkKeyRequestReply(const Address& address, packets::PacketView<true> key);
- hci::Status LinkKeyRequestNegativeReply(const Address& address);
- hci::Status IoCapabilityRequestReply(const Address& peer, uint8_t io_capability, uint8_t oob_data_present_flag,
- uint8_t authentication_requirements);
- hci::Status IoCapabilityRequestNegativeReply(const Address& peer, hci::Status reason);
- hci::Status UserConfirmationRequestReply(const Address& peer);
- hci::Status UserConfirmationRequestNegativeReply(const Address& peer);
- hci::Status UserPasskeyRequestReply(const Address& peer, uint32_t numeric_value);
- hci::Status UserPasskeyRequestNegativeReply(const Address& peer);
- hci::Status RemoteOobDataRequestReply(const Address& peer, const std::vector<uint8_t>& c,
- const std::vector<uint8_t>& r);
- hci::Status RemoteOobDataRequestNegativeReply(const Address& peer);
+ bluetooth::hci::ErrorCode LinkKeyRequestReply(const Address& address,
+ packets::PacketView<true> key);
+ bluetooth::hci::ErrorCode LinkKeyRequestNegativeReply(const Address& address);
+ bluetooth::hci::ErrorCode IoCapabilityRequestReply(
+ const Address& peer, uint8_t io_capability, uint8_t oob_data_present_flag,
+ uint8_t authentication_requirements);
+ bluetooth::hci::ErrorCode IoCapabilityRequestNegativeReply(
+ const Address& peer, hci::Status reason);
+ bluetooth::hci::ErrorCode UserConfirmationRequestReply(const Address& peer);
+ bluetooth::hci::ErrorCode UserConfirmationRequestNegativeReply(
+ const Address& peer);
+ bluetooth::hci::ErrorCode UserPasskeyRequestReply(const Address& peer,
+ uint32_t numeric_value);
+ bluetooth::hci::ErrorCode UserPasskeyRequestNegativeReply(
+ const Address& peer);
+ bluetooth::hci::ErrorCode RemoteOobDataRequestReply(
+ const Address& peer, const std::vector<uint8_t>& c,
+ const std::vector<uint8_t>& r);
+ bluetooth::hci::ErrorCode RemoteOobDataRequestNegativeReply(
+ const Address& peer);
void HandleSetConnectionEncryption(const Address& address, uint16_t handle, uint8_t encryption_enable);
- hci::Status SetConnectionEncryption(uint16_t handle, uint8_t encryption_enable);
+ bluetooth::hci::ErrorCode SetConnectionEncryption(uint16_t handle,
+ uint8_t encryption_enable);
void HandleAuthenticationRequest(const Address& address, uint16_t handle);
- hci::Status AuthenticationRequested(uint16_t handle);
+ bluetooth::hci::ErrorCode AuthenticationRequested(uint16_t handle);
- hci::Status AcceptConnectionRequest(const Address& addr, bool try_role_switch);
+ bluetooth::hci::ErrorCode AcceptConnectionRequest(const Address& addr,
+ bool try_role_switch);
void MakeSlaveConnection(const Address& addr, bool try_role_switch);
- hci::Status RejectConnectionRequest(const Address& addr, uint8_t reason);
+ bluetooth::hci::ErrorCode RejectConnectionRequest(const Address& addr,
+ uint8_t reason);
void RejectSlaveConnection(const Address& addr, uint8_t reason);
- hci::Status CreateConnection(const Address& addr, uint16_t packet_type, uint8_t page_scan_mode, uint16_t clock_offset,
- uint8_t allow_role_switch);
- hci::Status CreateConnectionCancel(const Address& addr);
- hci::Status Disconnect(uint16_t handle, uint8_t reason);
+ bluetooth::hci::ErrorCode CreateConnection(const Address& addr,
+ uint16_t packet_type,
+ uint8_t page_scan_mode,
+ uint16_t clock_offset,
+ uint8_t allow_role_switch);
+ bluetooth::hci::ErrorCode CreateConnectionCancel(const Address& addr);
+ bluetooth::hci::ErrorCode Disconnect(uint16_t handle, uint8_t reason);
private:
void DisconnectCleanup(uint16_t handle, uint8_t reason);
@@ -84,7 +104,9 @@
void CancelScheduledTask(AsyncTaskId task);
// Set the callbacks for sending packets to the HCI.
- void RegisterEventChannel(const std::function<void(std::shared_ptr<std::vector<uint8_t>>)>& send_event);
+ void RegisterEventChannel(
+ const std::function<void(
+ std::shared_ptr<bluetooth::hci::EventPacketBuilder>)>& send_event_);
void RegisterAclChannel(const std::function<void(std::shared_ptr<std::vector<uint8_t>>)>& send_acl);
@@ -129,10 +151,11 @@
bool LeResolvingListFull();
void LeSetPrivacyMode(uint8_t address_type, Address addr, uint8_t mode);
- hci::Status SetLeAdvertisingEnable(uint8_t le_advertising_enable) {
+ bluetooth::hci::ErrorCode SetLeAdvertisingEnable(
+ uint8_t le_advertising_enable) {
le_advertising_enable_ = le_advertising_enable;
// TODO: Check properties and return errors
- return hci::Status::SUCCESS;
+ return bluetooth::hci::ErrorCode::SUCCESS;
}
void SetLeScanEnable(uint8_t le_scan_enable) {
@@ -156,9 +179,9 @@
void SetLeAddressType(uint8_t le_address_type) {
le_address_type_ = le_address_type;
}
- hci::Status SetLeConnect(bool le_connect) {
+ bluetooth::hci::ErrorCode SetLeConnect(bool le_connect) {
le_connect_ = le_connect;
- return hci::Status::SUCCESS;
+ return bluetooth::hci::ErrorCode::SUCCESS;
}
void SetLeConnectionIntervalMin(uint16_t min) {
le_connection_interval_min_ = min;
@@ -200,20 +223,32 @@
void SetInquiryScanEnable(bool enable);
void SetPageScanEnable(bool enable);
- hci::Status ChangeConnectionPacketType(uint16_t handle, uint16_t types);
- hci::Status ChangeConnectionLinkKey(uint16_t handle);
- hci::Status MasterLinkKey(uint8_t key_flag);
- hci::Status HoldMode(uint16_t handle, uint16_t hold_mode_max_interval, uint16_t hold_mode_min_interval);
- hci::Status SniffMode(uint16_t handle, uint16_t sniff_max_interval, uint16_t sniff_min_interval,
- uint16_t sniff_attempt, uint16_t sniff_timeout);
- hci::Status ExitSniffMode(uint16_t handle);
- hci::Status QosSetup(uint16_t handle, uint8_t service_type, uint32_t token_rate, uint32_t peak_bandwidth,
- uint32_t latency, uint32_t delay_variation);
- hci::Status SwitchRole(Address bd_addr, uint8_t role);
- hci::Status WriteLinkPolicySettings(uint16_t handle, uint16_t settings);
- hci::Status FlowSpecification(uint16_t handle, uint8_t flow_direction, uint8_t service_type, uint32_t token_rate,
- uint32_t token_bucket_size, uint32_t peak_bandwidth, uint32_t access_latency);
- hci::Status WriteLinkSupervisionTimeout(uint16_t handle, uint16_t timeout);
+ bluetooth::hci::ErrorCode ChangeConnectionPacketType(uint16_t handle,
+ uint16_t types);
+ bluetooth::hci::ErrorCode ChangeConnectionLinkKey(uint16_t handle);
+ bluetooth::hci::ErrorCode MasterLinkKey(uint8_t key_flag);
+ bluetooth::hci::ErrorCode HoldMode(uint16_t handle,
+ uint16_t hold_mode_max_interval,
+ uint16_t hold_mode_min_interval);
+ bluetooth::hci::ErrorCode SniffMode(uint16_t handle,
+ uint16_t sniff_max_interval,
+ uint16_t sniff_min_interval,
+ uint16_t sniff_attempt,
+ uint16_t sniff_timeout);
+ bluetooth::hci::ErrorCode ExitSniffMode(uint16_t handle);
+ bluetooth::hci::ErrorCode QosSetup(uint16_t handle, uint8_t service_type,
+ uint32_t token_rate,
+ uint32_t peak_bandwidth, uint32_t latency,
+ uint32_t delay_variation);
+ bluetooth::hci::ErrorCode SwitchRole(Address bd_addr, uint8_t role);
+ bluetooth::hci::ErrorCode WriteLinkPolicySettings(uint16_t handle,
+ uint16_t settings);
+ bluetooth::hci::ErrorCode FlowSpecification(
+ uint16_t handle, uint8_t flow_direction, uint8_t service_type,
+ uint32_t token_rate, uint32_t token_bucket_size, uint32_t peak_bandwidth,
+ uint32_t access_latency);
+ bluetooth::hci::ErrorCode WriteLinkSupervisionTimeout(uint16_t handle,
+ uint16_t timeout);
protected:
void SendLeLinkLayerPacket(
@@ -270,7 +305,8 @@
// Callbacks to send packets back to the HCI.
std::function<void(std::shared_ptr<std::vector<uint8_t>>)> send_acl_;
- std::function<void(std::shared_ptr<std::vector<uint8_t>>)> send_event_;
+ std::function<void(std::shared_ptr<bluetooth::hci::EventPacketBuilder>)>
+ send_event_;
std::function<void(std::shared_ptr<std::vector<uint8_t>>)> send_sco_;
// Callback to send packets to remote devices.
diff --git a/vendor_libs/test_vendor_lib/model/controller/security_manager.h b/vendor_libs/test_vendor_lib/model/controller/security_manager.h
index 94284cb..8d566ea 100644
--- a/vendor_libs/test_vendor_lib/model/controller/security_manager.h
+++ b/vendor_libs/test_vendor_lib/model/controller/security_manager.h
@@ -21,10 +21,12 @@
#include <unordered_map>
#include <vector>
-#include "types/address.h"
+#include "hci/address.h"
namespace test_vendor_lib {
+using ::bluetooth::hci::Address;
+
enum class PairingType : uint8_t {
AUTO_CONFIRMATION,
CONFIRM_Y_N,
diff --git a/vendor_libs/test_vendor_lib/model/devices/car_kit.cc b/vendor_libs/test_vendor_lib/model/devices/car_kit.cc
index 9f325a4..0445312 100644
--- a/vendor_libs/test_vendor_lib/model/devices/car_kit.cc
+++ b/vendor_libs/test_vendor_lib/model/devices/car_kit.cc
@@ -32,7 +32,8 @@
// Stub in packet handling for now
link_layer_controller_.RegisterAclChannel([](std::shared_ptr<std::vector<uint8_t>>) {});
- link_layer_controller_.RegisterEventChannel([](std::shared_ptr<std::vector<uint8_t>>) {});
+ link_layer_controller_.RegisterEventChannel(
+ [](std::shared_ptr<bluetooth::hci::EventPacketBuilder>) {});
link_layer_controller_.RegisterScoChannel([](std::shared_ptr<std::vector<uint8_t>>) {});
link_layer_controller_.RegisterRemoteChannel(
[this](std::shared_ptr<model::packets::LinkLayerPacketBuilder> packet,
diff --git a/vendor_libs/test_vendor_lib/model/devices/car_kit.h b/vendor_libs/test_vendor_lib/model/devices/car_kit.h
index 6822f27..f59a2ad 100644
--- a/vendor_libs/test_vendor_lib/model/devices/car_kit.h
+++ b/vendor_libs/test_vendor_lib/model/devices/car_kit.h
@@ -20,6 +20,7 @@
#include <vector>
#include "device.h"
+#include "hci/hci_packets.h"
#include "model/controller/link_layer_controller.h"
namespace {
diff --git a/vendor_libs/test_vendor_lib/model/devices/device.h b/vendor_libs/test_vendor_lib/model/devices/device.h
index 6d781b8..90901df 100644
--- a/vendor_libs/test_vendor_lib/model/devices/device.h
+++ b/vendor_libs/test_vendor_lib/model/devices/device.h
@@ -22,14 +22,16 @@
#include <string>
#include <vector>
+#include "hci/address.h"
#include "model/devices/device_properties.h"
#include "model/setup/phy_layer.h"
-#include "types/address.h"
#include "packets/link_layer_packets.h"
namespace test_vendor_lib {
+using ::bluetooth::hci::Address;
+
// Represent a Bluetooth Device
// - Provide Get*() and Set*() functions for device attributes.
class Device {
diff --git a/vendor_libs/test_vendor_lib/model/devices/device_properties.h b/vendor_libs/test_vendor_lib/model/devices/device_properties.h
index fed710a..d787bb9 100644
--- a/vendor_libs/test_vendor_lib/model/devices/device_properties.h
+++ b/vendor_libs/test_vendor_lib/model/devices/device_properties.h
@@ -21,12 +21,15 @@
#include <vector>
#include "base/json/json_value_converter.h"
+#include "hci/address.h"
+#include "hci/hci_packets.h"
#include "os/log.h"
-#include "types/address.h"
-#include "types/class_of_device.h"
namespace test_vendor_lib {
+using ::bluetooth::hci::Address;
+using ::bluetooth::hci::ClassOfDevice;
+
class DeviceProperties {
public:
explicit DeviceProperties(const std::string& file_name = "");
diff --git a/vendor_libs/test_vendor_lib/model/devices/hci_socket_device.cc b/vendor_libs/test_vendor_lib/model/devices/hci_socket_device.cc
index c94a964..6865714 100644
--- a/vendor_libs/test_vendor_lib/model/devices/hci_socket_device.cc
+++ b/vendor_libs/test_vendor_lib/model/devices/hci_socket_device.cc
@@ -91,8 +91,9 @@
close_callback_();
});
- RegisterEventChannel(
- [this](std::shared_ptr<std::vector<uint8_t>> packet) { SendHci(hci::PacketType::EVENT, packet); });
+ RegisterEventChannel([this](std::shared_ptr<std::vector<uint8_t>> packet) {
+ SendHci(hci::PacketType::EVENT, packet);
+ });
RegisterAclChannel([this](std::shared_ptr<std::vector<uint8_t>> packet) { SendHci(hci::PacketType::ACL, packet); });
RegisterScoChannel([this](std::shared_ptr<std::vector<uint8_t>> packet) { SendHci(hci::PacketType::SCO, packet); });
}
diff --git a/vendor_libs/test_vendor_lib/model/devices/link_layer_socket_device.cc b/vendor_libs/test_vendor_lib/model/devices/link_layer_socket_device.cc
index ab2c5f1..ddff51b 100644
--- a/vendor_libs/test_vendor_lib/model/devices/link_layer_socket_device.cc
+++ b/vendor_libs/test_vendor_lib/model/devices/link_layer_socket_device.cc
@@ -18,8 +18,9 @@
#include <unistd.h>
-#include "packets/packet_view.h"
-#include "packets/view.h"
+#include "packet/packet_view.h"
+#include "packet/raw_builder.h"
+#include "packet/view.h"
using std::vector;
@@ -30,18 +31,18 @@
void LinkLayerSocketDevice::TimerTick() {
if (bytes_left_ == 0) {
- size_t size_bytes = sizeof(uint32_t);
- received_ = std::make_shared<std::vector<uint8_t>>(size_bytes);
- size_t bytes_received = socket_.TryReceive(size_bytes, received_->data());
+ auto packet_size = std::make_shared<std::vector<uint8_t>>(kSizeBytes);
+
+ size_t bytes_received = socket_.TryReceive(kSizeBytes, packet_size->data());
if (bytes_received == 0) {
return;
}
- ASSERT_LOG(bytes_received == size_bytes, "bytes_received == %d",
- static_cast<int>(bytes_received));
- packets::PacketView<true> size({packets::View(received_, 0, size_bytes)});
+ ASSERT_LOG(bytes_received == kSizeBytes, "bytes_received == %d", static_cast<int>(bytes_received));
+ bluetooth::packet::PacketView<bluetooth::packet::kLittleEndian> size(
+ {bluetooth::packet::View(packet_size, 0, kSizeBytes)});
bytes_left_ = size.begin().extract<uint32_t>();
- received_->resize(size_bytes + bytes_left_);
- offset_ = size_bytes;
+ received_ = std::make_shared<std::vector<uint8_t>>(bytes_left_);
+ offset_ = 0;
}
size_t bytes_received = socket_.TryReceive(bytes_left_, received_->data() + offset_);
if (bytes_received == 0) {
@@ -62,11 +63,16 @@
void LinkLayerSocketDevice::IncomingPacket(
model::packets::LinkLayerPacketView packet) {
- std::shared_ptr<std::vector<uint8_t>> payload_bytes =
- std::make_shared<std::vector<uint8_t>>(packet.begin(), packet.end());
- packets::PacketView<true> packet_view(payload_bytes);
+ auto size_packet = bluetooth::packet::RawBuilder();
+ size_packet.AddOctets4(packet.size());
+ std::vector<uint8_t> size_bytes;
+ bluetooth::packet::BitInserter bit_inserter(size_bytes);
+ size_packet.Serialize(bit_inserter);
- socket_.TrySend(packet_view);
+ if (socket_.TrySend(size_bytes) == kSizeBytes) {
+ std::vector<uint8_t> payload_bytes{packet.begin(), packet.end()};
+ socket_.TrySend(payload_bytes);
+ }
}
} // namespace test_vendor_lib
diff --git a/vendor_libs/test_vendor_lib/model/devices/link_layer_socket_device.h b/vendor_libs/test_vendor_lib/model/devices/link_layer_socket_device.h
index 2b662d1..564233c 100644
--- a/vendor_libs/test_vendor_lib/model/devices/link_layer_socket_device.h
+++ b/vendor_libs/test_vendor_lib/model/devices/link_layer_socket_device.h
@@ -47,6 +47,8 @@
virtual void TimerTick() override;
+ static constexpr size_t kSizeBytes = sizeof(uint32_t);
+
private:
net::PolledSocket socket_;
Phy::Type phy_type_;
diff --git a/vendor_libs/test_vendor_lib/model/devices/polled_socket.cc b/vendor_libs/test_vendor_lib/model/devices/polled_socket.cc
index 2f96665..6fea766 100644
--- a/vendor_libs/test_vendor_lib/model/devices/polled_socket.cc
+++ b/vendor_libs/test_vendor_lib/model/devices/polled_socket.cc
@@ -45,17 +45,11 @@
file_descriptor_ = -1;
}
-size_t PolledSocket::TrySend(packets::PacketView<true> packet) {
+size_t PolledSocket::TrySend(const std::vector<uint8_t>& packet) {
if (file_descriptor_ == -1) {
return 0;
}
- // Could skip this copy if the packet is guaranteed to be contiguous.
- std::vector<uint8_t> copy;
- copy.reserve(packet.size());
- for (const auto&& c : packet) {
- copy.push_back(c);
- }
- int ret = write(file_descriptor_, copy.data(), copy.size());
+ int ret = write(file_descriptor_, packet.data(), packet.size());
if (ret == -1) {
LOG_WARN("%s error %s", __func__, strerror(errno));
return 0;
diff --git a/vendor_libs/test_vendor_lib/model/devices/polled_socket.h b/vendor_libs/test_vendor_lib/model/devices/polled_socket.h
index b697f56..a196fd6 100644
--- a/vendor_libs/test_vendor_lib/model/devices/polled_socket.h
+++ b/vendor_libs/test_vendor_lib/model/devices/polled_socket.h
@@ -26,8 +26,6 @@
#include <sys/socket.h>
#include <unistd.h>
-#include "packets/packet_view.h"
-
namespace test_vendor_lib {
namespace net {
@@ -41,7 +39,7 @@
PolledSocket(PolledSocket&& p);
virtual ~PolledSocket();
- size_t TrySend(packets::PacketView<true> packet);
+ size_t TrySend(const std::vector<uint8_t>& packet);
// size_t TrySendVector(const std::vector<const std::vector<uint8_t>&>& data);
size_t TryReceive(size_t num_bytes, uint8_t* data);
diff --git a/vendor_libs/test_vendor_lib/model/devices/sniffer.h b/vendor_libs/test_vendor_lib/model/devices/sniffer.h
index 162a401..a5c7277 100644
--- a/vendor_libs/test_vendor_lib/model/devices/sniffer.h
+++ b/vendor_libs/test_vendor_lib/model/devices/sniffer.h
@@ -20,11 +20,13 @@
#include <vector>
#include "device.h"
+#include "hci/address.h"
#include "packets/link_layer_packets.h"
-#include "types/address.h"
namespace test_vendor_lib {
+using ::bluetooth::hci::Address;
+
class Sniffer : public Device {
public:
Sniffer();
diff --git a/vendor_libs/test_vendor_lib/packets/Android.bp b/vendor_libs/test_vendor_lib/packets/Android.bp
index 69a7b00..d25a11f 100644
--- a/vendor_libs/test_vendor_lib/packets/Android.bp
+++ b/vendor_libs/test_vendor_lib/packets/Android.bp
@@ -18,10 +18,7 @@
"hci/acl_packet_view.cc",
"hci/command_packet_builder.cc",
"hci/command_packet_view.cc",
- "hci/event_packet_builder.cc",
- "hci/event_payload_builder.cc",
"hci/hci_packet_builder.cc",
- "hci/le_meta_event_builder.cc",
"hci/sco_packet_builder.cc",
"hci/sco_packet_view.cc",
],
@@ -57,7 +54,7 @@
"test/packet_builder_test.cc",
"test/packet_view_test.cc",
"hci/test/acl_builder_test.cc",
- "hci/test/event_builder_test.cc",
+ ":BluetoothHciClassSources",
],
header_libs: [
"libbluetooth_headers",
diff --git a/vendor_libs/test_vendor_lib/packets/hci/event_packet_builder.cc b/vendor_libs/test_vendor_lib/packets/hci/event_packet_builder.cc
deleted file mode 100644
index 2dd1cd6..0000000
--- a/vendor_libs/test_vendor_lib/packets/hci/event_packet_builder.cc
+++ /dev/null
@@ -1,847 +0,0 @@
-/*
- * Copyright 2018 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include "packets/hci/event_packet_builder.h"
-
-#include "hci.h"
-#include "os/log.h"
-#include "packets/hci/le_meta_event_builder.h"
-
-using std::vector;
-using test_vendor_lib::hci::EventCode;
-using test_vendor_lib::hci::OpCode;
-using test_vendor_lib::hci::Status;
-
-namespace test_vendor_lib {
-namespace packets {
-
-EventPacketBuilder::EventPacketBuilder(EventCode event_code)
- : event_code_(event_code), payload_(std::make_unique<RawBuilder>()) {}
-
-EventPacketBuilder::EventPacketBuilder(EventCode event_code, std::unique_ptr<RawBuilder> payload)
- : event_code_(event_code), payload_(std::move(payload)) {}
-
-// Bluetooth Core Specification Version 4.2, Volume 2, Part E, Section 7.7.1
-std::unique_ptr<EventPacketBuilder> EventPacketBuilder::CreateInquiryCompleteEvent(hci::Status status) {
- std::unique_ptr<EventPacketBuilder> evt_ptr =
- std::unique_ptr<EventPacketBuilder>(new EventPacketBuilder(EventCode::INQUIRY_COMPLETE));
- ASSERT(evt_ptr->AddPayloadOctets1(static_cast<uint8_t>(status)));
-
- return evt_ptr;
-}
-
-// Bluetooth Core Specification Version 4.2, Volume 2, Part E, Section 7.7.14
-std::unique_ptr<EventPacketBuilder> EventPacketBuilder::CreateCommandCompleteEvent(
- hci::OpCode command_opcode, const vector<uint8_t>& event_return_parameters) {
- std::unique_ptr<EventPacketBuilder> evt_ptr =
- std::unique_ptr<EventPacketBuilder>(new EventPacketBuilder(EventCode::COMMAND_COMPLETE));
-
- ASSERT(evt_ptr->AddPayloadOctets1(1)); // num_hci_command_packets
- ASSERT(evt_ptr->AddPayloadOctets2(static_cast<uint16_t>(command_opcode)));
- ASSERT(evt_ptr->AddPayloadOctets(event_return_parameters));
-
- return evt_ptr;
-}
-
-std::unique_ptr<EventPacketBuilder> EventPacketBuilder::CreateCommandCompleteOnlyStatusEvent(hci::OpCode command_opcode,
- hci::Status status) {
- std::unique_ptr<EventPacketBuilder> evt_ptr =
- std::unique_ptr<EventPacketBuilder>(new EventPacketBuilder(EventCode::COMMAND_COMPLETE));
-
- ASSERT(evt_ptr->AddPayloadOctets1(1)); // num_hci_command_packets
- ASSERT(evt_ptr->AddPayloadOctets2(static_cast<uint16_t>(command_opcode)));
- ASSERT(evt_ptr->AddPayloadOctets1(static_cast<uint8_t>(status)));
-
- return evt_ptr;
-}
-
-std::unique_ptr<EventPacketBuilder> EventPacketBuilder::CreateCommandCompleteStatusAndAddressEvent(
- hci::OpCode command_opcode, hci::Status status, const Address& address) {
- std::unique_ptr<EventPacketBuilder> evt_ptr =
- std::unique_ptr<EventPacketBuilder>(new EventPacketBuilder(EventCode::COMMAND_COMPLETE));
-
- ASSERT(evt_ptr->AddPayloadOctets1(1)); // num_hci_command_packets
- ASSERT(evt_ptr->AddPayloadOctets2(static_cast<uint16_t>(command_opcode)));
- ASSERT(evt_ptr->AddPayloadOctets1(static_cast<uint8_t>(status)));
- ASSERT(evt_ptr->AddPayloadAddress(address));
-
- return evt_ptr;
-}
-
-std::unique_ptr<EventPacketBuilder> EventPacketBuilder::CreateCommandCompleteUnknownOpCodeEvent(
- uint16_t command_opcode) {
- std::unique_ptr<EventPacketBuilder> evt_ptr =
- std::unique_ptr<EventPacketBuilder>(new EventPacketBuilder(EventCode::COMMAND_COMPLETE));
-
- ASSERT(evt_ptr->AddPayloadOctets1(1)); // num_hci_command_packets
- ASSERT(evt_ptr->AddPayloadOctets2(static_cast<uint16_t>(command_opcode)));
- ASSERT(evt_ptr->AddPayloadOctets1(static_cast<uint8_t>(Status::UNKNOWN_COMMAND)));
-
- return evt_ptr;
-}
-
-// Bluetooth Core Specification Version 4.2, Volume 2, Part E, Section 7.7.15
-std::unique_ptr<EventPacketBuilder> EventPacketBuilder::CreateCommandStatusEvent(hci::Status status,
- hci::OpCode command_opcode) {
- std::unique_ptr<EventPacketBuilder> evt_ptr =
- std::unique_ptr<EventPacketBuilder>(new EventPacketBuilder(EventCode::COMMAND_STATUS));
-
- ASSERT(evt_ptr->AddPayloadOctets1(static_cast<uint8_t>(status)));
- ASSERT(evt_ptr->AddPayloadOctets1(1)); // num_hci_command_packets
- ASSERT(evt_ptr->AddPayloadOctets2(static_cast<uint16_t>(command_opcode)));
-
- return evt_ptr;
-}
-
-// Bluetooth Core Specification Version 4.2, Volume 2, Part E, Section 7.7.19
-std::unique_ptr<EventPacketBuilder> EventPacketBuilder::CreateNumberOfCompletedPacketsEvent(
- uint16_t handle, uint16_t num_completed_packets) {
- std::unique_ptr<RawBuilder> payload = std::make_unique<CountedBuilder>();
- std::unique_ptr<EventPacketBuilder> evt_ptr = std::unique_ptr<EventPacketBuilder>(
- new EventPacketBuilder(EventCode::NUMBER_OF_COMPLETED_PACKETS, std::move(payload)));
-
- evt_ptr->AddCompletedPackets(handle, num_completed_packets);
-
- return evt_ptr;
-}
-
-void EventPacketBuilder::AddCompletedPackets(uint16_t handle, uint16_t num_completed_packets) {
- ASSERT(event_code_ == EventCode::NUMBER_OF_COMPLETED_PACKETS);
-
- std::unique_ptr<RawBuilder> handle_pair = std::make_unique<RawBuilder>();
- ASSERT(handle_pair->AddOctets2(handle));
- ASSERT(handle_pair->AddOctets2(num_completed_packets));
- AddBuilder(std::move(handle_pair));
-}
-
-// Bluetooth Core Specification Version 4.2, Volume 2, Part E, Section 7.3.10
-std::unique_ptr<EventPacketBuilder> EventPacketBuilder::CreateCommandCompleteDeleteStoredLinkKey(
- hci::Status status, uint16_t num_keys_deleted) {
- std::unique_ptr<EventPacketBuilder> evt_ptr =
- EventPacketBuilder::CreateCommandCompleteOnlyStatusEvent(OpCode::DELETE_STORED_LINK_KEY, status);
-
- ASSERT(evt_ptr->AddPayloadOctets2(num_keys_deleted));
-
- return evt_ptr;
-}
-
-// Bluetooth Core Specification Version 4.2, Volume 2, Part E, Section 7.3.12
-std::unique_ptr<EventPacketBuilder> EventPacketBuilder::CreateCommandCompleteReadLocalName(
- hci::Status status, const std::vector<uint8_t>& local_name) {
- std::unique_ptr<EventPacketBuilder> evt_ptr =
- EventPacketBuilder::CreateCommandCompleteOnlyStatusEvent(OpCode::READ_LOCAL_NAME, status);
-
- size_t len = local_name.size();
- if (len > 247) {
- len = 247;
- }
- ASSERT(evt_ptr->AddPayloadOctets(len, local_name));
- ASSERT(evt_ptr->AddPayloadOctets1(0)); // Null terminated
- for (size_t i = 0; i < 248 - len - 1; i++) ASSERT(evt_ptr->AddPayloadOctets1(0xFF));
-
- return evt_ptr;
-}
-
-// Bluetooth Core Specification Version 4.2, Volume 2, Part E, Section 7.3.23
-std::unique_ptr<EventPacketBuilder> EventPacketBuilder::CreateCommandCompleteReadAuthenticationEnable(
- hci::Status status, uint8_t enable) {
- std::unique_ptr<EventPacketBuilder> evt_ptr =
- EventPacketBuilder::CreateCommandCompleteOnlyStatusEvent(OpCode::READ_LOCAL_NAME, status);
- ASSERT(evt_ptr->AddPayloadOctets1(enable));
- return evt_ptr;
-}
-
-// Bluetooth Core Specification Version 4.2, Volume 2, Part E, Section 7.4.1
-std::unique_ptr<EventPacketBuilder> EventPacketBuilder::CreateCommandCompleteReadLocalVersionInformation(
- hci::Status status, uint8_t hci_version, uint16_t hci_revision, uint8_t lmp_pal_version, uint16_t manufacturer_name,
- uint16_t lmp_pal_subversion) {
- std::unique_ptr<EventPacketBuilder> evt_ptr =
- EventPacketBuilder::CreateCommandCompleteOnlyStatusEvent(OpCode::READ_LOCAL_VERSION_INFORMATION, status);
-
- ASSERT(evt_ptr->AddPayloadOctets1(hci_version));
- ASSERT(evt_ptr->AddPayloadOctets2(hci_revision));
- ASSERT(evt_ptr->AddPayloadOctets1(lmp_pal_version));
- ASSERT(evt_ptr->AddPayloadOctets2(manufacturer_name));
- ASSERT(evt_ptr->AddPayloadOctets2(lmp_pal_subversion));
-
- return evt_ptr;
-}
-
-std::unique_ptr<EventPacketBuilder> EventPacketBuilder::CreateReadRemoteVersionInformationEvent(
- hci::Status status, uint16_t connection_handle, uint8_t lmp_pal_version, uint16_t manufacturer_name,
- uint16_t lmp_pal_subversion) {
- std::unique_ptr<EventPacketBuilder> evt_ptr =
- std::unique_ptr<EventPacketBuilder>(new EventPacketBuilder(EventCode::READ_REMOTE_VERSION_INFORMATION_COMPLETE));
-
- ASSERT(evt_ptr->AddPayloadOctets1(static_cast<uint8_t>(status)));
- ASSERT(evt_ptr->AddPayloadOctets2(connection_handle));
- ASSERT(evt_ptr->AddPayloadOctets1(lmp_pal_version));
- ASSERT(evt_ptr->AddPayloadOctets2(manufacturer_name));
- ASSERT(evt_ptr->AddPayloadOctets2(lmp_pal_subversion));
-
- return evt_ptr;
-}
-// Bluetooth Core Specification Version 4.2, Volume 2, Part E, Section 7.4.2
-std::unique_ptr<EventPacketBuilder> EventPacketBuilder::CreateCommandCompleteReadLocalSupportedCommands(
- hci::Status status, const vector<uint8_t>& supported_commands) {
- std::unique_ptr<EventPacketBuilder> evt_ptr =
- EventPacketBuilder::CreateCommandCompleteOnlyStatusEvent(OpCode::READ_LOCAL_SUPPORTED_COMMANDS, status);
-
- ASSERT(evt_ptr->AddPayloadOctets(64, supported_commands));
-
- return evt_ptr;
-}
-
-// Bluetooth Core Specification Version 4.2, Volume 2, Part E, Section 7.4.3
-std::unique_ptr<EventPacketBuilder> EventPacketBuilder::CreateCommandCompleteReadLocalSupportedFeatures(
- hci::Status status, uint64_t supported_features) {
- std::unique_ptr<EventPacketBuilder> evt_ptr =
- EventPacketBuilder::CreateCommandCompleteOnlyStatusEvent(OpCode::READ_LOCAL_SUPPORTED_FEATURES, status);
-
- ASSERT(evt_ptr->AddPayloadOctets8(supported_features));
-
- return evt_ptr;
-}
-
-// Bluetooth Core Specification Version 4.2, Volume 2, Part E, Section 7.4.4
-std::unique_ptr<EventPacketBuilder> EventPacketBuilder::CreateCommandCompleteReadLocalExtendedFeatures(
- hci::Status status, uint8_t page_number, uint8_t maximum_page_number, uint64_t extended_lmp_features) {
- std::unique_ptr<EventPacketBuilder> evt_ptr =
- EventPacketBuilder::CreateCommandCompleteOnlyStatusEvent(OpCode::READ_LOCAL_EXTENDED_FEATURES, status);
-
- ASSERT(evt_ptr->AddPayloadOctets1(page_number));
- ASSERT(evt_ptr->AddPayloadOctets1(maximum_page_number));
- ASSERT(evt_ptr->AddPayloadOctets8(extended_lmp_features));
-
- return evt_ptr;
-}
-
-std::unique_ptr<EventPacketBuilder> EventPacketBuilder::CreateReadRemoteExtendedFeaturesEvent(
- hci::Status status, uint16_t handle, uint8_t page_number, uint8_t maximum_page_number,
- uint64_t extended_lmp_features) {
- std::unique_ptr<EventPacketBuilder> evt_ptr =
- std::unique_ptr<EventPacketBuilder>(new EventPacketBuilder(EventCode::READ_REMOTE_EXTENDED_FEATURES_COMPLETE));
-
- ASSERT(evt_ptr->AddPayloadOctets1(static_cast<uint8_t>(status)));
- ASSERT(evt_ptr->AddPayloadOctets2(handle));
- ASSERT(evt_ptr->AddPayloadOctets1(page_number));
- ASSERT(evt_ptr->AddPayloadOctets1(maximum_page_number));
- ASSERT(evt_ptr->AddPayloadOctets8(extended_lmp_features));
-
- return evt_ptr;
-}
-
-// Bluetooth Core Specification Version 4.2, Volume 2, Part E, Section 7.4.5
-std::unique_ptr<EventPacketBuilder> EventPacketBuilder::CreateCommandCompleteReadBufferSize(
- hci::Status status, uint16_t hc_acl_data_packet_length, uint8_t hc_synchronous_data_packet_length,
- uint16_t hc_total_num_acl_data_packets, uint16_t hc_total_synchronous_data_packets) {
- std::unique_ptr<EventPacketBuilder> evt_ptr =
- EventPacketBuilder::CreateCommandCompleteOnlyStatusEvent(OpCode::READ_BUFFER_SIZE, status);
-
- ASSERT(evt_ptr->AddPayloadOctets2(hc_acl_data_packet_length));
- ASSERT(evt_ptr->AddPayloadOctets1(hc_synchronous_data_packet_length));
- ASSERT(evt_ptr->AddPayloadOctets2(hc_total_num_acl_data_packets));
- ASSERT(evt_ptr->AddPayloadOctets2(hc_total_synchronous_data_packets));
-
- return evt_ptr;
-}
-
-// Bluetooth Core Specification Version 4.2, Volume 2, Part E, Section 7.4.6
-std::unique_ptr<EventPacketBuilder> EventPacketBuilder::CreateCommandCompleteReadBdAddr(hci::Status status,
- const Address& address) {
- std::unique_ptr<EventPacketBuilder> evt_ptr =
- EventPacketBuilder::CreateCommandCompleteOnlyStatusEvent(OpCode::READ_BD_ADDR, status);
-
- ASSERT(evt_ptr->AddPayloadAddress(address));
-
- return evt_ptr;
-}
-
-// Bluetooth Core Specification Version 4.2, Volume 2, Part E, Section 7.4.8
-std::unique_ptr<EventPacketBuilder> EventPacketBuilder::CreateCommandCompleteReadLocalSupportedCodecs(
- hci::Status status, const vector<uint8_t>& supported_codecs, const vector<uint32_t>& vendor_specific_codecs) {
- std::unique_ptr<EventPacketBuilder> evt_ptr =
- EventPacketBuilder::CreateCommandCompleteOnlyStatusEvent(OpCode::READ_LOCAL_SUPPORTED_CODECS, status);
-
- ASSERT(evt_ptr->AddPayloadOctets1(supported_codecs.size()));
- ASSERT(evt_ptr->AddPayloadOctets(supported_codecs));
- ASSERT(evt_ptr->AddPayloadOctets1(vendor_specific_codecs.size()));
- for (size_t i = 0; i < vendor_specific_codecs.size(); i++)
- ASSERT(evt_ptr->AddPayloadOctets4(vendor_specific_codecs[i]));
-
- return evt_ptr;
-}
-
-// Bluetooth Core Specification Version 5.1, Volume 2, Part E, Section 7.5.7
-std::unique_ptr<EventPacketBuilder>
-EventPacketBuilder::CreateCommandCompleteReadEncryptionKeySize(
- hci::Status status, uint16_t handle, uint8_t key_size) {
- std::unique_ptr<EventPacketBuilder> evt_ptr =
- EventPacketBuilder::CreateCommandCompleteOnlyStatusEvent(
- OpCode::READ_ENCRYPTION_KEY_SIZE, status);
-
- ASSERT(evt_ptr->AddPayloadOctets2(handle));
- ASSERT(evt_ptr->AddPayloadOctets1(key_size));
-
- return evt_ptr;
-}
-
-// Bluetooth Core Specification Version 4.2, Volume 2, Part E, Section 7.6.1
-std::unique_ptr<EventPacketBuilder> EventPacketBuilder::CreateCommandCompleteReadLoopbackMode(hci::Status status,
- hci::LoopbackMode mode) {
- std::unique_ptr<EventPacketBuilder> evt_ptr =
- EventPacketBuilder::CreateCommandCompleteOnlyStatusEvent(OpCode::READ_LOOPBACK_MODE, status);
- ASSERT(evt_ptr->AddPayloadOctets1(static_cast<uint8_t>(mode)));
-
- return evt_ptr;
-}
-
-// Bluetooth Core Specification Version 4.2, Volume 2, Part E, Section 7.7.2
-std::unique_ptr<EventPacketBuilder> EventPacketBuilder::CreateInquiryResultEvent() {
- std::unique_ptr<RawBuilder> payload = std::unique_ptr<RawBuilder>(new CountedBuilder());
- std::unique_ptr<EventPacketBuilder> evt_ptr(new EventPacketBuilder(EventCode::INQUIRY_RESULT, std::move(payload)));
-
- return evt_ptr;
-}
-
-bool EventPacketBuilder::AddInquiryResult(const Address& address, uint8_t page_scan_repetition_mode,
- ClassOfDevice class_of_device, uint16_t clock_offset) {
- ASSERT(event_code_ == EventCode::INQUIRY_RESULT);
-
- if (!CanAddPayloadOctets(14)) return false;
-
- std::unique_ptr<RawBuilder> result = std::make_unique<RawBuilder>();
-
- ASSERT(result->AddAddress(address));
- ASSERT(result->AddOctets1(page_scan_repetition_mode));
- ASSERT(result->AddOctets2(0)); // Reserved
- ASSERT(result->AddOctets1(class_of_device.cod[0]));
- ASSERT(result->AddOctets1(class_of_device.cod[1]));
- ASSERT(result->AddOctets1(class_of_device.cod[2]));
- ASSERT(!(clock_offset & 0x8000));
- ASSERT(result->AddOctets2(clock_offset));
- AddBuilder(std::move(result));
- return true;
-}
-
-// Bluetooth Core Specification Version 4.2, Volume 2, Part E, Section 7.7.3
-std::unique_ptr<EventPacketBuilder> EventPacketBuilder::CreateConnectionCompleteEvent(
- hci::Status status, uint16_t handle, const Address& address, hci::LinkType link_type, bool encryption_enabled) {
- std::unique_ptr<EventPacketBuilder> evt_ptr =
- std::unique_ptr<EventPacketBuilder>(new EventPacketBuilder(EventCode::CONNECTION_COMPLETE));
-
- ASSERT(evt_ptr->AddPayloadOctets1(static_cast<uint8_t>(status)));
- ASSERT((handle & 0xf000) == 0); // Handles are 12-bit values.
- ASSERT(evt_ptr->AddPayloadOctets2(handle));
- ASSERT(evt_ptr->AddPayloadAddress(address));
- ASSERT(evt_ptr->AddPayloadOctets1(static_cast<uint8_t>(link_type)));
- ASSERT(evt_ptr->AddPayloadOctets1(encryption_enabled ? 1 : 0));
-
- return evt_ptr;
-}
-
-// Bluetooth Core Specification Version 4.2, Volume 2, Part E, Section 7.7.4
-std::unique_ptr<EventPacketBuilder> EventPacketBuilder::CreateConnectionRequestEvent(const Address& address,
- ClassOfDevice class_of_device,
- hci::LinkType link_type) {
- std::unique_ptr<EventPacketBuilder> evt_ptr =
- std::unique_ptr<EventPacketBuilder>(new EventPacketBuilder(EventCode::CONNECTION_REQUEST));
-
- ASSERT(evt_ptr->AddPayloadAddress(address));
- ASSERT(evt_ptr->AddPayloadOctets1(class_of_device.cod[0]));
- ASSERT(evt_ptr->AddPayloadOctets1(class_of_device.cod[1]));
- ASSERT(evt_ptr->AddPayloadOctets1(class_of_device.cod[2]));
- ASSERT(evt_ptr->AddPayloadOctets1(static_cast<uint8_t>(link_type)));
-
- return evt_ptr;
-}
-
-// Bluetooth Core Specification Version 4.2, Volume 2, Part E, Section 7.7.5
-std::unique_ptr<EventPacketBuilder> EventPacketBuilder::CreateDisconnectionCompleteEvent(hci::Status status,
- uint16_t handle,
- uint8_t reason) {
- std::unique_ptr<EventPacketBuilder> evt_ptr =
- std::unique_ptr<EventPacketBuilder>(new EventPacketBuilder(EventCode::DISCONNECTION_COMPLETE));
-
- ASSERT(evt_ptr->AddPayloadOctets1(static_cast<uint8_t>(status)));
- ASSERT((handle & 0xf000) == 0); // Handles are 12-bit values.
- ASSERT(evt_ptr->AddPayloadOctets2(handle));
- ASSERT(evt_ptr->AddPayloadOctets1(reason));
-
- return evt_ptr;
-}
-
-// Bluetooth Core Specification Version 4.2, Volume 2, Part E, Section 7.7.6
-std::unique_ptr<EventPacketBuilder> EventPacketBuilder::CreateAuthenticationCompleteEvent(hci::Status status,
- uint16_t handle) {
- std::unique_ptr<EventPacketBuilder> evt_ptr =
- std::unique_ptr<EventPacketBuilder>(new EventPacketBuilder(EventCode::AUTHENTICATION_COMPLETE));
- ASSERT(evt_ptr->AddPayloadOctets1(static_cast<uint8_t>(status)));
- ASSERT((handle & 0xf000) == 0); // Handles are 12-bit values.
- ASSERT(evt_ptr->AddPayloadOctets2(handle));
- return evt_ptr;
-}
-
-// Bluetooth Core Specification Version 4.2, Volume 2, Part E, Section 7.7.7
-std::unique_ptr<EventPacketBuilder> EventPacketBuilder::CreateRemoteNameRequestCompleteEvent(
- hci::Status status, const Address& address, const std::string& remote_name) {
- std::unique_ptr<EventPacketBuilder> evt_ptr =
- std::unique_ptr<EventPacketBuilder>(new EventPacketBuilder(EventCode::REMOTE_NAME_REQUEST_COMPLETE));
-
- ASSERT(evt_ptr->AddPayloadOctets1(static_cast<uint8_t>(status)));
- ASSERT(evt_ptr->AddPayloadAddress(address));
- for (size_t i = 0; i < remote_name.length(); i++) ASSERT(evt_ptr->AddPayloadOctets1(remote_name[i]));
- ASSERT(evt_ptr->AddPayloadOctets1(0)); // Null terminated
- for (size_t i = 0; i < 248 - remote_name.length() - 1; i++) ASSERT(evt_ptr->AddPayloadOctets1(0xFF));
-
- return evt_ptr;
-}
-
-// Bluetooth Core Specification Version 4.2, Volume 2, Part E, Section 7.7.23
-std::unique_ptr<EventPacketBuilder> EventPacketBuilder::CreateLinkKeyRequestEvent(const Address& remote) {
- std::unique_ptr<EventPacketBuilder> evt_ptr =
- std::unique_ptr<EventPacketBuilder>(new EventPacketBuilder(EventCode::LINK_KEY_REQUEST));
- ASSERT(evt_ptr->AddPayloadAddress(remote));
- return evt_ptr;
-}
-
-// Bluetooth Core Specification Version 4.2, Volume 2, Part E, Section 7.7.24
-std::unique_ptr<EventPacketBuilder> EventPacketBuilder::CreateLinkKeyNotificationEvent(const Address& remote,
- const std::vector<uint8_t>& key,
- uint8_t key_type) {
- std::unique_ptr<EventPacketBuilder> evt_ptr =
- std::unique_ptr<EventPacketBuilder>(new EventPacketBuilder(EventCode::LINK_KEY_NOTIFICATION));
- ASSERT(evt_ptr->AddPayloadAddress(remote));
- ASSERT(key.size() == 16);
- ASSERT(evt_ptr->AddPayloadOctets(key));
- ASSERT(evt_ptr->AddPayloadOctets1(key_type));
- return evt_ptr;
-}
-
-// Bluetooth Core Specification Version 4.2, Volume 2, Part E, Section 7.7.25
-std::unique_ptr<EventPacketBuilder> EventPacketBuilder::CreateLoopbackCommandEvent(hci::OpCode opcode,
- PacketView<true> payload) {
- std::unique_ptr<EventPacketBuilder> evt_ptr =
- std::unique_ptr<EventPacketBuilder>(new EventPacketBuilder(EventCode::LOOPBACK_COMMAND));
- ASSERT(evt_ptr->AddPayloadOctets2(static_cast<uint16_t>(opcode)));
- ASSERT(evt_ptr->AddPayloadOctets1(static_cast<uint8_t>(payload.size())));
- for (const auto& payload_byte : payload) // Fill the packet.
- evt_ptr->AddPayloadOctets1(payload_byte);
- return evt_ptr;
-}
-
-// Bluetooth Core Specification Version 4.2, Volume 2, Part E, Section 7.7.28
-std::unique_ptr<EventPacketBuilder> EventPacketBuilder::CreateReadClockOffsetEvent(hci::Status status, uint16_t handle,
- uint16_t offset) {
- std::unique_ptr<EventPacketBuilder> evt_ptr =
- std::unique_ptr<EventPacketBuilder>(new EventPacketBuilder(EventCode::READ_CLOCK_OFFSET_COMPLETE));
- ASSERT(evt_ptr->AddPayloadOctets1(static_cast<uint8_t>(status)));
- ASSERT(evt_ptr->AddPayloadOctets2(handle));
- ASSERT(evt_ptr->AddPayloadOctets2(offset));
- return evt_ptr;
-}
-
-// Bluetooth Core Specification Version 4.2, Volume 2, Part E, Section 7.7.29
-std::unique_ptr<EventPacketBuilder> EventPacketBuilder::CreateConnectionPacketTypeChangedEvent(hci::Status status,
- uint16_t handle,
- uint16_t packet_type) {
- std::unique_ptr<EventPacketBuilder> evt_ptr =
- std::unique_ptr<EventPacketBuilder>(new EventPacketBuilder(EventCode::CONNECTION_PACKET_TYPE_CHANGED));
- ASSERT(evt_ptr->AddPayloadOctets1(static_cast<uint8_t>(status)));
- ASSERT(evt_ptr->AddPayloadOctets2(handle));
- ASSERT(evt_ptr->AddPayloadOctets2(packet_type));
- return evt_ptr;
-}
-
-// Bluetooth Core Specification Version 4.2, Volume 2, Part E, Section 7.7.37
-std::unique_ptr<EventPacketBuilder> EventPacketBuilder::CreateSniffSubratingEvent(const hci::Status status,
- uint16_t handle) {
- std::unique_ptr<EventPacketBuilder> evt_ptr =
- EventPacketBuilder::CreateCommandCompleteOnlyStatusEvent(OpCode::SNIFF_SUBRATING, status);
-
- ASSERT(evt_ptr->AddPayloadOctets2(handle));
- return evt_ptr;
-}
-
-// Bluetooth Core Specification Version 4.2, Volume 2, Part E, Section 7.7.38
-std::unique_ptr<EventPacketBuilder> EventPacketBuilder::CreateExtendedInquiryResultEvent(
- const Address& address, uint8_t page_scan_repetition_mode, ClassOfDevice class_of_device, uint16_t clock_offset,
- uint8_t rssi, const vector<uint8_t>& extended_inquiry_response) {
- std::unique_ptr<EventPacketBuilder> evt_ptr =
- std::unique_ptr<EventPacketBuilder>(new EventPacketBuilder(EventCode::EXTENDED_INQUIRY_RESULT));
-
- ASSERT(evt_ptr->AddPayloadOctets1(1)); // Always contains a single response
-
- ASSERT(evt_ptr->AddPayloadAddress(address));
- ASSERT(evt_ptr->AddPayloadOctets1(page_scan_repetition_mode));
- ASSERT(evt_ptr->AddPayloadOctets1(0)); // Reserved
- ASSERT(evt_ptr->AddPayloadOctets1(class_of_device.cod[0]));
- ASSERT(evt_ptr->AddPayloadOctets1(class_of_device.cod[1]));
- ASSERT(evt_ptr->AddPayloadOctets1(class_of_device.cod[2]));
- ASSERT(!(clock_offset & 0x8000));
- ASSERT(evt_ptr->AddPayloadOctets2(clock_offset));
- ASSERT(evt_ptr->AddPayloadOctets1(rssi));
- ASSERT(evt_ptr->AddPayloadOctets(extended_inquiry_response));
- evt_ptr->AddPayloadOctets1(0x00); // End marker
- while (evt_ptr->AddPayloadOctets1(0x00))
- ; // Fill packet
- return evt_ptr;
-}
-
-// Bluetooth Core Specification Version 4.2, Volume 2, Part E, Section 7.7.38
-std::unique_ptr<EventPacketBuilder> EventPacketBuilder::CreateEncryptionKeyRefreshCompleteEvent(hci::Status status,
- uint16_t handle) {
- std::unique_ptr<EventPacketBuilder> evt_ptr =
- std::unique_ptr<EventPacketBuilder>(new EventPacketBuilder(EventCode::ENCRYPTION_KEY_REFRESH_COMPLETE));
- ASSERT(evt_ptr->AddPayloadOctets1(static_cast<uint8_t>(status)));
- ASSERT(evt_ptr->AddPayloadOctets2(handle));
- return evt_ptr;
-}
-
-// Bluetooth Core Specification Version 4.2, Volume 2, Part E, Section 7.7.40
-std::unique_ptr<EventPacketBuilder> EventPacketBuilder::CreateIoCapabilityRequestEvent(const Address& peer) {
- std::unique_ptr<EventPacketBuilder> evt_ptr =
- std::unique_ptr<EventPacketBuilder>(new EventPacketBuilder(EventCode::IO_CAPABILITY_REQUEST));
-
- ASSERT(evt_ptr->AddPayloadAddress(peer));
- return evt_ptr;
-} // namespace packets
-
-// Bluetooth Core Specification Version 4.2, Volume 2, Part E, Section 7.7.41
-std::unique_ptr<EventPacketBuilder> EventPacketBuilder::CreateIoCapabilityResponseEvent(
- const Address& peer, uint8_t io_capability, bool oob_data_present, uint8_t authentication_requirements) {
- std::unique_ptr<EventPacketBuilder> evt_ptr =
- std::unique_ptr<EventPacketBuilder>(new EventPacketBuilder(EventCode::IO_CAPABILITY_RESPONSE));
-
- ASSERT(evt_ptr->AddPayloadAddress(peer));
- ASSERT(evt_ptr->AddPayloadOctets1(io_capability));
- ASSERT(evt_ptr->AddPayloadOctets1(oob_data_present));
- ASSERT(evt_ptr->AddPayloadOctets1(authentication_requirements));
- return evt_ptr;
-} // namespace test_vendor_lib
-
-// Bluetooth Core Specification Version 4.2, Volume 2, Part E, Section 7.7.42
-std::unique_ptr<EventPacketBuilder> EventPacketBuilder::CreateUserConfirmationRequestEvent(const Address& peer,
- uint32_t numeric_value) {
- std::unique_ptr<EventPacketBuilder> evt_ptr =
- std::unique_ptr<EventPacketBuilder>(new EventPacketBuilder(EventCode::USER_CONFIRMATION_REQUEST));
-
- ASSERT(evt_ptr->AddPayloadAddress(peer));
- ASSERT(evt_ptr->AddPayloadOctets4(numeric_value));
- return evt_ptr;
-}
-
-// Bluetooth Core Specification Version 4.2, Volume 2, Part E, Section 7.7.43
-std::unique_ptr<EventPacketBuilder> EventPacketBuilder::CreateUserPasskeyRequestEvent(const Address& peer) {
- std::unique_ptr<EventPacketBuilder> evt_ptr =
- std::unique_ptr<EventPacketBuilder>(new EventPacketBuilder(EventCode::USER_PASSKEY_REQUEST));
-
- ASSERT(evt_ptr->AddPayloadAddress(peer));
- return evt_ptr;
-}
-
-// Bluetooth Core Specification Version 4.2, Volume 2, Part E, Section 7.7.44
-std::unique_ptr<EventPacketBuilder> EventPacketBuilder::CreateRemoteOobDataRequestEvent(const Address& peer) {
- std::unique_ptr<EventPacketBuilder> evt_ptr =
- std::unique_ptr<EventPacketBuilder>(new EventPacketBuilder(EventCode::REMOTE_OOB_DATA_REQUEST));
-
- ASSERT(evt_ptr->AddPayloadAddress(peer));
- return evt_ptr;
-}
-
-// Bluetooth Core Specification Version 4.2, Volume 2, Part E, Section 7.7.45
-std::unique_ptr<EventPacketBuilder> EventPacketBuilder::CreateSimplePairingCompleteEvent(hci::Status status,
- const Address& peer) {
- std::unique_ptr<EventPacketBuilder> evt_ptr =
- std::unique_ptr<EventPacketBuilder>(new EventPacketBuilder(EventCode::SIMPLE_PAIRING_COMPLETE));
-
- ASSERT(evt_ptr->AddPayloadOctets1(static_cast<uint8_t>(status)));
- ASSERT(evt_ptr->AddPayloadAddress(peer));
- return evt_ptr;
-}
-
-// Bluetooth Core Specification Version 4.2, Volume 2, Part E, Section 7.7.48
-std::unique_ptr<EventPacketBuilder> EventPacketBuilder::CreateUserPasskeyNotificationEvent(const Address& peer,
- uint32_t passkey) {
- std::unique_ptr<EventPacketBuilder> evt_ptr =
- std::unique_ptr<EventPacketBuilder>(new EventPacketBuilder(EventCode::USER_PASSKEY_NOTIFICATION));
-
- ASSERT(evt_ptr->AddPayloadAddress(peer));
- ASSERT(evt_ptr->AddPayloadOctets4(passkey));
- return evt_ptr;
-}
-
-// Bluetooth Core Specification Version 4.2, Volume 2, Part E, Section 7.7.49
-std::unique_ptr<EventPacketBuilder> EventPacketBuilder::CreateKeypressNotificationEvent(const Address& peer,
- uint8_t notification_type) {
- std::unique_ptr<EventPacketBuilder> evt_ptr =
- std::unique_ptr<EventPacketBuilder>(new EventPacketBuilder(EventCode::KEYPRESS_NOTIFICATION));
-
- ASSERT(evt_ptr->AddPayloadAddress(peer));
- ASSERT(evt_ptr->AddPayloadOctets1(notification_type));
- return evt_ptr;
-}
-
-// Bluetooth Core Specification Version 4.2, Volume 2, Part E, Section 7.7.65.1
-std::unique_ptr<EventPacketBuilder> EventPacketBuilder::CreateLeConnectionCompleteEvent(
- hci::Status status, uint16_t handle, uint8_t role, uint8_t peer_address_type, const Address& peer,
- uint16_t interval, uint16_t latency, uint16_t supervision_timeout) {
- std::unique_ptr<RawBuilder> meta_evt = LeMetaEventBuilder::CreateLeConnectionCompleteEvent(
- status, handle, role, peer_address_type, peer, interval, latency, supervision_timeout);
-
- return std::unique_ptr<EventPacketBuilder>(new EventPacketBuilder(EventCode::LE_META_EVENT, std::move(meta_evt)));
-}
-
-std::unique_ptr<EventPacketBuilder> EventPacketBuilder::CreateLeEnhancedConnectionCompleteEvent(
- hci::Status status, uint16_t handle, uint8_t role, uint8_t peer_address_type, const Address& peer,
- const Address& local_private_address, const Address& peer_private_address, uint16_t interval, uint16_t latency,
- uint16_t supervision_timeout) {
- std::unique_ptr<RawBuilder> meta_evt = LeMetaEventBuilder::CreateLeEnhancedConnectionCompleteEvent(
- status, handle, role, peer_address_type, peer, local_private_address, peer_private_address, interval, latency,
- supervision_timeout);
-
- return std::unique_ptr<EventPacketBuilder>(new EventPacketBuilder(EventCode::LE_META_EVENT, std::move(meta_evt)));
-}
-
-std::unique_ptr<EventPacketBuilder> EventPacketBuilder::CreateLeConnectionUpdateCompleteEvent(
- hci::Status status, uint16_t handle, uint16_t interval, uint16_t latency, uint16_t supervision_timeout) {
- std::unique_ptr<RawBuilder> meta_evt =
- LeMetaEventBuilder::CreateLeConnectionUpdateCompleteEvent(status, handle, interval, latency, supervision_timeout);
-
- return std::unique_ptr<EventPacketBuilder>(new EventPacketBuilder(EventCode::LE_META_EVENT, std::move(meta_evt)));
-}
-
-// Bluetooth Core Specification Version 4.2, Volume 2, Part E, Section 7.7.65.2
-std::unique_ptr<EventPacketBuilder> EventPacketBuilder::CreateLeAdvertisingReportEvent() {
- std::unique_ptr<RawBuilder> meta_evt = LeMetaEventBuilder::CreateLeAdvertisingReportEvent();
-
- return std::unique_ptr<EventPacketBuilder>(new EventPacketBuilder(EventCode::LE_META_EVENT, std::move(meta_evt)));
-}
-
-bool EventPacketBuilder::AddLeAdvertisingReport(LeAdvertisement::AdvertisementType event_type,
- LeAdvertisement::AddressType addr_type, const Address& addr,
- const vector<uint8_t>& data, uint8_t rssi) {
- ASSERT(event_code_ == EventCode::LE_META_EVENT);
-
- // Upcast the payload to add the next report.
- LeMetaEventBuilder* meta_ptr = static_cast<LeMetaEventBuilder*>(payload_.get());
- return meta_ptr->AddLeAdvertisingReport(event_type, addr_type, addr, data, rssi);
-}
-
-// Bluetooth Core Specification Version 4.2, Volume 2, Part E, Section 7.7.65.4
-std::unique_ptr<EventPacketBuilder> EventPacketBuilder::CreateLeRemoteUsedFeaturesEvent(hci::Status status,
- uint16_t handle,
- uint64_t features) {
- std::unique_ptr<RawBuilder> meta_evt = LeMetaEventBuilder::CreateLeRemoteUsedFeaturesEvent(status, handle, features);
- return std::unique_ptr<EventPacketBuilder>(new EventPacketBuilder(EventCode::LE_META_EVENT, std::move(meta_evt)));
-}
-
-std::unique_ptr<EventPacketBuilder> EventPacketBuilder::CreateRemoteSupportedFeaturesEvent(hci::Status status,
- uint16_t handle,
- uint64_t features) {
- std::unique_ptr<EventPacketBuilder> evt_ptr =
- std::unique_ptr<EventPacketBuilder>(new EventPacketBuilder(EventCode::READ_REMOTE_SUPPORTED_FEATURES_COMPLETE));
-
- ASSERT(evt_ptr->AddPayloadOctets1(static_cast<uint8_t>(status)));
- ASSERT(evt_ptr->AddPayloadOctets2(handle));
- ASSERT(evt_ptr->AddPayloadOctets8(features));
-
- return evt_ptr;
-}
-
-std::unique_ptr<EventPacketBuilder> EventPacketBuilder::CreateCommandCompleteLinkKeyRequestReply(hci::Status status,
- Address address) {
- std::unique_ptr<EventPacketBuilder> evt_ptr =
- EventPacketBuilder::CreateCommandCompleteOnlyStatusEvent(OpCode::LINK_KEY_REQUEST_REPLY, status);
-
- ASSERT(evt_ptr->AddPayloadAddress(address));
-
- return evt_ptr;
-}
-
-std::unique_ptr<EventPacketBuilder> EventPacketBuilder::CreateCommandCompleteLinkKeyRequestNegativeReply(
- hci::Status status, Address address) {
- std::unique_ptr<EventPacketBuilder> evt_ptr =
- EventPacketBuilder::CreateCommandCompleteOnlyStatusEvent(OpCode::LINK_KEY_REQUEST_NEGATIVE_REPLY, status);
-
- ASSERT(evt_ptr->AddPayloadAddress(address));
-
- return evt_ptr;
-}
-
-std::unique_ptr<EventPacketBuilder> EventPacketBuilder::CreateCommandCompleteWriteLinkPolicySettings(hci::Status status,
- uint16_t handle) {
- std::unique_ptr<EventPacketBuilder> evt_ptr =
- EventPacketBuilder::CreateCommandCompleteOnlyStatusEvent(OpCode::WRITE_LINK_POLICY_SETTINGS, status);
-
- ASSERT(evt_ptr->AddPayloadOctets2(handle));
-
- return evt_ptr;
-}
-
-std::unique_ptr<EventPacketBuilder> EventPacketBuilder::CreateCommandCompleteWriteLinkSupervisionTimeout(
- hci::Status status, uint16_t handle) {
- std::unique_ptr<EventPacketBuilder> evt_ptr =
- EventPacketBuilder::CreateCommandCompleteOnlyStatusEvent(OpCode::WRITE_LINK_SUPERVISION_TIMEOUT, status);
-
- ASSERT(evt_ptr->AddPayloadOctets2(handle));
-
- return evt_ptr;
-}
-
-// Bluetooth Core Specification Version 4.2, Volume 2, Part E, Section 7.8.2
-std::unique_ptr<EventPacketBuilder> EventPacketBuilder::CreateCommandCompleteLeReadBufferSize(
- hci::Status status, uint16_t hc_le_data_packet_length, uint8_t hc_total_num_le_data_packets) {
- std::unique_ptr<EventPacketBuilder> evt_ptr =
- EventPacketBuilder::CreateCommandCompleteOnlyStatusEvent(OpCode::LE_READ_BUFFER_SIZE, status);
-
- ASSERT(evt_ptr->AddPayloadOctets2(hc_le_data_packet_length));
- ASSERT(evt_ptr->AddPayloadOctets1(hc_total_num_le_data_packets));
-
- return evt_ptr;
-}
-
-// Bluetooth Core Specification Version 4.2, Volume 2, Part E, Section 7.8.3
-std::unique_ptr<EventPacketBuilder> EventPacketBuilder::CreateCommandCompleteLeReadLocalSupportedFeatures(
- hci::Status status, uint64_t le_features) {
- std::unique_ptr<EventPacketBuilder> evt_ptr =
- EventPacketBuilder::CreateCommandCompleteOnlyStatusEvent(OpCode::LE_READ_LOCAL_SUPPORTED_FEATURES, status);
-
- ASSERT(evt_ptr->AddPayloadOctets8(le_features));
-
- return evt_ptr;
-}
-
-// Bluetooth Core Specification Version 4.2, Volume 2, Part E, Section 7.8.14
-std::unique_ptr<EventPacketBuilder> EventPacketBuilder::CreateCommandCompleteLeReadWhiteListSize(
- hci::Status status, uint8_t white_list_size) {
- std::unique_ptr<EventPacketBuilder> evt_ptr =
- EventPacketBuilder::CreateCommandCompleteOnlyStatusEvent(OpCode::LE_READ_WHITE_LIST_SIZE, status);
-
- ASSERT(evt_ptr->AddPayloadOctets8(white_list_size));
-
- return evt_ptr;
-}
-
-// Bluetooth Core Specification Version 4.2, Volume 2, Part E, Section 7.8.23
-std::unique_ptr<EventPacketBuilder> EventPacketBuilder::CreateCommandCompleteLeRand(hci::Status status,
- uint64_t random_val) {
- std::unique_ptr<EventPacketBuilder> evt_ptr =
- EventPacketBuilder::CreateCommandCompleteOnlyStatusEvent(OpCode::LE_RAND, status);
-
- ASSERT(evt_ptr->AddPayloadOctets8(random_val));
-
- return evt_ptr;
-}
-
-// Bluetooth Core Specification Version 4.2, Volume 2, Part E, Section 7.8.27
-std::unique_ptr<EventPacketBuilder> EventPacketBuilder::CreateCommandCompleteLeReadSupportedStates(hci::Status status,
- uint64_t le_states) {
- std::unique_ptr<EventPacketBuilder> evt_ptr =
- EventPacketBuilder::CreateCommandCompleteOnlyStatusEvent(OpCode::LE_READ_SUPPORTED_STATES, status);
-
- ASSERT(evt_ptr->AddPayloadOctets8(le_states));
-
- return evt_ptr;
-}
-
-// Vendor-specific commands
-
-std::unique_ptr<EventPacketBuilder> EventPacketBuilder::CreateCommandCompleteLeGetVendorCapabilities(
- hci::Status status, const vector<uint8_t>& vendor_cap) {
- std::unique_ptr<EventPacketBuilder> evt_ptr =
- EventPacketBuilder::CreateCommandCompleteOnlyStatusEvent(OpCode::LE_GET_VENDOR_CAPABILITIES, status);
-
- ASSERT(evt_ptr->AddPayloadOctets(vendor_cap));
-
- return evt_ptr;
-}
-
-std::unique_ptr<EventPacketBuilder> EventPacketBuilder::CreateEncryptionChange(hci::Status status, uint16_t handle,
- uint8_t encryption_enable) {
- std::unique_ptr<EventPacketBuilder> evt_ptr =
- std::unique_ptr<EventPacketBuilder>(new EventPacketBuilder(EventCode::ENCRYPTION_CHANGE));
-
- ASSERT(evt_ptr->AddPayloadOctets1(static_cast<uint8_t>(status)));
- ASSERT(evt_ptr->AddPayloadOctets2(handle));
- ASSERT(evt_ptr->AddPayloadOctets1(encryption_enable));
-
- return evt_ptr;
-}
-
-size_t EventPacketBuilder::size() const {
- size_t header_size = 2; // Event code and payload size
- return header_size + payload_->size();
-}
-
-void EventPacketBuilder::Serialize(std::back_insert_iterator<std::vector<uint8_t>> it) const {
- insert(static_cast<uint8_t>(event_code_), it);
- uint8_t payload_size = size() - 2; // Event code and payload size
- ASSERT_LOG(size() - 2 == static_cast<size_t>(payload_size), "Payload too large for an event: %d",
- static_cast<int>(size()));
- insert(payload_size, it);
- payload_->Serialize(it);
-}
-
-bool EventPacketBuilder::CanAddPayloadOctets(size_t octets) {
- return payload_->CanAddOctets(octets);
-}
-
-bool EventPacketBuilder::AddPayloadOctets(size_t octets, const std::vector<uint8_t>& bytes) {
- return payload_->AddOctets(octets, bytes);
-}
-
-bool EventPacketBuilder::AddPayloadOctets(const std::vector<uint8_t>& bytes) {
- return payload_->AddOctets(bytes);
-}
-
-bool EventPacketBuilder::AddPayloadOctets1(uint8_t value) {
- return payload_->AddOctets1(value);
-}
-
-bool EventPacketBuilder::AddPayloadOctets2(uint16_t value) {
- return payload_->AddOctets2(value);
-}
-
-bool EventPacketBuilder::AddPayloadOctets3(uint32_t value) {
- return payload_->AddOctets3(value);
-}
-
-bool EventPacketBuilder::AddPayloadOctets4(uint32_t value) {
- return payload_->AddOctets4(value);
-}
-
-bool EventPacketBuilder::AddPayloadOctets6(uint64_t value) {
- return payload_->AddOctets6(value);
-}
-
-bool EventPacketBuilder::AddPayloadOctets8(uint64_t value) {
- return payload_->AddOctets8(value);
-}
-
-bool EventPacketBuilder::AddPayloadAddress(Address address) {
- return payload_->AddAddress(address);
-}
-
-bool EventPacketBuilder::AddBuilder(std::unique_ptr<BasePacketBuilder> builder) {
- // Upcast the payload to add the next builder.
- CountedBuilder* temp_ptr = static_cast<CountedBuilder*>(payload_.get());
- temp_ptr->Add(std::move(builder));
- return true;
-}
-
-} // namespace packets
-} // namespace test_vendor_lib
diff --git a/vendor_libs/test_vendor_lib/packets/hci/event_packet_builder.h b/vendor_libs/test_vendor_lib/packets/hci/event_packet_builder.h
deleted file mode 100644
index c0fe633..0000000
--- a/vendor_libs/test_vendor_lib/packets/hci/event_packet_builder.h
+++ /dev/null
@@ -1,340 +0,0 @@
-/*
- * Copyright 2018 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#pragma once
-
-#include <cstdint>
-#include <memory>
-#include <string>
-#include <vector>
-
-#include "include/hci.h"
-#include "include/le_advertisement.h"
-#include "packets/counted_builder.h"
-#include "packets/hci/hci_packet_builder.h"
-#include "packets/packet_builder.h"
-#include "packets/packet_view.h"
-#include "packets/raw_builder.h"
-#include "types/address.h"
-
-namespace test_vendor_lib {
-namespace packets {
-
-// Event Packets are specified in the Bluetooth Core Specification Version 4.2,
-// Volume 2, Part E, Section 5.4.4 (page 477). Event Packets begin with a 2
-// octet header formatted as follows:
-// - Event Code: 1 octet
-// - Parameter Total Length: 1 octet
-class EventPacketBuilder : public HciPacketBuilder {
- public:
- virtual ~EventPacketBuilder() override = default;
-
- // Bluetooth Core Specification Version 4.2, Volume 2, Part E, Section 7.7.1
- static std::unique_ptr<EventPacketBuilder> CreateInquiryCompleteEvent(hci::Status status);
-
- // Bluetooth Core Specification Version 4.2, Volume 2, Part E, Section 7.7.14
- // This should only be used for testing to send non-standard packets
- // Most code should use the more specific functions that follow
- static std::unique_ptr<EventPacketBuilder> CreateCommandCompleteEvent(
- hci::OpCode command_opcode, const std::vector<uint8_t>& event_return_parameters);
-
- static std::unique_ptr<EventPacketBuilder> CreateCommandCompleteOnlyStatusEvent(hci::OpCode command_opcode,
- hci::Status status);
-
- static std::unique_ptr<EventPacketBuilder> CreateCommandCompleteStatusAndAddressEvent(hci::OpCode command_opcode,
- hci::Status status,
- const Address& address);
-
- static std::unique_ptr<EventPacketBuilder> CreateCommandCompleteUnknownOpCodeEvent(uint16_t command_opcode);
-
- // Bluetooth Core Specification Version 4.2, Volume 2, Part E, Section 7.7.15
- static std::unique_ptr<EventPacketBuilder> CreateCommandStatusEvent(hci::Status status, hci::OpCode command_opcode);
-
- // Bluetooth Core Specification Version 4.2, Volume 2, Part E, Section 7.7.19
- static std::unique_ptr<EventPacketBuilder> CreateNumberOfCompletedPacketsEvent(uint16_t handle,
- uint16_t num_completed_packets);
-
- void AddCompletedPackets(uint16_t handle, uint16_t num_completed_packets);
-
- // Bluetooth Core Specification Version 4.2, Volume 2, Part E, Section 7.1.10
- static std::unique_ptr<EventPacketBuilder> CreateCommandCompleteLinkKeyRequestReply(hci::Status status,
- Address address);
-
- // Bluetooth Core Specification Version 4.2, Volume 2, Part E, Section 7.1.11
- static std::unique_ptr<EventPacketBuilder> CreateCommandCompleteLinkKeyRequestNegativeReply(hci::Status status,
- Address address);
-
- // Bluetooth Core Specification Version 4.2, Volume 2, Part E, Section 7.2.10
- static std::unique_ptr<EventPacketBuilder> CreateCommandCompleteWriteLinkPolicySettings(hci::Status status,
- uint16_t handle);
-
- // Bluetooth Core Specification Version 4.2, Volume 2, Part E, Section 7.3.10
- static std::unique_ptr<EventPacketBuilder> CreateCommandCompleteDeleteStoredLinkKey(hci::Status status,
- uint16_t num_keys_deleted);
-
- // Bluetooth Core Specification Version 4.2, Volume 2, Part E, Section 7.3.12
- static std::unique_ptr<EventPacketBuilder> CreateCommandCompleteReadLocalName(hci::Status status,
- const std::vector<uint8_t>& local_name);
-
- // Bluetooth Core Specification Version 4.2, Volume 2, Part E, Section 7.3.23
- static std::unique_ptr<EventPacketBuilder> CreateCommandCompleteReadAuthenticationEnable(hci::Status status,
- uint8_t enable);
-
- // Bluetooth Core Specification Version 4.2, Volume 2, Part E, Section 7.3.42
- static std::unique_ptr<EventPacketBuilder> CreateCommandCompleteWriteLinkSupervisionTimeout(hci::Status status,
- uint16_t handle);
-
- // Bluetooth Core Specification Version 4.2, Volume 2, Part E, Section 7.4.1
- static std::unique_ptr<EventPacketBuilder> CreateCommandCompleteReadLocalVersionInformation(
- hci::Status status, uint8_t hci_version, uint16_t hci_revision, uint8_t lmp_pal_version,
- uint16_t manufacturer_name, uint16_t lmp_pal_subversion);
-
- // Bluetooth Core Specification Version 4.2, Volume 2, Part E, Section 7.4.2
- static std::unique_ptr<EventPacketBuilder> CreateCommandCompleteReadLocalSupportedCommands(
- hci::Status status, const std::vector<uint8_t>& supported_commands);
-
- // Bluetooth Core Specification Version 4.2, Volume 2, Part E, Section 7.4.3
- static std::unique_ptr<EventPacketBuilder> CreateCommandCompleteReadLocalSupportedFeatures(
- hci::Status status, uint64_t supported_features);
-
- // Bluetooth Core Specification Version 4.2, Volume 2, Part E, Section 7.4.4
- static std::unique_ptr<EventPacketBuilder> CreateCommandCompleteReadLocalExtendedFeatures(
- hci::Status status, uint8_t page_number, uint8_t maximum_page_number, uint64_t extended_lmp_features);
-
- // Bluetooth Core Specification Version 4.2, Volume 2, Part E, Section 7.4.5
- static std::unique_ptr<EventPacketBuilder> CreateCommandCompleteReadBufferSize(
- hci::Status status, uint16_t hc_acl_data_packet_length, uint8_t hc_synchronous_data_packet_length,
- uint16_t hc_total_num_acl_data_packets, uint16_t hc_total_synchronous_data_packets);
-
- // Bluetooth Core Specification Version 4.2, Volume 2, Part E, Section 7.4.6
- static std::unique_ptr<EventPacketBuilder> CreateCommandCompleteReadBdAddr(hci::Status status,
- const Address& bt_address);
-
- // Bluetooth Core Specification Version 4.2, Volume 2, Part E, Section 7.4.8
- static std::unique_ptr<EventPacketBuilder> CreateCommandCompleteReadLocalSupportedCodecs(
- hci::Status status, const std::vector<uint8_t>& supported_codecs,
- const std::vector<uint32_t>& vendor_specific_codecs);
-
- // Bluetooth Core Specification Version 5.1, Volume 2, Part E, Section 7.5.7
- static std::unique_ptr<EventPacketBuilder>
- CreateCommandCompleteReadEncryptionKeySize(hci::Status status,
- uint16_t handle, uint8_t key_size);
-
- // Bluetooth Core Specification Version 4.2, Volume 2, Part E, Section 7.6.1
- static std::unique_ptr<EventPacketBuilder> CreateCommandCompleteReadLoopbackMode(hci::Status status,
- hci::LoopbackMode mode);
-
- // Bluetooth Core Specification Version 4.2, Volume 2, Part E, Section 7.7.2
- static std::unique_ptr<EventPacketBuilder> CreateInquiryResultEvent();
-
- // Returns true if the result can be added to the event packet.
- bool AddInquiryResult(const Address& bt_address, uint8_t page_scan_repetition_mode, ClassOfDevice class_of_device,
- uint16_t clock_offset);
-
- // Bluetooth Core Specification Version 4.2, Volume 2, Part E, Section 7.7.3
- static std::unique_ptr<EventPacketBuilder> CreateConnectionCompleteEvent(hci::Status status, uint16_t handle,
- const Address& address,
- hci::LinkType link_type,
- bool encryption_enabled);
-
- // Bluetooth Core Specification Version 4.2, Volume 2, Part E, Section 7.7.4
- static std::unique_ptr<EventPacketBuilder> CreateConnectionRequestEvent(const Address& address,
- ClassOfDevice class_of_device,
- hci::LinkType link_type);
-
- // Bluetooth Core Specification Version 4.2, Volume 2, Part E, Section 7.7.5
- static std::unique_ptr<EventPacketBuilder> CreateDisconnectionCompleteEvent(hci::Status status, uint16_t handle,
- uint8_t reason);
-
- // Bluetooth Core Specification Version 4.2, Volume 2, Part E, Section 7.7.6
- static std::unique_ptr<EventPacketBuilder> CreateAuthenticationCompleteEvent(hci::Status status, uint16_t handle);
-
- // Bluetooth Core Specification Version 4.2, Volume 2, Part E, Section 7.7.7
- static std::unique_ptr<EventPacketBuilder> CreateRemoteNameRequestCompleteEvent(hci::Status status,
- const Address& bt_address,
- const std::string& name);
-
- // Bluetooth Core Specification Version 4.2, Volume 2, Part E, Section 7.7.11
- static std::unique_ptr<EventPacketBuilder> CreateRemoteSupportedFeaturesEvent(hci::Status status, uint16_t handle,
- uint64_t features);
-
- // Bluetooth Core Specification Version 4.2, Volume 2, Part E, Section 7.7.12
- static std::unique_ptr<EventPacketBuilder> CreateReadRemoteVersionInformationEvent(hci::Status status,
- uint16_t connection_handle,
- uint8_t lmp_pal_version,
- uint16_t manufacturer_name,
- uint16_t lmp_pal_subversion);
-
- // Bluetooth Core Specification Version 4.2, Volume 2, Part E, Section 7.7.23
- static std::unique_ptr<EventPacketBuilder> CreateLinkKeyRequestEvent(const Address& remote);
-
- // Bluetooth Core Specification Version 4.2, Volume 2, Part E, Section 7.7.24
- static std::unique_ptr<EventPacketBuilder> CreateLinkKeyNotificationEvent(const Address& remote,
- const std::vector<uint8_t>& key,
- uint8_t key_type);
-
- // Bluetooth Core Specification Version 4.2, Volume 2, Part E, Section 7.7.25
- static std::unique_ptr<EventPacketBuilder> CreateLoopbackCommandEvent(hci::OpCode opcode, PacketView<true> payload);
-
- // Bluetooth Core Specification Version 4.2, Volume 2, Part E, Section 7.7.28
- static std::unique_ptr<EventPacketBuilder> CreateReadClockOffsetEvent(hci::Status status, uint16_t handle,
- uint16_t packet_type);
-
- // Bluetooth Core Specification Version 4.2, Volume 2, Part E, Section 7.7.29
- static std::unique_ptr<EventPacketBuilder> CreateConnectionPacketTypeChangedEvent(hci::Status status, uint16_t handle,
- uint16_t offset);
-
- // Bluetooth Core Specification Version 4.2, Volume 2, Part E, Section 7.7.34
- static std::unique_ptr<EventPacketBuilder> CreateReadRemoteExtendedFeaturesEvent(hci::Status status, uint16_t handle,
- uint8_t page_number,
- uint8_t maximum_page_number,
- uint64_t extended_lmp_features);
-
- // Bluetooth Core Specification Version 4.2, Volume 2, Part E, Section 7.7.37
- static std::unique_ptr<EventPacketBuilder> CreateSniffSubratingEvent(hci::Status status, uint16_t handle);
-
- // Bluetooth Core Specification Version 4.2, Volume 2, Part E, Section 7.7.38
- static std::unique_ptr<EventPacketBuilder> CreateExtendedInquiryResultEvent(
- const Address& bt_address, uint8_t page_scan_repetition_mode, ClassOfDevice class_of_device,
- uint16_t clock_offset, uint8_t rssi, const std::vector<uint8_t>& extended_inquiry_response);
-
- // Bluetooth Core Specification Version 4.2, Volume 2, Part E, Section 7.7.39
- static std::unique_ptr<EventPacketBuilder> CreateEncryptionKeyRefreshCompleteEvent(hci::Status status,
- uint16_t handle);
-
- // Bluetooth Core Specification Version 4.2, Volume 2, Part E, Section 7.7.40
- static std::unique_ptr<EventPacketBuilder> CreateIoCapabilityRequestEvent(const Address& peer);
-
- // Bluetooth Core Specification Version 4.2, Volume 2, Part E, Section 7.7.41
- static std::unique_ptr<EventPacketBuilder> CreateIoCapabilityResponseEvent(const Address& peer, uint8_t io_capability,
- bool oob_data_present,
- uint8_t authentication_requirements);
-
- // Bluetooth Core Specification Version 4.2, Volume 2, Part E, Section 7.7.42
- static std::unique_ptr<EventPacketBuilder> CreateUserConfirmationRequestEvent(const Address& peer,
- uint32_t numeric_value);
-
- // Bluetooth Core Specification Version 4.2, Volume 2, Part E, Section 7.7.43
- static std::unique_ptr<EventPacketBuilder> CreateUserPasskeyRequestEvent(const Address& peer);
-
- // Bluetooth Core Specification Version 4.2, Volume 2, Part E, Section 7.7.44
- static std::unique_ptr<EventPacketBuilder> CreateRemoteOobDataRequestEvent(const Address& peer);
-
- // Bluetooth Core Specification Version 4.2, Volume 2, Part E, Section 7.7.45
- static std::unique_ptr<EventPacketBuilder> CreateSimplePairingCompleteEvent(hci::Status status, const Address& peer);
-
- // Bluetooth Core Specification Version 4.2, Volume 2, Part E, Section 7.7.48
- static std::unique_ptr<EventPacketBuilder> CreateUserPasskeyNotificationEvent(const Address& peer, uint32_t passkey);
-
- // Bluetooth Core Specification Version 4.2, Volume 2, Part E, Section 7.7.49
- static std::unique_ptr<EventPacketBuilder> CreateKeypressNotificationEvent(const Address& peer,
- uint8_t notification_type);
-
- // Bluetooth Core Specification Version 4.2, Volume 2, Part E, Section
- // 7.7.65.1
- static std::unique_ptr<EventPacketBuilder> CreateLeConnectionCompleteEvent(hci::Status status, uint16_t handle,
- uint8_t role, uint8_t peer_address_type,
- const Address& peer, uint16_t interval,
- uint16_t latency,
- uint16_t supervision_timeout);
-
- // Bluetooth Core Specification Version 4.2, Volume 2, Part E, Section
- // 7.7.65.2
- static std::unique_ptr<EventPacketBuilder> CreateLeAdvertisingReportEvent();
-
- // Returns true if the report can be added to the event packet.
- bool AddLeAdvertisingReport(LeAdvertisement::AdvertisementType event_type, LeAdvertisement::AddressType addr_type,
- const Address& addr, const std::vector<uint8_t>& data, uint8_t rssi);
-
- // Bluetooth Core Specification Version 4.2, Volume 2, Part E, Section
- // 7.7.65.3
- static std::unique_ptr<EventPacketBuilder> CreateLeConnectionUpdateCompleteEvent(hci::Status status, uint16_t handle,
- uint16_t interval, uint16_t latency,
- uint16_t supervision_timeout);
-
- // Bluetooth Core Specification Version 4.2, Volume 2, Part E, Section
- // 7.7.65.4
- static std::unique_ptr<EventPacketBuilder> CreateLeRemoteUsedFeaturesEvent(hci::Status status, uint16_t handle,
- uint64_t features);
-
- // Bluetooth Core Specification Version 4.2, Volume 2, Part E, Section
- // 7.7.65.10
- static std::unique_ptr<EventPacketBuilder> CreateLeEnhancedConnectionCompleteEvent(
- hci::Status status, uint16_t handle, uint8_t role, uint8_t peer_address_type, const Address& peer,
- const Address& local_private_address, const Address& peer_private_address, uint16_t interval, uint16_t latency,
- uint16_t supervision_timeout);
-
- // Bluetooth Core Specification Version 4.2, Volume 2, Part E, Section 7.8.2
- static std::unique_ptr<EventPacketBuilder> CreateCommandCompleteLeReadBufferSize(
- hci::Status status, uint16_t hc_le_data_packet_length, uint8_t hc_total_num_le_data_packets);
-
- // Bluetooth Core Specification Version 4.2, Volume 2, Part E, Section 7.8.3
- static std::unique_ptr<EventPacketBuilder> CreateCommandCompleteLeReadLocalSupportedFeatures(hci::Status status,
- uint64_t le_features);
-
- // Bluetooth Core Specification Version 4.2, Volume 2, Part E, Section 7.8.14
- static std::unique_ptr<EventPacketBuilder> CreateCommandCompleteLeReadWhiteListSize(hci::Status status,
- uint8_t white_list_size);
-
- // Bluetooth Core Specification Version 4.2, Volume 2, Part E, Section 7.8.23
- static std::unique_ptr<EventPacketBuilder> CreateCommandCompleteLeRand(hci::Status status, uint64_t random_val);
-
- // Bluetooth Core Specification Version 4.2, Volume 2, Part E, Section 7.8.27
- static std::unique_ptr<EventPacketBuilder> CreateCommandCompleteLeReadSupportedStates(hci::Status status,
- uint64_t le_states);
-
- /*
- static std::unique_ptr<EventPacketBuilder>
- CreateLeStartEncryption(hci::Status status, uint8_t encryption_enable);
-*/
- static std::unique_ptr<EventPacketBuilder> CreateEncryptionChange(hci::Status status, uint16_t handle,
- uint8_t encryption_enable);
-
- // Vendor-specific commands
-
- static std::unique_ptr<EventPacketBuilder> CreateCommandCompleteLeGetVendorCapabilities(
- hci::Status status, const std::vector<uint8_t>& vendor_cap);
-
- virtual size_t size() const override;
-
- virtual void Serialize(std::back_insert_iterator<std::vector<uint8_t>> it) const override;
-
- bool CanAddPayloadOctets(size_t octets);
-
- bool AddPayloadOctets(size_t octets, const std::vector<uint8_t>& bytes);
-
- bool AddPayloadOctets(const std::vector<uint8_t>& bytes);
-
- bool AddPayloadOctets1(uint8_t value);
- bool AddPayloadOctets2(uint16_t value);
- bool AddPayloadOctets3(uint32_t value);
- bool AddPayloadOctets4(uint32_t value);
- bool AddPayloadOctets6(uint64_t value);
- bool AddPayloadOctets8(uint64_t value);
-
- bool AddPayloadAddress(Address address);
-
- bool AddBuilder(std::unique_ptr<BasePacketBuilder> builder);
-
- private:
- explicit EventPacketBuilder(hci::EventCode event_code);
- explicit EventPacketBuilder(hci::EventCode event_code, std::unique_ptr<RawBuilder> payload);
- hci::EventCode event_code_;
- std::unique_ptr<RawBuilder> payload_;
-};
-
-} // namespace packets
-} // namespace test_vendor_lib
diff --git a/vendor_libs/test_vendor_lib/packets/hci/event_payload_builder.cc b/vendor_libs/test_vendor_lib/packets/hci/event_payload_builder.cc
deleted file mode 100644
index 9c9bdc5..0000000
--- a/vendor_libs/test_vendor_lib/packets/hci/event_payload_builder.cc
+++ /dev/null
@@ -1,96 +0,0 @@
-/*
- * Copyright 2018 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include "event_payload_builder.h"
-
-#include <algorithm>
-
-using std::vector;
-
-namespace test_vendor_lib {
-namespace packets {
-
-EventPayloadBuilder::EventPayloadBuilder(size_t max_bytes) : max_bytes_(max_bytes) {}
-
-bool EventPayloadBuilder::AddPayloadOctets(size_t octets, const vector<uint8_t>& bytes) {
- if (payload_.size() + octets > max_bytes_) return false;
-
- if (octets != bytes.size()) return false;
-
- payload_.insert(payload_.end(), bytes.begin(), bytes.end());
-
- return true;
-}
-
-bool EventPayloadBuilder::AddPayloadOctets(const vector<uint8_t>& bytes) {
- return AddPayloadOctets(bytes.size(), bytes);
-}
-
-bool EventPayloadBuilder::AddPayloadOctets(size_t octets, uint64_t value) {
- vector<uint8_t> val_vector;
-
- uint64_t v = value;
-
- if (octets > sizeof(uint64_t)) return false;
-
- for (size_t i = 0; i < octets; i++) {
- val_vector.push_back(v & 0xff);
- v = v >> 8;
- }
-
- if (v != 0) return false;
-
- return AddPayloadOctets(octets, val_vector);
-}
-
-bool EventPayloadBuilder::AddPayloadAddress(const Address& address) {
- if (payload_.size() + Address::kLength > max_bytes_) return false;
-
- for (size_t i = 0; i < Address::kLength; i++) {
- payload_.push_back(address.address[i]);
- }
- return true;
-}
-
-bool EventPayloadBuilder::AddPayloadOctets1(uint8_t value) {
- return AddPayloadOctets(1, value);
-}
-
-bool EventPayloadBuilder::AddPayloadOctets2(uint16_t value) {
- return AddPayloadOctets(2, value);
-}
-
-bool EventPayloadBuilder::AddPayloadOctets3(uint32_t value) {
- return AddPayloadOctets(3, value);
-}
-
-bool EventPayloadBuilder::AddPayloadOctets4(uint32_t value) {
- return AddPayloadOctets(4, value);
-}
-
-bool EventPayloadBuilder::AddPayloadOctets6(uint64_t value) {
- return AddPayloadOctets(6, value);
-}
-
-bool EventPayloadBuilder::AddPayloadOctets8(uint64_t value) {
- return AddPayloadOctets(8, value);
-}
-
-bool EventPayloadBuilder::CanAddPayloadOctets(size_t num_bytes) const {
- return payload_.size() + num_bytes <= max_bytes_;
-}
-} // namespace packets
-} // namespace test_vendor_lib
diff --git a/vendor_libs/test_vendor_lib/packets/hci/event_payload_builder.h b/vendor_libs/test_vendor_lib/packets/hci/event_payload_builder.h
deleted file mode 100644
index b656edf..0000000
--- a/vendor_libs/test_vendor_lib/packets/hci/event_payload_builder.h
+++ /dev/null
@@ -1,72 +0,0 @@
-/*
- * Copyright 2018 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#pragma once
-
-#include <cstdint>
-#include <vector>
-
-#include "packets/packet_builder.h"
-#include "types/address.h"
-
-namespace test_vendor_lib {
-namespace packets {
-
-class EventPayloadBuilder : public PacketBuilder<true> {
- public:
- EventPayloadBuilder() = default;
- EventPayloadBuilder(size_t max_bytes);
- virtual ~EventPayloadBuilder() = default;
-
- virtual size_t size() const override;
-
- virtual void Serialize(std::back_insert_iterator<std::vector<uint8_t>> it) const;
-
- // Add |octets| bytes to the payload. Return true if:
- // - the size of |bytes| is equal to |octets| and
- // - the new size of the payload is still < |max_bytes_|
- bool AddPayloadOctets(size_t octets, const std::vector<uint8_t>& bytes);
-
- bool AddPayloadOctets(const std::vector<uint8_t>& bytes);
-
- bool AddPayloadOctets1(uint8_t value);
- bool AddPayloadOctets2(uint16_t value);
- bool AddPayloadOctets3(uint32_t value);
- bool AddPayloadOctets4(uint32_t value);
- bool AddPayloadOctets6(uint64_t value);
- bool AddPayloadOctets8(uint64_t value);
-
- private:
- // Add |octets| bytes to the payload. Return true if:
- // - the value of |value| fits in |octets| bytes and
- // - the new size of the payload is still < |max_bytes_|
- bool AddPayloadOctets(size_t octets, uint64_t value);
-
- // Add |address| to the payload. Return true if:
- // - the new size of the payload is still < |max_bytes_|
- bool AddPayloadAddress(const Address& address);
-
- // Return true if |num_bytes| can be added to the payload.
- bool CanAddPayloadOctets(size_t num_bytes) const;
-
- size_t max_bytes_{255};
-
- // Underlying containers for storing the actual packet
- std::vector<uint8_t> payload_;
-};
-
-} // namespace packets
-} // namespace test_vendor_lib
diff --git a/vendor_libs/test_vendor_lib/packets/hci/le_meta_event_builder.cc b/vendor_libs/test_vendor_lib/packets/hci/le_meta_event_builder.cc
deleted file mode 100644
index caaf136..0000000
--- a/vendor_libs/test_vendor_lib/packets/hci/le_meta_event_builder.cc
+++ /dev/null
@@ -1,150 +0,0 @@
-/*
- * Copyright 2018 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include "packets/hci/le_meta_event_builder.h"
-
-#include "os/log.h"
-
-using std::vector;
-using test_vendor_lib::hci::LeSubEventCode;
-using test_vendor_lib::hci::Status;
-
-namespace test_vendor_lib {
-namespace packets {
-
-LeMetaEventBuilder::LeMetaEventBuilder(LeSubEventCode sub_event_code)
- : sub_event_code_(sub_event_code), payload_(std::make_unique<RawBuilder>()) {}
-
-LeMetaEventBuilder::LeMetaEventBuilder(LeSubEventCode sub_event_code, std::unique_ptr<RawBuilder> payload)
- : sub_event_code_(sub_event_code), payload_(std::move(payload)) {}
-
-// Bluetooth Core Specification Version 4.2, Volume 2, Part E, Section 7.7.65.1
-std::unique_ptr<LeMetaEventBuilder> LeMetaEventBuilder::CreateLeConnectionCompleteEvent(
- Status status, uint16_t handle, uint8_t role, uint8_t peer_address_type, const Address& peer, uint16_t interval,
- uint16_t latency, uint16_t supervision_timeout, uint8_t master_clock_accuracy) {
- std::unique_ptr<LeMetaEventBuilder> evt_ptr =
- std::unique_ptr<LeMetaEventBuilder>(new LeMetaEventBuilder(LeSubEventCode::CONNECTION_COMPLETE));
-
- ASSERT(evt_ptr->AddOctets1(static_cast<uint8_t>(status)));
- ASSERT(evt_ptr->AddOctets2(handle));
- ASSERT(evt_ptr->AddOctets1(role));
- ASSERT(evt_ptr->AddOctets1(peer_address_type));
- ASSERT(evt_ptr->AddAddress(peer));
- ASSERT(evt_ptr->AddOctets2(interval));
- ASSERT(evt_ptr->AddOctets2(latency));
- ASSERT(evt_ptr->AddOctets2(supervision_timeout));
- ASSERT(evt_ptr->AddOctets1(master_clock_accuracy));
-
- return evt_ptr;
-}
-
-std::unique_ptr<LeMetaEventBuilder> LeMetaEventBuilder::CreateLeEnhancedConnectionCompleteEvent(
- Status status, uint16_t handle, uint8_t role, uint8_t peer_address_type, const Address& peer,
- const Address& local_private_address, const Address& peer_private_address, uint16_t interval, uint16_t latency,
- uint16_t supervision_timeout) {
- std::unique_ptr<LeMetaEventBuilder> evt_ptr =
- std::unique_ptr<LeMetaEventBuilder>(new LeMetaEventBuilder(LeSubEventCode::ENHANCED_CONNECTION_COMPLETE));
-
- ASSERT(evt_ptr->AddOctets1(static_cast<uint8_t>(status)));
- ASSERT(evt_ptr->AddOctets2(handle));
- ASSERT(evt_ptr->AddOctets1(role));
- ASSERT(evt_ptr->AddOctets1(peer_address_type));
- ASSERT(evt_ptr->AddAddress(peer));
- ASSERT(evt_ptr->AddAddress(local_private_address));
- ASSERT(evt_ptr->AddAddress(peer_private_address));
- ASSERT(evt_ptr->AddOctets2(interval));
- ASSERT(evt_ptr->AddOctets2(latency));
- ASSERT(evt_ptr->AddOctets2(supervision_timeout));
- ASSERT(evt_ptr->AddOctets1(0x00)); // Master Clock Accuracy (unused for master)
-
- return evt_ptr;
-}
-
-std::unique_ptr<LeMetaEventBuilder> LeMetaEventBuilder::CreateLeConnectionUpdateCompleteEvent(
- Status status, uint16_t handle, uint16_t interval, uint16_t latency, uint16_t supervision_timeout) {
- std::unique_ptr<LeMetaEventBuilder> evt_ptr =
- std::unique_ptr<LeMetaEventBuilder>(new LeMetaEventBuilder(LeSubEventCode::CONNECTION_UPDATE_COMPLETE));
-
- ASSERT(evt_ptr->AddOctets1(static_cast<uint8_t>(status)));
- ASSERT(evt_ptr->AddOctets2(handle));
- ASSERT(evt_ptr->AddOctets2(interval));
- ASSERT(evt_ptr->AddOctets2(latency));
- ASSERT(evt_ptr->AddOctets2(supervision_timeout));
-
- return evt_ptr;
-}
-
-// Bluetooth Core Specification Version 4.2, Volume 2, Part E, Section 7.7.65.2
-std::unique_ptr<LeMetaEventBuilder> LeMetaEventBuilder::CreateLeAdvertisingReportEvent() {
- std::unique_ptr<LeMetaEventBuilder> evt_ptr = std::unique_ptr<LeMetaEventBuilder>(
- new LeMetaEventBuilder(LeSubEventCode::ADVERTISING_REPORT, std::unique_ptr<RawBuilder>(new CountedBuilder())));
-
- return evt_ptr;
-}
-
-bool LeMetaEventBuilder::AddLeAdvertisingReport(LeAdvertisement::AdvertisementType event_type,
- LeAdvertisement::AddressType addr_type, const Address& addr,
- const vector<uint8_t>& data, uint8_t rssi) {
- if (!CanAddOctets(10 + data.size())) return false;
-
- ASSERT(sub_event_code_ == LeSubEventCode::ADVERTISING_REPORT);
-
- std::unique_ptr<RawBuilder> ad = std::make_unique<RawBuilder>();
-
- ASSERT(ad->AddOctets1(static_cast<uint8_t>(event_type)));
- ASSERT(ad->AddOctets1(static_cast<uint8_t>(addr_type)));
- ASSERT(ad->AddAddress(addr));
- ASSERT(ad->AddOctets1(data.size()));
- ASSERT(ad->AddOctets(data));
- ASSERT(ad->AddOctets1(rssi));
- AddBuilder(std::move(ad));
- return true;
-}
-
-// Bluetooth Core Specification Version 4.2, Volume 2, Part E, Section 7.7.65.4
-std::unique_ptr<LeMetaEventBuilder> LeMetaEventBuilder::CreateLeRemoteUsedFeaturesEvent(Status status, uint16_t handle,
- uint64_t features) {
- std::unique_ptr<LeMetaEventBuilder> evt_ptr =
- std::unique_ptr<LeMetaEventBuilder>(new LeMetaEventBuilder(LeSubEventCode::READ_REMOTE_FEATURES_COMPLETE));
-
- ASSERT(evt_ptr->AddOctets1(static_cast<uint8_t>(status)));
- ASSERT(evt_ptr->AddOctets2(handle));
- ASSERT(evt_ptr->AddOctets8(features));
-
- return evt_ptr;
-}
-
-size_t LeMetaEventBuilder::size() const {
- return 1 + RawBuilder::size() + payload_->size(); // Add the sub_event_code
-}
-
-void LeMetaEventBuilder::Serialize(std::back_insert_iterator<std::vector<uint8_t>> it) const {
- insert(static_cast<uint8_t>(sub_event_code_), it);
- uint8_t payload_size = size() - sizeof(uint8_t);
- ASSERT_LOG(size() - sizeof(uint8_t) == static_cast<size_t>(payload_size), "Payload too large for an event: %d",
- static_cast<int>(size()));
- RawBuilder::Serialize(it);
- payload_->Serialize(it);
-}
-
-bool LeMetaEventBuilder::AddBuilder(std::unique_ptr<BasePacketBuilder> builder) {
- // Upcast the payload to add the next builder.
- CountedBuilder* temp_ptr = static_cast<CountedBuilder*>(payload_.get());
- temp_ptr->Add(std::move(builder));
- return true;
-}
-} // namespace packets
-} // namespace test_vendor_lib
diff --git a/vendor_libs/test_vendor_lib/packets/hci/le_meta_event_builder.h b/vendor_libs/test_vendor_lib/packets/hci/le_meta_event_builder.h
deleted file mode 100644
index a56700c..0000000
--- a/vendor_libs/test_vendor_lib/packets/hci/le_meta_event_builder.h
+++ /dev/null
@@ -1,89 +0,0 @@
-/*
- * Copyright 2018 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#pragma once
-
-#include <cstdint>
-#include <memory>
-#include <string>
-#include <vector>
-
-#include "include/hci.h"
-#include "include/le_advertisement.h"
-#include "packets/counted_builder.h"
-#include "packets/hci/hci_packet_builder.h"
-#include "packets/packet_builder.h"
-#include "packets/packet_view.h"
-#include "packets/raw_builder.h"
-#include "types/address.h"
-
-namespace test_vendor_lib {
-namespace packets {
-
-// LE Meta Event Packets are specified in the Bluetooth Core Specification
-// Version 4.2, Volume 2, Part E, Section 7.7.65. The first byte is the
-// Subevent_Code.
-class LeMetaEventBuilder : public RawBuilder {
- public:
- virtual ~LeMetaEventBuilder() override = default;
-
- // Bluetooth Core Specification Version 4.2, Volume 2, Part E, Section
- // 7.7.65.1
- static std::unique_ptr<LeMetaEventBuilder> CreateLeConnectionCompleteEvent(
- hci::Status status, uint16_t handle, uint8_t role, uint8_t peer_address_type, const Address& peer,
- uint16_t interval, uint16_t latency, uint16_t supervision_timeout, uint8_t master_clock_accuracy = 0);
-
- // Bluetooth Core Specification Version 4.2, Volume 2, Part E, Section
- // 7.7.65.2
- static std::unique_ptr<LeMetaEventBuilder> CreateLeAdvertisingReportEvent();
-
- // Returns true if the report can be added to the event packet.
- bool AddLeAdvertisingReport(LeAdvertisement::AdvertisementType event_type, LeAdvertisement::AddressType addr_type,
- const Address& addr, const std::vector<uint8_t>& data, uint8_t rssi);
-
- // Bluetooth Core Specification Version 4.2, Volume 2, Part E, Section
- // 7.7.65.3
- static std::unique_ptr<LeMetaEventBuilder> CreateLeConnectionUpdateCompleteEvent(hci::Status status, uint16_t handle,
- uint16_t interval, uint16_t latency,
- uint16_t supervision_timeout);
-
- // Bluetooth Core Specification Version 4.2, Volume 2, Part E, Section
- // 7.7.65.4
- static std::unique_ptr<LeMetaEventBuilder> CreateLeRemoteUsedFeaturesEvent(hci::Status status, uint16_t handle,
- uint64_t features);
-
- // Bluetooth Core Specification Version 4.2, Volume 2, Part E, Section
- // 7.7.65.10
- static std::unique_ptr<LeMetaEventBuilder> CreateLeEnhancedConnectionCompleteEvent(
- hci::Status status, uint16_t handle, uint8_t role, uint8_t peer_address_type, const Address& peer,
- const Address& local_private_address, const Address& peer_private_address, uint16_t interval, uint16_t latency,
- uint16_t supervision_timeout);
-
- virtual size_t size() const override;
-
- virtual void Serialize(std::back_insert_iterator<std::vector<uint8_t>> it) const override;
-
- bool AddBuilder(std::unique_ptr<BasePacketBuilder> builder);
-
- private:
- explicit LeMetaEventBuilder(hci::LeSubEventCode sub_event_code);
- explicit LeMetaEventBuilder(hci::LeSubEventCode sub_event_code, std::unique_ptr<RawBuilder> payload);
- hci::LeSubEventCode sub_event_code_;
- std::unique_ptr<RawBuilder> payload_;
-};
-
-} // namespace packets
-} // namespace test_vendor_lib
diff --git a/vendor_libs/test_vendor_lib/packets/hci/test/acl_builder_test.cc b/vendor_libs/test_vendor_lib/packets/hci/test/acl_builder_test.cc
index fb34489..ad99df1 100644
--- a/vendor_libs/test_vendor_lib/packets/hci/test/acl_builder_test.cc
+++ b/vendor_libs/test_vendor_lib/packets/hci/test/acl_builder_test.cc
@@ -22,8 +22,9 @@
#include <forward_list>
#include <memory>
-#include "types/address.h"
+#include "hci/address.h"
+using ::bluetooth::hci::Address;
using std::vector;
using test_vendor_lib::acl::BroadcastFlagsType;
using test_vendor_lib::acl::PacketBoundaryFlagsType;
diff --git a/vendor_libs/test_vendor_lib/packets/hci/test/event_builder_test.cc b/vendor_libs/test_vendor_lib/packets/hci/test/event_builder_test.cc
deleted file mode 100644
index 8a11d45..0000000
--- a/vendor_libs/test_vendor_lib/packets/hci/test/event_builder_test.cc
+++ /dev/null
@@ -1,161 +0,0 @@
-/*
- * Copyright 2018 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include "packets/hci/event_packet_builder.h"
-
-#include <gtest/gtest.h>
-#include <forward_list>
-#include <memory>
-
-#include "types/address.h"
-
-using std::vector;
-
-namespace {
-vector<uint8_t> count = {
- 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
- 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
-};
-
-} // namespace
-
-namespace test_vendor_lib {
-namespace packets {
-
-class EventBuilderTest : public ::testing::Test {
- public:
- EventBuilderTest() = default;
- ~EventBuilderTest() override = default;
-};
-
-TEST(EventBuilderTest, buildLeAdvertisementSmallTest) {
- LeAdvertisement::AdvertisementType adv_type = LeAdvertisement::AdvertisementType::ADV_SCAN_IND;
- LeAdvertisement::AddressType addr_type = LeAdvertisement::AddressType::RANDOM;
- std::unique_ptr<EventPacketBuilder> le_adv = EventPacketBuilder::CreateLeAdvertisingReportEvent();
- Address addr({1, 2, 3, 4, 5, 6});
- uint8_t rssi = -93;
-
- std::vector<uint8_t> payload({0x23});
- le_adv->AddLeAdvertisingReport(adv_type, addr_type, addr, {payload}, rssi);
-
- uint8_t payload_size = payload.size();
- uint8_t event_size = payload_size + sizeof(Address) + sizeof(rssi) + 5;
- std::vector<uint8_t> expected({
- 0x3e, // HCI LE Event
- event_size,
- 0x02, // LE Advertising subevent code
- 0x01, // Number of responses
- 0x02, // Event type is scannable undirected
- 0x01, // Address type is random
- 0x01, // Address
- 0x02, // Address
- 0x03, // Address
- 0x04, // Address
- 0x05, // Address
- 0x06, // Address
- payload_size, // Length of the data
- });
-
- expected.push_back(payload[0]);
- expected.push_back(rssi);
-
- ASSERT_EQ(expected.size(), le_adv->size());
- ASSERT_EQ(expected, *le_adv->ToVector());
-}
-
-TEST(EventBuilderTest, buildLeAdvertisementTest) {
- LeAdvertisement::AdvertisementType adv_type = LeAdvertisement::AdvertisementType::ADV_SCAN_IND;
- LeAdvertisement::AddressType addr_type = LeAdvertisement::AddressType::RANDOM;
- std::unique_ptr<EventPacketBuilder> le_adv = EventPacketBuilder::CreateLeAdvertisingReportEvent();
- Address addr({1, 2, 3, 4, 5, 6});
- uint8_t rssi = -93;
-
- le_adv->AddLeAdvertisingReport(adv_type, addr_type, addr, count, rssi);
-
- uint8_t count_size = static_cast<uint8_t>(count.size());
- uint8_t event_size = count_size + sizeof(Address) + sizeof(rssi) + 5;
- std::vector<uint8_t> expected({
- 0x3e, // HCI LE Event
- event_size,
- 0x02, // LE Advertising subevent code
- 0x01, // Number of responses
- 0x02, // Event type is scannable undirected
- 0x01, // Address type is random
- 0x01, // Address
- 0x02, // Address
- 0x03, // Address
- 0x04, // Address
- 0x05, // Address
- 0x06, // Address
- count_size, // Length of the data
- });
-
- for (size_t i = 0; i < count.size(); i++) {
- expected.push_back(count[i]);
- }
- expected.push_back(rssi);
-
- std::shared_ptr<std::vector<uint8_t>> raw_adv = le_adv->ToVector();
- ASSERT_EQ(expected, *raw_adv);
-}
-
-TEST(EventBuilderTest, buildNumberOfCompletedPackets) {
- uint16_t handle = 0x0102;
- uint16_t num_packets = 0x0304;
-
- std::unique_ptr<EventPacketBuilder> event =
- EventPacketBuilder::CreateNumberOfCompletedPacketsEvent(handle, num_packets);
-
- uint8_t number_of_handles = 1;
- uint8_t event_size = sizeof(uint8_t) + number_of_handles * 2 * sizeof(uint16_t);
- std::vector<uint8_t> expected({
- 0x13, // HCI Number Of Completed Packets Event code
- event_size, number_of_handles, //
- 0x02, 0x01, // handle
- 0x04, 0x03, // count
- });
-
- std::shared_ptr<std::vector<uint8_t>> raw_event = event->ToVector();
- ASSERT_EQ(expected, *raw_event);
-}
-
-TEST(EventBuilderTest, buildNumberOfCompletedPacketsMultiple) {
- uint16_t handle = 0x0102;
- uint16_t num_packets = 0x0304;
- uint16_t handle2 = 0x0506;
- uint16_t num_packets2 = 0x0708;
-
- std::unique_ptr<EventPacketBuilder> event =
- EventPacketBuilder::CreateNumberOfCompletedPacketsEvent(handle, num_packets);
- event->AddCompletedPackets(handle2, num_packets2);
-
- uint8_t number_of_handles = 2;
- uint8_t event_size = sizeof(uint8_t) + number_of_handles * 2 * sizeof(uint16_t);
- std::vector<uint8_t> expected({
- 0x13, // HCI Number Of Completed Packets Event code
- event_size, number_of_handles, //
- 0x02, 0x01, // handle
- 0x04, 0x03, // count
- 0x06, 0x05, // handle
- 0x08, 0x07, // count
- });
-
- std::shared_ptr<std::vector<uint8_t>> raw_event = event->ToVector();
- ASSERT_EQ(expected, *raw_event);
-}
-
-} // namespace packets
-} // namespace test_vendor_lib
diff --git a/vendor_libs/test_vendor_lib/packets/iterator.h b/vendor_libs/test_vendor_lib/packets/iterator.h
index b84ce64..2f01fb9 100644
--- a/vendor_libs/test_vendor_lib/packets/iterator.h
+++ b/vendor_libs/test_vendor_lib/packets/iterator.h
@@ -19,12 +19,14 @@
#include <cstdint>
#include <forward_list>
-#include "types/address.h"
+#include "hci/address.h"
#include "view.h"
namespace test_vendor_lib {
namespace packets {
+using ::bluetooth::hci::Address;
+
// Templated Iterator for endianness
template <bool little_endian>
class Iterator : public std::iterator<std::random_access_iterator_tag, uint8_t> {
diff --git a/vendor_libs/test_vendor_lib/packets/link_layer_packets.pdl b/vendor_libs/test_vendor_lib/packets/link_layer_packets.pdl
index 0194ab3..a7e6614 100644
--- a/vendor_libs/test_vendor_lib/packets/link_layer_packets.pdl
+++ b/vendor_libs/test_vendor_lib/packets/link_layer_packets.pdl
@@ -1,7 +1,7 @@
little_endian_packets
-custom_field Address : 48 "types/"
-custom_field ClassOfDevice : 24 "types/"
+custom_field Address : 48 "hci/"
+custom_field ClassOfDevice : 24 "hci/"
enum PacketType : 8 {
UNKNOWN = 0x00,
diff --git a/vendor_libs/test_vendor_lib/packets/packet_builder.h b/vendor_libs/test_vendor_lib/packets/packet_builder.h
index 947b02a..44feac8 100644
--- a/vendor_libs/test_vendor_lib/packets/packet_builder.h
+++ b/vendor_libs/test_vendor_lib/packets/packet_builder.h
@@ -23,12 +23,14 @@
#include <vector>
#include "base_packet_builder.h"
-#include "types/address.h"
+#include "hci/address.h"
#include "types/class_of_device.h"
namespace test_vendor_lib {
namespace packets {
+using ::bluetooth::hci::Address;
+
// Abstract base class that is subclassed to build specifc packets.
// The template parameter little_endian controls the generation of insert().
template <bool little_endian>
diff --git a/vendor_libs/test_vendor_lib/packets/raw_builder.h b/vendor_libs/test_vendor_lib/packets/raw_builder.h
index cbc7d6f..82ba885 100644
--- a/vendor_libs/test_vendor_lib/packets/raw_builder.h
+++ b/vendor_libs/test_vendor_lib/packets/raw_builder.h
@@ -19,12 +19,14 @@
#include <cstdint>
#include <vector>
+#include "hci/address.h"
#include "packets/packet_builder.h"
-#include "types/address.h"
namespace test_vendor_lib {
namespace packets {
+using ::bluetooth::hci::Address;
+
class RawBuilder : public PacketBuilder<true> {
public:
RawBuilder() = default;
diff --git a/vendor_libs/test_vendor_lib/packets/test/counted_builder_test.cc b/vendor_libs/test_vendor_lib/packets/test/counted_builder_test.cc
index bedc228..c91466b 100644
--- a/vendor_libs/test_vendor_lib/packets/test/counted_builder_test.cc
+++ b/vendor_libs/test_vendor_lib/packets/test/counted_builder_test.cc
@@ -20,8 +20,9 @@
#include <forward_list>
#include <memory>
-#include "types/address.h"
+#include "hci/address.h"
+using ::bluetooth::hci::Address;
using std::vector;
namespace {
diff --git a/vendor_libs/test_vendor_lib/packets/test/packet_view_test.cc b/vendor_libs/test_vendor_lib/packets/test/packet_view_test.cc
index 760388e..11891c6 100644
--- a/vendor_libs/test_vendor_lib/packets/test/packet_view_test.cc
+++ b/vendor_libs/test_vendor_lib/packets/test/packet_view_test.cc
@@ -20,8 +20,9 @@
#include <forward_list>
#include <memory>
-#include "types/address.h"
+#include "hci/address.h"
+using ::bluetooth::hci::Address;
using std::vector;
namespace {
diff --git a/vendor_libs/test_vendor_lib/packets/test/raw_builder_test.cc b/vendor_libs/test_vendor_lib/packets/test/raw_builder_test.cc
index a179b8b..8e69f9f 100644
--- a/vendor_libs/test_vendor_lib/packets/test/raw_builder_test.cc
+++ b/vendor_libs/test_vendor_lib/packets/test/raw_builder_test.cc
@@ -20,8 +20,9 @@
#include <forward_list>
#include <memory>
-#include "types/address.h"
+#include "hci/address.h"
+using ::bluetooth::hci::Address;
using std::vector;
namespace {
diff --git a/vendor_libs/test_vendor_lib/test/packet_stream_unittest.cc b/vendor_libs/test_vendor_lib/test/packet_stream_unittest.cc
index 7481235..c67c95e 100644
--- a/vendor_libs/test_vendor_lib/test/packet_stream_unittest.cc
+++ b/vendor_libs/test_vendor_lib/test/packet_stream_unittest.cc
@@ -83,33 +83,6 @@
for (int i = 0; i < payload_size; ++i) EXPECT_EQ(packet[4 + i], received_payload[i + 1]);
}
- void CheckedSendEvent(std::unique_ptr<EventPacket> event) {
- const vector<uint8_t> expected_payload = event->GetPayload();
- auto expected_size = event->GetPacketSize();
- auto expected_code = event->GetEventCode();
- auto expected_payload_size = event->GetPayloadSize();
-
- EXPECT_TRUE(packet_stream_.SendEvent(std::move(event), socketpair_fds_[0]));
-
- // Read the packet sent by |packet_stream_|.
- uint8_t event_header[2];
- read(socketpair_fds_[1], event_header, 2);
-
- uint8_t return_parameters_size;
- read(socketpair_fds_[1], &return_parameters_size, 1);
-
- uint8_t return_parameters[return_parameters_size];
- read(socketpair_fds_[1], return_parameters, sizeof(return_parameters));
-
- // Validate the packet by checking that it's the
- // appropriate size and then checking each byte.
- EXPECT_EQ(expected_size, sizeof(event_header) + return_parameters_size + 1);
- EXPECT_EQ(DATA_TYPE_EVENT, event_header[0]);
- EXPECT_EQ(expected_code, event_header[1]);
- EXPECT_EQ(expected_payload_size, static_cast<size_t>(return_parameters_size) + 1);
- for (int i = 0; i < return_parameters_size; ++i) EXPECT_EQ(expected_payload[i + 1], return_parameters[i]);
- }
-
protected:
PacketStream packet_stream_;
@@ -141,9 +114,4 @@
CheckedReceiveCommand(large_payload, HCI_RESET);
}
-TEST_F(PacketStreamTest, SendEvent) {
- const vector<uint8_t> return_parameters = {0};
- CheckedSendEvent(EventPacket::CreateCommandCompleteEvent(HCI_RESET, return_parameters));
-}
-
} // namespace test_vendor_lib
diff --git a/vendor_libs/test_vendor_lib/types/Android.bp b/vendor_libs/test_vendor_lib/types/Android.bp
index 07198e9..7e1193c 100644
--- a/vendor_libs/test_vendor_lib/types/Android.bp
+++ b/vendor_libs/test_vendor_lib/types/Android.bp
@@ -16,8 +16,6 @@
],
host_supported: true,
srcs: [
- "class_of_device.cc",
- "address.cc",
"bluetooth/uuid.cc",
],
header_libs: ["libbt-rootcanal-types-header"],
@@ -31,8 +29,6 @@
defaults: ["fluoride_defaults"],
host_supported: true,
srcs: [
- "test/class_of_device_unittest.cc",
- "test/address_unittest.cc",
"test/bluetooth/uuid_unittest.cc",
],
static_libs: [
diff --git a/vendor_libs/test_vendor_lib/types/address.cc b/vendor_libs/test_vendor_lib/types/address.cc
deleted file mode 100644
index b3c1db4..0000000
--- a/vendor_libs/test_vendor_lib/types/address.cc
+++ /dev/null
@@ -1,71 +0,0 @@
-/******************************************************************************
- *
- * Copyright 2017 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at:
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- ******************************************************************************/
-
-#include "address.h"
-
-#include <base/strings/string_split.h>
-#include <base/strings/stringprintf.h>
-#include <stdint.h>
-#include <algorithm>
-#include <vector>
-
-static_assert(sizeof(Address) == 6, "Address must be 6 bytes long!");
-
-const Address Address::kAny{{0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}};
-const Address Address::kEmpty{{0x00, 0x00, 0x00, 0x00, 0x00, 0x00}};
-
-Address::Address(const uint8_t (&addr)[6]) {
- std::copy(addr, addr + kLength, address);
-};
-
-std::string Address::ToString() const {
- return base::StringPrintf("%02x:%02x:%02x:%02x:%02x:%02x", address[5], address[4], address[3], address[2], address[1],
- address[0]);
-}
-
-bool Address::FromString(const std::string& from, Address& to) {
- Address new_addr;
- if (from.length() != 17) return false;
-
- std::vector<std::string> byte_tokens = base::SplitString(from, ":", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
-
- if (byte_tokens.size() != 6) return false;
-
- for (int i = 0; i < 6; i++) {
- const auto& token = byte_tokens[i];
-
- if (token.length() != 2) return false;
-
- char* temp = nullptr;
- new_addr.address[5 - i] = strtol(token.c_str(), &temp, 16);
- if (*temp != '\0') return false;
- }
-
- to = new_addr;
- return true;
-}
-
-size_t Address::FromOctets(const uint8_t* from) {
- std::copy(from, from + kLength, address);
- return kLength;
-};
-
-bool Address::IsValidAddress(const std::string& address) {
- Address tmp;
- return Address::FromString(address, tmp);
-}
diff --git a/vendor_libs/test_vendor_lib/types/address.h b/vendor_libs/test_vendor_lib/types/address.h
deleted file mode 100644
index 12e2dbb..0000000
--- a/vendor_libs/test_vendor_lib/types/address.h
+++ /dev/null
@@ -1,84 +0,0 @@
-/******************************************************************************
- *
- * Copyright 2017 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at:
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- ******************************************************************************/
-
-#pragma once
-
-#include <string>
-
-namespace bluetooth {
-namespace types {
-
-/** Bluetooth Address */
-class Address final {
- public:
- static constexpr unsigned int kLength = 6;
-
- uint8_t address[kLength];
-
- Address() = default;
- Address(const uint8_t (&addr)[6]);
-
- bool operator<(const Address& rhs) const {
- return (std::memcmp(address, rhs.address, sizeof(address)) < 0);
- }
- bool operator==(const Address& rhs) const {
- return (std::memcmp(address, rhs.address, sizeof(address)) == 0);
- }
- bool operator>(const Address& rhs) const {
- return (rhs < *this);
- }
- bool operator<=(const Address& rhs) const {
- return !(*this > rhs);
- }
- bool operator>=(const Address& rhs) const {
- return !(*this < rhs);
- }
- bool operator!=(const Address& rhs) const {
- return !(*this == rhs);
- }
-
- bool IsEmpty() const {
- return *this == kEmpty;
- }
-
- std::string ToString() const;
-
- // Converts |string| to Address and places it in |to|. If |from| does
- // not represent a Bluetooth address, |to| is not modified and this function
- // returns false. Otherwise, it returns true.
- static bool FromString(const std::string& from, Address& to);
-
- // Copies |from| raw Bluetooth address octets to the local object.
- // Returns the number of copied octets - should be always Address::kLength
- size_t FromOctets(const uint8_t* from);
-
- static bool IsValidAddress(const std::string& address);
-
- static const Address kEmpty; // 00:00:00:00:00:00
- static const Address kAny; // FF:FF:FF:FF:FF:FF
-};
-
-inline std::ostream& operator<<(std::ostream& os, const Address& a) {
- os << a.ToString();
- return os;
-}
-
-} // namespace types
-} // namespace bluetooth
-
-using ::bluetooth::types::Address; // TODO, remove
diff --git a/vendor_libs/test_vendor_lib/types/class_of_device.cc b/vendor_libs/test_vendor_lib/types/class_of_device.cc
deleted file mode 100644
index c5f1c3f..0000000
--- a/vendor_libs/test_vendor_lib/types/class_of_device.cc
+++ /dev/null
@@ -1,75 +0,0 @@
-/******************************************************************************
- *
- * Copyright 2018 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at:
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- ******************************************************************************/
-
-#include "class_of_device.h"
-
-#include <base/strings/string_split.h>
-#include <base/strings/stringprintf.h>
-#include <stdint.h>
-#include <algorithm>
-#include <vector>
-
-static_assert(sizeof(ClassOfDevice) == ClassOfDevice::kLength, "ClassOfDevice must be 3 bytes long!");
-
-ClassOfDevice::ClassOfDevice(const uint8_t (&class_of_device)[kLength]) {
- std::copy(class_of_device, class_of_device + kLength, cod);
-};
-
-std::string ClassOfDevice::ToString() const {
- return base::StringPrintf("%03x-%01x-%02x", (static_cast<uint16_t>(cod[2]) << 4) | cod[1] >> 4, cod[1] & 0x0f,
- cod[0]);
-}
-
-bool ClassOfDevice::FromString(const std::string& from, ClassOfDevice& to) {
- ClassOfDevice new_cod;
- if (from.length() != 8) return false;
-
- std::vector<std::string> byte_tokens = base::SplitString(from, "-", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
-
- if (byte_tokens.size() != 3) return false;
- if (byte_tokens[0].length() != 3) return false;
- if (byte_tokens[1].length() != 1) return false;
- if (byte_tokens[2].length() != 2) return false;
-
- uint16_t values[3];
-
- for (size_t i = 0; i < kLength; i++) {
- const auto& token = byte_tokens[i];
-
- char* temp = nullptr;
- values[i] = strtol(token.c_str(), &temp, 16);
- if (*temp != '\0') return false;
- }
-
- new_cod.cod[0] = values[2];
- new_cod.cod[1] = values[1] | ((values[0] & 0xf) << 4);
- new_cod.cod[2] = values[0] >> 4;
-
- to = new_cod;
- return true;
-}
-
-size_t ClassOfDevice::FromOctets(const uint8_t* from) {
- std::copy(from, from + kLength, cod);
- return kLength;
-};
-
-bool ClassOfDevice::IsValid(const std::string& cod) {
- ClassOfDevice tmp;
- return ClassOfDevice::FromString(cod, tmp);
-}
diff --git a/vendor_libs/test_vendor_lib/types/class_of_device.h b/vendor_libs/test_vendor_lib/types/class_of_device.h
deleted file mode 100644
index 4c37ebf..0000000
--- a/vendor_libs/test_vendor_lib/types/class_of_device.h
+++ /dev/null
@@ -1,62 +0,0 @@
-/******************************************************************************
- *
- * Copyright 2018 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at:
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- ******************************************************************************/
-
-#pragma once
-
-#include <string>
-
-namespace bluetooth {
-namespace types {
-
-/** Bluetooth Class of Device */
-class ClassOfDevice final {
- public:
- static constexpr unsigned int kLength = 3;
-
- uint8_t cod[kLength];
-
- ClassOfDevice() = default;
- ClassOfDevice(const uint8_t (&class_of_device)[kLength]);
-
- bool operator==(const ClassOfDevice& rhs) const {
- return (std::memcmp(cod, rhs.cod, sizeof(cod)) == 0);
- }
-
- std::string ToString() const;
-
- // Converts |string| to ClassOfDevice and places it in |to|. If |from| does
- // not represent a Class of Device, |to| is not modified and this function
- // returns false. Otherwise, it returns true.
- static bool FromString(const std::string& from, ClassOfDevice& to);
-
- // Copies |from| raw Class of Device octets to the local object.
- // Returns the number of copied octets (always ClassOfDevice::kLength)
- size_t FromOctets(const uint8_t* from);
-
- static bool IsValid(const std::string& class_of_device);
-};
-
-inline std::ostream& operator<<(std::ostream& os, const ClassOfDevice& c) {
- os << c.ToString();
- return os;
-}
-
-} // namespace types
-} // namespace bluetooth
-
-using ::bluetooth::types::ClassOfDevice; // TODO, remove
\ No newline at end of file
diff --git a/vendor_libs/test_vendor_lib/types/test/address_unittest.cc b/vendor_libs/test_vendor_lib/types/test/address_unittest.cc
deleted file mode 100644
index 65fd26d..0000000
--- a/vendor_libs/test_vendor_lib/types/test/address_unittest.cc
+++ /dev/null
@@ -1,197 +0,0 @@
-/******************************************************************************
- *
- * Copyright 2017 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at:
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- ******************************************************************************/
-
-#include <gtest/gtest.h>
-
-#include "address.h"
-
-static const char* test_addr = "bc:9a:78:56:34:12";
-static const char* test_addr2 = "21:43:65:87:a9:cb";
-
-TEST(AddressUnittest, test_constructor_array) {
- Address bdaddr({0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc});
-
- ASSERT_EQ(0x12, bdaddr.address[0]);
- ASSERT_EQ(0x34, bdaddr.address[1]);
- ASSERT_EQ(0x56, bdaddr.address[2]);
- ASSERT_EQ(0x78, bdaddr.address[3]);
- ASSERT_EQ(0x9A, bdaddr.address[4]);
- ASSERT_EQ(0xBC, bdaddr.address[5]);
-
- std::string ret = bdaddr.ToString();
-
- ASSERT_STREQ(test_addr, ret.c_str());
-}
-
-TEST(AddressUnittest, test_is_empty) {
- Address empty;
- Address::FromString("00:00:00:00:00:00", empty);
- ASSERT_TRUE(empty.IsEmpty());
-
- Address not_empty;
- Address::FromString("00:00:00:00:00:01", not_empty);
- ASSERT_FALSE(not_empty.IsEmpty());
-}
-
-TEST(AddressUnittest, test_to_from_str) {
- Address bdaddr;
- Address::FromString(test_addr, bdaddr);
-
- ASSERT_EQ(0x12, bdaddr.address[0]);
- ASSERT_EQ(0x34, bdaddr.address[1]);
- ASSERT_EQ(0x56, bdaddr.address[2]);
- ASSERT_EQ(0x78, bdaddr.address[3]);
- ASSERT_EQ(0x9A, bdaddr.address[4]);
- ASSERT_EQ(0xBC, bdaddr.address[5]);
-
- std::string ret = bdaddr.ToString();
-
- ASSERT_STREQ(test_addr, ret.c_str());
-}
-
-TEST(AddressUnittest, test_from_octets) {
- static const uint8_t test_addr_array[] = {0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc};
-
- Address bdaddr;
- size_t expected_result = Address::kLength;
- ASSERT_EQ(expected_result, bdaddr.FromOctets(test_addr_array));
-
- ASSERT_EQ(0x12, bdaddr.address[0]);
- ASSERT_EQ(0x34, bdaddr.address[1]);
- ASSERT_EQ(0x56, bdaddr.address[2]);
- ASSERT_EQ(0x78, bdaddr.address[3]);
- ASSERT_EQ(0x9A, bdaddr.address[4]);
- ASSERT_EQ(0xBC, bdaddr.address[5]);
-
- std::string ret = bdaddr.ToString();
-
- ASSERT_STREQ(test_addr, ret.c_str());
-}
-
-TEST(AddressTest, test_equals) {
- Address bdaddr1;
- Address bdaddr2;
- Address bdaddr3;
- Address::FromString(test_addr, bdaddr1);
- Address::FromString(test_addr, bdaddr2);
- EXPECT_TRUE(bdaddr1 == bdaddr2);
- EXPECT_FALSE(bdaddr1 != bdaddr2);
- EXPECT_TRUE(bdaddr1 == bdaddr1);
- EXPECT_FALSE(bdaddr1 != bdaddr1);
-
- Address::FromString(test_addr2, bdaddr3);
- EXPECT_FALSE(bdaddr2 == bdaddr3);
- EXPECT_TRUE(bdaddr2 != bdaddr3);
-}
-
-TEST(AddressTest, test_less_than) {
- Address bdaddr1;
- Address bdaddr2;
- Address bdaddr3;
- Address::FromString(test_addr, bdaddr1);
- Address::FromString(test_addr, bdaddr2);
- EXPECT_FALSE(bdaddr1 < bdaddr2);
- EXPECT_FALSE(bdaddr1 < bdaddr1);
-
- Address::FromString(test_addr2, bdaddr3);
- EXPECT_TRUE(bdaddr2 < bdaddr3);
- EXPECT_FALSE(bdaddr3 < bdaddr2);
-}
-
-TEST(AddressTest, test_more_than) {
- Address bdaddr1;
- Address bdaddr2;
- Address bdaddr3;
- Address::FromString(test_addr, bdaddr1);
- Address::FromString(test_addr, bdaddr2);
- EXPECT_FALSE(bdaddr1 > bdaddr2);
- EXPECT_FALSE(bdaddr1 > bdaddr1);
-
- Address::FromString(test_addr2, bdaddr3);
- EXPECT_FALSE(bdaddr2 > bdaddr3);
- EXPECT_TRUE(bdaddr3 > bdaddr2);
-}
-
-TEST(AddressTest, test_less_than_or_equal) {
- Address bdaddr1;
- Address bdaddr2;
- Address bdaddr3;
- Address::FromString(test_addr, bdaddr1);
- Address::FromString(test_addr, bdaddr2);
- EXPECT_TRUE(bdaddr1 <= bdaddr2);
- EXPECT_TRUE(bdaddr1 <= bdaddr1);
-
- Address::FromString(test_addr2, bdaddr3);
- EXPECT_TRUE(bdaddr2 <= bdaddr3);
- EXPECT_FALSE(bdaddr3 <= bdaddr2);
-}
-
-TEST(AddressTest, test_more_than_or_equal) {
- Address bdaddr1;
- Address bdaddr2;
- Address bdaddr3;
- Address::FromString(test_addr, bdaddr1);
- Address::FromString(test_addr, bdaddr2);
- EXPECT_TRUE(bdaddr1 >= bdaddr2);
- EXPECT_TRUE(bdaddr1 >= bdaddr1);
-
- Address::FromString(test_addr2, bdaddr3);
- EXPECT_FALSE(bdaddr2 >= bdaddr3);
- EXPECT_TRUE(bdaddr3 >= bdaddr2);
-}
-
-TEST(AddressTest, test_copy) {
- Address bdaddr1;
- Address bdaddr2;
- Address::FromString(test_addr, bdaddr1);
- bdaddr2 = bdaddr1;
-
- EXPECT_TRUE(bdaddr1 == bdaddr2);
-}
-
-TEST(AddressTest, IsValidAddress) {
- EXPECT_FALSE(Address::IsValidAddress(""));
- EXPECT_FALSE(Address::IsValidAddress("000000000000"));
- EXPECT_FALSE(Address::IsValidAddress("00:00:00:00:0000"));
- EXPECT_FALSE(Address::IsValidAddress("00:00:00:00:00:0"));
- EXPECT_FALSE(Address::IsValidAddress("00:00:00:00:00:0;"));
- EXPECT_TRUE(Address::IsValidAddress("00:00:00:00:00:00"));
- EXPECT_TRUE(Address::IsValidAddress("AB:cd:00:00:00:00"));
- EXPECT_FALSE(Address::IsValidAddress("aB:cD:eF:Gh:iJ:Kl"));
-}
-
-TEST(AddressTest, BdAddrFromString) {
- Address addr;
- memset(&addr, 0, sizeof(addr));
-
- EXPECT_TRUE(Address::FromString("00:00:00:00:00:00", addr));
- const Address result0 = {{0x00, 0x00, 0x00, 0x00, 0x00, 0x00}};
- EXPECT_EQ(0, memcmp(&addr, &result0, sizeof(addr)));
-
- EXPECT_TRUE(Address::FromString("ab:01:4C:d5:21:9f", addr));
- const Address result1 = {{0x9f, 0x21, 0xd5, 0x4c, 0x01, 0xab}};
- EXPECT_EQ(0, memcmp(&addr, &result1, sizeof(addr)));
-}
-
-TEST(AddressTest, BdAddrFromStringToStringEquivalent) {
- std::string address = "c1:c2:c3:d1:d2:d3";
- Address addr;
-
- EXPECT_TRUE(Address::FromString(address, addr));
- EXPECT_EQ(addr.ToString(), address);
-}
diff --git a/vendor_libs/test_vendor_lib/types/test/class_of_device_unittest.cc b/vendor_libs/test_vendor_lib/types/test/class_of_device_unittest.cc
deleted file mode 100644
index 5d652a5..0000000
--- a/vendor_libs/test_vendor_lib/types/test/class_of_device_unittest.cc
+++ /dev/null
@@ -1,96 +0,0 @@
-/******************************************************************************
- *
- * Copyright 2018 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at:
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- ******************************************************************************/
-
-#include <gtest/gtest.h>
-
-#include "class_of_device.h"
-
-static const char* test_class = "efc-d-ab";
-static const uint8_t test_bytes[]{0xab, 0xcd, 0xef};
-
-TEST(ClassOfDeviceUnittest, test_constructor_array) {
- ClassOfDevice cod(test_bytes);
-
- ASSERT_EQ(test_bytes[0], cod.cod[0]);
- ASSERT_EQ(test_bytes[1], cod.cod[1]);
- ASSERT_EQ(test_bytes[2], cod.cod[2]);
-
- std::string ret = cod.ToString();
-
- ASSERT_STREQ(test_class, ret.c_str());
-}
-
-TEST(ClassOfDeviceUnittest, test_to_from_str) {
- ClassOfDevice cod;
- ClassOfDevice::FromString(test_class, cod);
-
- ASSERT_EQ(test_bytes[0], cod.cod[0]);
- ASSERT_EQ(test_bytes[1], cod.cod[1]);
- ASSERT_EQ(test_bytes[2], cod.cod[2]);
-
- std::string ret = cod.ToString();
-
- ASSERT_STREQ(test_class, ret.c_str());
-}
-
-TEST(ClassOfDeviceUnittest, test_from_octets) {
- ClassOfDevice cod;
- size_t expected_result = ClassOfDevice::kLength;
- ASSERT_EQ(expected_result, cod.FromOctets(test_bytes));
-
- ASSERT_EQ(test_bytes[0], cod.cod[0]);
- ASSERT_EQ(test_bytes[1], cod.cod[1]);
- ASSERT_EQ(test_bytes[2], cod.cod[2]);
-
- std::string ret = cod.ToString();
-
- ASSERT_STREQ(test_class, ret.c_str());
-}
-
-TEST(ClassOfDeviceTest, test_copy) {
- ClassOfDevice cod1;
- ClassOfDevice cod2;
- ClassOfDevice::FromString(test_class, cod1);
- cod2 = cod1;
-
- ASSERT_EQ(cod1.cod[0], cod2.cod[0]);
- ASSERT_EQ(cod1.cod[1], cod2.cod[1]);
- ASSERT_EQ(cod1.cod[2], cod2.cod[2]);
-}
-
-TEST(ClassOfDeviceTest, IsValid) {
- EXPECT_FALSE(ClassOfDevice::IsValid(""));
- EXPECT_FALSE(ClassOfDevice::IsValid("000000"));
- EXPECT_FALSE(ClassOfDevice::IsValid("00-00-00"));
- EXPECT_FALSE(ClassOfDevice::IsValid("000-0-0"));
- EXPECT_TRUE(ClassOfDevice::IsValid("000-0-00"));
- EXPECT_TRUE(ClassOfDevice::IsValid("ABc-d-00"));
- EXPECT_TRUE(ClassOfDevice::IsValid("aBc-D-eF"));
-}
-
-TEST(ClassOfDeviceTest, classOfDeviceFromString) {
- ClassOfDevice cod;
-
- EXPECT_TRUE(ClassOfDevice::FromString("000-0-00", cod));
- const ClassOfDevice result0 = {{0x00, 0x00, 0x00}};
- EXPECT_EQ(0, memcmp(&cod, &result0, sizeof(cod)));
-
- EXPECT_TRUE(ClassOfDevice::FromString("ab2-1-4C", cod));
- const ClassOfDevice result1 = {{0x4c, 0x21, 0xab}};
- EXPECT_EQ(0, memcmp(&cod, &result1, sizeof(cod)));
-}