• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 #include <list>
21 #include <memory>
22 
23 #include "hal/hci_hal.h"
24 #include "hci/hci_packets.h"
25 #include "module.h"
26 #include "os/log.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 
51 constexpr std::chrono::milliseconds kTimeout = HciLayer::kHciTimeoutMs / 2;
52 constexpr std::chrono::milliseconds kAclTimeout = std::chrono::milliseconds(1000);
53 
54 class TestHciHal : public hal::HciHal {
55  public:
TestHciHal()56   TestHciHal() : hal::HciHal() {}
57 
~TestHciHal()58   ~TestHciHal() {
59     ASSERT_LOG(callbacks == nullptr, "unregisterIncomingPacketCallback() must be called");
60   }
61 
registerIncomingPacketCallback(hal::HciHalCallbacks * callback)62   void registerIncomingPacketCallback(hal::HciHalCallbacks* callback) override {
63     callbacks = callback;
64   }
65 
unregisterIncomingPacketCallback()66   void unregisterIncomingPacketCallback() override {
67     callbacks = nullptr;
68   }
69 
sendHciCommand(hal::HciPacket command)70   void sendHciCommand(hal::HciPacket command) override {
71     outgoing_commands_.push_back(std::move(command));
72     if (sent_command_promise_ != nullptr) {
73       auto promise = std::move(sent_command_promise_);
74       sent_command_promise_.reset();
75       promise->set_value();
76     }
77   }
78 
sendAclData(hal::HciPacket data)79   void sendAclData(hal::HciPacket data) override {
80     outgoing_acl_.push_front(std::move(data));
81     if (sent_acl_promise_ != nullptr) {
82       auto promise = std::move(sent_acl_promise_);
83       sent_acl_promise_.reset();
84       promise->set_value();
85     }
86   }
87 
sendScoData(hal::HciPacket data)88   void sendScoData(hal::HciPacket data) override {
89     outgoing_sco_.push_front(std::move(data));
90   }
91 
92   hal::HciHalCallbacks* callbacks = nullptr;
93 
GetPacketView(hal::HciPacket data)94   PacketView<kLittleEndian> GetPacketView(hal::HciPacket data) {
95     auto shared = std::make_shared<std::vector<uint8_t>>(data);
96     return PacketView<kLittleEndian>(shared);
97   }
98 
GetNumSentCommands()99   size_t GetNumSentCommands() {
100     return outgoing_commands_.size();
101   }
102 
GetSentCommandFuture()103   std::future<void> GetSentCommandFuture() {
104     ASSERT_LOG(sent_command_promise_ == nullptr, "Promises promises ... Only one at a time");
105     sent_command_promise_ = std::make_unique<std::promise<void>>();
106     return sent_command_promise_->get_future();
107   }
108 
GetSentCommand()109   CommandPacketView GetSentCommand() {
110     auto packetview = GetPacketView(std::move(outgoing_commands_.front()));
111     outgoing_commands_.pop_front();
112     return CommandPacketView::Create(packetview);
113   }
114 
GetSentAclFuture()115   std::future<void> GetSentAclFuture() {
116     ASSERT_LOG(sent_acl_promise_ == nullptr, "Promises promises ... Only one at a time");
117     sent_acl_promise_ = std::make_unique<std::promise<void>>();
118     return sent_acl_promise_->get_future();
119   }
120 
GetSentAcl()121   PacketView<kLittleEndian> GetSentAcl() {
122     auto packetview = GetPacketView(std::move(outgoing_acl_.front()));
123     outgoing_acl_.pop_front();
124     return packetview;
125   }
126 
Start()127   void Start() {}
128 
Stop()129   void Stop() {}
130 
ListDependencies(ModuleList *)131   void ListDependencies(ModuleList*) {}
132 
133   static const ModuleFactory Factory;
134 
135  private:
136   std::list<hal::HciPacket> outgoing_commands_;
137   std::list<hal::HciPacket> outgoing_acl_;
138   std::list<hal::HciPacket> outgoing_sco_;
139   std::unique_ptr<std::promise<void>> sent_command_promise_;
140   std::unique_ptr<std::promise<void>> sent_acl_promise_;
141 };
142 
__anon76f367630202() 143 const ModuleFactory TestHciHal::Factory = ModuleFactory([]() { return new TestHciHal(); });
144 
145 class DependsOnHci : public Module {
146  public:
DependsOnHci()147   DependsOnHci() : Module() {}
148 
SendHciCommandExpectingStatus(std::unique_ptr<CommandPacketBuilder> command)149   void SendHciCommandExpectingStatus(std::unique_ptr<CommandPacketBuilder> command) {
150     hci_->EnqueueCommand(std::move(command),
151                          common::Bind(&DependsOnHci::handle_event<CommandStatusView>, common::Unretained(this)),
152                          GetHandler());
153   }
154 
SendHciCommandExpectingComplete(std::unique_ptr<CommandPacketBuilder> command)155   void SendHciCommandExpectingComplete(std::unique_ptr<CommandPacketBuilder> command) {
156     hci_->EnqueueCommand(std::move(command),
157                          common::Bind(&DependsOnHci::handle_event<CommandCompleteView>, common::Unretained(this)),
158                          GetHandler());
159   }
160 
SendSecurityCommandExpectingComplete(std::unique_ptr<SecurityCommandBuilder> command)161   void SendSecurityCommandExpectingComplete(std::unique_ptr<SecurityCommandBuilder> command) {
162     if (security_interface_ == nullptr) {
163       security_interface_ = hci_->GetSecurityInterface(
164           common::Bind(&DependsOnHci::handle_event<EventPacketView>, common::Unretained(this)), GetHandler());
165     }
166     hci_->EnqueueCommand(std::move(command),
167                          common::Bind(&DependsOnHci::handle_event<CommandCompleteView>, common::Unretained(this)),
168                          GetHandler());
169   }
170 
SendLeSecurityCommandExpectingComplete(std::unique_ptr<LeSecurityCommandBuilder> command)171   void SendLeSecurityCommandExpectingComplete(std::unique_ptr<LeSecurityCommandBuilder> command) {
172     if (le_security_interface_ == nullptr) {
173       le_security_interface_ = hci_->GetLeSecurityInterface(
174           common::Bind(&DependsOnHci::handle_event<LeMetaEventView>, common::Unretained(this)), GetHandler());
175     }
176     hci_->EnqueueCommand(std::move(command),
177                          common::Bind(&DependsOnHci::handle_event<CommandCompleteView>, common::Unretained(this)),
178                          GetHandler());
179   }
180 
SendAclData(std::unique_ptr<AclPacketBuilder> acl)181   void SendAclData(std::unique_ptr<AclPacketBuilder> acl) {
182     outgoing_acl_.push(std::move(acl));
183     auto queue_end = hci_->GetAclQueueEnd();
184     queue_end->RegisterEnqueue(GetHandler(), common::Bind(&DependsOnHci::handle_enqueue, common::Unretained(this)));
185   }
186 
GetReceivedEventFuture()187   std::future<void> GetReceivedEventFuture() {
188     ASSERT_LOG(event_promise_ == nullptr, "Promises promises ... Only one at a time");
189     event_promise_ = std::make_unique<std::promise<void>>();
190     return event_promise_->get_future();
191   }
192 
GetReceivedEvent()193   EventPacketView GetReceivedEvent() {
194     EventPacketView packetview = incoming_events_.front();
195     incoming_events_.pop_front();
196     return packetview;
197   }
198 
GetReceivedAclFuture()199   std::future<void> GetReceivedAclFuture() {
200     ASSERT_LOG(acl_promise_ == nullptr, "Promises promises ... Only one at a time");
201     acl_promise_ = std::make_unique<std::promise<void>>();
202     return acl_promise_->get_future();
203   }
204 
GetNumReceivedAclPackets()205   size_t GetNumReceivedAclPackets() {
206     return incoming_acl_packets_.size();
207   }
208 
GetReceivedAcl()209   AclPacketView GetReceivedAcl() {
210     AclPacketView packetview = incoming_acl_packets_.front();
211     incoming_acl_packets_.pop_front();
212     return packetview;
213   }
214 
Start()215   void Start() {
216     hci_ = GetDependency<HciLayer>();
217     hci_->RegisterEventHandler(EventCode::CONNECTION_COMPLETE,
218                                common::Bind(&DependsOnHci::handle_event<EventPacketView>, common::Unretained(this)),
219                                GetHandler());
220     hci_->RegisterLeEventHandler(SubeventCode::CONNECTION_COMPLETE,
221                                  common::Bind(&DependsOnHci::handle_event<LeMetaEventView>, common::Unretained(this)),
222                                  GetHandler());
223     hci_->GetAclQueueEnd()->RegisterDequeue(GetHandler(),
224                                             common::Bind(&DependsOnHci::handle_acl, common::Unretained(this)));
225   }
226 
Stop()227   void Stop() {
228     hci_->GetAclQueueEnd()->UnregisterDequeue();
229   }
230 
ListDependencies(ModuleList * list)231   void ListDependencies(ModuleList* list) {
232     list->add<HciLayer>();
233   }
234 
235   static const ModuleFactory Factory;
236 
237  private:
238   HciLayer* hci_ = nullptr;
239   const SecurityInterface* security_interface_;
240   const LeSecurityInterface* le_security_interface_;
241   std::list<EventPacketView> incoming_events_;
242   std::list<AclPacketView> incoming_acl_packets_;
243   std::unique_ptr<std::promise<void>> event_promise_;
244   std::unique_ptr<std::promise<void>> acl_promise_;
245 
handle_acl()246   void handle_acl() {
247     auto acl_ptr = hci_->GetAclQueueEnd()->TryDequeue();
248     incoming_acl_packets_.push_back(*acl_ptr);
249     if (acl_promise_ != nullptr) {
250       auto promise = std::move(acl_promise_);
251       acl_promise_.reset();
252       promise->set_value();
253     }
254   }
255 
256   template <typename T>
handle_event(T event)257   void handle_event(T event) {
258     incoming_events_.push_back(event);
259     if (event_promise_ != nullptr) {
260       auto promise = std::move(event_promise_);
261       event_promise_.reset();
262       promise->set_value();
263     }
264   }
265 
266   std::queue<std::unique_ptr<AclPacketBuilder>> outgoing_acl_;
267 
handle_enqueue()268   std::unique_ptr<AclPacketBuilder> handle_enqueue() {
269     hci_->GetAclQueueEnd()->UnregisterEnqueue();
270     auto acl = std::move(outgoing_acl_.front());
271     outgoing_acl_.pop();
272     return acl;
273   }
274 };
275 
__anon76f367630302() 276 const ModuleFactory DependsOnHci::Factory = ModuleFactory([]() { return new DependsOnHci(); });
277 
278 class HciTest : public ::testing::Test {
279  public:
SetUp()280   void SetUp() override {
281     counting_bytes.reserve(count_size);
282     counting_down_bytes.reserve(count_size);
283     for (size_t i = 0; i < count_size; i++) {
284       counting_bytes.push_back(i);
285       counting_down_bytes.push_back(~i);
286     }
287     hal = new TestHciHal();
288 
289     auto command_future = hal->GetSentCommandFuture();
290 
291     fake_registry_.InjectTestModule(&hal::HciHal::Factory, hal);
292     fake_registry_.Start<DependsOnHci>(&fake_registry_.GetTestThread());
293     hci = static_cast<HciLayer*>(fake_registry_.GetModuleUnderTest(&HciLayer::Factory));
294     upper = static_cast<DependsOnHci*>(fake_registry_.GetModuleUnderTest(&DependsOnHci::Factory));
295     ASSERT(fake_registry_.IsStarted<HciLayer>());
296 
297     auto reset_sent_status = command_future.wait_for(kTimeout);
298     ASSERT_EQ(reset_sent_status, std::future_status::ready);
299 
300     // Verify that reset was received
301     ASSERT_EQ(1, hal->GetNumSentCommands());
302 
303     auto sent_command = hal->GetSentCommand();
304     auto reset_view = ResetView::Create(CommandPacketView::Create(sent_command));
305     ASSERT_TRUE(reset_view.IsValid());
306 
307     // Verify that only one was sent
308     ASSERT_EQ(0, hal->GetNumSentCommands());
309 
310     // Send the response event
311     uint8_t num_packets = 1;
312     ErrorCode error_code = ErrorCode::SUCCESS;
313     hal->callbacks->hciEventReceived(GetPacketBytes(ResetCompleteBuilder::Create(num_packets, error_code)));
314   }
315 
TearDown()316   void TearDown() override {
317     fake_registry_.StopAll();
318   }
319 
GetPacketBytes(std::unique_ptr<packet::BasePacketBuilder> packet)320   std::vector<uint8_t> GetPacketBytes(std::unique_ptr<packet::BasePacketBuilder> packet) {
321     std::vector<uint8_t> bytes;
322     BitInserter i(bytes);
323     bytes.reserve(packet->size());
324     packet->Serialize(i);
325     return bytes;
326   }
327 
328   DependsOnHci* upper = nullptr;
329   TestHciHal* hal = nullptr;
330   HciLayer* hci = nullptr;
331   TestModuleRegistry fake_registry_;
332 };
333 
TEST_F(HciTest,initAndClose)334 TEST_F(HciTest, initAndClose) {}
335 
TEST_F(HciTest,leMetaEvent)336 TEST_F(HciTest, leMetaEvent) {
337   auto event_future = upper->GetReceivedEventFuture();
338 
339   // Send an LE event
340   ErrorCode status = ErrorCode::SUCCESS;
341   uint16_t handle = 0x123;
342   Role role = Role::MASTER;
343   AddressType peer_address_type = AddressType::PUBLIC_DEVICE_ADDRESS;
344   Address peer_address = Address::kAny;
345   uint16_t conn_interval = 0x0ABC;
346   uint16_t conn_latency = 0x0123;
347   uint16_t supervision_timeout = 0x0B05;
348   MasterClockAccuracy master_clock_accuracy = MasterClockAccuracy::PPM_50;
349   hal->callbacks->hciEventReceived(GetPacketBytes(
350       LeConnectionCompleteBuilder::Create(status, handle, role, peer_address_type, peer_address, conn_interval,
351                                           conn_latency, supervision_timeout, master_clock_accuracy)));
352 
353   // Wait for the event
354   auto event_status = event_future.wait_for(kTimeout);
355   ASSERT_EQ(event_status, std::future_status::ready);
356 
357   auto event = upper->GetReceivedEvent();
358   ASSERT(LeConnectionCompleteView::Create(LeMetaEventView::Create(EventPacketView::Create(event))).IsValid());
359 }
360 
TEST_F(HciTest,noOpCredits)361 TEST_F(HciTest, noOpCredits) {
362   ASSERT_EQ(0, hal->GetNumSentCommands());
363 
364   // Send 0 credits
365   uint8_t num_packets = 0;
366   hal->callbacks->hciEventReceived(GetPacketBytes(NoCommandCompleteBuilder::Create(num_packets)));
367 
368   auto command_future = hal->GetSentCommandFuture();
369   upper->SendHciCommandExpectingComplete(ReadLocalVersionInformationBuilder::Create());
370 
371   // Verify that nothing was sent
372   ASSERT_EQ(0, hal->GetNumSentCommands());
373 
374   num_packets = 1;
375   hal->callbacks->hciEventReceived(GetPacketBytes(NoCommandCompleteBuilder::Create(num_packets)));
376 
377   auto command_sent_status = command_future.wait_for(kTimeout);
378   ASSERT_EQ(command_sent_status, std::future_status::ready);
379 
380   // Verify that one was sent
381   ASSERT_EQ(1, hal->GetNumSentCommands());
382 
383   auto event_future = upper->GetReceivedEventFuture();
384 
385   // Send the response event
386   ErrorCode error_code = ErrorCode::SUCCESS;
387   LocalVersionInformation local_version_information;
388   local_version_information.hci_version_ = HciVersion::V_5_0;
389   local_version_information.hci_revision_ = 0x1234;
390   local_version_information.lmp_version_ = LmpVersion::V_4_2;
391   local_version_information.manufacturer_name_ = 0xBAD;
392   local_version_information.lmp_subversion_ = 0x5678;
393   hal->callbacks->hciEventReceived(GetPacketBytes(
394       ReadLocalVersionInformationCompleteBuilder::Create(num_packets, error_code, local_version_information)));
395 
396   // Wait for the event
397   auto event_status = event_future.wait_for(kTimeout);
398   ASSERT_EQ(event_status, std::future_status::ready);
399 
400   auto event = upper->GetReceivedEvent();
401   ASSERT(ReadLocalVersionInformationCompleteView::Create(CommandCompleteView::Create(EventPacketView::Create(event)))
402              .IsValid());
403 }
404 
TEST_F(HciTest,creditsTest)405 TEST_F(HciTest, creditsTest) {
406   ASSERT_EQ(0, hal->GetNumSentCommands());
407 
408   auto command_future = hal->GetSentCommandFuture();
409 
410   // Send all three commands
411   upper->SendHciCommandExpectingComplete(ReadLocalVersionInformationBuilder::Create());
412   upper->SendHciCommandExpectingComplete(ReadLocalSupportedCommandsBuilder::Create());
413   upper->SendHciCommandExpectingComplete(ReadLocalSupportedFeaturesBuilder::Create());
414 
415   auto command_sent_status = command_future.wait_for(kTimeout);
416   ASSERT_EQ(command_sent_status, std::future_status::ready);
417 
418   // Verify that the first one is sent
419   ASSERT_EQ(1, hal->GetNumSentCommands());
420 
421   auto sent_command = hal->GetSentCommand();
422   auto version_view = ReadLocalVersionInformationView::Create(CommandPacketView::Create(sent_command));
423   ASSERT_TRUE(version_view.IsValid());
424 
425   // Verify that only one was sent
426   ASSERT_EQ(0, hal->GetNumSentCommands());
427 
428   // Get a new future
429   auto event_future = upper->GetReceivedEventFuture();
430 
431   // Send the response event
432   uint8_t num_packets = 1;
433   ErrorCode error_code = ErrorCode::SUCCESS;
434   LocalVersionInformation local_version_information;
435   local_version_information.hci_version_ = HciVersion::V_5_0;
436   local_version_information.hci_revision_ = 0x1234;
437   local_version_information.lmp_version_ = LmpVersion::V_4_2;
438   local_version_information.manufacturer_name_ = 0xBAD;
439   local_version_information.lmp_subversion_ = 0x5678;
440   hal->callbacks->hciEventReceived(GetPacketBytes(
441       ReadLocalVersionInformationCompleteBuilder::Create(num_packets, error_code, local_version_information)));
442 
443   // Wait for the event
444   auto event_status = event_future.wait_for(kTimeout);
445   ASSERT_EQ(event_status, std::future_status::ready);
446 
447   auto event = upper->GetReceivedEvent();
448   ASSERT(ReadLocalVersionInformationCompleteView::Create(CommandCompleteView::Create(EventPacketView::Create(event)))
449              .IsValid());
450 
451   // Verify that the second one is sent
452   command_sent_status = command_future.wait_for(kTimeout);
453   ASSERT_EQ(command_sent_status, std::future_status::ready);
454   ASSERT_EQ(1, hal->GetNumSentCommands());
455 
456   sent_command = hal->GetSentCommand();
457   auto supported_commands_view = ReadLocalSupportedCommandsView::Create(CommandPacketView::Create(sent_command));
458   ASSERT_TRUE(supported_commands_view.IsValid());
459 
460   // Verify that only one was sent
461   ASSERT_EQ(0, hal->GetNumSentCommands());
462   event_future = upper->GetReceivedEventFuture();
463   command_future = hal->GetSentCommandFuture();
464 
465   // Send the response event
466   std::array<uint8_t, 64> supported_commands;
467   for (uint8_t i = 0; i < 64; i++) {
468     supported_commands[i] = i;
469   }
470   hal->callbacks->hciEventReceived(
471       GetPacketBytes(ReadLocalSupportedCommandsCompleteBuilder::Create(num_packets, error_code, supported_commands)));
472   // Wait for the event
473   event_status = event_future.wait_for(kTimeout);
474   ASSERT_EQ(event_status, std::future_status::ready);
475 
476   event = upper->GetReceivedEvent();
477   ASSERT(ReadLocalSupportedCommandsCompleteView::Create(CommandCompleteView::Create(EventPacketView::Create(event)))
478              .IsValid());
479   // Verify that the third one is sent
480   command_sent_status = command_future.wait_for(kTimeout);
481   ASSERT_EQ(command_sent_status, std::future_status::ready);
482   ASSERT_EQ(1, hal->GetNumSentCommands());
483 
484   sent_command = hal->GetSentCommand();
485   auto supported_features_view = ReadLocalSupportedFeaturesView::Create(CommandPacketView::Create(sent_command));
486   ASSERT_TRUE(supported_features_view.IsValid());
487 
488   // Verify that only one was sent
489   ASSERT_EQ(0, hal->GetNumSentCommands());
490   event_future = upper->GetReceivedEventFuture();
491 
492   // Send the response event
493   uint64_t lmp_features = 0x012345678abcdef;
494   hal->callbacks->hciEventReceived(
495       GetPacketBytes(ReadLocalSupportedFeaturesCompleteBuilder::Create(num_packets, error_code, lmp_features)));
496 
497   // Wait for the event
498   event_status = event_future.wait_for(kTimeout);
499   ASSERT_EQ(event_status, std::future_status::ready);
500   event = upper->GetReceivedEvent();
501   ASSERT(ReadLocalSupportedFeaturesCompleteView::Create(CommandCompleteView::Create(EventPacketView::Create(event)))
502              .IsValid());
503 }
504 
TEST_F(HciTest,leSecurityInterfaceTest)505 TEST_F(HciTest, leSecurityInterfaceTest) {
506   // Send LeRand to the controller
507   auto command_future = hal->GetSentCommandFuture();
508   upper->SendLeSecurityCommandExpectingComplete(LeRandBuilder::Create());
509 
510   auto command_sent_status = command_future.wait_for(kTimeout);
511   ASSERT_EQ(command_sent_status, std::future_status::ready);
512 
513   // Check the command
514   auto sent_command = hal->GetSentCommand();
515   ASSERT_LT(0, sent_command.size());
516   LeRandView view = LeRandView::Create(LeSecurityCommandView::Create(CommandPacketView::Create(sent_command)));
517   ASSERT_TRUE(view.IsValid());
518 
519   // Send a Command Complete to the host
520   auto event_future = upper->GetReceivedEventFuture();
521   uint8_t num_packets = 1;
522   ErrorCode status = ErrorCode::SUCCESS;
523   uint64_t rand = 0x0123456789abcdef;
524   hal->callbacks->hciEventReceived(GetPacketBytes(LeRandCompleteBuilder::Create(num_packets, status, rand)));
525 
526   // Verify the event
527   auto event_status = event_future.wait_for(kTimeout);
528   ASSERT_EQ(event_status, std::future_status::ready);
529   auto event = upper->GetReceivedEvent();
530   ASSERT_TRUE(event.IsValid());
531   ASSERT_EQ(EventCode::COMMAND_COMPLETE, event.GetEventCode());
532   ASSERT_TRUE(LeRandCompleteView::Create(CommandCompleteView::Create(event)).IsValid());
533 }
534 
TEST_F(HciTest,securityInterfacesTest)535 TEST_F(HciTest, securityInterfacesTest) {
536   // Send WriteSimplePairingMode to the controller
537   auto command_future = hal->GetSentCommandFuture();
538   Enable enable = Enable::ENABLED;
539   upper->SendSecurityCommandExpectingComplete(WriteSimplePairingModeBuilder::Create(enable));
540 
541   auto command_sent_status = command_future.wait_for(kTimeout);
542   ASSERT_EQ(command_sent_status, std::future_status::ready);
543 
544   // Check the command
545   auto sent_command = hal->GetSentCommand();
546   ASSERT_LT(0, sent_command.size());
547   auto view = WriteSimplePairingModeView::Create(SecurityCommandView::Create(CommandPacketView::Create(sent_command)));
548   ASSERT_TRUE(view.IsValid());
549 
550   // Send a Command Complete to the host
551   auto event_future = upper->GetReceivedEventFuture();
552   uint8_t num_packets = 1;
553   ErrorCode status = ErrorCode::SUCCESS;
554   hal->callbacks->hciEventReceived(GetPacketBytes(WriteSimplePairingModeCompleteBuilder::Create(num_packets, status)));
555 
556   // Verify the event
557   auto event_status = event_future.wait_for(kTimeout);
558   ASSERT_EQ(event_status, std::future_status::ready);
559   auto event = upper->GetReceivedEvent();
560   ASSERT_TRUE(event.IsValid());
561   ASSERT_EQ(EventCode::COMMAND_COMPLETE, event.GetEventCode());
562   ASSERT_TRUE(WriteSimplePairingModeCompleteView::Create(CommandCompleteView::Create(event)).IsValid());
563 }
564 
TEST_F(HciTest,createConnectionTest)565 TEST_F(HciTest, createConnectionTest) {
566   // Send CreateConnection to the controller
567   auto command_future = hal->GetSentCommandFuture();
568   Address bd_addr;
569   ASSERT_TRUE(Address::FromString("A1:A2:A3:A4:A5:A6", bd_addr));
570   uint16_t packet_type = 0x1234;
571   PageScanRepetitionMode page_scan_repetition_mode = PageScanRepetitionMode::R0;
572   uint16_t clock_offset = 0x3456;
573   ClockOffsetValid clock_offset_valid = ClockOffsetValid::VALID;
574   CreateConnectionRoleSwitch allow_role_switch = CreateConnectionRoleSwitch::ALLOW_ROLE_SWITCH;
575   upper->SendHciCommandExpectingStatus(CreateConnectionBuilder::Create(
576       bd_addr, packet_type, page_scan_repetition_mode, clock_offset, clock_offset_valid, allow_role_switch));
577 
578   auto command_sent_status = command_future.wait_for(kTimeout);
579   ASSERT_EQ(command_sent_status, std::future_status::ready);
580 
581   // Check the command
582   auto sent_command = hal->GetSentCommand();
583   ASSERT_LT(0, sent_command.size());
584   CreateConnectionView view =
585       CreateConnectionView::Create(ConnectionManagementCommandView::Create(CommandPacketView::Create(sent_command)));
586   ASSERT_TRUE(view.IsValid());
587   ASSERT_EQ(bd_addr, view.GetBdAddr());
588   ASSERT_EQ(packet_type, view.GetPacketType());
589   ASSERT_EQ(page_scan_repetition_mode, view.GetPageScanRepetitionMode());
590   ASSERT_EQ(clock_offset, view.GetClockOffset());
591   ASSERT_EQ(clock_offset_valid, view.GetClockOffsetValid());
592   ASSERT_EQ(allow_role_switch, view.GetAllowRoleSwitch());
593 
594   // Send a Command Status to the host
595   auto event_future = upper->GetReceivedEventFuture();
596   ErrorCode status = ErrorCode::SUCCESS;
597   uint16_t handle = 0x123;
598   LinkType link_type = LinkType::ACL;
599   Enable encryption_enabled = Enable::DISABLED;
600   hal->callbacks->hciEventReceived(GetPacketBytes(CreateConnectionStatusBuilder::Create(ErrorCode::SUCCESS, 1)));
601 
602   // Verify the event
603   auto event_status = event_future.wait_for(kTimeout);
604   ASSERT_EQ(event_status, std::future_status::ready);
605   auto event = upper->GetReceivedEvent();
606   ASSERT_TRUE(event.IsValid());
607   ASSERT_EQ(EventCode::COMMAND_STATUS, event.GetEventCode());
608 
609   // Send a ConnectionComplete to the host
610   event_future = upper->GetReceivedEventFuture();
611   hal->callbacks->hciEventReceived(
612       GetPacketBytes(ConnectionCompleteBuilder::Create(status, handle, bd_addr, link_type, encryption_enabled)));
613 
614   // Verify the event
615   event_status = event_future.wait_for(kTimeout);
616   ASSERT_EQ(event_status, std::future_status::ready);
617   event = upper->GetReceivedEvent();
618   ASSERT_TRUE(event.IsValid());
619   ASSERT_EQ(EventCode::CONNECTION_COMPLETE, event.GetEventCode());
620   ConnectionCompleteView connection_complete_view = ConnectionCompleteView::Create(event);
621   ASSERT_TRUE(connection_complete_view.IsValid());
622   ASSERT_EQ(status, connection_complete_view.GetStatus());
623   ASSERT_EQ(handle, connection_complete_view.GetConnectionHandle());
624   ASSERT_EQ(link_type, connection_complete_view.GetLinkType());
625   ASSERT_EQ(encryption_enabled, connection_complete_view.GetEncryptionEnabled());
626 
627   // Send an ACL packet from the remote
628   PacketBoundaryFlag packet_boundary_flag = PacketBoundaryFlag::FIRST_AUTOMATICALLY_FLUSHABLE;
629   BroadcastFlag broadcast_flag = BroadcastFlag::POINT_TO_POINT;
630   auto acl_payload = std::make_unique<RawBuilder>();
631   acl_payload->AddAddress(bd_addr);
632   acl_payload->AddOctets2(handle);
633   auto incoming_acl_future = upper->GetReceivedAclFuture();
634   hal->callbacks->aclDataReceived(
635       GetPacketBytes(AclPacketBuilder::Create(handle, packet_boundary_flag, broadcast_flag, std::move(acl_payload))));
636 
637   // Verify the ACL packet
638   auto incoming_acl_status = incoming_acl_future.wait_for(kAclTimeout);
639   ASSERT_EQ(incoming_acl_status, std::future_status::ready);
640   auto acl_view = upper->GetReceivedAcl();
641   ASSERT_TRUE(acl_view.IsValid());
642   ASSERT_EQ(sizeof(bd_addr) + sizeof(handle), acl_view.GetPayload().size());
643   auto itr = acl_view.GetPayload().begin();
644   ASSERT_EQ(bd_addr, itr.extract<Address>());
645   ASSERT_EQ(handle, itr.extract<uint16_t>());
646 
647   // Send an ACL packet from DependsOnHci
648   PacketBoundaryFlag packet_boundary_flag2 = PacketBoundaryFlag::FIRST_AUTOMATICALLY_FLUSHABLE;
649   BroadcastFlag broadcast_flag2 = BroadcastFlag::POINT_TO_POINT;
650   auto acl_payload2 = std::make_unique<RawBuilder>();
651   acl_payload2->AddOctets2(handle);
652   acl_payload2->AddAddress(bd_addr);
653   auto sent_acl_future = hal->GetSentAclFuture();
654   upper->SendAclData(AclPacketBuilder::Create(handle, packet_boundary_flag2, broadcast_flag2, std::move(acl_payload2)));
655 
656   // Verify the ACL packet
657   auto sent_acl_status = sent_acl_future.wait_for(kAclTimeout);
658   ASSERT_EQ(sent_acl_status, std::future_status::ready);
659   auto sent_acl = hal->GetSentAcl();
660   ASSERT_LT(0, sent_acl.size());
661   AclPacketView sent_acl_view = AclPacketView::Create(sent_acl);
662   ASSERT_TRUE(sent_acl_view.IsValid());
663   ASSERT_EQ(sizeof(bd_addr) + sizeof(handle), sent_acl_view.GetPayload().size());
664   auto sent_itr = sent_acl_view.GetPayload().begin();
665   ASSERT_EQ(handle, sent_itr.extract<uint16_t>());
666   ASSERT_EQ(bd_addr, sent_itr.extract<Address>());
667 }
668 
TEST_F(HciTest,receiveMultipleAclPackets)669 TEST_F(HciTest, receiveMultipleAclPackets) {
670   Address bd_addr;
671   ASSERT_TRUE(Address::FromString("A1:A2:A3:A4:A5:A6", bd_addr));
672   uint16_t handle = 0x0001;
673   uint16_t num_packets = 100;
674   PacketBoundaryFlag packet_boundary_flag = PacketBoundaryFlag::FIRST_AUTOMATICALLY_FLUSHABLE;
675   BroadcastFlag broadcast_flag = BroadcastFlag::POINT_TO_POINT;
676   for (uint16_t i = 0; i < num_packets; i++) {
677     auto acl_payload = std::make_unique<RawBuilder>();
678     acl_payload->AddAddress(bd_addr);
679     acl_payload->AddOctets2(handle);
680     acl_payload->AddOctets2(i);
681     hal->callbacks->aclDataReceived(
682         GetPacketBytes(AclPacketBuilder::Create(handle, packet_boundary_flag, broadcast_flag, std::move(acl_payload))));
683   }
684   auto incoming_acl_future = upper->GetReceivedAclFuture();
685   uint16_t received_packets = 0;
686   while (received_packets < num_packets - 1) {
687     auto incoming_acl_status = incoming_acl_future.wait_for(kAclTimeout);
688     // Get the next future.
689     incoming_acl_future = upper->GetReceivedAclFuture();
690     ASSERT_EQ(incoming_acl_status, std::future_status::ready);
691     size_t num_packets = upper->GetNumReceivedAclPackets();
692     for (size_t i = 0; i < num_packets; i++) {
693       auto acl_view = upper->GetReceivedAcl();
694       ASSERT_TRUE(acl_view.IsValid());
695       ASSERT_EQ(sizeof(bd_addr) + sizeof(handle) + sizeof(received_packets), acl_view.GetPayload().size());
696       auto itr = acl_view.GetPayload().begin();
697       ASSERT_EQ(bd_addr, itr.extract<Address>());
698       ASSERT_EQ(handle, itr.extract<uint16_t>());
699       ASSERT_EQ(received_packets, itr.extract<uint16_t>());
700       received_packets += 1;
701     }
702   }
703 
704   // Check to see if this future was already fulfilled.
705   auto acl_race_status = incoming_acl_future.wait_for(std::chrono::milliseconds(1));
706   if (acl_race_status == std::future_status::ready) {
707     // Get the next future.
708     incoming_acl_future = upper->GetReceivedAclFuture();
709   }
710 
711   // One last packet to make sure they were all sent.  Already got the future.
712   auto acl_payload = std::make_unique<RawBuilder>();
713   acl_payload->AddAddress(bd_addr);
714   acl_payload->AddOctets2(handle);
715   acl_payload->AddOctets2(num_packets);
716   hal->callbacks->aclDataReceived(
717       GetPacketBytes(AclPacketBuilder::Create(handle, packet_boundary_flag, broadcast_flag, std::move(acl_payload))));
718   auto incoming_acl_status = incoming_acl_future.wait_for(kAclTimeout);
719   ASSERT_EQ(incoming_acl_status, std::future_status::ready);
720   auto acl_view = upper->GetReceivedAcl();
721   ASSERT_TRUE(acl_view.IsValid());
722   ASSERT_EQ(sizeof(bd_addr) + sizeof(handle) + sizeof(received_packets), acl_view.GetPayload().size());
723   auto itr = acl_view.GetPayload().begin();
724   ASSERT_EQ(bd_addr, itr.extract<Address>());
725   ASSERT_EQ(handle, itr.extract<uint16_t>());
726   ASSERT_EQ(received_packets, itr.extract<uint16_t>());
727 }
728 }  // namespace hci
729 }  // namespace bluetooth
730