1 /*
2  * Copyright 2019 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include "hci/hci_layer.h"
18 
19 #include <gtest/gtest.h>
20 
21 #include <list>
22 #include <memory>
23 
24 #include "hal/hci_hal_fake.h"
25 #include "hci/hci_packets.h"
26 #include "module.h"
27 #include "os/thread.h"
28 #include "packet/bit_inserter.h"
29 #include "packet/raw_builder.h"
30 
31 using bluetooth::os::Thread;
32 using bluetooth::packet::BitInserter;
33 using bluetooth::packet::RawBuilder;
34 using std::vector;
35 
36 namespace {
37 vector<uint8_t> information_request = {
38         0xfe, 0x2e, 0x0a, 0x00, 0x06, 0x00, 0x01, 0x00, 0x0a, 0x02, 0x02, 0x00, 0x02, 0x00,
39 };
40 // 0x00, 0x01, 0x02, 0x03, ...
41 vector<uint8_t> counting_bytes;
42 // 0xFF, 0xFE, 0xFD, 0xFC, ...
43 vector<uint8_t> counting_down_bytes;
44 const size_t count_size = 0x8;
45 
46 }  // namespace
47 
48 namespace bluetooth {
49 namespace hci {
50 namespace {
51 
52 constexpr std::chrono::milliseconds kTimeout = HciLayer::kHciTimeoutMs / 2;
53 
54 class DependsOnHci : public Module {
55 public:
DependsOnHci()56   DependsOnHci() : Module() {}
57 
SendHciCommandExpectingStatus(std::unique_ptr<CommandBuilder> command)58   void SendHciCommandExpectingStatus(std::unique_ptr<CommandBuilder> command) {
59     hci_->EnqueueCommand(
60             std::move(command),
61             GetHandler()->BindOnceOn(this, &DependsOnHci::handle_event<CommandStatusView>));
62   }
63 
SendHciCommandExpectingComplete(std::unique_ptr<CommandBuilder> command)64   void SendHciCommandExpectingComplete(std::unique_ptr<CommandBuilder> command) {
65     hci_->EnqueueCommand(
66             std::move(command),
67             GetHandler()->BindOnceOn(this, &DependsOnHci::handle_event<CommandCompleteView>));
68   }
69 
SendSecurityCommandExpectingComplete(std::unique_ptr<SecurityCommandBuilder> command)70   void SendSecurityCommandExpectingComplete(std::unique_ptr<SecurityCommandBuilder> command) {
71     if (security_interface_ == nullptr) {
72       security_interface_ = hci_->GetSecurityInterface(
73               GetHandler()->BindOn(this, &DependsOnHci::handle_event<EventView>));
74     }
75     hci_->EnqueueCommand(
76             std::move(command),
77             GetHandler()->BindOnceOn(this, &DependsOnHci::handle_event<CommandCompleteView>));
78   }
79 
SendLeSecurityCommandExpectingComplete(std::unique_ptr<LeSecurityCommandBuilder> command)80   void SendLeSecurityCommandExpectingComplete(std::unique_ptr<LeSecurityCommandBuilder> command) {
81     if (le_security_interface_ == nullptr) {
82       le_security_interface_ = hci_->GetLeSecurityInterface(
83               GetHandler()->BindOn(this, &DependsOnHci::handle_event<LeMetaEventView>));
84     }
85     hci_->EnqueueCommand(
86             std::move(command),
87             GetHandler()->BindOnceOn(this, &DependsOnHci::handle_event<CommandCompleteView>));
88   }
89 
SendAclData(std::unique_ptr<AclBuilder> acl)90   void SendAclData(std::unique_ptr<AclBuilder> acl) {
91     outgoing_acl_.push(std::move(acl));
92     auto queue_end = hci_->GetAclQueueEnd();
93     queue_end->RegisterEnqueue(
94             GetHandler(), common::Bind(&DependsOnHci::handle_enqueue, common::Unretained(this)));
95   }
96 
SendIsoData(std::unique_ptr<IsoBuilder> iso)97   void SendIsoData(std::unique_ptr<IsoBuilder> iso) {
98     outgoing_iso_.push(std::move(iso));
99     auto queue_end = hci_->GetIsoQueueEnd();
100     queue_end->RegisterEnqueue(GetHandler(), common::Bind(&DependsOnHci::handle_enqueue_iso,
101                                                           common::Unretained(this)));
102   }
103 
GetReceivedEvent(std::chrono::milliseconds timeout=kTimeout)104   std::optional<EventView> GetReceivedEvent(std::chrono::milliseconds timeout = kTimeout) {
105     if (!incoming_events_.wait_to_take(timeout)) {
106       return {};
107     }
108     auto event = EventView::Create(incoming_events_.take());
109     log::assert_that(event.IsValid(), "assert failed: event.IsValid()");
110     return event;
111   }
112 
GetReceivedAcl(std::chrono::milliseconds timeout=std::chrono::seconds (1))113   std::optional<AclView> GetReceivedAcl(
114           std::chrono::milliseconds timeout = std::chrono::seconds(1)) {
115     if (!incoming_acl_.wait_to_take(timeout)) {
116       return {};
117     }
118     auto acl = AclView::Create(incoming_acl_.take());
119     log::assert_that(acl.IsValid(), "assert failed: acl.IsValid()");
120     return acl;
121   }
122 
GetReceivedIso(std::chrono::milliseconds timeout=std::chrono::seconds (1))123   std::optional<IsoView> GetReceivedIso(
124           std::chrono::milliseconds timeout = std::chrono::seconds(1)) {
125     if (!incoming_iso_.wait_to_take(timeout)) {
126       return {};
127     }
128     auto iso = IsoView::Create(incoming_iso_.take());
129     log::assert_that(iso.IsValid(), "assert failed: iso.IsValid()");
130     return iso;
131   }
132 
Start()133   void Start() {
134     hci_ = GetDependency<HciLayer>();
135     hci_->RegisterEventHandler(EventCode::CONNECTION_COMPLETE,
136                                GetHandler()->BindOn(this, &DependsOnHci::handle_event<EventView>));
137     hci_->RegisterLeEventHandler(
138             SubeventCode::CONNECTION_COMPLETE,
139             GetHandler()->BindOn(this, &DependsOnHci::handle_event<LeMetaEventView>));
140     hci_->GetAclQueueEnd()->RegisterDequeue(
141             GetHandler(), common::Bind(&DependsOnHci::handle_acl, common::Unretained(this)));
142     hci_->GetIsoQueueEnd()->RegisterDequeue(
143             GetHandler(), common::Bind(&DependsOnHci::handle_iso, common::Unretained(this)));
144   }
145 
Stop()146   void Stop() {
147     hci_->GetAclQueueEnd()->UnregisterDequeue();
148     hci_->GetIsoQueueEnd()->UnregisterDequeue();
149   }
150 
ListDependencies(ModuleList * list) const151   void ListDependencies(ModuleList* list) const { list->add<HciLayer>(); }
152 
ToString() const153   std::string ToString() const override { return std::string("DependsOnHci"); }
154 
155   static const ModuleFactory Factory;
156 
157 private:
158   HciLayer* hci_ = nullptr;
159   const SecurityInterface* security_interface_;
160   const LeSecurityInterface* le_security_interface_;
161   common::BlockingQueue<EventView> incoming_events_;
162   common::BlockingQueue<AclView> incoming_acl_;
163   common::BlockingQueue<IsoView> incoming_iso_;
164 
handle_acl()165   void handle_acl() {
166     auto acl_ptr = hci_->GetAclQueueEnd()->TryDequeue();
167     incoming_acl_.push(*acl_ptr);
168   }
169 
170   template <typename T>
handle_event(T event)171   void handle_event(T event) {
172     incoming_events_.push(event);
173   }
174 
handle_iso()175   void handle_iso() {
176     auto iso_ptr = hci_->GetIsoQueueEnd()->TryDequeue();
177     incoming_iso_.push(*iso_ptr);
178   }
179 
180   std::queue<std::unique_ptr<AclBuilder>> outgoing_acl_;
181 
handle_enqueue()182   std::unique_ptr<AclBuilder> handle_enqueue() {
183     hci_->GetAclQueueEnd()->UnregisterEnqueue();
184     auto acl = std::move(outgoing_acl_.front());
185     outgoing_acl_.pop();
186     return acl;
187   }
188 
189   std::queue<std::unique_ptr<IsoBuilder>> outgoing_iso_;
190 
handle_enqueue_iso()191   std::unique_ptr<IsoBuilder> handle_enqueue_iso() {
192     hci_->GetIsoQueueEnd()->UnregisterEnqueue();
193     auto iso = std::move(outgoing_iso_.front());
194     outgoing_iso_.pop();
195     return iso;
196   }
197 };
198 
__anond9ca92640302() 199 const ModuleFactory DependsOnHci::Factory = ModuleFactory([]() { return new DependsOnHci(); });
200 
201 class HciTest : public ::testing::Test {
202 public:
SetUp()203   void SetUp() override {
204     counting_bytes.reserve(count_size);
205     counting_down_bytes.reserve(count_size);
206     for (size_t i = 0; i < count_size; i++) {
207       counting_bytes.push_back(i);
208       counting_down_bytes.push_back(~i);
209     }
210     hal = new hal::TestHciHal();
211 
212     fake_registry_.InjectTestModule(&hal::HciHal::Factory, hal);
213     fake_registry_.Start<DependsOnHci>(&fake_registry_.GetTestThread());
214     hci = static_cast<HciLayer*>(fake_registry_.GetModuleUnderTest(&HciLayer::Factory));
215     upper = static_cast<DependsOnHci*>(fake_registry_.GetModuleUnderTest(&DependsOnHci::Factory));
216     ASSERT_TRUE(fake_registry_.IsStarted<HciLayer>());
217 
218     // Verify that reset was received
219     auto sent_command = hal->GetSentCommand();
220     ASSERT_TRUE(sent_command.has_value());
221     auto reset_view = ResetView::Create(CommandView::Create(*sent_command));
222     ASSERT_TRUE(reset_view.IsValid());
223 
224     // Send the response event
225     uint8_t num_packets = 1;
226     ErrorCode error_code = ErrorCode::SUCCESS;
227     hal->callbacks->hciEventReceived(
228             GetPacketBytes(ResetCompleteBuilder::Create(num_packets, error_code)));
229   }
230 
TearDown()231   void TearDown() override { fake_registry_.StopAll(); }
232 
GetPacketBytes(std::unique_ptr<packet::BasePacketBuilder> packet)233   std::vector<uint8_t> GetPacketBytes(std::unique_ptr<packet::BasePacketBuilder> packet) {
234     std::vector<uint8_t> bytes;
235     BitInserter i(bytes);
236     bytes.reserve(packet->size());
237     packet->Serialize(i);
238     return bytes;
239   }
240 
241   DependsOnHci* upper = nullptr;
242   hal::TestHciHal* hal = nullptr;
243   HciLayer* hci = nullptr;
244   TestModuleRegistry fake_registry_;
245 };
246 
TEST_F(HciTest,initAndClose)247 TEST_F(HciTest, initAndClose) {}
248 
TEST_F(HciTest,leMetaEvent)249 TEST_F(HciTest, leMetaEvent) {
250   // Send an LE event
251   ErrorCode status = ErrorCode::SUCCESS;
252   uint16_t handle = 0x123;
253   Role role = Role::CENTRAL;
254   AddressType peer_address_type = AddressType::PUBLIC_DEVICE_ADDRESS;
255   Address peer_address = Address::kAny;
256   uint16_t conn_interval = 0x0ABC;
257   uint16_t conn_latency = 0x0123;
258   uint16_t supervision_timeout = 0x0B05;
259   ClockAccuracy central_clock_accuracy = ClockAccuracy::PPM_50;
260   hal->callbacks->hciEventReceived(GetPacketBytes(LeConnectionCompleteBuilder::Create(
261           status, handle, role, peer_address_type, peer_address, conn_interval, conn_latency,
262           supervision_timeout, central_clock_accuracy)));
263 
264   // Wait for the event
265   auto event = upper->GetReceivedEvent();
266   ASSERT_TRUE(event.has_value());
267   ASSERT_TRUE(LeConnectionCompleteView::Create(LeMetaEventView::Create(EventView::Create(*event)))
268                       .IsValid());
269 }
270 
TEST_F(HciTest,postEventsOnceOnHciHandler)271 TEST_F(HciTest, postEventsOnceOnHciHandler) {
272   // Send a CreateConnection command.
273   Address addr;
274   Address::FromString("01:02:03:04:05:06", addr);
275   upper->SendHciCommandExpectingStatus(CreateConnectionBuilder::Create(
276           addr, 0, PageScanRepetitionMode::R0, 0, ClockOffsetValid::INVALID,
277           CreateConnectionRoleSwitch::ALLOW_ROLE_SWITCH));
278 
279   // Validate the received command.
280   auto sent_command = hal->GetSentCommand();
281   ASSERT_TRUE(sent_command.has_value());
282   auto command = CreateConnectionView::Create(
283           ConnectionManagementCommandView::Create(AclCommandView::Create(*sent_command)));
284   ASSERT_TRUE(command.IsValid());
285 
286   // Send a status and a connection complete at the same time.
287   uint8_t num_packets = 1;
288   hal->callbacks->hciEventReceived(
289           GetPacketBytes(CreateConnectionStatusBuilder::Create(ErrorCode::SUCCESS, num_packets)));
290   hal->callbacks->hciEventReceived(GetPacketBytes(ConnectionCompleteBuilder::Create(
291           ErrorCode::SUCCESS, 0x123, addr, LinkType::ACL, Enable::DISABLED)));
292 
293   // Make sure the status comes first.
294   auto event = upper->GetReceivedEvent();
295   ASSERT_TRUE(event.has_value());
296   ASSERT_TRUE(
297           CreateConnectionStatusView::Create(CommandStatusView::Create(EventView::Create(*event)))
298                   .IsValid());
299 }
300 
TEST_F(HciTest,DISABLED_hciTimeOut)301 TEST_F(HciTest, DISABLED_hciTimeOut) {
302   upper->SendHciCommandExpectingComplete(ResetBuilder::Create());
303   auto sent_command = hal->GetSentCommand();
304   ASSERT_TRUE(sent_command.has_value());
305   auto reset = ResetView::Create(*sent_command);
306   ASSERT_TRUE(reset.IsValid());
307 
308   auto event = upper->GetReceivedEvent(HciLayer::kHciTimeoutMs);
309   ASSERT_FALSE(event.has_value());
310 
311   sent_command = hal->GetSentCommand();
312   ASSERT_TRUE(sent_command.has_value());
313   auto debug = ControllerDebugInfoView::Create(VendorCommandView::Create(*sent_command));
314   ASSERT_TRUE(debug.IsValid());
315 }
316 
TEST_F(HciTest,noOpCredits)317 TEST_F(HciTest, noOpCredits) {
318   // Send 0 credits
319   uint8_t num_packets = 0;
320   hal->callbacks->hciEventReceived(GetPacketBytes(NoCommandCompleteBuilder::Create(num_packets)));
321 
322   upper->SendHciCommandExpectingComplete(ReadLocalVersionInformationBuilder::Create());
323 
324   // Verify that nothing was sent
325   ASSERT_FALSE(hal->GetSentCommand(std::chrono::milliseconds(10)).has_value());
326 
327   num_packets = 1;
328   hal->callbacks->hciEventReceived(GetPacketBytes(NoCommandCompleteBuilder::Create(num_packets)));
329 
330   // Verify that one was sent
331   auto sent_command = hal->GetSentCommand();
332   ASSERT_TRUE(sent_command.has_value());
333 
334   // Send the response event
335   ErrorCode error_code = ErrorCode::SUCCESS;
336   LocalVersionInformation local_version_information;
337   local_version_information.hci_version_ = HciVersion::V_5_0;
338   local_version_information.hci_revision_ = 0x1234;
339   local_version_information.lmp_version_ = LmpVersion::V_4_2;
340   local_version_information.manufacturer_name_ = 0xBAD;
341   local_version_information.lmp_subversion_ = 0x5678;
342   hal->callbacks->hciEventReceived(
343           GetPacketBytes(ReadLocalVersionInformationCompleteBuilder::Create(
344                   num_packets, error_code, local_version_information)));
345 
346   // Wait for the event
347   auto event = upper->GetReceivedEvent();
348   ASSERT_TRUE(event.has_value());
349   ASSERT_TRUE(ReadLocalVersionInformationCompleteView::Create(
350                       CommandCompleteView::Create(EventView::Create(*event)))
351                       .IsValid());
352 }
353 
TEST_F(HciTest,creditsTest)354 TEST_F(HciTest, creditsTest) {
355   auto sent_command = hal->GetSentCommand(std::chrono::milliseconds(10));
356   ASSERT_FALSE(sent_command.has_value());
357 
358   // Send all three commands
359   upper->SendHciCommandExpectingComplete(ReadLocalVersionInformationBuilder::Create());
360   upper->SendHciCommandExpectingComplete(ReadLocalSupportedCommandsBuilder::Create());
361   upper->SendHciCommandExpectingComplete(ReadLocalSupportedFeaturesBuilder::Create());
362 
363   // Verify that the first one is sent
364   sent_command = hal->GetSentCommand();
365   ASSERT_TRUE(sent_command.has_value());
366   auto version_view = ReadLocalVersionInformationView::Create(CommandView::Create(*sent_command));
367   ASSERT_TRUE(version_view.IsValid());
368 
369   // Verify that only one was sent
370   sent_command = hal->GetSentCommand(std::chrono::milliseconds(10));
371   ASSERT_FALSE(sent_command.has_value());
372 
373   // Send the response event
374   uint8_t num_packets = 1;
375   ErrorCode error_code = ErrorCode::SUCCESS;
376   LocalVersionInformation local_version_information;
377   local_version_information.hci_version_ = HciVersion::V_5_0;
378   local_version_information.hci_revision_ = 0x1234;
379   local_version_information.lmp_version_ = LmpVersion::V_4_2;
380   local_version_information.manufacturer_name_ = 0xBAD;
381   local_version_information.lmp_subversion_ = 0x5678;
382   hal->callbacks->hciEventReceived(
383           GetPacketBytes(ReadLocalVersionInformationCompleteBuilder::Create(
384                   num_packets, error_code, local_version_information)));
385 
386   // Wait for the event
387   auto event = upper->GetReceivedEvent();
388   ASSERT_TRUE(event.has_value());
389   ASSERT_TRUE(ReadLocalVersionInformationCompleteView::Create(
390                       CommandCompleteView::Create(EventView::Create(*event)))
391                       .IsValid());
392 
393   // Verify that the second one is sent
394   sent_command = hal->GetSentCommand();
395   ASSERT_TRUE(sent_command.has_value());
396   auto supported_commands_view =
397           ReadLocalSupportedCommandsView::Create(CommandView::Create(*sent_command));
398   ASSERT_TRUE(supported_commands_view.IsValid());
399 
400   // Verify that only one was sent
401   sent_command = hal->GetSentCommand(std::chrono::milliseconds(10));
402   ASSERT_FALSE(sent_command.has_value());
403 
404   // Send the response event
405   std::array<uint8_t, 64> supported_commands;
406   for (uint8_t i = 0; i < 64; i++) {
407     supported_commands[i] = i;
408   }
409   hal->callbacks->hciEventReceived(GetPacketBytes(ReadLocalSupportedCommandsCompleteBuilder::Create(
410           num_packets, error_code, supported_commands)));
411 
412   // Wait for the event
413   event = upper->GetReceivedEvent();
414   ASSERT_TRUE(event.has_value());
415   ASSERT_TRUE(ReadLocalSupportedCommandsCompleteView::Create(CommandCompleteView::Create(*event))
416                       .IsValid());
417   // Verify that the third one is sent
418   sent_command = hal->GetSentCommand();
419   ASSERT_TRUE(sent_command.has_value());
420   auto supported_features_view =
421           ReadLocalSupportedFeaturesView::Create(CommandView::Create(*sent_command));
422   ASSERT_TRUE(supported_features_view.IsValid());
423 
424   // Verify that only one was sent
425   sent_command = hal->GetSentCommand(std::chrono::milliseconds(10));
426   ASSERT_FALSE(sent_command.has_value());
427 
428   // Send the response event
429   uint64_t lmp_features = 0x012345678abcdef;
430   hal->callbacks->hciEventReceived(GetPacketBytes(ReadLocalSupportedFeaturesCompleteBuilder::Create(
431           num_packets, error_code, lmp_features)));
432 
433   // Wait for the event
434   event = upper->GetReceivedEvent();
435   ASSERT_TRUE(event.has_value());
436   ASSERT_TRUE(ReadLocalSupportedFeaturesCompleteView::Create(CommandCompleteView::Create(*event))
437                       .IsValid());
438 }
439 
TEST_F(HciTest,leSecurityInterfaceTest)440 TEST_F(HciTest, leSecurityInterfaceTest) {
441   // Send LeRand to the controller
442   upper->SendLeSecurityCommandExpectingComplete(LeRandBuilder::Create());
443 
444   // Check the command
445   auto sent_command = hal->GetSentCommand();
446   ASSERT_TRUE(sent_command.has_value());
447   LeRandView view =
448           LeRandView::Create(LeSecurityCommandView::Create(CommandView::Create(*sent_command)));
449   ASSERT_TRUE(view.IsValid());
450 
451   // Send a Command Complete to the host
452   uint8_t num_packets = 1;
453   ErrorCode status = ErrorCode::SUCCESS;
454   uint64_t rand = 0x0123456789abcdef;
455   hal->callbacks->hciEventReceived(
456           GetPacketBytes(LeRandCompleteBuilder::Create(num_packets, status, rand)));
457 
458   // Verify the event
459   auto event = upper->GetReceivedEvent();
460   ASSERT_TRUE(event.has_value());
461   ASSERT_TRUE(LeRandCompleteView::Create(CommandCompleteView::Create(*event)).IsValid());
462 }
463 
TEST_F(HciTest,securityInterfacesTest)464 TEST_F(HciTest, securityInterfacesTest) {
465   // Send WriteSimplePairingMode to the controller
466   Enable enable = Enable::ENABLED;
467   upper->SendSecurityCommandExpectingComplete(WriteSimplePairingModeBuilder::Create(enable));
468 
469   // Check the command
470   auto sent_command = hal->GetSentCommand();
471   ASSERT_TRUE(sent_command.has_value());
472   auto view = WriteSimplePairingModeView::Create(
473           SecurityCommandView::Create(CommandView::Create(*sent_command)));
474   ASSERT_TRUE(view.IsValid());
475 
476   // Send a Command Complete to the host
477   uint8_t num_packets = 1;
478   ErrorCode status = ErrorCode::SUCCESS;
479   hal->callbacks->hciEventReceived(
480           GetPacketBytes(WriteSimplePairingModeCompleteBuilder::Create(num_packets, status)));
481 
482   // Verify the event
483   auto event = upper->GetReceivedEvent();
484   ASSERT_TRUE(event.has_value());
485   ASSERT_TRUE(WriteSimplePairingModeCompleteView::Create(CommandCompleteView::Create(*event))
486                       .IsValid());
487 }
488 
TEST_F(HciTest,createConnectionTest)489 TEST_F(HciTest, createConnectionTest) {
490   // Send CreateConnection to the controller
491   Address bd_addr;
492   ASSERT_TRUE(Address::FromString("A1:A2:A3:A4:A5:A6", bd_addr));
493   uint16_t packet_type = 0x1234;
494   PageScanRepetitionMode page_scan_repetition_mode = PageScanRepetitionMode::R0;
495   uint16_t clock_offset = 0x3456;
496   ClockOffsetValid clock_offset_valid = ClockOffsetValid::VALID;
497   CreateConnectionRoleSwitch allow_role_switch = CreateConnectionRoleSwitch::ALLOW_ROLE_SWITCH;
498   upper->SendHciCommandExpectingStatus(
499           CreateConnectionBuilder::Create(bd_addr, packet_type, page_scan_repetition_mode,
500                                           clock_offset, clock_offset_valid, allow_role_switch));
501 
502   // Check the command
503   auto sent_command = hal->GetSentCommand();
504   ASSERT_TRUE(sent_command.has_value());
505   CreateConnectionView view = CreateConnectionView::Create(ConnectionManagementCommandView::Create(
506           AclCommandView::Create(CommandView::Create(*sent_command))));
507   ASSERT_TRUE(view.IsValid());
508   ASSERT_EQ(bd_addr, view.GetBdAddr());
509   ASSERT_EQ(packet_type, view.GetPacketType());
510   ASSERT_EQ(page_scan_repetition_mode, view.GetPageScanRepetitionMode());
511   ASSERT_EQ(clock_offset, view.GetClockOffset());
512   ASSERT_EQ(clock_offset_valid, view.GetClockOffsetValid());
513   ASSERT_EQ(allow_role_switch, view.GetAllowRoleSwitch());
514 
515   // Send a Command Status to the host
516   ErrorCode status = ErrorCode::SUCCESS;
517   uint16_t handle = 0x123;
518   LinkType link_type = LinkType::ACL;
519   Enable encryption_enabled = Enable::DISABLED;
520   hal->callbacks->hciEventReceived(
521           GetPacketBytes(CreateConnectionStatusBuilder::Create(ErrorCode::SUCCESS, 1)));
522 
523   // Verify the event
524   auto event = upper->GetReceivedEvent();
525   ASSERT_TRUE(event.has_value());
526   ASSERT_TRUE(CreateConnectionStatusView::Create(CommandStatusView::Create(*event)).IsValid());
527 
528   // Send a ConnectionComplete to the host
529   hal->callbacks->hciEventReceived(GetPacketBytes(ConnectionCompleteBuilder::Create(
530           status, handle, bd_addr, link_type, encryption_enabled)));
531 
532   // Verify the event
533   event = upper->GetReceivedEvent();
534   ASSERT_TRUE(event.has_value());
535   ConnectionCompleteView connection_complete_view = ConnectionCompleteView::Create(*event);
536   ASSERT_TRUE(connection_complete_view.IsValid());
537   ASSERT_EQ(status, connection_complete_view.GetStatus());
538   ASSERT_EQ(handle, connection_complete_view.GetConnectionHandle());
539   ASSERT_EQ(link_type, connection_complete_view.GetLinkType());
540   ASSERT_EQ(encryption_enabled, connection_complete_view.GetEncryptionEnabled());
541 
542   // Send an ACL packet from the remote
543   PacketBoundaryFlag packet_boundary_flag = PacketBoundaryFlag::FIRST_AUTOMATICALLY_FLUSHABLE;
544   BroadcastFlag broadcast_flag = BroadcastFlag::POINT_TO_POINT;
545   auto acl_payload = std::make_unique<RawBuilder>();
546   acl_payload->AddOctets(bd_addr.address);
547   acl_payload->AddOctets2(handle);
548   hal->callbacks->aclDataReceived(GetPacketBytes(AclBuilder::Create(
549           handle, packet_boundary_flag, broadcast_flag, std::move(acl_payload))));
550 
551   // Verify the ACL packet
552   auto acl_view_result = upper->GetReceivedAcl();
553   ASSERT_TRUE(acl_view_result.has_value());
554   auto acl_view = *acl_view_result;
555   ASSERT_TRUE(acl_view.IsValid());
556   ASSERT_EQ(bd_addr.length() + sizeof(handle), acl_view.GetPayload().size());
557   auto itr = acl_view.GetPayload().begin();
558   ASSERT_EQ(bd_addr, itr.extract<Address>());
559   ASSERT_EQ(handle, itr.extract<uint16_t>());
560 
561   // Send an ACL packet from DependsOnHci
562   PacketBoundaryFlag packet_boundary_flag2 = PacketBoundaryFlag::FIRST_AUTOMATICALLY_FLUSHABLE;
563   BroadcastFlag broadcast_flag2 = BroadcastFlag::POINT_TO_POINT;
564   auto acl_payload2 = std::make_unique<RawBuilder>();
565   acl_payload2->AddOctets2(handle);
566   acl_payload2->AddOctets(bd_addr.address);
567   upper->SendAclData(AclBuilder::Create(handle, packet_boundary_flag2, broadcast_flag2,
568                                         std::move(acl_payload2)));
569 
570   // Verify the ACL packet
571   auto sent_acl = hal->GetSentAcl();
572   ASSERT_TRUE(sent_acl.has_value());
573   AclView sent_acl_view = AclView::Create(*sent_acl);
574   ASSERT_TRUE(sent_acl_view.IsValid());
575   ASSERT_EQ(bd_addr.length() + sizeof(handle), sent_acl_view.GetPayload().size());
576   auto sent_itr = sent_acl_view.GetPayload().begin();
577   ASSERT_EQ(handle, sent_itr.extract<uint16_t>());
578   ASSERT_EQ(bd_addr, sent_itr.extract<Address>());
579 }
580 
TEST_F(HciTest,receiveMultipleAclPackets)581 TEST_F(HciTest, receiveMultipleAclPackets) {
582   Address bd_addr;
583   ASSERT_TRUE(Address::FromString("A1:A2:A3:A4:A5:A6", bd_addr));
584   uint16_t handle = 0x0001;
585   const uint16_t num_packets = 100;
586   PacketBoundaryFlag packet_boundary_flag = PacketBoundaryFlag::FIRST_AUTOMATICALLY_FLUSHABLE;
587   BroadcastFlag broadcast_flag = BroadcastFlag::POINT_TO_POINT;
588   for (uint16_t i = 0; i < num_packets; i++) {
589     auto acl_payload = std::make_unique<RawBuilder>();
590     acl_payload->AddOctets(bd_addr.address);
591     acl_payload->AddOctets2(handle);
592     acl_payload->AddOctets2(i);
593     hal->callbacks->aclDataReceived(GetPacketBytes(AclBuilder::Create(
594             handle, packet_boundary_flag, broadcast_flag, std::move(acl_payload))));
595   }
596 
597   for (uint16_t i = 0; i < num_packets; i++) {
598     auto acl_opt = upper->GetReceivedAcl();
599     ASSERT_TRUE(acl_opt.has_value());
600     auto acl_view = *acl_opt;
601     ASSERT_TRUE(acl_view.IsValid());
602     ASSERT_EQ(bd_addr.length() + sizeof(handle) + sizeof(i), acl_view.GetPayload().size());
603     auto itr = acl_view.GetPayload().begin();
604     ASSERT_EQ(bd_addr, itr.extract<Address>());
605     ASSERT_EQ(handle, itr.extract<uint16_t>());
606     ASSERT_EQ(i, itr.extract<uint16_t>());
607   }
608 }
609 
TEST_F(HciTest,receiveMultipleIsoPackets)610 TEST_F(HciTest, receiveMultipleIsoPackets) {
611   uint16_t handle = 0x0001;
612   const uint16_t num_packets = 100;
613   IsoPacketBoundaryFlag packet_boundary_flag = IsoPacketBoundaryFlag::COMPLETE_SDU;
614   TimeStampFlag timestamp_flag = TimeStampFlag::NOT_PRESENT;
615   for (uint16_t i = 0; i < num_packets; i++) {
616     auto iso_payload = std::make_unique<RawBuilder>();
617     iso_payload->AddOctets2(handle);
618     iso_payload->AddOctets2(i);
619     hal->callbacks->isoDataReceived(GetPacketBytes(IsoBuilder::Create(
620             handle, packet_boundary_flag, timestamp_flag, std::move(iso_payload))));
621   }
622   for (uint16_t i = 0; i < num_packets; i++) {
623     auto iso_opt = upper->GetReceivedIso();
624     ASSERT_TRUE(iso_opt.has_value());
625     auto iso_view = *iso_opt;
626     ASSERT_TRUE(iso_view.IsValid());
627     ASSERT_EQ(sizeof(handle) + sizeof(i), iso_view.GetPayload().size());
628     auto itr = iso_view.GetPayload().begin();
629     ASSERT_EQ(handle, itr.extract<uint16_t>());
630     ASSERT_EQ(i, itr.extract<uint16_t>());
631   }
632 }
633 
634 }  // namespace
635 }  // namespace hci
636 }  // namespace bluetooth
637