• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2016 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 #define LOG_TAG "bluetooth_hidl_hal_test"
18 #include <android-base/logging.h>
19 
20 #include <android/hardware/bluetooth/1.0/IBluetoothHci.h>
21 #include <android/hardware/bluetooth/1.0/IBluetoothHciCallbacks.h>
22 #include <android/hardware/bluetooth/1.0/types.h>
23 #include <hardware/bluetooth.h>
24 #include <utils/Log.h>
25 
26 #include <VtsHalHidlTargetCallbackBase.h>
27 #include <VtsHalHidlTargetTestBase.h>
28 #include <VtsHalHidlTargetTestEnvBase.h>
29 
30 #include <chrono>
31 #include <queue>
32 #include <thread>
33 
34 using ::android::sp;
35 using ::android::hardware::hidl_death_recipient;
36 using ::android::hardware::hidl_vec;
37 using ::android::hardware::Return;
38 using ::android::hardware::Void;
39 using ::android::hardware::bluetooth::V1_0::IBluetoothHci;
40 using ::android::hardware::bluetooth::V1_0::IBluetoothHciCallbacks;
41 using ::android::hardware::bluetooth::V1_0::Status;
42 
43 #define HCI_MINIMUM_HCI_VERSION 5  // Bluetooth Core Specification 3.0 + HS
44 #define HCI_MINIMUM_LMP_VERSION 5  // Bluetooth Core Specification 3.0 + HS
45 #define NUM_HCI_COMMANDS_BANDWIDTH 1000
46 #define NUM_SCO_PACKETS_BANDWIDTH 1000
47 #define NUM_ACL_PACKETS_BANDWIDTH 1000
48 #define WAIT_FOR_INIT_TIMEOUT std::chrono::milliseconds(2000)
49 #define WAIT_FOR_HCI_EVENT_TIMEOUT std::chrono::milliseconds(2000)
50 #define WAIT_FOR_SCO_DATA_TIMEOUT std::chrono::milliseconds(1000)
51 #define WAIT_FOR_ACL_DATA_TIMEOUT std::chrono::milliseconds(1000)
52 #define INTERFACE_CLOSE_DELAY_MS std::chrono::milliseconds(200)
53 
54 #define COMMAND_HCI_SHOULD_BE_UNKNOWN \
55   { 0xff, 0x3B, 0x08, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07 }
56 #define COMMAND_HCI_READ_LOCAL_VERSION_INFORMATION \
57   { 0x01, 0x10, 0x00 }
58 #define COMMAND_HCI_READ_BUFFER_SIZE \
59   { 0x05, 0x10, 0x00 }
60 #define COMMAND_HCI_WRITE_LOOPBACK_MODE_LOCAL \
61   { 0x02, 0x18, 0x01, 0x01 }
62 #define COMMAND_HCI_RESET \
63   { 0x03, 0x0c, 0x00 }
64 #define COMMAND_HCI_WRITE_LOCAL_NAME \
65   { 0x13, 0x0c, 0xf8 }
66 #define HCI_STATUS_SUCCESS 0x00
67 #define HCI_STATUS_UNKNOWN_HCI_COMMAND 0x01
68 
69 #define EVENT_CONNECTION_COMPLETE 0x03
70 #define EVENT_COMMAND_COMPLETE 0x0e
71 #define EVENT_COMMAND_STATUS 0x0f
72 #define EVENT_NUMBER_OF_COMPLETED_PACKETS 0x13
73 #define EVENT_LOOPBACK_COMMAND 0x19
74 
75 #define EVENT_CODE_BYTE 0
76 #define EVENT_LENGTH_BYTE 1
77 #define EVENT_FIRST_PAYLOAD_BYTE 2
78 #define EVENT_COMMAND_STATUS_STATUS_BYTE 2
79 #define EVENT_COMMAND_STATUS_ALLOWED_PACKETS_BYTE 3
80 #define EVENT_COMMAND_STATUS_OPCODE_LSBYTE 4  // Bytes 4 and 5
81 #define EVENT_COMMAND_COMPLETE_ALLOWED_PACKETS_BYTE 2
82 #define EVENT_COMMAND_COMPLETE_OPCODE_LSBYTE 3  // Bytes 3 and 4
83 #define EVENT_COMMAND_COMPLETE_STATUS_BYTE 5
84 #define EVENT_COMMAND_COMPLETE_FIRST_PARAM_BYTE 6
85 #define EVENT_LOCAL_HCI_VERSION_BYTE EVENT_COMMAND_COMPLETE_FIRST_PARAM_BYTE
86 #define EVENT_LOCAL_LMP_VERSION_BYTE EVENT_LOCAL_HCI_VERSION_BYTE + 3
87 
88 #define EVENT_CONNECTION_COMPLETE_PARAM_LENGTH 11
89 #define EVENT_CONNECTION_COMPLETE_TYPE 11
90 #define EVENT_CONNECTION_COMPLETE_TYPE_SCO 0
91 #define EVENT_CONNECTION_COMPLETE_TYPE_ACL 1
92 #define EVENT_CONNECTION_COMPLETE_HANDLE_LSBYTE 3
93 #define EVENT_COMMAND_STATUS_LENGTH 4
94 
95 #define EVENT_NUMBER_OF_COMPLETED_PACKETS_NUM_HANDLES 2
96 
97 #define ACL_BROADCAST_FLAG_OFFSET 6
98 #define ACL_BROADCAST_FLAG_POINT_TO_POINT 0x0
99 #define ACL_BROADCAST_POINT_TO_POINT \
100   (ACL_BROADCAST_FLAG_POINT_TO_POINT << ACL_BROADCAST_FLAG_OFFSET)
101 
102 #define ACL_PACKET_BOUNDARY_FLAG_OFFSET 4
103 #define ACL_PACKET_BOUNDARY_FLAG_FIRST_AUTO_FLUSHABLE 0x2
104 #define ACL_PACKET_BOUNDARY_FIRST_AUTO_FLUSHABLE \
105   (ACL_PACKET_BOUNDARY_FLAG_FIRST_AUTO_FLUSHABLE \
106    << ACL_PACKET_BOUNDARY_FLAG_OFFSET)
107 
108 // To be removed in VTS release builds
109 #define ACL_HANDLE_QCA_DEBUG_MESSAGE 0xedc
110 
111 constexpr char kCallbackNameAclEventReceived[] = "aclDataReceived";
112 constexpr char kCallbackNameHciEventReceived[] = "hciEventReceived";
113 constexpr char kCallbackNameInitializationComplete[] = "initializationComplete";
114 constexpr char kCallbackNameScoEventReceived[] = "scoDataReceived";
115 
116 class ThroughputLogger {
117  public:
ThroughputLogger(std::string task)118   ThroughputLogger(std::string task)
119       : task_(task), start_time_(std::chrono::steady_clock::now()) {}
120 
~ThroughputLogger()121   ~ThroughputLogger() {
122     if (total_bytes_ == 0) return;
123     std::chrono::duration<double> duration =
124         std::chrono::steady_clock::now() - start_time_;
125     double s = duration.count();
126     if (s == 0) return;
127     double rate_kb = (static_cast<double>(total_bytes_) / s) / 1024;
128     ALOGD("%s %.1f KB/s (%zu bytes in %.3fs)", task_.c_str(), rate_kb,
129           total_bytes_, s);
130   }
131 
setTotalBytes(size_t total_bytes)132   void setTotalBytes(size_t total_bytes) { total_bytes_ = total_bytes; }
133 
134  private:
135   size_t total_bytes_;
136   std::string task_;
137   std::chrono::steady_clock::time_point start_time_;
138 };
139 
140 // Test environment for Bluetooth HIDL HAL.
141 class BluetoothHidlEnvironment : public ::testing::VtsHalHidlTargetTestEnvBase {
142  public:
143   // get the test environment singleton
Instance()144   static BluetoothHidlEnvironment* Instance() {
145     static BluetoothHidlEnvironment* instance = new BluetoothHidlEnvironment;
146     return instance;
147   }
148 
registerTestServices()149   virtual void registerTestServices() override {
150     registerTestService<IBluetoothHci>();
151   }
152 
153  private:
BluetoothHidlEnvironment()154   BluetoothHidlEnvironment() {}
155 };
156 
157 // The main test class for Bluetooth HIDL HAL.
158 class BluetoothHidlTest : public ::testing::VtsHalHidlTargetTestBase {
159  public:
SetUp()160   virtual void SetUp() override {
161     // currently test passthrough mode only
162     bluetooth =
163         ::testing::VtsHalHidlTargetTestBase::getService<IBluetoothHci>();
164     ASSERT_NE(bluetooth, nullptr);
165     ALOGI("%s: getService() for bluetooth is %s", __func__,
166           bluetooth->isRemote() ? "remote" : "local");
167 
168     bluetooth_hci_death_recipient = new BluetoothHciDeathRecipient();
169     ASSERT_NE(bluetooth_hci_death_recipient, nullptr);
170     ASSERT_TRUE(
171         bluetooth->linkToDeath(bluetooth_hci_death_recipient, 0).isOk());
172 
173     bluetooth_cb = new BluetoothHciCallbacks(*this);
174     ASSERT_NE(bluetooth_cb, nullptr);
175 
176     max_acl_data_packet_length = 0;
177     max_sco_data_packet_length = 0;
178     max_acl_data_packets = 0;
179     max_sco_data_packets = 0;
180 
181     initialized = false;
182     event_cb_count = 0;
183     acl_cb_count = 0;
184     sco_cb_count = 0;
185 
186     ASSERT_FALSE(initialized);
187     // Should not be checked in production code
188     ASSERT_TRUE(bluetooth->initialize(bluetooth_cb).isOk());
189 
190     bluetooth_cb->SetWaitTimeout(kCallbackNameInitializationComplete,
191                                  WAIT_FOR_INIT_TIMEOUT);
192     bluetooth_cb->SetWaitTimeout(kCallbackNameHciEventReceived,
193                                  WAIT_FOR_HCI_EVENT_TIMEOUT);
194     bluetooth_cb->SetWaitTimeout(kCallbackNameAclEventReceived,
195                                  WAIT_FOR_ACL_DATA_TIMEOUT);
196     bluetooth_cb->SetWaitTimeout(kCallbackNameScoEventReceived,
197                                  WAIT_FOR_SCO_DATA_TIMEOUT);
198 
199     EXPECT_TRUE(
200         bluetooth_cb->WaitForCallback(kCallbackNameInitializationComplete)
201             .no_timeout);
202 
203     ASSERT_TRUE(initialized);
204   }
205 
TearDown()206   virtual void TearDown() override {
207     ALOGI("TearDown");
208     // Should not be checked in production code
209     ASSERT_TRUE(bluetooth->close().isOk());
210     std::this_thread::sleep_for(INTERFACE_CLOSE_DELAY_MS);
211     handle_no_ops();
212     EXPECT_EQ(static_cast<size_t>(0), event_queue.size());
213     EXPECT_EQ(static_cast<size_t>(0), sco_queue.size());
214     EXPECT_EQ(static_cast<size_t>(0), acl_queue.size());
215   }
216 
217   void setBufferSizes();
218 
219   // Functions called from within tests in loopback mode
220   void sendAndCheckHCI(int num_packets);
221   void sendAndCheckSCO(int num_packets, size_t size, uint16_t handle);
222   void sendAndCheckACL(int num_packets, size_t size, uint16_t handle);
223 
224   // Helper functions to try to get a handle on verbosity
225   void enterLoopbackMode(std::vector<uint16_t>& sco_handles,
226                          std::vector<uint16_t>& acl_handles);
227   void handle_no_ops();
228   void wait_for_event(bool timeout_is_error);
229   void wait_for_command_complete_event(hidl_vec<uint8_t> cmd);
230   int wait_for_completed_packets_event(uint16_t handle);
231 
232   class BluetoothHciDeathRecipient : public hidl_death_recipient {
233    public:
serviceDied(uint64_t,const android::wp<::android::hidl::base::V1_0::IBase> &)234     void serviceDied(
235         uint64_t /*cookie*/,
236         const android::wp<::android::hidl::base::V1_0::IBase>& /*who*/)
237         override {
238       FAIL();
239     }
240   };
241 
242   // A simple test implementation of BluetoothHciCallbacks.
243   class BluetoothHciCallbacks
244       : public ::testing::VtsHalHidlTargetCallbackBase<BluetoothHidlTest>,
245         public IBluetoothHciCallbacks {
246     BluetoothHidlTest& parent_;
247 
248    public:
BluetoothHciCallbacks(BluetoothHidlTest & parent)249     BluetoothHciCallbacks(BluetoothHidlTest& parent) : parent_(parent){};
250 
251     virtual ~BluetoothHciCallbacks() = default;
252 
initializationComplete(Status status)253     Return<void> initializationComplete(Status status) override {
254       parent_.initialized = (status == Status::SUCCESS);
255       NotifyFromCallback(kCallbackNameInitializationComplete);
256       ALOGV("%s (status = %d)", __func__, static_cast<int>(status));
257       return Void();
258     };
259 
hciEventReceived(const::android::hardware::hidl_vec<uint8_t> & event)260     Return<void> hciEventReceived(
261         const ::android::hardware::hidl_vec<uint8_t>& event) override {
262       parent_.event_cb_count++;
263       parent_.event_queue.push(event);
264       NotifyFromCallback(kCallbackNameHciEventReceived);
265       ALOGV("Event received (length = %d)", static_cast<int>(event.size()));
266       return Void();
267     };
268 
aclDataReceived(const::android::hardware::hidl_vec<uint8_t> & data)269     Return<void> aclDataReceived(
270         const ::android::hardware::hidl_vec<uint8_t>& data) override {
271       parent_.acl_cb_count++;
272       parent_.acl_queue.push(data);
273       NotifyFromCallback(kCallbackNameAclEventReceived);
274       return Void();
275     };
276 
scoDataReceived(const::android::hardware::hidl_vec<uint8_t> & data)277     Return<void> scoDataReceived(
278         const ::android::hardware::hidl_vec<uint8_t>& data) override {
279       parent_.sco_cb_count++;
280       parent_.sco_queue.push(data);
281       NotifyFromCallback(kCallbackNameScoEventReceived);
282       return Void();
283     };
284   };
285 
286   sp<IBluetoothHci> bluetooth;
287   sp<BluetoothHciCallbacks> bluetooth_cb;
288   sp<BluetoothHciDeathRecipient> bluetooth_hci_death_recipient;
289   std::queue<hidl_vec<uint8_t>> event_queue;
290   std::queue<hidl_vec<uint8_t>> acl_queue;
291   std::queue<hidl_vec<uint8_t>> sco_queue;
292 
293   bool initialized;
294 
295   int event_cb_count;
296   int sco_cb_count;
297   int acl_cb_count;
298 
299   int max_acl_data_packet_length;
300   int max_sco_data_packet_length;
301   int max_acl_data_packets;
302   int max_sco_data_packets;
303 };
304 
305 // Discard NO-OPs from the event queue.
handle_no_ops()306 void BluetoothHidlTest::handle_no_ops() {
307   while (event_queue.size() > 0) {
308     hidl_vec<uint8_t> event = event_queue.front();
309     EXPECT_GE(event.size(),
310               static_cast<size_t>(EVENT_COMMAND_COMPLETE_STATUS_BYTE));
311     bool event_is_no_op =
312         (event[EVENT_CODE_BYTE] == EVENT_COMMAND_COMPLETE) &&
313         (event[EVENT_COMMAND_COMPLETE_OPCODE_LSBYTE] == 0x00) &&
314         (event[EVENT_COMMAND_COMPLETE_OPCODE_LSBYTE + 1] == 0x00);
315     event_is_no_op |= (event[EVENT_CODE_BYTE] == EVENT_COMMAND_STATUS) &&
316                       (event[EVENT_COMMAND_STATUS_OPCODE_LSBYTE] == 0x00) &&
317                       (event[EVENT_COMMAND_STATUS_OPCODE_LSBYTE + 1] == 0x00);
318     if (event_is_no_op) {
319       event_queue.pop();
320     } else {
321       break;
322     }
323   }
324   // To be removed in VTS release builds
325   while (acl_queue.size() > 0) {
326     hidl_vec<uint8_t> acl_packet = acl_queue.front();
327     uint16_t connection_handle = acl_packet[1] & 0xF;
328     connection_handle <<= 8;
329     connection_handle |= acl_packet[0];
330     bool packet_is_no_op = connection_handle == ACL_HANDLE_QCA_DEBUG_MESSAGE;
331     if (packet_is_no_op) {
332       acl_queue.pop();
333     } else {
334       break;
335     }
336   }
337 }
338 
339 // Receive an event, discarding NO-OPs.
wait_for_event(bool timeout_is_error=true)340 void BluetoothHidlTest::wait_for_event(bool timeout_is_error = true) {
341   hidl_vec<uint8_t> event;
342   do {
343     bool no_timeout =
344         bluetooth_cb->WaitForCallback(kCallbackNameHciEventReceived).no_timeout;
345     EXPECT_TRUE(no_timeout || !timeout_is_error);
346     if (no_timeout && timeout_is_error) {
347       EXPECT_LT(static_cast<size_t>(0), event_queue.size());
348     }
349     if (event_queue.size() == 0) {
350       // WaitForCallback timed out.
351       return;
352     }
353     handle_no_ops();
354   } while (event_queue.size() == 0);
355 }
356 
357 // Wait until a COMMAND_COMPLETE is received.
wait_for_command_complete_event(hidl_vec<uint8_t> cmd)358 void BluetoothHidlTest::wait_for_command_complete_event(hidl_vec<uint8_t> cmd) {
359   wait_for_event();
360   hidl_vec<uint8_t> event = event_queue.front();
361   event_queue.pop();
362 
363   EXPECT_GT(event.size(),
364             static_cast<size_t>(EVENT_COMMAND_COMPLETE_STATUS_BYTE));
365   EXPECT_EQ(EVENT_COMMAND_COMPLETE, event[EVENT_CODE_BYTE]);
366   EXPECT_EQ(cmd[0], event[EVENT_COMMAND_COMPLETE_OPCODE_LSBYTE]);
367   EXPECT_EQ(cmd[1], event[EVENT_COMMAND_COMPLETE_OPCODE_LSBYTE + 1]);
368   EXPECT_EQ(HCI_STATUS_SUCCESS, event[EVENT_COMMAND_COMPLETE_STATUS_BYTE]);
369 }
370 
371 // Send the command to read the controller's buffer sizes.
setBufferSizes()372 void BluetoothHidlTest::setBufferSizes() {
373   hidl_vec<uint8_t> cmd = COMMAND_HCI_READ_BUFFER_SIZE;
374   bluetooth->sendHciCommand(cmd);
375 
376   wait_for_event();
377   if (event_queue.size() == 0) return;
378 
379   hidl_vec<uint8_t> event = event_queue.front();
380   event_queue.pop();
381 
382   EXPECT_EQ(EVENT_COMMAND_COMPLETE, event[EVENT_CODE_BYTE]);
383   EXPECT_EQ(cmd[0], event[EVENT_COMMAND_COMPLETE_OPCODE_LSBYTE]);
384   EXPECT_EQ(cmd[1], event[EVENT_COMMAND_COMPLETE_OPCODE_LSBYTE + 1]);
385   EXPECT_EQ(HCI_STATUS_SUCCESS, event[EVENT_COMMAND_COMPLETE_STATUS_BYTE]);
386 
387   max_acl_data_packet_length =
388       event[EVENT_COMMAND_COMPLETE_STATUS_BYTE + 1] +
389       (event[EVENT_COMMAND_COMPLETE_STATUS_BYTE + 2] << 8);
390   max_sco_data_packet_length = event[EVENT_COMMAND_COMPLETE_STATUS_BYTE + 3];
391   max_acl_data_packets = event[EVENT_COMMAND_COMPLETE_STATUS_BYTE + 4] +
392                          (event[EVENT_COMMAND_COMPLETE_STATUS_BYTE + 5] << 8);
393   max_sco_data_packets = event[EVENT_COMMAND_COMPLETE_STATUS_BYTE + 6] +
394                          (event[EVENT_COMMAND_COMPLETE_STATUS_BYTE + 7] << 8);
395 
396   ALOGD("%s: ACL max %d num %d SCO max %d num %d", __func__,
397         static_cast<int>(max_acl_data_packet_length),
398         static_cast<int>(max_acl_data_packets),
399         static_cast<int>(max_sco_data_packet_length),
400         static_cast<int>(max_sco_data_packets));
401 }
402 
403 // Send an HCI command (in Loopback mode) and check the response.
sendAndCheckHCI(int num_packets)404 void BluetoothHidlTest::sendAndCheckHCI(int num_packets) {
405   ThroughputLogger logger = {__func__};
406   int command_size = 0;
407   for (int n = 0; n < num_packets; n++) {
408     // Send an HCI packet
409     std::vector<uint8_t> write_name = COMMAND_HCI_WRITE_LOCAL_NAME;
410     // With a name
411     char new_name[] = "John Jacob Jingleheimer Schmidt ___________________0";
412     size_t new_name_length = strlen(new_name);
413     for (size_t i = 0; i < new_name_length; i++)
414       write_name.push_back(static_cast<uint8_t>(new_name[i]));
415     // And the packet number
416     size_t i = new_name_length - 1;
417     for (int digits = n; digits > 0; digits = digits / 10, i--)
418       write_name[i] = static_cast<uint8_t>('0' + digits % 10);
419     // And padding
420     for (size_t i = 0; i < 248 - new_name_length; i++)
421       write_name.push_back(static_cast<uint8_t>(0));
422 
423     hidl_vec<uint8_t> cmd = write_name;
424     bluetooth->sendHciCommand(cmd);
425 
426     // Check the loopback of the HCI packet
427     wait_for_event();
428     if (event_queue.size() == 0) return;
429 
430     hidl_vec<uint8_t> event = event_queue.front();
431     event_queue.pop();
432     size_t compare_length =
433         (cmd.size() > static_cast<size_t>(0xff) ? static_cast<size_t>(0xff)
434                                                 : cmd.size());
435     EXPECT_GT(event.size(), compare_length + EVENT_FIRST_PAYLOAD_BYTE - 1);
436 
437     EXPECT_EQ(EVENT_LOOPBACK_COMMAND, event[EVENT_CODE_BYTE]);
438     EXPECT_EQ(compare_length, event[EVENT_LENGTH_BYTE]);
439 
440     // Don't compare past the end of the event.
441     if (compare_length + EVENT_FIRST_PAYLOAD_BYTE > event.size()) {
442       compare_length = event.size() - EVENT_FIRST_PAYLOAD_BYTE;
443       ALOGE("Only comparing %d bytes", static_cast<int>(compare_length));
444     }
445 
446     if (n == num_packets - 1) {
447       command_size = cmd.size();
448     }
449 
450     for (size_t i = 0; i < compare_length; i++)
451       EXPECT_EQ(cmd[i], event[EVENT_FIRST_PAYLOAD_BYTE + i]);
452   }
453   logger.setTotalBytes(command_size * num_packets * 2);
454 }
455 
456 // Send a SCO data packet (in Loopback mode) and check the response.
sendAndCheckSCO(int num_packets,size_t size,uint16_t handle)457 void BluetoothHidlTest::sendAndCheckSCO(int num_packets, size_t size,
458                                         uint16_t handle) {
459   ThroughputLogger logger = {__func__};
460   for (int n = 0; n < num_packets; n++) {
461     // Send a SCO packet
462     hidl_vec<uint8_t> sco_packet;
463     std::vector<uint8_t> sco_vector;
464     sco_vector.push_back(static_cast<uint8_t>(handle & 0xff));
465     sco_vector.push_back(static_cast<uint8_t>((handle & 0x0f00) >> 8));
466     sco_vector.push_back(static_cast<uint8_t>(size & 0xff));
467     sco_vector.push_back(static_cast<uint8_t>((size & 0xff00) >> 8));
468     for (size_t i = 0; i < size; i++) {
469       sco_vector.push_back(static_cast<uint8_t>(i + n));
470     }
471     sco_packet = sco_vector;
472     bluetooth->sendScoData(sco_vector);
473 
474     // Check the loopback of the SCO packet
475     EXPECT_TRUE(bluetooth_cb->WaitForCallback(kCallbackNameScoEventReceived)
476                     .no_timeout);
477     hidl_vec<uint8_t> sco_loopback = sco_queue.front();
478     sco_queue.pop();
479 
480     EXPECT_EQ(sco_packet.size(), sco_loopback.size());
481     size_t successful_bytes = 0;
482 
483     for (size_t i = 0; i < sco_packet.size(); i++) {
484       if (sco_packet[i] == sco_loopback[i]) {
485         successful_bytes = i;
486       } else {
487         ALOGE("Miscompare at %d (expected %x, got %x)", static_cast<int>(i),
488               sco_packet[i], sco_loopback[i]);
489         ALOGE("At %d (expected %x, got %x)", static_cast<int>(i + 1),
490               sco_packet[i + 1], sco_loopback[i + 1]);
491         break;
492       }
493     }
494     EXPECT_EQ(sco_packet.size(), successful_bytes + 1);
495   }
496   logger.setTotalBytes(num_packets * size * 2);
497 }
498 
499 // Send an ACL data packet (in Loopback mode) and check the response.
sendAndCheckACL(int num_packets,size_t size,uint16_t handle)500 void BluetoothHidlTest::sendAndCheckACL(int num_packets, size_t size,
501                                         uint16_t handle) {
502   ThroughputLogger logger = {__func__};
503   for (int n = 0; n < num_packets; n++) {
504     // Send an ACL packet
505     hidl_vec<uint8_t> acl_packet;
506     std::vector<uint8_t> acl_vector;
507     acl_vector.push_back(static_cast<uint8_t>(handle & 0xff));
508     acl_vector.push_back(static_cast<uint8_t>((handle & 0x0f00) >> 8) |
509                          ACL_BROADCAST_POINT_TO_POINT |
510                          ACL_PACKET_BOUNDARY_FIRST_AUTO_FLUSHABLE);
511     acl_vector.push_back(static_cast<uint8_t>(size & 0xff));
512     acl_vector.push_back(static_cast<uint8_t>((size & 0xff00) >> 8));
513     for (size_t i = 0; i < size; i++) {
514       acl_vector.push_back(static_cast<uint8_t>(i + n));
515     }
516     acl_packet = acl_vector;
517     bluetooth->sendAclData(acl_vector);
518 
519     // Check the loopback of the ACL packet
520     EXPECT_TRUE(bluetooth_cb->WaitForCallback(kCallbackNameAclEventReceived)
521                     .no_timeout);
522     hidl_vec<uint8_t> acl_loopback = acl_queue.front();
523     acl_queue.pop();
524 
525     EXPECT_EQ(acl_packet.size(), acl_loopback.size());
526     size_t successful_bytes = 0;
527 
528     for (size_t i = 0; i < acl_packet.size(); i++) {
529       if (acl_packet[i] == acl_loopback[i]) {
530         successful_bytes = i;
531       } else {
532         ALOGE("Miscompare at %d (expected %x, got %x)", static_cast<int>(i),
533               acl_packet[i], acl_loopback[i]);
534         ALOGE("At %d (expected %x, got %x)", static_cast<int>(i + 1),
535               acl_packet[i + 1], acl_loopback[i + 1]);
536         break;
537       }
538     }
539     EXPECT_EQ(acl_packet.size(), successful_bytes + 1);
540   }
541   logger.setTotalBytes(num_packets * size * 2);
542 }
543 
544 // Return the number of completed packets reported by the controller.
wait_for_completed_packets_event(uint16_t handle)545 int BluetoothHidlTest::wait_for_completed_packets_event(uint16_t handle) {
546   int packets_processed = 0;
547   wait_for_event(false);
548   if (event_queue.size() == 0) {
549     ALOGW("%s: WaitForCallback timed out.", __func__);
550     return packets_processed;
551   }
552   while (event_queue.size() > 0) {
553     hidl_vec<uint8_t> event = event_queue.front();
554     event_queue.pop();
555 
556     EXPECT_EQ(EVENT_NUMBER_OF_COMPLETED_PACKETS, event[EVENT_CODE_BYTE]);
557     EXPECT_EQ(1, event[EVENT_NUMBER_OF_COMPLETED_PACKETS_NUM_HANDLES]);
558 
559     uint16_t event_handle = event[3] + (event[4] << 8);
560     EXPECT_EQ(handle, event_handle);
561 
562     packets_processed += event[5] + (event[6] << 8);
563   }
564   return packets_processed;
565 }
566 
567 // Send local loopback command and initialize SCO and ACL handles.
enterLoopbackMode(std::vector<uint16_t> & sco_handles,std::vector<uint16_t> & acl_handles)568 void BluetoothHidlTest::enterLoopbackMode(std::vector<uint16_t>& sco_handles,
569                                           std::vector<uint16_t>& acl_handles) {
570   hidl_vec<uint8_t> cmd = COMMAND_HCI_WRITE_LOOPBACK_MODE_LOCAL;
571   bluetooth->sendHciCommand(cmd);
572 
573   // Receive connection complete events with data channels
574   int connection_event_count = 0;
575   bool command_complete_received = false;
576   while (true) {
577     wait_for_event(false);
578     if (event_queue.size() == 0) {
579       // Fail if there was no event received or no connections completed.
580       EXPECT_TRUE(command_complete_received);
581       EXPECT_LT(0, connection_event_count);
582       return;
583     }
584     hidl_vec<uint8_t> event = event_queue.front();
585     event_queue.pop();
586     EXPECT_GT(event.size(),
587               static_cast<size_t>(EVENT_COMMAND_COMPLETE_STATUS_BYTE));
588     if (event[EVENT_CODE_BYTE] == EVENT_CONNECTION_COMPLETE) {
589       EXPECT_GT(event.size(),
590                 static_cast<size_t>(EVENT_CONNECTION_COMPLETE_TYPE));
591       EXPECT_EQ(event[EVENT_LENGTH_BYTE],
592                 EVENT_CONNECTION_COMPLETE_PARAM_LENGTH);
593       uint8_t connection_type = event[EVENT_CONNECTION_COMPLETE_TYPE];
594 
595       EXPECT_TRUE(connection_type == EVENT_CONNECTION_COMPLETE_TYPE_SCO ||
596                   connection_type == EVENT_CONNECTION_COMPLETE_TYPE_ACL);
597 
598       // Save handles
599       uint16_t handle = event[EVENT_CONNECTION_COMPLETE_HANDLE_LSBYTE] |
600                         event[EVENT_CONNECTION_COMPLETE_HANDLE_LSBYTE + 1] << 8;
601       if (connection_type == EVENT_CONNECTION_COMPLETE_TYPE_SCO)
602         sco_handles.push_back(handle);
603       else
604         acl_handles.push_back(handle);
605 
606       ALOGD("Connect complete type = %d handle = %d",
607             event[EVENT_CONNECTION_COMPLETE_TYPE], handle);
608       connection_event_count++;
609     } else {
610       EXPECT_EQ(EVENT_COMMAND_COMPLETE, event[EVENT_CODE_BYTE]);
611       EXPECT_EQ(cmd[0], event[EVENT_COMMAND_COMPLETE_OPCODE_LSBYTE]);
612       EXPECT_EQ(cmd[1], event[EVENT_COMMAND_COMPLETE_OPCODE_LSBYTE + 1]);
613       EXPECT_EQ(HCI_STATUS_SUCCESS, event[EVENT_COMMAND_COMPLETE_STATUS_BYTE]);
614       command_complete_received = true;
615     }
616   }
617 }
618 
619 // Empty test: Initialize()/Close() are called in SetUp()/TearDown().
TEST_F(BluetoothHidlTest,InitializeAndClose)620 TEST_F(BluetoothHidlTest, InitializeAndClose) {}
621 
622 // Send an HCI Reset with sendHciCommand and wait for a command complete event.
TEST_F(BluetoothHidlTest,HciReset)623 TEST_F(BluetoothHidlTest, HciReset) {
624   hidl_vec<uint8_t> cmd = COMMAND_HCI_RESET;
625   bluetooth->sendHciCommand(cmd);
626 
627   wait_for_command_complete_event(cmd);
628 }
629 
630 // Read and check the HCI version of the controller.
TEST_F(BluetoothHidlTest,HciVersionTest)631 TEST_F(BluetoothHidlTest, HciVersionTest) {
632   hidl_vec<uint8_t> cmd = COMMAND_HCI_READ_LOCAL_VERSION_INFORMATION;
633   bluetooth->sendHciCommand(cmd);
634 
635   wait_for_event();
636   if (event_queue.size() == 0) return;
637 
638   hidl_vec<uint8_t> event = event_queue.front();
639   event_queue.pop();
640   EXPECT_GT(event.size(), static_cast<size_t>(EVENT_LOCAL_LMP_VERSION_BYTE));
641 
642   EXPECT_EQ(EVENT_COMMAND_COMPLETE, event[EVENT_CODE_BYTE]);
643   EXPECT_EQ(cmd[0], event[EVENT_COMMAND_COMPLETE_OPCODE_LSBYTE]);
644   EXPECT_EQ(cmd[1], event[EVENT_COMMAND_COMPLETE_OPCODE_LSBYTE + 1]);
645   EXPECT_EQ(HCI_STATUS_SUCCESS, event[EVENT_COMMAND_COMPLETE_STATUS_BYTE]);
646 
647   EXPECT_LE(HCI_MINIMUM_HCI_VERSION, event[EVENT_LOCAL_HCI_VERSION_BYTE]);
648   EXPECT_LE(HCI_MINIMUM_LMP_VERSION, event[EVENT_LOCAL_LMP_VERSION_BYTE]);
649 }
650 
651 // Send an unknown HCI command and wait for the error message.
TEST_F(BluetoothHidlTest,HciUnknownCommand)652 TEST_F(BluetoothHidlTest, HciUnknownCommand) {
653   hidl_vec<uint8_t> cmd = COMMAND_HCI_SHOULD_BE_UNKNOWN;
654   bluetooth->sendHciCommand(cmd);
655 
656   wait_for_event();
657   if (event_queue.size() == 0) return;
658 
659   hidl_vec<uint8_t> event = event_queue.front();
660   event_queue.pop();
661 
662   EXPECT_GT(event.size(),
663             static_cast<size_t>(EVENT_COMMAND_COMPLETE_STATUS_BYTE));
664   if (event[EVENT_CODE_BYTE] == EVENT_COMMAND_COMPLETE) {
665     EXPECT_EQ(cmd[0], event[EVENT_COMMAND_COMPLETE_OPCODE_LSBYTE]);
666     EXPECT_EQ(cmd[1], event[EVENT_COMMAND_COMPLETE_OPCODE_LSBYTE + 1]);
667     EXPECT_EQ(HCI_STATUS_UNKNOWN_HCI_COMMAND,
668               event[EVENT_COMMAND_COMPLETE_STATUS_BYTE]);
669   } else {
670     EXPECT_EQ(EVENT_COMMAND_STATUS, event[EVENT_CODE_BYTE]);
671     EXPECT_EQ(cmd[0], event[EVENT_COMMAND_STATUS_OPCODE_LSBYTE]);
672     EXPECT_EQ(cmd[1], event[EVENT_COMMAND_STATUS_OPCODE_LSBYTE + 1]);
673     EXPECT_EQ(HCI_STATUS_UNKNOWN_HCI_COMMAND,
674               event[EVENT_COMMAND_STATUS_STATUS_BYTE]);
675   }
676 }
677 
678 // Enter loopback mode, but don't send any packets.
TEST_F(BluetoothHidlTest,WriteLoopbackMode)679 TEST_F(BluetoothHidlTest, WriteLoopbackMode) {
680   std::vector<uint16_t> sco_connection_handles;
681   std::vector<uint16_t> acl_connection_handles;
682   enterLoopbackMode(sco_connection_handles, acl_connection_handles);
683 }
684 
685 // Enter loopback mode and send single packets.
TEST_F(BluetoothHidlTest,LoopbackModeSinglePackets)686 TEST_F(BluetoothHidlTest, LoopbackModeSinglePackets) {
687   setBufferSizes();
688 
689   std::vector<uint16_t> sco_connection_handles;
690   std::vector<uint16_t> acl_connection_handles;
691   enterLoopbackMode(sco_connection_handles, acl_connection_handles);
692 
693   sendAndCheckHCI(1);
694 
695   // This should work, but breaks on some current platforms.  Figure out how to
696   // grandfather older devices but test new ones.
697   if (0 && sco_connection_handles.size() > 0) {
698     EXPECT_LT(0, max_sco_data_packet_length);
699     sendAndCheckSCO(1, max_sco_data_packet_length, sco_connection_handles[0]);
700     int sco_packets_sent = 1;
701     int completed_packets =
702         wait_for_completed_packets_event(sco_connection_handles[0]);
703     if (sco_packets_sent != completed_packets) {
704       ALOGW("%s: packets_sent (%d) != completed_packets (%d)", __func__,
705             sco_packets_sent, completed_packets);
706     }
707   }
708 
709   if (acl_connection_handles.size() > 0) {
710     EXPECT_LT(0, max_acl_data_packet_length);
711     sendAndCheckACL(1, max_acl_data_packet_length, acl_connection_handles[0]);
712     int acl_packets_sent = 1;
713     int completed_packets =
714         wait_for_completed_packets_event(acl_connection_handles[0]);
715     if (acl_packets_sent != completed_packets) {
716       ALOGW("%s: packets_sent (%d) != completed_packets (%d)", __func__,
717             acl_packets_sent, completed_packets);
718     }
719   }
720 }
721 
722 // Enter loopback mode and send packets for bandwidth measurements.
TEST_F(BluetoothHidlTest,LoopbackModeBandwidth)723 TEST_F(BluetoothHidlTest, LoopbackModeBandwidth) {
724   setBufferSizes();
725 
726   std::vector<uint16_t> sco_connection_handles;
727   std::vector<uint16_t> acl_connection_handles;
728   enterLoopbackMode(sco_connection_handles, acl_connection_handles);
729 
730   sendAndCheckHCI(NUM_HCI_COMMANDS_BANDWIDTH);
731 
732   // This should work, but breaks on some current platforms.  Figure out how to
733   // grandfather older devices but test new ones.
734   if (0 && sco_connection_handles.size() > 0) {
735     EXPECT_LT(0, max_sco_data_packet_length);
736     sendAndCheckSCO(NUM_SCO_PACKETS_BANDWIDTH, max_sco_data_packet_length,
737                     sco_connection_handles[0]);
738     int sco_packets_sent = NUM_SCO_PACKETS_BANDWIDTH;
739     int completed_packets =
740         wait_for_completed_packets_event(sco_connection_handles[0]);
741     if (sco_packets_sent != completed_packets) {
742       ALOGW("%s: packets_sent (%d) != completed_packets (%d)", __func__,
743             sco_packets_sent, completed_packets);
744     }
745   }
746 
747   if (acl_connection_handles.size() > 0) {
748     EXPECT_LT(0, max_acl_data_packet_length);
749     sendAndCheckACL(NUM_ACL_PACKETS_BANDWIDTH, max_acl_data_packet_length,
750                     acl_connection_handles[0]);
751     int acl_packets_sent = NUM_ACL_PACKETS_BANDWIDTH;
752     int completed_packets =
753         wait_for_completed_packets_event(acl_connection_handles[0]);
754     if (acl_packets_sent != completed_packets) {
755       ALOGW("%s: packets_sent (%d) != completed_packets (%d)", __func__,
756             acl_packets_sent, completed_packets);
757     }
758   }
759 }
760 
main(int argc,char ** argv)761 int main(int argc, char** argv) {
762   ::testing::AddGlobalTestEnvironment(BluetoothHidlEnvironment::Instance());
763   ::testing::InitGoogleTest(&argc, argv);
764   BluetoothHidlEnvironment::Instance()->init(&argc, argv);
765   int status = RUN_ALL_TESTS();
766   ALOGI("Test result = %d", status);
767   return status;
768 }
769