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,
39     0x2e,
40     0x0a,
41     0x00,
42     0x06,
43     0x00,
44     0x01,
45     0x00,
46     0x0a,
47     0x02,
48     0x02,
49     0x00,
50     0x02,
51     0x00,
52 };
53 // 0x00, 0x01, 0x02, 0x03, ...
54 vector<uint8_t> counting_bytes;
55 // 0xFF, 0xFE, 0xFD, 0xFC, ...
56 vector<uint8_t> counting_down_bytes;
57 const size_t count_size = 0x8;
58 
59 }  // namespace
60 
61 namespace bluetooth {
62 namespace hci {
63 
64 constexpr std::chrono::milliseconds kTimeout = HciLayer::kHciTimeoutMs / 2;
65 constexpr std::chrono::milliseconds kAclTimeout = std::chrono::milliseconds(1000);
66 
67 class TestHciHal : public hal::HciHal {
68  public:
TestHciHal()69   TestHciHal() : hal::HciHal() {}
70 
~TestHciHal()71   ~TestHciHal() {
72     ASSERT_LOG(callbacks == nullptr, "unregisterIncomingPacketCallback() must be called");
73   }
74 
registerIncomingPacketCallback(hal::HciHalCallbacks * callback)75   void registerIncomingPacketCallback(hal::HciHalCallbacks* callback) override {
76     callbacks = callback;
77   }
78 
unregisterIncomingPacketCallback()79   void unregisterIncomingPacketCallback() override {
80     callbacks = nullptr;
81   }
82 
sendHciCommand(hal::HciPacket command)83   void sendHciCommand(hal::HciPacket command) override {
84     outgoing_commands_.push_back(std::move(command));
85     if (sent_command_promise_ != nullptr) {
86       auto promise = std::move(sent_command_promise_);
87       sent_command_promise_.reset();
88       promise->set_value();
89     }
90   }
91 
sendAclData(hal::HciPacket data)92   void sendAclData(hal::HciPacket data) override {
93     outgoing_acl_.push_back(std::move(data));
94     if (sent_acl_promise_ != nullptr) {
95       auto promise = std::move(sent_acl_promise_);
96       sent_acl_promise_.reset();
97       promise->set_value();
98     }
99   }
100 
sendScoData(hal::HciPacket data)101   void sendScoData(hal::HciPacket data) override {
102     outgoing_sco_.push_back(std::move(data));
103   }
104 
sendIsoData(hal::HciPacket data)105   void sendIsoData(hal::HciPacket data) override {
106     outgoing_iso_.push_back(std::move(data));
107     if (sent_iso_promise_ != nullptr) {
108       auto promise = std::move(sent_iso_promise_);
109       sent_iso_promise_.reset();
110       promise->set_value();
111     }
112   }
113 
114   hal::HciHalCallbacks* callbacks = nullptr;
115 
GetPacketView(hal::HciPacket data)116   PacketView<kLittleEndian> GetPacketView(hal::HciPacket data) {
117     auto shared = std::make_shared<std::vector<uint8_t>>(data);
118     return PacketView<kLittleEndian>(shared);
119   }
120 
GetNumSentCommands()121   size_t GetNumSentCommands() {
122     return outgoing_commands_.size();
123   }
124 
GetSentCommandFuture()125   std::future<void> GetSentCommandFuture() {
126     ASSERT_LOG(sent_command_promise_ == nullptr, "Promises promises ... Only one at a time");
127     sent_command_promise_ = std::make_unique<std::promise<void>>();
128     return sent_command_promise_->get_future();
129   }
130 
GetSentCommand()131   CommandView GetSentCommand() {
132     auto packetview = GetPacketView(std::move(outgoing_commands_.front()));
133     outgoing_commands_.pop_front();
134     return CommandView::Create(packetview);
135   }
136 
GetSentAclFuture()137   std::future<void> GetSentAclFuture() {
138     ASSERT_LOG(sent_acl_promise_ == nullptr, "Promises promises ... Only one at a time");
139     sent_acl_promise_ = std::make_unique<std::promise<void>>();
140     return sent_acl_promise_->get_future();
141   }
142 
GetSentAcl()143   PacketView<kLittleEndian> GetSentAcl() {
144     auto packetview = GetPacketView(std::move(outgoing_acl_.front()));
145     outgoing_acl_.pop_front();
146     return packetview;
147   }
148 
GetSentIsoFuture()149   std::future<void> GetSentIsoFuture() {
150     ASSERT_LOG(sent_iso_promise_ == nullptr, "Promises promises ... Only one at a time");
151     sent_iso_promise_ = std::make_unique<std::promise<void>>();
152     return sent_iso_promise_->get_future();
153   }
154 
GetSentIso()155   PacketView<kLittleEndian> GetSentIso() {
156     auto packetview = GetPacketView(std::move(outgoing_iso_.front()));
157     outgoing_iso_.pop_front();
158     return packetview;
159   }
160 
Start()161   void Start() {}
162 
Stop()163   void Stop() {}
164 
ListDependencies(ModuleList *)165   void ListDependencies(ModuleList*) {}
166 
ToString() const167   std::string ToString() const override {
168     return std::string("TestHciHal");
169   }
170 
171   static const ModuleFactory Factory;
172 
173  private:
174   std::list<hal::HciPacket> outgoing_commands_;
175   std::list<hal::HciPacket> outgoing_acl_;
176   std::list<hal::HciPacket> outgoing_sco_;
177   std::list<hal::HciPacket> outgoing_iso_;
178   std::unique_ptr<std::promise<void>> sent_command_promise_;
179   std::unique_ptr<std::promise<void>> sent_acl_promise_;
180   std::unique_ptr<std::promise<void>> sent_iso_promise_;
181 };
182 
__anon79f781040202() 183 const ModuleFactory TestHciHal::Factory = ModuleFactory([]() { return new TestHciHal(); });
184 
185 class DependsOnHci : public Module {
186  public:
DependsOnHci()187   DependsOnHci() : Module() {}
188 
SendHciCommandExpectingStatus(std::unique_ptr<CommandBuilder> command)189   void SendHciCommandExpectingStatus(std::unique_ptr<CommandBuilder> command) {
190     hci_->EnqueueCommand(
191         std::move(command), GetHandler()->BindOnceOn(this, &DependsOnHci::handle_event<CommandStatusView>));
192   }
193 
SendHciCommandExpectingComplete(std::unique_ptr<CommandBuilder> command)194   void SendHciCommandExpectingComplete(std::unique_ptr<CommandBuilder> command) {
195     hci_->EnqueueCommand(
196         std::move(command), GetHandler()->BindOnceOn(this, &DependsOnHci::handle_event<CommandCompleteView>));
197   }
198 
SendSecurityCommandExpectingComplete(std::unique_ptr<SecurityCommandBuilder> command)199   void SendSecurityCommandExpectingComplete(std::unique_ptr<SecurityCommandBuilder> command) {
200     if (security_interface_ == nullptr) {
201       security_interface_ =
202           hci_->GetSecurityInterface(GetHandler()->BindOn(this, &DependsOnHci::handle_event<EventView>));
203     }
204     hci_->EnqueueCommand(
205         std::move(command), GetHandler()->BindOnceOn(this, &DependsOnHci::handle_event<CommandCompleteView>));
206   }
207 
SendLeSecurityCommandExpectingComplete(std::unique_ptr<LeSecurityCommandBuilder> command)208   void SendLeSecurityCommandExpectingComplete(std::unique_ptr<LeSecurityCommandBuilder> command) {
209     if (le_security_interface_ == nullptr) {
210       le_security_interface_ =
211           hci_->GetLeSecurityInterface(GetHandler()->BindOn(this, &DependsOnHci::handle_event<LeMetaEventView>));
212     }
213     hci_->EnqueueCommand(
214         std::move(command), GetHandler()->BindOnceOn(this, &DependsOnHci::handle_event<CommandCompleteView>));
215   }
216 
SendAclData(std::unique_ptr<AclBuilder> acl)217   void SendAclData(std::unique_ptr<AclBuilder> acl) {
218     outgoing_acl_.push(std::move(acl));
219     auto queue_end = hci_->GetAclQueueEnd();
220     queue_end->RegisterEnqueue(GetHandler(), common::Bind(&DependsOnHci::handle_enqueue, common::Unretained(this)));
221   }
222 
SendIsoData(std::unique_ptr<IsoBuilder> iso)223   void SendIsoData(std::unique_ptr<IsoBuilder> iso) {
224     outgoing_iso_.push(std::move(iso));
225     auto queue_end = hci_->GetIsoQueueEnd();
226     queue_end->RegisterEnqueue(GetHandler(), common::Bind(&DependsOnHci::handle_enqueue_iso, common::Unretained(this)));
227   }
228 
GetReceivedEventFuture()229   std::future<void> GetReceivedEventFuture() {
230     ASSERT_LOG(event_promise_ == nullptr, "Promises promises ... Only one at a time");
231     event_promise_ = std::make_unique<std::promise<void>>();
232     return event_promise_->get_future();
233   }
234 
GetReceivedEvent()235   EventView GetReceivedEvent() {
236     std::lock_guard<std::mutex> lock(list_protector_);
237     EventView packetview = incoming_events_.front();
238     incoming_events_.pop_front();
239     return packetview;
240   }
241 
GetReceivedAclFuture()242   std::future<void> GetReceivedAclFuture() {
243     ASSERT_LOG(acl_promise_ == nullptr, "Promises promises ... Only one at a time");
244     acl_promise_ = std::make_unique<std::promise<void>>();
245     return acl_promise_->get_future();
246   }
247 
GetNumReceivedAclPackets()248   size_t GetNumReceivedAclPackets() {
249     return incoming_acl_packets_.size();
250   }
251 
GetReceivedAcl()252   AclView GetReceivedAcl() {
253     std::lock_guard<std::mutex> lock(list_protector_);
254     AclView packetview = incoming_acl_packets_.front();
255     incoming_acl_packets_.pop_front();
256     return packetview;
257   }
258 
GetReceivedIsoFuture()259   std::future<void> GetReceivedIsoFuture() {
260     ASSERT_LOG(iso_promise_ == nullptr, "Promises promises ... Only one at a time");
261     iso_promise_ = std::make_unique<std::promise<void>>();
262     return iso_promise_->get_future();
263   }
264 
GetNumReceivedIsoPackets()265   size_t GetNumReceivedIsoPackets() {
266     return incoming_iso_packets_.size();
267   }
268 
GetReceivedIso()269   IsoView GetReceivedIso() {
270     std::lock_guard<std::mutex> lock(list_protector_);
271     IsoView packetview = incoming_iso_packets_.front();
272     incoming_iso_packets_.pop_front();
273     return packetview;
274   }
275 
Start()276   void Start() {
277     hci_ = GetDependency<HciLayer>();
278     hci_->RegisterEventHandler(
279         EventCode::CONNECTION_COMPLETE, GetHandler()->BindOn(this, &DependsOnHci::handle_event<EventView>));
280     hci_->RegisterLeEventHandler(
281         SubeventCode::CONNECTION_COMPLETE, GetHandler()->BindOn(this, &DependsOnHci::handle_event<LeMetaEventView>));
282     hci_->GetAclQueueEnd()->RegisterDequeue(
283         GetHandler(), common::Bind(&DependsOnHci::handle_acl, common::Unretained(this)));
284     hci_->GetIsoQueueEnd()->RegisterDequeue(
285         GetHandler(), common::Bind(&DependsOnHci::handle_iso, common::Unretained(this)));
286   }
287 
Stop()288   void Stop() {
289     hci_->GetAclQueueEnd()->UnregisterDequeue();
290     hci_->GetIsoQueueEnd()->UnregisterDequeue();
291   }
292 
ListDependencies(ModuleList * list)293   void ListDependencies(ModuleList* list) {
294     list->add<HciLayer>();
295   }
296 
ToString() const297   std::string ToString() const override {
298     return std::string("DependsOnHci");
299   }
300 
301   static const ModuleFactory Factory;
302 
303  private:
304   HciLayer* hci_ = nullptr;
305   const SecurityInterface* security_interface_;
306   const LeSecurityInterface* le_security_interface_;
307   std::list<EventView> incoming_events_;
308   std::list<AclView> incoming_acl_packets_;
309   std::list<IsoView> incoming_iso_packets_;
310   std::unique_ptr<std::promise<void>> event_promise_;
311   std::unique_ptr<std::promise<void>> acl_promise_;
312   std::unique_ptr<std::promise<void>> iso_promise_;
313   /* This mutex is protecting lists above from being pushed/popped from different threads at same time */
314   std::mutex list_protector_;
315 
handle_acl()316   void handle_acl() {
317     std::lock_guard<std::mutex> lock(list_protector_);
318     auto acl_ptr = hci_->GetAclQueueEnd()->TryDequeue();
319     incoming_acl_packets_.push_back(*acl_ptr);
320     if (acl_promise_ != nullptr) {
321       auto promise = std::move(acl_promise_);
322       acl_promise_.reset();
323       promise->set_value();
324     }
325   }
326 
327   template <typename T>
handle_event(T event)328   void handle_event(T event) {
329     std::lock_guard<std::mutex> lock(list_protector_);
330     incoming_events_.push_back(event);
331     if (event_promise_ != nullptr) {
332       auto promise = std::move(event_promise_);
333       event_promise_.reset();
334       promise->set_value();
335     }
336   }
337 
handle_iso()338   void handle_iso() {
339     std::lock_guard<std::mutex> lock(list_protector_);
340     auto iso_ptr = hci_->GetIsoQueueEnd()->TryDequeue();
341     incoming_iso_packets_.push_back(*iso_ptr);
342     if (iso_promise_ != nullptr) {
343       auto promise = std::move(iso_promise_);
344       iso_promise_.reset();
345       promise->set_value();
346     }
347   }
348 
349   std::queue<std::unique_ptr<AclBuilder>> outgoing_acl_;
350 
handle_enqueue()351   std::unique_ptr<AclBuilder> handle_enqueue() {
352     hci_->GetAclQueueEnd()->UnregisterEnqueue();
353     auto acl = std::move(outgoing_acl_.front());
354     outgoing_acl_.pop();
355     return acl;
356   }
357 
358   std::queue<std::unique_ptr<IsoBuilder>> outgoing_iso_;
359 
handle_enqueue_iso()360   std::unique_ptr<IsoBuilder> handle_enqueue_iso() {
361     hci_->GetIsoQueueEnd()->UnregisterEnqueue();
362     auto iso = std::move(outgoing_iso_.front());
363     outgoing_iso_.pop();
364     return iso;
365   }
366 };
367 
__anon79f781040302() 368 const ModuleFactory DependsOnHci::Factory = ModuleFactory([]() { return new DependsOnHci(); });
369 
370 class HciTest : public ::testing::Test {
371  public:
SetUp()372   void SetUp() override {
373     counting_bytes.reserve(count_size);
374     counting_down_bytes.reserve(count_size);
375     for (size_t i = 0; i < count_size; i++) {
376       counting_bytes.push_back(i);
377       counting_down_bytes.push_back(~i);
378     }
379     hal = new TestHciHal();
380 
381     auto command_future = hal->GetSentCommandFuture();
382 
383     fake_registry_.InjectTestModule(&hal::HciHal::Factory, hal);
384     fake_registry_.Start<DependsOnHci>(&fake_registry_.GetTestThread());
385     hci = static_cast<HciLayer*>(fake_registry_.GetModuleUnderTest(&HciLayer::Factory));
386     upper = static_cast<DependsOnHci*>(fake_registry_.GetModuleUnderTest(&DependsOnHci::Factory));
387     ASSERT_TRUE(fake_registry_.IsStarted<HciLayer>());
388 
389     auto reset_sent_status = command_future.wait_for(kTimeout);
390     ASSERT_EQ(reset_sent_status, std::future_status::ready);
391 
392     // Verify that reset was received
393     ASSERT_EQ(1, hal->GetNumSentCommands());
394 
395     auto sent_command = hal->GetSentCommand();
396     auto reset_view = ResetView::Create(CommandView::Create(sent_command));
397     ASSERT_TRUE(reset_view.IsValid());
398 
399     // Verify that only one was sent
400     ASSERT_EQ(0, hal->GetNumSentCommands());
401 
402     // Send the response event
403     uint8_t num_packets = 1;
404     ErrorCode error_code = ErrorCode::SUCCESS;
405     hal->callbacks->hciEventReceived(GetPacketBytes(ResetCompleteBuilder::Create(num_packets, error_code)));
406   }
407 
TearDown()408   void TearDown() override {
409     fake_registry_.StopAll();
410   }
411 
GetPacketBytes(std::unique_ptr<packet::BasePacketBuilder> packet)412   std::vector<uint8_t> GetPacketBytes(std::unique_ptr<packet::BasePacketBuilder> packet) {
413     std::vector<uint8_t> bytes;
414     BitInserter i(bytes);
415     bytes.reserve(packet->size());
416     packet->Serialize(i);
417     return bytes;
418   }
419 
420   DependsOnHci* upper = nullptr;
421   TestHciHal* hal = nullptr;
422   HciLayer* hci = nullptr;
423   TestModuleRegistry fake_registry_;
424 };
425 
TEST_F(HciTest,initAndClose)426 TEST_F(HciTest, initAndClose) {}
427 
TEST_F(HciTest,leMetaEvent)428 TEST_F(HciTest, leMetaEvent) {
429   auto event_future = upper->GetReceivedEventFuture();
430 
431   // Send an LE event
432   ErrorCode status = ErrorCode::SUCCESS;
433   uint16_t handle = 0x123;
434   Role role = Role::CENTRAL;
435   AddressType peer_address_type = AddressType::PUBLIC_DEVICE_ADDRESS;
436   Address peer_address = Address::kAny;
437   uint16_t conn_interval = 0x0ABC;
438   uint16_t conn_latency = 0x0123;
439   uint16_t supervision_timeout = 0x0B05;
440   ClockAccuracy central_clock_accuracy = ClockAccuracy::PPM_50;
441   hal->callbacks->hciEventReceived(GetPacketBytes(LeConnectionCompleteBuilder::Create(
442       status,
443       handle,
444       role,
445       peer_address_type,
446       peer_address,
447       conn_interval,
448       conn_latency,
449       supervision_timeout,
450       central_clock_accuracy)));
451 
452   // Wait for the event
453   auto event_status = event_future.wait_for(kTimeout);
454   ASSERT_EQ(event_status, std::future_status::ready);
455 
456   auto event = upper->GetReceivedEvent();
457   ASSERT_TRUE(LeConnectionCompleteView::Create(LeMetaEventView::Create(EventView::Create(event))).IsValid());
458 }
459 
TEST_F(HciTest,hciTimeOut)460 TEST_F(HciTest, hciTimeOut) {
461   auto event_future = upper->GetReceivedEventFuture();
462   auto reset_command_future = hal->GetSentCommandFuture();
463   upper->SendHciCommandExpectingComplete(ResetBuilder::Create());
464   auto reset_command_sent_status = reset_command_future.wait_for(kTimeout);
465   ASSERT_EQ(reset_command_sent_status, std::future_status::ready);
466   auto reset = hal->GetSentCommand();
467   ASSERT_TRUE(reset.IsValid());
468   ASSERT_EQ(reset.GetOpCode(), OpCode::RESET);
469 
470   auto debug_command_future = hal->GetSentCommandFuture();
471   auto event_status = event_future.wait_for(HciLayer::kHciTimeoutMs);
472   ASSERT_NE(event_status, std::future_status::ready);
473   auto debug_command_sent_status = debug_command_future.wait_for(kTimeout);
474   ASSERT_EQ(debug_command_sent_status, std::future_status::ready);
475   auto debug = hal->GetSentCommand();
476   ASSERT_TRUE(debug.IsValid());
477   ASSERT_EQ(debug.GetOpCode(), OpCode::CONTROLLER_DEBUG_INFO);
478 }
479 
TEST_F(HciTest,noOpCredits)480 TEST_F(HciTest, noOpCredits) {
481   ASSERT_EQ(0, hal->GetNumSentCommands());
482 
483   // Send 0 credits
484   uint8_t num_packets = 0;
485   hal->callbacks->hciEventReceived(GetPacketBytes(NoCommandCompleteBuilder::Create(num_packets)));
486 
487   auto command_future = hal->GetSentCommandFuture();
488   upper->SendHciCommandExpectingComplete(ReadLocalVersionInformationBuilder::Create());
489 
490   // Verify that nothing was sent
491   ASSERT_EQ(0, hal->GetNumSentCommands());
492 
493   num_packets = 1;
494   hal->callbacks->hciEventReceived(GetPacketBytes(NoCommandCompleteBuilder::Create(num_packets)));
495 
496   auto command_sent_status = command_future.wait_for(kTimeout);
497   ASSERT_EQ(command_sent_status, std::future_status::ready);
498 
499   // Verify that one was sent
500   ASSERT_EQ(1, hal->GetNumSentCommands());
501 
502   auto event_future = upper->GetReceivedEventFuture();
503 
504   // Send the response event
505   ErrorCode error_code = ErrorCode::SUCCESS;
506   LocalVersionInformation local_version_information;
507   local_version_information.hci_version_ = HciVersion::V_5_0;
508   local_version_information.hci_revision_ = 0x1234;
509   local_version_information.lmp_version_ = LmpVersion::V_4_2;
510   local_version_information.manufacturer_name_ = 0xBAD;
511   local_version_information.lmp_subversion_ = 0x5678;
512   hal->callbacks->hciEventReceived(GetPacketBytes(
513       ReadLocalVersionInformationCompleteBuilder::Create(num_packets, error_code, local_version_information)));
514 
515   // Wait for the event
516   auto event_status = event_future.wait_for(kTimeout);
517   ASSERT_EQ(event_status, std::future_status::ready);
518 
519   auto event = upper->GetReceivedEvent();
520   ASSERT_TRUE(
521       ReadLocalVersionInformationCompleteView::Create(CommandCompleteView::Create(EventView::Create(event))).IsValid());
522 }
523 
TEST_F(HciTest,creditsTest)524 TEST_F(HciTest, creditsTest) {
525   ASSERT_EQ(0, hal->GetNumSentCommands());
526 
527   auto command_future = hal->GetSentCommandFuture();
528 
529   // Send all three commands
530   upper->SendHciCommandExpectingComplete(ReadLocalVersionInformationBuilder::Create());
531   upper->SendHciCommandExpectingComplete(ReadLocalSupportedCommandsBuilder::Create());
532   upper->SendHciCommandExpectingComplete(ReadLocalSupportedFeaturesBuilder::Create());
533 
534   auto command_sent_status = command_future.wait_for(kTimeout);
535   ASSERT_EQ(command_sent_status, std::future_status::ready);
536 
537   // Verify that the first one is sent
538   ASSERT_EQ(1, hal->GetNumSentCommands());
539 
540   auto sent_command = hal->GetSentCommand();
541   auto version_view = ReadLocalVersionInformationView::Create(CommandView::Create(sent_command));
542   ASSERT_TRUE(version_view.IsValid());
543 
544   // Verify that only one was sent
545   ASSERT_EQ(0, hal->GetNumSentCommands());
546 
547   // Get a new future
548   auto event_future = upper->GetReceivedEventFuture();
549 
550   // Send the response event
551   uint8_t num_packets = 1;
552   ErrorCode error_code = ErrorCode::SUCCESS;
553   LocalVersionInformation local_version_information;
554   local_version_information.hci_version_ = HciVersion::V_5_0;
555   local_version_information.hci_revision_ = 0x1234;
556   local_version_information.lmp_version_ = LmpVersion::V_4_2;
557   local_version_information.manufacturer_name_ = 0xBAD;
558   local_version_information.lmp_subversion_ = 0x5678;
559   hal->callbacks->hciEventReceived(GetPacketBytes(
560       ReadLocalVersionInformationCompleteBuilder::Create(num_packets, error_code, local_version_information)));
561 
562   // Wait for the event
563   auto event_status = event_future.wait_for(kTimeout);
564   ASSERT_EQ(event_status, std::future_status::ready);
565 
566   auto event = upper->GetReceivedEvent();
567   ASSERT_TRUE(
568       ReadLocalVersionInformationCompleteView::Create(CommandCompleteView::Create(EventView::Create(event))).IsValid());
569 
570   // Verify that the second one is sent
571   command_sent_status = command_future.wait_for(kTimeout);
572   ASSERT_EQ(command_sent_status, std::future_status::ready);
573   ASSERT_EQ(1, hal->GetNumSentCommands());
574 
575   sent_command = hal->GetSentCommand();
576   auto supported_commands_view = ReadLocalSupportedCommandsView::Create(CommandView::Create(sent_command));
577   ASSERT_TRUE(supported_commands_view.IsValid());
578 
579   // Verify that only one was sent
580   ASSERT_EQ(0, hal->GetNumSentCommands());
581   event_future = upper->GetReceivedEventFuture();
582   command_future = hal->GetSentCommandFuture();
583 
584   // Send the response event
585   std::array<uint8_t, 64> supported_commands;
586   for (uint8_t i = 0; i < 64; i++) {
587     supported_commands[i] = i;
588   }
589   hal->callbacks->hciEventReceived(
590       GetPacketBytes(ReadLocalSupportedCommandsCompleteBuilder::Create(num_packets, error_code, supported_commands)));
591   // Wait for the event
592   event_status = event_future.wait_for(kTimeout);
593   ASSERT_EQ(event_status, std::future_status::ready);
594 
595   event = upper->GetReceivedEvent();
596   ASSERT_TRUE(
597       ReadLocalSupportedCommandsCompleteView::Create(CommandCompleteView::Create(EventView::Create(event))).IsValid());
598   // Verify that the third one is sent
599   command_sent_status = command_future.wait_for(kTimeout);
600   ASSERT_EQ(command_sent_status, std::future_status::ready);
601   ASSERT_EQ(1, hal->GetNumSentCommands());
602 
603   sent_command = hal->GetSentCommand();
604   auto supported_features_view = ReadLocalSupportedFeaturesView::Create(CommandView::Create(sent_command));
605   ASSERT_TRUE(supported_features_view.IsValid());
606 
607   // Verify that only one was sent
608   ASSERT_EQ(0, hal->GetNumSentCommands());
609   event_future = upper->GetReceivedEventFuture();
610 
611   // Send the response event
612   uint64_t lmp_features = 0x012345678abcdef;
613   hal->callbacks->hciEventReceived(
614       GetPacketBytes(ReadLocalSupportedFeaturesCompleteBuilder::Create(num_packets, error_code, lmp_features)));
615 
616   // Wait for the event
617   event_status = event_future.wait_for(kTimeout);
618   ASSERT_EQ(event_status, std::future_status::ready);
619   event = upper->GetReceivedEvent();
620   ASSERT_TRUE(
621       ReadLocalSupportedFeaturesCompleteView::Create(CommandCompleteView::Create(EventView::Create(event))).IsValid());
622 }
623 
TEST_F(HciTest,leSecurityInterfaceTest)624 TEST_F(HciTest, leSecurityInterfaceTest) {
625   // Send LeRand to the controller
626   auto command_future = hal->GetSentCommandFuture();
627   upper->SendLeSecurityCommandExpectingComplete(LeRandBuilder::Create());
628 
629   auto command_sent_status = command_future.wait_for(kTimeout);
630   ASSERT_EQ(command_sent_status, std::future_status::ready);
631 
632   // Check the command
633   auto sent_command = hal->GetSentCommand();
634   ASSERT_LT(0, sent_command.size());
635   LeRandView view = LeRandView::Create(LeSecurityCommandView::Create(CommandView::Create(sent_command)));
636   ASSERT_TRUE(view.IsValid());
637 
638   // Send a Command Complete to the host
639   auto event_future = upper->GetReceivedEventFuture();
640   uint8_t num_packets = 1;
641   ErrorCode status = ErrorCode::SUCCESS;
642   uint64_t rand = 0x0123456789abcdef;
643   hal->callbacks->hciEventReceived(GetPacketBytes(LeRandCompleteBuilder::Create(num_packets, status, rand)));
644 
645   // Verify the event
646   auto event_status = event_future.wait_for(kTimeout);
647   ASSERT_EQ(event_status, std::future_status::ready);
648   auto event = upper->GetReceivedEvent();
649   ASSERT_TRUE(event.IsValid());
650   ASSERT_EQ(EventCode::COMMAND_COMPLETE, event.GetEventCode());
651   ASSERT_TRUE(LeRandCompleteView::Create(CommandCompleteView::Create(event)).IsValid());
652 }
653 
TEST_F(HciTest,securityInterfacesTest)654 TEST_F(HciTest, securityInterfacesTest) {
655   // Send WriteSimplePairingMode to the controller
656   auto command_future = hal->GetSentCommandFuture();
657   Enable enable = Enable::ENABLED;
658   upper->SendSecurityCommandExpectingComplete(WriteSimplePairingModeBuilder::Create(enable));
659 
660   auto command_sent_status = command_future.wait_for(kTimeout);
661   ASSERT_EQ(command_sent_status, std::future_status::ready);
662 
663   // Check the command
664   auto sent_command = hal->GetSentCommand();
665   ASSERT_LT(0, sent_command.size());
666   auto view = WriteSimplePairingModeView::Create(SecurityCommandView::Create(CommandView::Create(sent_command)));
667   ASSERT_TRUE(view.IsValid());
668 
669   // Send a Command Complete to the host
670   auto event_future = upper->GetReceivedEventFuture();
671   uint8_t num_packets = 1;
672   ErrorCode status = ErrorCode::SUCCESS;
673   hal->callbacks->hciEventReceived(GetPacketBytes(WriteSimplePairingModeCompleteBuilder::Create(num_packets, status)));
674 
675   // Verify the event
676   auto event_status = event_future.wait_for(kTimeout);
677   ASSERT_EQ(event_status, std::future_status::ready);
678   auto event = upper->GetReceivedEvent();
679   ASSERT_TRUE(event.IsValid());
680   ASSERT_EQ(EventCode::COMMAND_COMPLETE, event.GetEventCode());
681   ASSERT_TRUE(WriteSimplePairingModeCompleteView::Create(CommandCompleteView::Create(event)).IsValid());
682 }
683 
TEST_F(HciTest,createConnectionTest)684 TEST_F(HciTest, createConnectionTest) {
685   // Send CreateConnection to the controller
686   auto command_future = hal->GetSentCommandFuture();
687   Address bd_addr;
688   ASSERT_TRUE(Address::FromString("A1:A2:A3:A4:A5:A6", bd_addr));
689   uint16_t packet_type = 0x1234;
690   PageScanRepetitionMode page_scan_repetition_mode = PageScanRepetitionMode::R0;
691   uint16_t clock_offset = 0x3456;
692   ClockOffsetValid clock_offset_valid = ClockOffsetValid::VALID;
693   CreateConnectionRoleSwitch allow_role_switch = CreateConnectionRoleSwitch::ALLOW_ROLE_SWITCH;
694   upper->SendHciCommandExpectingStatus(CreateConnectionBuilder::Create(
695       bd_addr, packet_type, page_scan_repetition_mode, clock_offset, clock_offset_valid, allow_role_switch));
696 
697   auto command_sent_status = command_future.wait_for(kTimeout);
698   ASSERT_EQ(command_sent_status, std::future_status::ready);
699 
700   // Check the command
701   auto sent_command = hal->GetSentCommand();
702   ASSERT_LT(0, sent_command.size());
703   CreateConnectionView view = CreateConnectionView::Create(
704       ConnectionManagementCommandView::Create(AclCommandView::Create(CommandView::Create(sent_command))));
705   ASSERT_TRUE(view.IsValid());
706   ASSERT_EQ(bd_addr, view.GetBdAddr());
707   ASSERT_EQ(packet_type, view.GetPacketType());
708   ASSERT_EQ(page_scan_repetition_mode, view.GetPageScanRepetitionMode());
709   ASSERT_EQ(clock_offset, view.GetClockOffset());
710   ASSERT_EQ(clock_offset_valid, view.GetClockOffsetValid());
711   ASSERT_EQ(allow_role_switch, view.GetAllowRoleSwitch());
712 
713   // Send a Command Status to the host
714   auto event_future = upper->GetReceivedEventFuture();
715   ErrorCode status = ErrorCode::SUCCESS;
716   uint16_t handle = 0x123;
717   LinkType link_type = LinkType::ACL;
718   Enable encryption_enabled = Enable::DISABLED;
719   hal->callbacks->hciEventReceived(GetPacketBytes(CreateConnectionStatusBuilder::Create(ErrorCode::SUCCESS, 1)));
720 
721   // Verify the event
722   auto event_status = event_future.wait_for(kTimeout);
723   ASSERT_EQ(event_status, std::future_status::ready);
724   auto event = upper->GetReceivedEvent();
725   ASSERT_TRUE(event.IsValid());
726   ASSERT_EQ(EventCode::COMMAND_STATUS, event.GetEventCode());
727 
728   // Send a ConnectionComplete to the host
729   event_future = upper->GetReceivedEventFuture();
730   hal->callbacks->hciEventReceived(
731       GetPacketBytes(ConnectionCompleteBuilder::Create(status, handle, bd_addr, link_type, encryption_enabled)));
732 
733   // Verify the event
734   event_status = event_future.wait_for(kTimeout);
735   ASSERT_EQ(event_status, std::future_status::ready);
736   event = upper->GetReceivedEvent();
737   ASSERT_TRUE(event.IsValid());
738   ASSERT_EQ(EventCode::CONNECTION_COMPLETE, event.GetEventCode());
739   ConnectionCompleteView connection_complete_view = ConnectionCompleteView::Create(event);
740   ASSERT_TRUE(connection_complete_view.IsValid());
741   ASSERT_EQ(status, connection_complete_view.GetStatus());
742   ASSERT_EQ(handle, connection_complete_view.GetConnectionHandle());
743   ASSERT_EQ(link_type, connection_complete_view.GetLinkType());
744   ASSERT_EQ(encryption_enabled, connection_complete_view.GetEncryptionEnabled());
745 
746   // Send an ACL packet from the remote
747   PacketBoundaryFlag packet_boundary_flag = PacketBoundaryFlag::FIRST_AUTOMATICALLY_FLUSHABLE;
748   BroadcastFlag broadcast_flag = BroadcastFlag::POINT_TO_POINT;
749   auto acl_payload = std::make_unique<RawBuilder>();
750   acl_payload->AddAddress(bd_addr);
751   acl_payload->AddOctets2(handle);
752   auto incoming_acl_future = upper->GetReceivedAclFuture();
753   hal->callbacks->aclDataReceived(
754       GetPacketBytes(AclBuilder::Create(handle, packet_boundary_flag, broadcast_flag, std::move(acl_payload))));
755 
756   // Verify the ACL packet
757   auto incoming_acl_status = incoming_acl_future.wait_for(kAclTimeout);
758   ASSERT_EQ(incoming_acl_status, std::future_status::ready);
759   auto acl_view = upper->GetReceivedAcl();
760   ASSERT_TRUE(acl_view.IsValid());
761   ASSERT_EQ(bd_addr.length() + sizeof(handle), acl_view.GetPayload().size());
762   auto itr = acl_view.GetPayload().begin();
763   ASSERT_EQ(bd_addr, itr.extract<Address>());
764   ASSERT_EQ(handle, itr.extract<uint16_t>());
765 
766   // Send an ACL packet from DependsOnHci
767   PacketBoundaryFlag packet_boundary_flag2 = PacketBoundaryFlag::FIRST_AUTOMATICALLY_FLUSHABLE;
768   BroadcastFlag broadcast_flag2 = BroadcastFlag::POINT_TO_POINT;
769   auto acl_payload2 = std::make_unique<RawBuilder>();
770   acl_payload2->AddOctets2(handle);
771   acl_payload2->AddAddress(bd_addr);
772   auto sent_acl_future = hal->GetSentAclFuture();
773   upper->SendAclData(AclBuilder::Create(handle, packet_boundary_flag2, broadcast_flag2, std::move(acl_payload2)));
774 
775   // Verify the ACL packet
776   auto sent_acl_status = sent_acl_future.wait_for(kAclTimeout);
777   ASSERT_EQ(sent_acl_status, std::future_status::ready);
778   auto sent_acl = hal->GetSentAcl();
779   ASSERT_LT(0, sent_acl.size());
780   AclView sent_acl_view = AclView::Create(sent_acl);
781   ASSERT_TRUE(sent_acl_view.IsValid());
782   ASSERT_EQ(bd_addr.length() + sizeof(handle), sent_acl_view.GetPayload().size());
783   auto sent_itr = sent_acl_view.GetPayload().begin();
784   ASSERT_EQ(handle, sent_itr.extract<uint16_t>());
785   ASSERT_EQ(bd_addr, sent_itr.extract<Address>());
786 }
787 
TEST_F(HciTest,receiveMultipleAclPackets)788 TEST_F(HciTest, receiveMultipleAclPackets) {
789   Address bd_addr;
790   ASSERT_TRUE(Address::FromString("A1:A2:A3:A4:A5:A6", bd_addr));
791   uint16_t handle = 0x0001;
792   const uint16_t num_packets = 100;
793   PacketBoundaryFlag packet_boundary_flag = PacketBoundaryFlag::FIRST_AUTOMATICALLY_FLUSHABLE;
794   BroadcastFlag broadcast_flag = BroadcastFlag::POINT_TO_POINT;
795   for (uint16_t i = 0; i < num_packets; i++) {
796     auto acl_payload = std::make_unique<RawBuilder>();
797     acl_payload->AddAddress(bd_addr);
798     acl_payload->AddOctets2(handle);
799     acl_payload->AddOctets2(i);
800     hal->callbacks->aclDataReceived(
801         GetPacketBytes(AclBuilder::Create(handle, packet_boundary_flag, broadcast_flag, std::move(acl_payload))));
802   }
803   auto incoming_acl_future = upper->GetReceivedAclFuture();
804   uint16_t received_packets = 0;
805   while (received_packets < num_packets - 1) {
806     size_t num_rcv_packets = upper->GetNumReceivedAclPackets();
807     if (num_rcv_packets == 0) {
808       auto incoming_acl_status = incoming_acl_future.wait_for(kAclTimeout);
809       // Get the next future.
810       ASSERT_EQ(incoming_acl_status, std::future_status::ready);
811       incoming_acl_future = upper->GetReceivedAclFuture();
812       num_rcv_packets = upper->GetNumReceivedAclPackets();
813     }
814     for (size_t i = 0; i < num_rcv_packets; i++) {
815       auto acl_view = upper->GetReceivedAcl();
816       ASSERT_TRUE(acl_view.IsValid());
817       ASSERT_EQ(bd_addr.length() + sizeof(handle) + sizeof(received_packets), acl_view.GetPayload().size());
818       auto itr = acl_view.GetPayload().begin();
819       ASSERT_EQ(bd_addr, itr.extract<Address>());
820       ASSERT_EQ(handle, itr.extract<uint16_t>());
821       ASSERT_EQ(received_packets, itr.extract<uint16_t>());
822       received_packets += 1;
823     }
824   }
825 
826   // Check to see if this future was already fulfilled.
827   auto acl_race_status = incoming_acl_future.wait_for(std::chrono::milliseconds(1));
828   if (acl_race_status == std::future_status::ready) {
829     // Get the next future.
830     incoming_acl_future = upper->GetReceivedAclFuture();
831   }
832 
833   // One last packet to make sure they were all sent.  Already got the future.
834   auto acl_payload = std::make_unique<RawBuilder>();
835   acl_payload->AddAddress(bd_addr);
836   acl_payload->AddOctets2(handle);
837   acl_payload->AddOctets2(num_packets);
838   hal->callbacks->aclDataReceived(
839       GetPacketBytes(AclBuilder::Create(handle, packet_boundary_flag, broadcast_flag, std::move(acl_payload))));
840   auto incoming_acl_status = incoming_acl_future.wait_for(kAclTimeout);
841   ASSERT_EQ(incoming_acl_status, std::future_status::ready);
842   auto acl_view = upper->GetReceivedAcl();
843   ASSERT_TRUE(acl_view.IsValid());
844   ASSERT_EQ(bd_addr.length() + sizeof(handle) + sizeof(received_packets), acl_view.GetPayload().size());
845   auto itr = acl_view.GetPayload().begin();
846   ASSERT_EQ(bd_addr, itr.extract<Address>());
847   ASSERT_EQ(handle, itr.extract<uint16_t>());
848   ASSERT_EQ(received_packets, itr.extract<uint16_t>());
849 }
850 
TEST_F(HciTest,receiveMultipleIsoPackets)851 TEST_F(HciTest, receiveMultipleIsoPackets) {
852   uint16_t handle = 0x0001;
853   const uint16_t num_packets = 100;
854   IsoPacketBoundaryFlag packet_boundary_flag = IsoPacketBoundaryFlag::COMPLETE_SDU;
855   TimeStampFlag timestamp_flag = TimeStampFlag::NOT_PRESENT;
856   for (uint16_t i = 0; i < num_packets; i++) {
857     auto iso_payload = std::make_unique<RawBuilder>();
858     iso_payload->AddOctets2(handle);
859     iso_payload->AddOctets2(i);
860     hal->callbacks->isoDataReceived(
861         GetPacketBytes(IsoBuilder::Create(handle, packet_boundary_flag, timestamp_flag, std::move(iso_payload))));
862   }
863   auto incoming_iso_future = upper->GetReceivedIsoFuture();
864   uint16_t received_packets = 0;
865   while (received_packets < num_packets - 1) {
866     size_t num_rcv_packets = upper->GetNumReceivedIsoPackets();
867     if (num_rcv_packets == 0) {
868       auto incoming_iso_status = incoming_iso_future.wait_for(kAclTimeout);
869       // Get the next future.
870       ASSERT_EQ(incoming_iso_status, std::future_status::ready);
871       incoming_iso_future = upper->GetReceivedIsoFuture();
872       num_rcv_packets = upper->GetNumReceivedIsoPackets();
873     }
874     for (size_t i = 0; i < num_rcv_packets; i++) {
875       auto iso_view = upper->GetReceivedIso();
876       ASSERT_TRUE(iso_view.IsValid());
877       ASSERT_EQ(sizeof(handle) + sizeof(received_packets), iso_view.GetPayload().size());
878       auto itr = iso_view.GetPayload().begin();
879       ASSERT_EQ(handle, itr.extract<uint16_t>());
880       ASSERT_EQ(received_packets, itr.extract<uint16_t>());
881       received_packets += 1;
882     }
883   }
884 
885   // Check to see if this future was already fulfilled.
886   auto iso_race_status = incoming_iso_future.wait_for(std::chrono::milliseconds(1));
887   if (iso_race_status == std::future_status::ready) {
888     // Get the next future.
889     incoming_iso_future = upper->GetReceivedIsoFuture();
890   }
891 
892   // One last packet to make sure they were all sent.  Already got the future.
893   auto iso_payload = std::make_unique<RawBuilder>();
894   iso_payload->AddOctets2(handle);
895   iso_payload->AddOctets2(num_packets);
896   hal->callbacks->isoDataReceived(
897       GetPacketBytes(IsoBuilder::Create(handle, packet_boundary_flag, timestamp_flag, std::move(iso_payload))));
898   auto incoming_iso_status = incoming_iso_future.wait_for(kAclTimeout);
899   ASSERT_EQ(incoming_iso_status, std::future_status::ready);
900   auto iso_view = upper->GetReceivedIso();
901   ASSERT_TRUE(iso_view.IsValid());
902   ASSERT_EQ(sizeof(handle) + sizeof(received_packets), iso_view.GetPayload().size());
903   auto itr = iso_view.GetPayload().begin();
904   ASSERT_EQ(handle, itr.extract<uint16_t>());
905   ASSERT_EQ(received_packets, itr.extract<uint16_t>());
906 }
907 }  // namespace hci
908 }  // namespace bluetooth
909