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/controller.h"
18 
19 #include <bluetooth/log.h>
20 #include <com_android_bluetooth_flags.h>
21 #include <gtest/gtest.h>
22 #include <unistd.h>
23 
24 #include <chrono>
25 #include <future>
26 #include <memory>
27 #include <sstream>
28 
29 #include "common/bind.h"
30 #include "common/init_flags.h"
31 #include "hci/address.h"
32 #include "hci/hci_layer_fake.h"
33 #include "module_dumper.h"
34 #include "os/thread.h"
35 #include "packet/raw_builder.h"
36 
37 using namespace bluetooth;
38 using namespace std::chrono_literals;
39 
40 using packet::kLittleEndian;
41 using packet::PacketView;
42 using packet::RawBuilder;
43 
44 namespace bluetooth {
45 namespace hci {
46 
47 namespace {
48 
49 constexpr uint16_t kHandle1 = 0x123;
50 constexpr uint16_t kCredits1 = 0x78;
51 constexpr uint16_t kHandle2 = 0x456;
52 constexpr uint16_t kCredits2 = 0x9a;
53 constexpr uint64_t kRandomNumber = 0x123456789abcdef0;
54 /*sbc_supported= 1, aac_supported= 1, aptx_supported= 0, aptx_hd_supported= 0, ldac_supported= 1 */
55 constexpr uint32_t kDynamicAudioBufferSupport = 0x13;
56 uint16_t feature_spec_version = 55;
57 constexpr char title[] = "hci_controller_test";
58 
59 }  // namespace
60 
61 namespace {
62 
63 class HciLayerFakeForController : public HciLayerFake {
64  public:
EnqueueCommand(std::unique_ptr<CommandBuilder> command,common::ContextualOnceCallback<void (CommandCompleteView)> on_complete)65   void EnqueueCommand(
66       std::unique_ptr<CommandBuilder> command,
67       common::ContextualOnceCallback<void(CommandCompleteView)> on_complete) override {
68     GetHandler()->Post(common::BindOnce(
69         &HciLayerFakeForController::HandleCommand,
70         common::Unretained(this),
71         std::move(command),
72         std::move(on_complete)));
73   }
74 
EnqueueCommand(std::unique_ptr<CommandBuilder>,common::ContextualOnceCallback<void (CommandStatusView)>)75   void EnqueueCommand(
76       std::unique_ptr<CommandBuilder> /* command */,
77       common::ContextualOnceCallback<void(CommandStatusView)> /* on_status */) override {
78     FAIL() << "Controller properties should not generate Command Status";
79   }
80 
HandleCommand(std::unique_ptr<CommandBuilder> command_builder,common::ContextualOnceCallback<void (CommandCompleteView)> on_complete)81   void HandleCommand(
82       std::unique_ptr<CommandBuilder> command_builder,
83       common::ContextualOnceCallback<void(CommandCompleteView)> on_complete) {
84     auto bytes = std::make_shared<std::vector<uint8_t>>();
85     BitInserter i(*bytes);
86     bytes->reserve((command_builder)->size());
87     command_builder->Serialize(i);
88     auto packet_view = packet::PacketView<packet::kLittleEndian>(bytes);
89     CommandView command = CommandView::Create(packet_view);
90     ASSERT_TRUE(command.IsValid());
91 
92     uint8_t num_packets = 1;
93     std::unique_ptr<packet::BasePacketBuilder> event_builder;
94     switch (command.GetOpCode()) {
95       case (OpCode::READ_LOCAL_NAME): {
96         std::array<uint8_t, 248> local_name = {'D', 'U', 'T', '\0'};
97         event_builder = ReadLocalNameCompleteBuilder::Create(num_packets, ErrorCode::SUCCESS, local_name);
98       } break;
99       case (OpCode::READ_LOCAL_VERSION_INFORMATION): {
100         LocalVersionInformation local_version_information;
101         local_version_information.hci_version_ = HciVersion::V_5_0;
102         local_version_information.hci_revision_ = 0x1234;
103         local_version_information.lmp_version_ = LmpVersion::V_4_2;
104         local_version_information.manufacturer_name_ = 0xBAD;
105         local_version_information.lmp_subversion_ = 0x5678;
106         event_builder = ReadLocalVersionInformationCompleteBuilder::Create(
107             num_packets, ErrorCode::SUCCESS, local_version_information);
108       } break;
109       case (OpCode::READ_LOCAL_SUPPORTED_COMMANDS): {
110         std::array<uint8_t, 64> supported_commands;
111         for (int i = 0; i < 37; i++) {
112           supported_commands[i] = 0xff;
113         }
114         for (int i = 37; i < 64; i++) {
115           supported_commands[i] = 0x00;
116         }
117         event_builder =
118             ReadLocalSupportedCommandsCompleteBuilder::Create(num_packets, ErrorCode::SUCCESS, supported_commands);
119       } break;
120       case (OpCode::READ_LOCAL_SUPPORTED_CODECS_V1): {
121         std::vector<uint8_t> supported_codecs{0, 1, 2, 3, 4, 5, 6};
122         std::vector<uint32_t> supported_vendor_codecs;
123         event_builder = ReadLocalSupportedCodecsV1CompleteBuilder::Create(
124             num_packets, ErrorCode::SUCCESS, supported_codecs, supported_vendor_codecs);
125       } break;
126       case (OpCode::READ_LOCAL_EXTENDED_FEATURES): {
127         ReadLocalExtendedFeaturesView read_command = ReadLocalExtendedFeaturesView::Create(command);
128         ASSERT_TRUE(read_command.IsValid());
129         uint8_t page_bumber = read_command.GetPageNumber();
130         uint64_t lmp_features = 0x012345678abcdef;
131         lmp_features += page_bumber;
132         event_builder = ReadLocalExtendedFeaturesCompleteBuilder::Create(
133             num_packets, ErrorCode::SUCCESS, page_bumber, 0x02, lmp_features);
134       } break;
135       case (OpCode::READ_BUFFER_SIZE): {
136         event_builder = ReadBufferSizeCompleteBuilder::Create(
137             num_packets,
138             ErrorCode::SUCCESS,
139             acl_data_packet_length,
140             synchronous_data_packet_length,
141             total_num_acl_data_packets,
142             total_num_synchronous_data_packets);
143       } break;
144       case (OpCode::READ_BD_ADDR): {
145         event_builder = ReadBdAddrCompleteBuilder::Create(num_packets, ErrorCode::SUCCESS, Address::kAny);
146       } break;
147       case (OpCode::LE_READ_BUFFER_SIZE_V1): {
148         LeBufferSize le_buffer_size;
149         le_buffer_size.le_data_packet_length_ = 0x16;
150         le_buffer_size.total_num_le_packets_ = 0x08;
151         event_builder = LeReadBufferSizeV1CompleteBuilder::Create(num_packets, ErrorCode::SUCCESS, le_buffer_size);
152       } break;
153       case (OpCode::LE_READ_LOCAL_SUPPORTED_FEATURES): {
154         event_builder =
155             LeReadLocalSupportedFeaturesCompleteBuilder::Create(num_packets, ErrorCode::SUCCESS, 0x001f123456789abc);
156       } break;
157       case (OpCode::LE_READ_SUPPORTED_STATES): {
158         event_builder =
159             LeReadSupportedStatesCompleteBuilder::Create(num_packets, ErrorCode::SUCCESS, 0x001f123456789abe);
160       } break;
161       case (OpCode::LE_READ_MAXIMUM_DATA_LENGTH): {
162         LeMaximumDataLength le_maximum_data_length;
163         le_maximum_data_length.supported_max_tx_octets_ = 0x12;
164         le_maximum_data_length.supported_max_tx_time_ = 0x34;
165         le_maximum_data_length.supported_max_rx_octets_ = 0x56;
166         le_maximum_data_length.supported_max_rx_time_ = 0x78;
167         event_builder =
168             LeReadMaximumDataLengthCompleteBuilder::Create(num_packets, ErrorCode::SUCCESS, le_maximum_data_length);
169       } break;
170       case (OpCode::LE_READ_MAXIMUM_ADVERTISING_DATA_LENGTH): {
171         event_builder =
172             LeReadMaximumAdvertisingDataLengthCompleteBuilder::Create(num_packets, ErrorCode::SUCCESS, 0x0672);
173       } break;
174       case (OpCode::LE_READ_NUMBER_OF_SUPPORTED_ADVERTISING_SETS): {
175         event_builder =
176             LeReadNumberOfSupportedAdvertisingSetsCompleteBuilder::Create(num_packets, ErrorCode::SUCCESS, 0xF0);
177       } break;
178       case (OpCode::LE_GET_VENDOR_CAPABILITIES):
179         if (vendor_capabilities_ == nullptr) {
180           BaseVendorCapabilities base_vendor_capabilities;
181           base_vendor_capabilities.max_advt_instances_ = 0x10;
182           base_vendor_capabilities.offloaded_resolution_of_private_address_ = 0x01;
183           base_vendor_capabilities.total_scan_results_storage_ = 0x2800;
184           base_vendor_capabilities.max_irk_list_sz_ = 0x20;
185           base_vendor_capabilities.filtering_support_ = 0x01;
186           base_vendor_capabilities.max_filter_ = 0x10;
187           base_vendor_capabilities.activity_energy_info_support_ = 0x01;
188 
189           auto payload = std::make_unique<RawBuilder>();
190           if (feature_spec_version > 55) {
191             std::vector<uint8_t> payload_bytes = {
192                 0x20, 0x00, 0x01, 0x00, 0x00, 0x1f, 0x00, 0x00, 0x00, 0x00};
193             payload->AddOctets2(feature_spec_version);
194             payload->AddOctets(payload_bytes);
195           }
196           event_builder = LeGetVendorCapabilitiesCompleteBuilder::Create(
197               num_packets, ErrorCode::SUCCESS, base_vendor_capabilities, std::move(payload));
198         } else {
199           event_builder = std::move(vendor_capabilities_);
200           vendor_capabilities_.reset();
201         }
202         break;
203       case (OpCode::DYNAMIC_AUDIO_BUFFER): {
204         auto dab_command =
205             DynamicAudioBufferView::CreateOptional(VendorCommandView::Create(command));
206         if (dab_command->GetDabCommand() == DabCommand::GET_AUDIO_BUFFER_TIME_CAPABILITY) {
207           std::array<DynamicAudioBufferCodecCapability, 32> capabilities{};
208           capabilities[0] =
209               DynamicAudioBufferCodecCapability(0x123, 0x103, 0x1234);  // sbc_capabilities
210           capabilities[1] =
211               DynamicAudioBufferCodecCapability(0x223, 0x123, 0x2340);  // aac_capabilities
212           capabilities[4] =
213               DynamicAudioBufferCodecCapability(0x323, 0x223, 0x3456);  // ldac_capabilities
214           event_builder = DabGetAudioBufferTimeCapabilityCompleteBuilder::Create(
215               1, ErrorCode::SUCCESS, kDynamicAudioBufferSupport, capabilities);
216         } else {
217           auto set_command = DabSetAudioBufferTimeView::CreateOptional(*dab_command);
218           dynamic_audio_buffer_time = set_command->GetBufferTimeMs();
219           event_builder = DabSetAudioBufferTimeCompleteBuilder::Create(
220               1, ErrorCode::SUCCESS, dynamic_audio_buffer_time);
221         }
222       } break;
223       case (OpCode::SET_EVENT_MASK): {
224         auto view = SetEventMaskView::Create(command);
225         ASSERT_TRUE(view.IsValid());
226         event_mask = view.GetEventMask();
227         event_builder = SetEventMaskCompleteBuilder::Create(num_packets, ErrorCode::SUCCESS);
228       } break;
229       case (OpCode::LE_SET_EVENT_MASK): {
230         auto view = LeSetEventMaskView::Create(command);
231         ASSERT_TRUE(view.IsValid());
232         le_event_mask = view.GetLeEventMask();
233         event_builder = LeSetEventMaskCompleteBuilder::Create(num_packets, ErrorCode::SUCCESS);
234       } break;
235 
236       case (OpCode::LE_RAND): {
237         auto view = LeRandView::Create(LeSecurityCommandView::Create(command));
238         ASSERT_TRUE(view.IsValid());
239         event_builder = LeRandCompleteBuilder::Create(num_packets, ErrorCode::SUCCESS, kRandomNumber);
240       } break;
241 
242       // Let the test check and handle these commands.
243       case (OpCode::RESET):
244       case (OpCode::SET_EVENT_FILTER):
245       case (OpCode::HOST_BUFFER_SIZE):
246         HciLayerFake::EnqueueCommand(std::move(command_builder), std::move(on_complete));
247         return;
248 
249       default:
250         log::info("Dropping unhandled packet ({})", OpCodeText(command.GetOpCode()));
251         return;
252     }
253     auto packet = GetPacketView(std::move(event_builder));
254     EventView event = EventView::Create(packet);
255     ASSERT_TRUE(event.IsValid());
256     CommandCompleteView command_complete = CommandCompleteView::Create(event);
257     ASSERT_TRUE(command_complete.IsValid());
258     on_complete(std::move(command_complete));
259   }
260 
IncomingCredit()261   void IncomingCredit() {
262     std::vector<CompletedPackets> completed_packets;
263     CompletedPackets cp;
264     cp.host_num_of_completed_packets_ = kCredits1;
265     cp.connection_handle_ = kHandle1;
266     completed_packets.push_back(cp);
267     cp.host_num_of_completed_packets_ = kCredits2;
268     cp.connection_handle_ = kHandle2;
269     completed_packets.push_back(cp);
270     IncomingEvent(NumberOfCompletedPacketsBuilder::Create(completed_packets));
271   }
272 
273   std::unique_ptr<EventBuilder> vendor_capabilities_ = nullptr;
274   constexpr static uint16_t acl_data_packet_length = 1024;
275   constexpr static uint8_t synchronous_data_packet_length = 60;
276   constexpr static uint16_t total_num_acl_data_packets = 10;
277   constexpr static uint16_t total_num_synchronous_data_packets = 12;
278   uint64_t event_mask = 0;
279   uint64_t le_event_mask = 0;
280   uint16_t dynamic_audio_buffer_time = 0;
281 };
282 
283 class ControllerTest : public ::testing::Test {
284  protected:
SetUp()285   void SetUp() override {
286     feature_spec_version = feature_spec_version_;
287     bluetooth::common::InitFlags::SetAllForTesting();
288     test_hci_layer_ = new HciLayerFakeForController;
289     test_hci_layer_->vendor_capabilities_ = std::move(vendor_capabilities_);
290     vendor_capabilities_.reset();
291     fake_registry_.InjectTestModule(&HciLayer::Factory, test_hci_layer_);
292     client_handler_ = fake_registry_.GetTestModuleHandler(&HciLayer::Factory);
293     fake_registry_.Start<Controller>(&thread_);
294     controller_ = static_cast<Controller*>(fake_registry_.GetModuleUnderTest(&Controller::Factory));
295   }
296 
TearDown()297   void TearDown() override {
298     fake_registry_.StopAll();
299   }
300 
301   TestModuleRegistry fake_registry_;
302   HciLayerFakeForController* test_hci_layer_ = nullptr;
303   os::Thread& thread_ = fake_registry_.GetTestThread();
304   Controller* controller_ = nullptr;
305   os::Handler* client_handler_ = nullptr;
306   uint16_t feature_spec_version_ = 98;
307   std::unique_ptr<EventBuilder> vendor_capabilities_ = nullptr;
308 };
309 }  // namespace
310 
311 class Controller055Test : public ControllerTest {
312  protected:
SetUp()313   void SetUp() override {
314     feature_spec_version_ = 55;
315     ControllerTest::SetUp();
316   }
317 };
318 
319 class Controller095Test : public ControllerTest {
320  protected:
SetUp()321   void SetUp() override {
322     feature_spec_version_ = 95;
323     ControllerTest::SetUp();
324   }
325 };
326 
327 class Controller096Test : public ControllerTest {
328  protected:
SetUp()329   void SetUp() override {
330     feature_spec_version_ = 96;
331     ControllerTest::SetUp();
332   }
333 };
334 
335 class Controller103Test : public ControllerTest {
336  protected:
SetUp()337   void SetUp() override {
338     feature_spec_version_ = 0x100 + 0x03;
339     BaseVendorCapabilities base_vendor_capabilities;
340     base_vendor_capabilities.max_advt_instances_ = 0x10;
341     base_vendor_capabilities.offloaded_resolution_of_private_address_ = 0x01;
342     base_vendor_capabilities.total_scan_results_storage_ = 0x2800;
343     base_vendor_capabilities.max_irk_list_sz_ = 0x20;
344     base_vendor_capabilities.filtering_support_ = 0x01;
345     base_vendor_capabilities.max_filter_ = 0x10;
346     base_vendor_capabilities.activity_energy_info_support_ = 0x01;
347     vendor_capabilities_ = LeGetVendorCapabilitiesComplete103Builder::Create(
348         1,
349         ErrorCode::SUCCESS,
350         base_vendor_capabilities,
351         feature_spec_version_,
352         0x102,
353         /*extended_scan_support=*/1,
354         /*debug_logging_supported=*/1,
355         /*le_address_generation_offloading_support=*/0,
356         /*a2dp_source_offload_capability_mask=*/0x4,
357         /*bluetooth_quality_report_support=*/1,
358         kDynamicAudioBufferSupport,
359         std::make_unique<RawBuilder>());
360     ControllerTest::SetUp();
361   }
362 };
363 
364 class Controller104Test : public ControllerTest {
365  protected:
SetUp()366   void SetUp() override {
367     feature_spec_version_ = 0x100 + 0x04;
368     BaseVendorCapabilities base_vendor_capabilities;
369     base_vendor_capabilities.max_advt_instances_ = 0x10;
370     base_vendor_capabilities.offloaded_resolution_of_private_address_ = 0x01;
371     base_vendor_capabilities.total_scan_results_storage_ = 0x2800;
372     base_vendor_capabilities.max_irk_list_sz_ = 0x20;
373     base_vendor_capabilities.filtering_support_ = 0x01;
374     base_vendor_capabilities.max_filter_ = 0x10;
375     base_vendor_capabilities.activity_energy_info_support_ = 0x01;
376     vendor_capabilities_ = LeGetVendorCapabilitiesComplete104Builder::Create(
377         1,
378         ErrorCode::SUCCESS,
379         base_vendor_capabilities,
380         feature_spec_version_,
381         0x102,
382         /*extended_scan_support=*/1,
383         /*debug_logging_supported=*/1,
384         /*le_address_generation_offloading_support=*/0,
385         /*a2dp_source_offload_capability_mask=*/0x4,
386         /*bluetooth_quality_report_support=*/1,
387         kDynamicAudioBufferSupport,
388         /*a2dp_offload_v2_support=*/1,
389         std::make_unique<RawBuilder>());
390     ControllerTest::SetUp();
391   }
392 };
393 
TEST_F(ControllerTest,startup_teardown)394 TEST_F(ControllerTest, startup_teardown) {}
395 
TEST_F(ControllerTest,read_controller_info)396 TEST_F(ControllerTest, read_controller_info) {
397   ASSERT_EQ(controller_->GetAclPacketLength(), test_hci_layer_->acl_data_packet_length);
398   ASSERT_EQ(controller_->GetNumAclPacketBuffers(), test_hci_layer_->total_num_acl_data_packets);
399   ASSERT_EQ(controller_->GetScoPacketLength(), test_hci_layer_->synchronous_data_packet_length);
400   ASSERT_EQ(controller_->GetNumScoPacketBuffers(), test_hci_layer_->total_num_synchronous_data_packets);
401   ASSERT_EQ(controller_->GetMacAddress(), Address::kAny);
402   LocalVersionInformation local_version_information = controller_->GetLocalVersionInformation();
403   ASSERT_EQ(local_version_information.hci_version_, HciVersion::V_5_0);
404   ASSERT_EQ(local_version_information.hci_revision_, 0x1234);
405   ASSERT_EQ(local_version_information.lmp_version_, LmpVersion::V_4_2);
406   ASSERT_EQ(local_version_information.manufacturer_name_, 0xBAD);
407   ASSERT_EQ(local_version_information.lmp_subversion_, 0x5678);
408   ASSERT_EQ(controller_->GetLeBufferSize().le_data_packet_length_, 0x16);
409   ASSERT_EQ(controller_->GetLeBufferSize().total_num_le_packets_, 0x08);
410   ASSERT_EQ(controller_->GetLeSupportedStates(), 0x001f123456789abeUL);
411   ASSERT_EQ(controller_->GetLeMaximumDataLength().supported_max_tx_octets_, 0x12);
412   ASSERT_EQ(controller_->GetLeMaximumDataLength().supported_max_tx_time_, 0x34);
413   ASSERT_EQ(controller_->GetLeMaximumDataLength().supported_max_rx_octets_, 0x56);
414   ASSERT_EQ(controller_->GetLeMaximumDataLength().supported_max_rx_time_, 0x78);
415   ASSERT_EQ(controller_->GetLeMaximumAdvertisingDataLength(), 0x0672);
416   ASSERT_EQ(controller_->GetLeNumberOfSupportedAdverisingSets(), 0xF0);
417   ASSERT_TRUE(controller_->GetLocalSupportedBrEdrCodecIds().size() > 0);
418 }
419 
TEST_F(ControllerTest,read_write_local_name)420 TEST_F(ControllerTest, read_write_local_name) {
421   ASSERT_EQ(controller_->GetLocalName(), "DUT");
422   controller_->WriteLocalName("New name");
423   ASSERT_EQ(controller_->GetLocalName(), "New name");
424 }
425 
TEST_F(ControllerTest,send_set_event_mask_command)426 TEST_F(ControllerTest, send_set_event_mask_command) {
427   uint64_t new_event_mask = test_hci_layer_->event_mask - 1;
428   controller_->SetEventMask(new_event_mask);
429   // Send another command to make sure it was applied
430   controller_->Reset();
431   auto packet = test_hci_layer_->GetCommand(OpCode::RESET);
432   ASSERT_EQ(new_event_mask, test_hci_layer_->event_mask);
433 }
434 
TEST_F(ControllerTest,send_reset_command)435 TEST_F(ControllerTest, send_reset_command) {
436   controller_->Reset();
437   auto packet = test_hci_layer_->GetCommand(OpCode::RESET);
438   auto command = ResetView::Create(packet);
439   ASSERT_TRUE(command.IsValid());
440 }
441 
TEST_F(ControllerTest,send_set_event_filter_command)442 TEST_F(ControllerTest, send_set_event_filter_command) {
443   controller_->SetEventFilterInquiryResultAllDevices();
444   auto packet = test_hci_layer_->GetCommand(OpCode::SET_EVENT_FILTER);
445   auto set_event_filter_view1 = SetEventFilterView::Create(packet);
446   auto set_event_filter_inquiry_result_view1 = SetEventFilterInquiryResultView::Create(set_event_filter_view1);
447   auto command1 = SetEventFilterInquiryResultAllDevicesView::Create(set_event_filter_inquiry_result_view1);
448   ASSERT_TRUE(command1.IsValid());
449 
450   ClassOfDevice class_of_device({0xab, 0xcd, 0xef});
451   ClassOfDevice class_of_device_mask({0x12, 0x34, 0x56});
452   controller_->SetEventFilterInquiryResultClassOfDevice(class_of_device, class_of_device_mask);
453   packet = test_hci_layer_->GetCommand(OpCode::SET_EVENT_FILTER);
454   auto set_event_filter_view2 = SetEventFilterView::Create(packet);
455   auto set_event_filter_inquiry_result_view2 = SetEventFilterInquiryResultView::Create(set_event_filter_view2);
456   auto command2 = SetEventFilterInquiryResultClassOfDeviceView::Create(set_event_filter_inquiry_result_view2);
457   ASSERT_TRUE(command2.IsValid());
458   ASSERT_EQ(command2.GetClassOfDevice(), class_of_device);
459 
460   Address bdaddr({0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc});
461   controller_->SetEventFilterConnectionSetupAddress(bdaddr, AutoAcceptFlag::AUTO_ACCEPT_ON_ROLE_SWITCH_ENABLED);
462   packet = test_hci_layer_->GetCommand(OpCode::SET_EVENT_FILTER);
463   auto set_event_filter_view3 = SetEventFilterView::Create(packet);
464   auto set_event_filter_connection_setup_view = SetEventFilterConnectionSetupView::Create(set_event_filter_view3);
465   auto command3 = SetEventFilterConnectionSetupAddressView::Create(set_event_filter_connection_setup_view);
466   ASSERT_TRUE(command3.IsValid());
467   ASSERT_EQ(command3.GetAddress(), bdaddr);
468 }
469 
TEST_F(ControllerTest,send_host_buffer_size_command)470 TEST_F(ControllerTest, send_host_buffer_size_command) {
471   controller_->HostBufferSize(0xFF00, 0xF1, 0xFF02, 0xFF03);
472   auto packet = test_hci_layer_->GetCommand(OpCode::HOST_BUFFER_SIZE);
473   auto command = HostBufferSizeView::Create(packet);
474   ASSERT_TRUE(command.IsValid());
475   ASSERT_EQ(command.GetHostAclDataPacketLength(), 0xFF00);
476   ASSERT_EQ(command.GetHostSynchronousDataPacketLength(), 0xF1);
477   ASSERT_EQ(command.GetHostTotalNumAclDataPackets(), 0xFF02);
478   ASSERT_EQ(command.GetHostTotalNumSynchronousDataPackets(), 0xFF03);
479 }
480 
TEST_F(ControllerTest,send_le_set_event_mask_command)481 TEST_F(ControllerTest, send_le_set_event_mask_command) {
482   uint64_t new_le_event_mask = test_hci_layer_->event_mask - 1;
483   controller_->LeSetEventMask(new_le_event_mask);
484   // Send another command to make sure it was applied
485   controller_->Reset();
486   auto packet = test_hci_layer_->GetCommand(OpCode::RESET);
487   ASSERT_EQ(new_le_event_mask, test_hci_layer_->le_event_mask);
488 }
489 
TEST_F(ControllerTest,is_supported_test)490 TEST_F(ControllerTest, is_supported_test) {
491   ASSERT_TRUE(controller_->IsSupported(OpCode::INQUIRY));
492   ASSERT_TRUE(controller_->IsSupported(OpCode::REJECT_CONNECTION_REQUEST));
493   ASSERT_TRUE(controller_->IsSupported(OpCode::ACCEPT_CONNECTION_REQUEST));
494   ASSERT_FALSE(controller_->IsSupported(OpCode::LE_REMOVE_ADVERTISING_SET));
495   ASSERT_FALSE(controller_->IsSupported(OpCode::LE_CLEAR_ADVERTISING_SETS));
496   ASSERT_FALSE(controller_->IsSupported(OpCode::LE_SET_PERIODIC_ADVERTISING_PARAMETERS));
497 }
498 
TEST_F(Controller055Test,feature_spec_version_055_test)499 TEST_F(Controller055Test, feature_spec_version_055_test) {
500   ASSERT_EQ(controller_->GetVendorCapabilities().version_supported_, 55);
501   ASSERT_TRUE(controller_->IsSupported(OpCode::LE_MULTI_ADVT));
502   ASSERT_FALSE(controller_->IsSupported(OpCode::CONTROLLER_DEBUG_INFO));
503   ASSERT_FALSE(controller_->IsSupported(OpCode::CONTROLLER_A2DP_OPCODE));
504 }
505 
TEST_F(Controller095Test,feature_spec_version_095_test)506 TEST_F(Controller095Test, feature_spec_version_095_test) {
507   ASSERT_EQ(controller_->GetVendorCapabilities().version_supported_, 95);
508   ASSERT_TRUE(controller_->IsSupported(OpCode::LE_MULTI_ADVT));
509   ASSERT_FALSE(controller_->IsSupported(OpCode::CONTROLLER_DEBUG_INFO));
510   ASSERT_FALSE(controller_->IsSupported(OpCode::CONTROLLER_A2DP_OPCODE));
511 }
512 
TEST_F(Controller096Test,feature_spec_version_096_test)513 TEST_F(Controller096Test, feature_spec_version_096_test) {
514   ASSERT_EQ(controller_->GetVendorCapabilities().version_supported_, 96);
515   ASSERT_TRUE(controller_->IsSupported(OpCode::LE_MULTI_ADVT));
516   ASSERT_FALSE(controller_->IsSupported(OpCode::CONTROLLER_DEBUG_INFO));
517   ASSERT_FALSE(controller_->IsSupported(OpCode::CONTROLLER_A2DP_OPCODE));
518 }
519 
TEST_F(ControllerTest,feature_spec_version_098_test)520 TEST_F(ControllerTest, feature_spec_version_098_test) {
521   ASSERT_EQ(controller_->GetVendorCapabilities().version_supported_, 98);
522   ASSERT_TRUE(controller_->IsSupported(OpCode::LE_MULTI_ADVT));
523   ASSERT_FALSE(controller_->IsSupported(OpCode::CONTROLLER_DEBUG_INFO));
524   ASSERT_TRUE(controller_->IsSupported(OpCode::CONTROLLER_A2DP_OPCODE));
525 }
526 
TEST_F(ControllerTest,feature_spec_version_098_no_dab_test)527 TEST_F(ControllerTest, feature_spec_version_098_no_dab_test) {
528   ASSERT_FALSE(controller_->IsSupported(OpCode::DYNAMIC_AUDIO_BUFFER));
529 }
530 
TEST_F(ControllerTest,set_dynamic_audio_buffer_time)531 TEST_F(ControllerTest, set_dynamic_audio_buffer_time) {
532   controller_->SetDabAudioBufferTime(123);
533   thread_.GetReactor()->WaitForIdle(std::chrono::seconds(1));
534   ASSERT_EQ(0, test_hci_layer_->dynamic_audio_buffer_time);
535 }
536 
TEST_F(Controller103Test,feature_spec_version_103_dab_test)537 TEST_F(Controller103Test, feature_spec_version_103_dab_test) {
538   ASSERT_EQ(controller_->GetVendorCapabilities().version_supported_, 0x100 + 3);
539   ASSERT_FALSE(controller_->GetVendorCapabilities().a2dp_offload_v2_support_);
540   ASSERT_TRUE(controller_->IsSupported(OpCode::LE_MULTI_ADVT));
541   ASSERT_TRUE(controller_->IsSupported(OpCode::CONTROLLER_DEBUG_INFO));
542   ASSERT_TRUE(controller_->IsSupported(OpCode::CONTROLLER_A2DP_OPCODE));
543   ASSERT_TRUE(controller_->IsSupported(OpCode::DYNAMIC_AUDIO_BUFFER));
544   ASSERT_EQ(controller_->GetDabSupportedCodecs(), kDynamicAudioBufferSupport);
545   for (size_t bit = 0; bit < 32; bit++) {
546     if (kDynamicAudioBufferSupport & (1u << bit)) {
547       ASSERT_GT(controller_->GetDabCodecCapabilities()[bit].maximum_time_ms_, 0) << " bit " << bit;
548     } else {
549       ASSERT_EQ(controller_->GetDabCodecCapabilities()[bit].maximum_time_ms_, 0);
550       ASSERT_EQ(controller_->GetDabCodecCapabilities()[bit].minimum_time_ms_, 0);
551       ASSERT_EQ(controller_->GetDabCodecCapabilities()[bit].default_time_ms_, 0);
552     }
553   }
554 }
555 
TEST_F(Controller103Test,set_dynamic_audio_buffer_time)556 TEST_F(Controller103Test, set_dynamic_audio_buffer_time) {
557   controller_->SetDabAudioBufferTime(123);
558   thread_.GetReactor()->WaitForIdle(std::chrono::seconds(1));
559   ASSERT_EQ(123, test_hci_layer_->dynamic_audio_buffer_time);
560 }
561 
TEST_F(Controller104Test,feature_spec_version_104_test)562 TEST_F(Controller104Test, feature_spec_version_104_test) {
563   ASSERT_EQ(controller_->GetVendorCapabilities().version_supported_, 0x100 + 4);
564   if (com::android::bluetooth::flags::a2dp_offload_codec_extensibility()) {
565     ASSERT_TRUE(controller_->GetVendorCapabilities().a2dp_offload_v2_support_);
566   } else {
567     ASSERT_FALSE(controller_->GetVendorCapabilities().a2dp_offload_v2_support_);
568   }
569   ASSERT_TRUE(controller_->IsSupported(OpCode::LE_MULTI_ADVT));
570   ASSERT_TRUE(controller_->IsSupported(OpCode::CONTROLLER_DEBUG_INFO));
571   ASSERT_TRUE(controller_->IsSupported(OpCode::CONTROLLER_A2DP_OPCODE));
572   ASSERT_TRUE(controller_->IsSupported(OpCode::DYNAMIC_AUDIO_BUFFER));
573   ASSERT_EQ(controller_->GetDabSupportedCodecs(), kDynamicAudioBufferSupport);
574   for (size_t bit = 0; bit < 32; bit++) {
575     if (kDynamicAudioBufferSupport & (1u << bit)) {
576       ASSERT_GT(controller_->GetDabCodecCapabilities()[bit].maximum_time_ms_, 0) << " bit " << bit;
577     } else {
578       ASSERT_EQ(controller_->GetDabCodecCapabilities()[bit].maximum_time_ms_, 0);
579       ASSERT_EQ(controller_->GetDabCodecCapabilities()[bit].minimum_time_ms_, 0);
580       ASSERT_EQ(controller_->GetDabCodecCapabilities()[bit].default_time_ms_, 0);
581     }
582   }
583 }
584 
585 std::promise<void> credits1_set;
586 std::promise<void> credits2_set;
587 
CheckReceivedCredits(uint16_t handle,uint16_t credits)588 void CheckReceivedCredits(uint16_t handle, uint16_t credits) {
589   switch (handle) {
590     case (kHandle1):
591       ASSERT_EQ(kCredits1, credits);
592       credits1_set.set_value();
593       break;
594     case (kHandle2):
595       ASSERT_EQ(kCredits2, credits);
596       credits2_set.set_value();
597       break;
598     default:
599       log::fatal("Unknown handle 0x{:0x} with 0x{:0x} credits", handle, credits);
600   }
601 }
602 
TEST_F(ControllerTest,aclCreditCallbacksTest)603 TEST_F(ControllerTest, aclCreditCallbacksTest) {
604   credits1_set = std::promise<void>();
605   credits2_set = std::promise<void>();
606 
607   auto credits1_set_future = credits1_set.get_future();
608   auto credits2_set_future = credits2_set.get_future();
609 
610   controller_->RegisterCompletedAclPacketsCallback(client_handler_->Bind(&CheckReceivedCredits));
611 
612   test_hci_layer_->IncomingCredit();
613 
614   ASSERT_EQ(std::future_status::ready, credits1_set_future.wait_for(2s));
615   ASSERT_EQ(std::future_status::ready, credits2_set_future.wait_for(2s));
616 }
617 
TEST_F(ControllerTest,aclCreditCallbackListenerUnregistered)618 TEST_F(ControllerTest, aclCreditCallbackListenerUnregistered) {
619   os::Thread thread("test_thread", os::Thread::Priority::NORMAL);
620   os::Handler handler(&thread);
621   controller_->RegisterCompletedAclPacketsCallback(handler.Bind(&CheckReceivedCredits));
622 
623   handler.Clear();
624   handler.WaitUntilStopped(std::chrono::milliseconds(100));
625   controller_->UnregisterCompletedAclPacketsCallback();
626 
627   test_hci_layer_->IncomingCredit();
628 }
629 
630 std::promise<uint64_t> le_rand_set;
631 
le_rand_callback(uint64_t random)632 void le_rand_callback(uint64_t random) {
633   le_rand_set.set_value(random);
634 }
635 
TEST_F(ControllerTest,leRandTest)636 TEST_F(ControllerTest, leRandTest) {
637   le_rand_set = std::promise<uint64_t>();
638   auto le_rand_set_future = le_rand_set.get_future();
639 
640   controller_->LeRand(client_handler_->BindOnce(le_rand_callback));
641 
642   ASSERT_EQ(std::future_status::ready, le_rand_set_future.wait_for(2s));
643   ASSERT_EQ(kRandomNumber, le_rand_set_future.get());
644 }
645 
TEST_F(ControllerTest,Dumpsys)646 TEST_F(ControllerTest, Dumpsys) {
647   ModuleDumper dumper(STDOUT_FILENO, fake_registry_, title);
648 
649   std::string output;
650   std::ostringstream oss;
651   dumper.DumpState(&output, oss);
652 
653   ASSERT_TRUE(output.find("Hci Controller Dumpsys") != std::string::npos);
654 }
655 
656 }  // namespace hci
657 }  // namespace bluetooth
658