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