• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //
2 // Copyright 2015 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 "dual_mode_controller"
18 
19 #include "dual_mode_controller.h"
20 
21 #include <memory>
22 
23 #include <base/logging.h>
24 #include "base/files/file_util.h"
25 #include "base/json/json_reader.h"
26 #include "base/values.h"
27 #include "event_packet.h"
28 
29 #include "osi/include/log.h"
30 #include "osi/include/osi.h"
31 #include "stack/include/hcidefs.h"
32 
33 using std::vector;
34 
35 namespace {
36 
37 // Included in certain events to indicate success (specific to the event
38 // context).
39 const uint8_t kSuccessStatus = 0;
40 
41 const uint8_t kUnknownHciCommand = 1;
42 
43 // The location of the config file loaded to populate controller attributes.
44 const std::string kControllerPropertiesFile =
45     "/etc/bluetooth/controller_properties.json";
46 
47 // Inquiry modes for specifiying inquiry result formats.
48 const uint8_t kStandardInquiry = 0x00;
49 const uint8_t kRssiInquiry = 0x01;
50 const uint8_t kExtendedOrRssiInquiry = 0x02;
51 
52 // The bd address of another (fake) device.
53 const vector<uint8_t> kOtherDeviceBdAddress = {6, 5, 4, 3, 2, 1};
54 
LogCommand(const char * command)55 void LogCommand(const char* command) {
56   LOG_INFO(LOG_TAG, "Controller performing command: %s", command);
57 }
58 
59 // Functions used by JSONValueConverter to read stringified JSON into Properties
60 // object.
ParseUint8t(const base::StringPiece & value,uint8_t * field)61 bool ParseUint8t(const base::StringPiece& value, uint8_t* field) {
62   *field = std::stoi(value.as_string());
63   return true;
64 }
65 
ParseUint16t(const base::StringPiece & value,uint16_t * field)66 bool ParseUint16t(const base::StringPiece& value, uint16_t* field) {
67   *field = std::stoi(value.as_string());
68   return true;
69 }
70 
71 }  // namespace
72 
73 namespace test_vendor_lib {
74 
AddControllerEvent(std::chrono::milliseconds delay,const TaskCallback & task)75 void DualModeController::AddControllerEvent(std::chrono::milliseconds delay,
76                                             const TaskCallback& task) {
77   controller_events_.push_back(schedule_task_(delay, task));
78 }
79 
SendCommandCompleteSuccess(uint16_t command_opcode) const80 void DualModeController::SendCommandCompleteSuccess(
81     uint16_t command_opcode) const {
82   send_event_(EventPacket::CreateCommandCompleteOnlyStatusEvent(
83       command_opcode, kSuccessStatus));
84 }
85 
SendCommandCompleteOnlyStatus(uint16_t command_opcode,uint8_t status) const86 void DualModeController::SendCommandCompleteOnlyStatus(uint16_t command_opcode,
87                                                        uint8_t status) const {
88   send_event_(EventPacket::CreateCommandCompleteOnlyStatusEvent(command_opcode,
89                                                                 status));
90 }
91 
SendCommandStatus(uint8_t status,uint16_t command_opcode) const92 void DualModeController::SendCommandStatus(uint8_t status,
93                                            uint16_t command_opcode) const {
94   send_event_(EventPacket::CreateCommandStatusEvent(status, command_opcode));
95 }
96 
SendCommandStatusSuccess(uint16_t command_opcode) const97 void DualModeController::SendCommandStatusSuccess(
98     uint16_t command_opcode) const {
99   SendCommandStatus(kSuccessStatus, command_opcode);
100 }
101 
DualModeController()102 DualModeController::DualModeController()
103     : state_(kStandby),
104       properties_(kControllerPropertiesFile),
105       test_channel_state_(kNone) {
106 #define SET_HANDLER(opcode, method)                                     \
107   active_hci_commands_[opcode] = [this](const vector<uint8_t>& param) { \
108     method(param);                                                      \
109   };
110   SET_HANDLER(HCI_RESET, HciReset);
111   SET_HANDLER(HCI_READ_BUFFER_SIZE, HciReadBufferSize);
112   SET_HANDLER(HCI_HOST_BUFFER_SIZE, HciHostBufferSize);
113   SET_HANDLER(HCI_READ_LOCAL_VERSION_INFO, HciReadLocalVersionInformation);
114   SET_HANDLER(HCI_READ_BD_ADDR, HciReadBdAddr);
115   SET_HANDLER(HCI_READ_LOCAL_SUPPORTED_CMDS, HciReadLocalSupportedCommands);
116   SET_HANDLER(HCI_READ_LOCAL_SUPPORTED_CODECS, HciReadLocalSupportedCodecs);
117   SET_HANDLER(HCI_READ_LOCAL_EXT_FEATURES, HciReadLocalExtendedFeatures);
118   SET_HANDLER(HCI_WRITE_SIMPLE_PAIRING_MODE, HciWriteSimplePairingMode);
119   SET_HANDLER(HCI_WRITE_LE_HOST_SUPPORT, HciWriteLeHostSupport);
120   SET_HANDLER(HCI_SET_EVENT_MASK, HciSetEventMask);
121   SET_HANDLER(HCI_WRITE_INQUIRY_MODE, HciWriteInquiryMode);
122   SET_HANDLER(HCI_WRITE_PAGESCAN_TYPE, HciWritePageScanType);
123   SET_HANDLER(HCI_WRITE_INQSCAN_TYPE, HciWriteInquiryScanType);
124   SET_HANDLER(HCI_WRITE_CLASS_OF_DEVICE, HciWriteClassOfDevice);
125   SET_HANDLER(HCI_WRITE_PAGE_TOUT, HciWritePageTimeout);
126   SET_HANDLER(HCI_WRITE_DEF_POLICY_SETTINGS, HciWriteDefaultLinkPolicySettings);
127   SET_HANDLER(HCI_READ_LOCAL_NAME, HciReadLocalName);
128   SET_HANDLER(HCI_CHANGE_LOCAL_NAME, HciWriteLocalName);
129   SET_HANDLER(HCI_WRITE_EXT_INQ_RESPONSE, HciWriteExtendedInquiryResponse);
130   SET_HANDLER(HCI_WRITE_VOICE_SETTINGS, HciWriteVoiceSetting);
131   SET_HANDLER(HCI_WRITE_CURRENT_IAC_LAP, HciWriteCurrentIacLap);
132   SET_HANDLER(HCI_WRITE_INQUIRYSCAN_CFG, HciWriteInquiryScanActivity);
133   SET_HANDLER(HCI_WRITE_SCAN_ENABLE, HciWriteScanEnable);
134   SET_HANDLER(HCI_SET_EVENT_FILTER, HciSetEventFilter);
135   SET_HANDLER(HCI_INQUIRY, HciInquiry);
136   SET_HANDLER(HCI_INQUIRY_CANCEL, HciInquiryCancel);
137   SET_HANDLER(HCI_DELETE_STORED_LINK_KEY, HciDeleteStoredLinkKey);
138   SET_HANDLER(HCI_RMT_NAME_REQUEST, HciRemoteNameRequest);
139   SET_HANDLER(HCI_BLE_SET_EVENT_MASK, HciLeSetEventMask);
140   SET_HANDLER(HCI_BLE_READ_BUFFER_SIZE, HciLeReadBufferSize);
141   SET_HANDLER(HCI_BLE_READ_LOCAL_SPT_FEAT, HciLeReadLocalSupportedFeatures);
142   SET_HANDLER(HCI_BLE_WRITE_RANDOM_ADDR, HciLeSetRandomAddress);
143   SET_HANDLER(HCI_BLE_WRITE_ADV_DATA, HciLeSetAdvertisingData);
144   SET_HANDLER(HCI_BLE_WRITE_ADV_PARAMS, HciLeSetAdvertisingParameters);
145   SET_HANDLER(HCI_BLE_WRITE_SCAN_PARAMS, HciLeSetScanParameters);
146   SET_HANDLER(HCI_BLE_WRITE_SCAN_ENABLE, HciLeSetScanEnable);
147   SET_HANDLER(HCI_BLE_READ_WHITE_LIST_SIZE, HciLeReadWhiteListSize);
148   SET_HANDLER(HCI_BLE_RAND, HciLeRand);
149   SET_HANDLER(HCI_BLE_READ_SUPPORTED_STATES, HciLeReadSupportedStates);
150   SET_HANDLER((HCI_GRP_VENDOR_SPECIFIC | 0x27), HciBleVendorSleepMode);
151   SET_HANDLER(HCI_BLE_VENDOR_CAP_OCF, HciBleVendorCap);
152   SET_HANDLER(HCI_BLE_MULTI_ADV_OCF, HciBleVendorMultiAdv);
153   SET_HANDLER((HCI_GRP_VENDOR_SPECIFIC | 0x155), HciBleVendor155);
154   SET_HANDLER((HCI_GRP_VENDOR_SPECIFIC | 0x157), HciBleVendor157);
155   SET_HANDLER(HCI_BLE_ENERGY_INFO_OCF, HciBleEnergyInfo);
156   SET_HANDLER(HCI_BLE_EXTENDED_SCAN_PARAMS_OCF, HciBleExtendedScanParams);
157 #undef SET_HANDLER
158 
159 #define SET_TEST_HANDLER(command_name, method)  \
160   active_test_channel_commands_[command_name] = \
161       [this](const vector<std::string>& param) { method(param); };
162   SET_TEST_HANDLER("CLEAR", TestChannelClear);
163   SET_TEST_HANDLER("CLEAR_EVENT_DELAY", TestChannelClearEventDelay);
164   SET_TEST_HANDLER("DISCOVER", TestChannelDiscover);
165   SET_TEST_HANDLER("SET_EVENT_DELAY", TestChannelSetEventDelay);
166   SET_TEST_HANDLER("TIMEOUT_ALL", TestChannelTimeoutAll);
167 #undef SET_TEST_HANDLER
168 }
169 
RegisterTaskScheduler(std::function<AsyncTaskId (std::chrono::milliseconds,const TaskCallback &)> oneshotScheduler)170 void DualModeController::RegisterTaskScheduler(
171     std::function<AsyncTaskId(std::chrono::milliseconds, const TaskCallback&)>
172         oneshotScheduler) {
173   schedule_task_ = oneshotScheduler;
174 }
175 
RegisterPeriodicTaskScheduler(std::function<AsyncTaskId (std::chrono::milliseconds,std::chrono::milliseconds,const TaskCallback &)> periodicScheduler)176 void DualModeController::RegisterPeriodicTaskScheduler(
177     std::function<AsyncTaskId(std::chrono::milliseconds,
178                               std::chrono::milliseconds, const TaskCallback&)>
179         periodicScheduler) {
180   schedule_periodic_task_ = periodicScheduler;
181 }
182 
RegisterTaskCancel(std::function<void (AsyncTaskId)> task_cancel)183 void DualModeController::RegisterTaskCancel(
184     std::function<void(AsyncTaskId)> task_cancel) {
185   cancel_task_ = task_cancel;
186 }
187 
HandleTestChannelCommand(const std::string & name,const vector<std::string> & args)188 void DualModeController::HandleTestChannelCommand(
189     const std::string& name, const vector<std::string>& args) {
190   if (active_test_channel_commands_.count(name) == 0) return;
191   active_test_channel_commands_[name](args);
192 }
193 
HandleCommand(std::unique_ptr<CommandPacket> command_packet)194 void DualModeController::HandleCommand(
195     std::unique_ptr<CommandPacket> command_packet) {
196   uint16_t opcode = command_packet->GetOpcode();
197   LOG_INFO(LOG_TAG, "Command opcode: 0x%04X, OGF: 0x%04X, OCF: 0x%04X", opcode,
198            command_packet->GetOGF(), command_packet->GetOCF());
199 
200   // The command hasn't been registered with the handler yet. There is nothing
201   // to do.
202   if (active_hci_commands_.count(opcode) == 0)
203     return;
204   else if (test_channel_state_ == kTimeoutAll)
205     return;
206   active_hci_commands_[opcode](command_packet->GetPayload());
207 }
208 
RegisterEventChannel(const std::function<void (std::unique_ptr<EventPacket>)> & callback)209 void DualModeController::RegisterEventChannel(
210     const std::function<void(std::unique_ptr<EventPacket>)>& callback) {
211   send_event_ = callback;
212 }
213 
HandleTimerTick()214 void DualModeController::HandleTimerTick() {
215   // PageScan();
216   if (le_scan_enable_) LOG_ERROR(LOG_TAG, "LE scan");
217   // LeScan();
218 }
219 
SetTimerPeriod(std::chrono::milliseconds new_period)220 void DualModeController::SetTimerPeriod(std::chrono::milliseconds new_period) {
221   timer_period_ = new_period;
222 
223   if (timer_tick_task_ == kInvalidTaskId) return;
224 
225   // Restart the timer with the new period
226   StopTimer();
227   StartTimer();
228 }
229 
StartTimer()230 void DualModeController::StartTimer() {
231   LOG_ERROR(LOG_TAG, "StartTimer");
232   timer_tick_task_ = schedule_periodic_task_(
233       std::chrono::milliseconds(0), timer_period_,
234       [this]() { DualModeController::HandleTimerTick(); });
235 }
236 
StopTimer()237 void DualModeController::StopTimer() {
238   LOG_ERROR(LOG_TAG, "StopTimer");
239   cancel_task_(timer_tick_task_);
240   timer_tick_task_ = kInvalidTaskId;
241 }
242 
TestChannelClear(UNUSED_ATTR const vector<std::string> & args)243 void DualModeController::TestChannelClear(
244     UNUSED_ATTR const vector<std::string>& args) {
245   LogCommand("TestChannel Clear");
246   test_channel_state_ = kNone;
247 }
248 
TestChannelDiscover(UNUSED_ATTR const vector<std::string> & args)249 void DualModeController::TestChannelDiscover(
250     UNUSED_ATTR const vector<std::string>& args) {
251   LogCommand("TestChannel Discover");
252   /* TODO: Replace with adding devices */
253   /*
254 
255     for (size_t i = 0; i < args.size() - 1; i += 2)
256       SendExtendedInquiryResult(args[i], args[i + 1]);
257   */
258 }
259 
TestChannelTimeoutAll(UNUSED_ATTR const vector<std::string> & args)260 void DualModeController::TestChannelTimeoutAll(
261     UNUSED_ATTR const vector<std::string>& args) {
262   LogCommand("TestChannel Timeout All");
263   test_channel_state_ = kTimeoutAll;
264 }
265 
TestChannelSetEventDelay(const vector<std::string> & args UNUSED_ATTR)266 void DualModeController::TestChannelSetEventDelay(
267     const vector<std::string>& args UNUSED_ATTR) {
268   LogCommand("TestChannel Set Event Delay");
269   test_channel_state_ = kDelayedResponse;
270 }
271 
TestChannelClearEventDelay(UNUSED_ATTR const vector<std::string> & args)272 void DualModeController::TestChannelClearEventDelay(
273     UNUSED_ATTR const vector<std::string>& args) {
274   LogCommand("TestChannel Clear Event Delay");
275   test_channel_state_ = kNone;
276 }
277 
HciReset(UNUSED_ATTR const vector<uint8_t> & args)278 void DualModeController::HciReset(UNUSED_ATTR const vector<uint8_t>& args) {
279   LogCommand("Reset");
280   state_ = kStandby;
281   if (timer_tick_task_ != kInvalidTaskId) {
282     LOG_INFO(LOG_TAG, "The timer was already running!");
283     StopTimer();
284   }
285   LOG_INFO(LOG_TAG, "Starting timer.");
286   StartTimer();
287 
288   SendCommandCompleteSuccess(HCI_RESET);
289 }
290 
HciReadBufferSize(UNUSED_ATTR const vector<uint8_t> & args)291 void DualModeController::HciReadBufferSize(
292     UNUSED_ATTR const vector<uint8_t>& args) {
293   LogCommand("Read Buffer Size");
294   std::unique_ptr<EventPacket> command_complete =
295       EventPacket::CreateCommandCompleteReadBufferSize(
296           kSuccessStatus, properties_.GetAclDataPacketSize(),
297           properties_.GetSynchronousDataPacketSize(),
298           properties_.GetTotalNumAclDataPackets(),
299           properties_.GetTotalNumSynchronousDataPackets());
300 
301   send_event_(std::move(command_complete));
302 }
303 
HciHostBufferSize(UNUSED_ATTR const vector<uint8_t> & args)304 void DualModeController::HciHostBufferSize(
305     UNUSED_ATTR const vector<uint8_t>& args) {
306   LogCommand("Host Buffer Size");
307   SendCommandCompleteSuccess(HCI_HOST_BUFFER_SIZE);
308 }
309 
HciReadLocalVersionInformation(UNUSED_ATTR const vector<uint8_t> & args)310 void DualModeController::HciReadLocalVersionInformation(
311     UNUSED_ATTR const vector<uint8_t>& args) {
312   LogCommand("Read Local Version Information");
313   std::unique_ptr<EventPacket> command_complete =
314       EventPacket::CreateCommandCompleteReadLocalVersionInformation(
315           kSuccessStatus, properties_.GetVersion(), properties_.GetRevision(),
316           properties_.GetLmpPalVersion(), properties_.GetManufacturerName(),
317           properties_.GetLmpPalSubversion());
318   send_event_(std::move(command_complete));
319 }
320 
HciReadBdAddr(UNUSED_ATTR const vector<uint8_t> & args)321 void DualModeController::HciReadBdAddr(
322     UNUSED_ATTR const vector<uint8_t>& args) {
323   std::unique_ptr<EventPacket> command_complete =
324       EventPacket::CreateCommandCompleteReadBdAddr(kSuccessStatus,
325                                                    properties_.GetAddress());
326   send_event_(std::move(command_complete));
327 }
328 
HciReadLocalSupportedCommands(UNUSED_ATTR const vector<uint8_t> & args)329 void DualModeController::HciReadLocalSupportedCommands(
330     UNUSED_ATTR const vector<uint8_t>& args) {
331   LogCommand("Read Local Supported Commands");
332   std::unique_ptr<EventPacket> command_complete =
333       EventPacket::CreateCommandCompleteReadLocalSupportedCommands(
334           kSuccessStatus, properties_.GetLocalSupportedCommands());
335   send_event_(std::move(command_complete));
336 }
337 
HciReadLocalSupportedCodecs(UNUSED_ATTR const vector<uint8_t> & args)338 void DualModeController::HciReadLocalSupportedCodecs(
339     UNUSED_ATTR const vector<uint8_t>& args) {
340   LogCommand("Read Local Supported Codecs");
341   std::unique_ptr<EventPacket> command_complete =
342       EventPacket::CreateCommandCompleteReadLocalSupportedCodecs(
343           kSuccessStatus, properties_.GetSupportedCodecs(),
344           properties_.GetVendorSpecificCodecs());
345   send_event_(std::move(command_complete));
346 }
347 
HciReadLocalExtendedFeatures(const vector<uint8_t> & args)348 void DualModeController::HciReadLocalExtendedFeatures(
349     const vector<uint8_t>& args) {
350   LogCommand("Read Local Extended Features");
351   CHECK(args.size() == 2);
352   std::unique_ptr<EventPacket> command_complete =
353       EventPacket::CreateCommandCompleteReadLocalExtendedFeatures(
354           kSuccessStatus, args[1],
355           properties_.GetLocalExtendedFeaturesMaximumPageNumber(),
356           properties_.GetLocalExtendedFeatures(args[1]));
357   send_event_(std::move(command_complete));
358 }
359 
HciWriteSimplePairingMode(UNUSED_ATTR const vector<uint8_t> & args)360 void DualModeController::HciWriteSimplePairingMode(
361     UNUSED_ATTR const vector<uint8_t>& args) {
362   LogCommand("Write Simple Pairing Mode");
363   SendCommandCompleteSuccess(HCI_WRITE_SIMPLE_PAIRING_MODE);
364 }
365 
HciWriteLeHostSupport(UNUSED_ATTR const vector<uint8_t> & args)366 void DualModeController::HciWriteLeHostSupport(
367     UNUSED_ATTR const vector<uint8_t>& args) {
368   LogCommand("Write Le Host Support");
369   SendCommandCompleteSuccess(HCI_WRITE_LE_HOST_SUPPORT);
370 }
371 
HciSetEventMask(UNUSED_ATTR const vector<uint8_t> & args)372 void DualModeController::HciSetEventMask(
373     UNUSED_ATTR const vector<uint8_t>& args) {
374   LogCommand("Set Event Mask");
375   SendCommandCompleteSuccess(HCI_SET_EVENT_MASK);
376 }
377 
HciWriteInquiryMode(const vector<uint8_t> & args)378 void DualModeController::HciWriteInquiryMode(const vector<uint8_t>& args) {
379   LogCommand("Write Inquiry Mode");
380   CHECK(args.size() == 2);
381   inquiry_mode_ = args[1];
382   SendCommandCompleteSuccess(HCI_WRITE_INQUIRY_MODE);
383 }
384 
HciWritePageScanType(UNUSED_ATTR const vector<uint8_t> & args)385 void DualModeController::HciWritePageScanType(
386     UNUSED_ATTR const vector<uint8_t>& args) {
387   LogCommand("Write Page Scan Type");
388   SendCommandCompleteSuccess(HCI_WRITE_PAGESCAN_TYPE);
389 }
390 
HciWriteInquiryScanType(UNUSED_ATTR const vector<uint8_t> & args)391 void DualModeController::HciWriteInquiryScanType(
392     UNUSED_ATTR const vector<uint8_t>& args) {
393   LogCommand("Write Inquiry Scan Type");
394   SendCommandCompleteSuccess(HCI_WRITE_INQSCAN_TYPE);
395 }
396 
HciWriteClassOfDevice(UNUSED_ATTR const vector<uint8_t> & args)397 void DualModeController::HciWriteClassOfDevice(
398     UNUSED_ATTR const vector<uint8_t>& args) {
399   LogCommand("Write Class Of Device");
400   SendCommandCompleteSuccess(HCI_WRITE_CLASS_OF_DEVICE);
401 }
402 
HciWritePageTimeout(UNUSED_ATTR const vector<uint8_t> & args)403 void DualModeController::HciWritePageTimeout(
404     UNUSED_ATTR const vector<uint8_t>& args) {
405   LogCommand("Write Page Timeout");
406   SendCommandCompleteSuccess(HCI_WRITE_PAGE_TOUT);
407 }
408 
HciWriteDefaultLinkPolicySettings(UNUSED_ATTR const vector<uint8_t> & args)409 void DualModeController::HciWriteDefaultLinkPolicySettings(
410     UNUSED_ATTR const vector<uint8_t>& args) {
411   LogCommand("Write Default Link Policy Settings");
412   SendCommandCompleteSuccess(HCI_WRITE_DEF_POLICY_SETTINGS);
413 }
414 
HciReadLocalName(UNUSED_ATTR const vector<uint8_t> & args)415 void DualModeController::HciReadLocalName(
416     UNUSED_ATTR const vector<uint8_t>& args) {
417   LogCommand("Get Local Name");
418   std::unique_ptr<EventPacket> command_complete =
419       EventPacket::CreateCommandCompleteReadLocalName(
420           kSuccessStatus, properties_.GetLocalName());
421   send_event_(std::move(command_complete));
422 }
423 
HciWriteLocalName(UNUSED_ATTR const vector<uint8_t> & args)424 void DualModeController::HciWriteLocalName(
425     UNUSED_ATTR const vector<uint8_t>& args) {
426   LogCommand("Write Local Name");
427   SendCommandCompleteSuccess(HCI_CHANGE_LOCAL_NAME);
428 }
429 
HciWriteExtendedInquiryResponse(UNUSED_ATTR const vector<uint8_t> & args)430 void DualModeController::HciWriteExtendedInquiryResponse(
431     UNUSED_ATTR const vector<uint8_t>& args) {
432   LogCommand("Write Extended Inquiry Response");
433   SendCommandCompleteSuccess(HCI_WRITE_EXT_INQ_RESPONSE);
434 }
435 
HciWriteVoiceSetting(UNUSED_ATTR const vector<uint8_t> & args)436 void DualModeController::HciWriteVoiceSetting(
437     UNUSED_ATTR const vector<uint8_t>& args) {
438   LogCommand("Write Voice Setting");
439   SendCommandCompleteSuccess(HCI_WRITE_VOICE_SETTINGS);
440 }
441 
HciWriteCurrentIacLap(UNUSED_ATTR const vector<uint8_t> & args)442 void DualModeController::HciWriteCurrentIacLap(
443     UNUSED_ATTR const vector<uint8_t>& args) {
444   LogCommand("Write Current IAC LAP");
445   SendCommandCompleteSuccess(HCI_WRITE_CURRENT_IAC_LAP);
446 }
447 
HciWriteInquiryScanActivity(UNUSED_ATTR const vector<uint8_t> & args)448 void DualModeController::HciWriteInquiryScanActivity(
449     UNUSED_ATTR const vector<uint8_t>& args) {
450   LogCommand("Write Inquiry Scan Activity");
451   SendCommandCompleteSuccess(HCI_WRITE_INQUIRYSCAN_CFG);
452 }
453 
HciWriteScanEnable(UNUSED_ATTR const vector<uint8_t> & args)454 void DualModeController::HciWriteScanEnable(
455     UNUSED_ATTR const vector<uint8_t>& args) {
456   LogCommand("Write Scan Enable");
457   SendCommandCompleteSuccess(HCI_WRITE_SCAN_ENABLE);
458 }
459 
HciSetEventFilter(UNUSED_ATTR const vector<uint8_t> & args)460 void DualModeController::HciSetEventFilter(
461     UNUSED_ATTR const vector<uint8_t>& args) {
462   LogCommand("Set Event Filter");
463   SendCommandCompleteSuccess(HCI_SET_EVENT_FILTER);
464 }
465 
HciInquiry(const vector<uint8_t> & args)466 void DualModeController::HciInquiry(const vector<uint8_t>& args) {
467   // Fake inquiry response for a fake device.
468   const EventPacket::PageScanRepetitionMode kPageScanRepetitionMode =
469       EventPacket::kR0;
470   const uint32_t kClassOfDevice = 0x030201;
471   const uint16_t kClockOffset = 513;
472   BtAddress other_addr;
473   other_addr.FromVector(kOtherDeviceBdAddress);
474 
475   LogCommand("Inquiry");
476   state_ = kInquiry;
477   SendCommandStatusSuccess(HCI_INQUIRY);
478   switch (inquiry_mode_) {
479     case (kStandardInquiry): {
480       std::unique_ptr<EventPacket> inquiry_result_evt =
481           EventPacket::CreateInquiryResultEvent(other_addr,
482                                                 kPageScanRepetitionMode,
483                                                 kClassOfDevice, kClockOffset);
484       send_event_(std::move(inquiry_result_evt));
485       /* TODO: Return responses from modeled devices */
486     } break;
487 
488     case (kRssiInquiry):
489       LOG_INFO(LOG_TAG, "RSSI Inquiry Mode currently not supported.");
490       break;
491 
492     case (kExtendedOrRssiInquiry): {
493       const std::string name = "Foobar";
494       vector<uint8_t> extended_inquiry_data = {
495           static_cast<uint8_t>(name.length() + 1), 0x09};
496 
497       for (size_t i = 0; i < name.length(); i++)
498         extended_inquiry_data.push_back(name[i]);
499       extended_inquiry_data.push_back('\0');
500 
501       uint8_t rssi = static_cast<uint8_t>(-20);
502       send_event_(EventPacket::CreateExtendedInquiryResultEvent(
503           other_addr, kPageScanRepetitionMode, kClassOfDevice, kClockOffset,
504           rssi, extended_inquiry_data));
505       /* TODO: Return responses from modeled devices */
506     } break;
507   }
508   AddControllerEvent(std::chrono::milliseconds(args[4] * 1280),
509                      [this]() { DualModeController::InquiryTimeout(); });
510 }
511 
HciInquiryCancel(UNUSED_ATTR const vector<uint8_t> & args)512 void DualModeController::HciInquiryCancel(
513     UNUSED_ATTR const vector<uint8_t>& args) {
514   LogCommand("Inquiry Cancel");
515   CHECK(state_ == kInquiry);
516   state_ = kStandby;
517   SendCommandCompleteSuccess(HCI_INQUIRY_CANCEL);
518 }
519 
InquiryTimeout()520 void DualModeController::InquiryTimeout() {
521   LOG_INFO(LOG_TAG, "InquiryTimer fired");
522   if (state_ == kInquiry) {
523     state_ = kStandby;
524     send_event_(EventPacket::CreateInquiryCompleteEvent(kSuccessStatus));
525   }
526 }
527 
HciDeleteStoredLinkKey(UNUSED_ATTR const vector<uint8_t> & args)528 void DualModeController::HciDeleteStoredLinkKey(
529     UNUSED_ATTR const vector<uint8_t>& args) {
530   LogCommand("Delete Stored Link Key");
531   /* Check the last octect in |args|. If it is 0, delete only the link key for
532    * the given BD_ADDR. If is is 1, delete all stored link keys. */
533   SendCommandCompleteOnlyStatus(HCI_INQUIRY_CANCEL, kUnknownHciCommand);
534 }
535 
HciRemoteNameRequest(UNUSED_ATTR const vector<uint8_t> & args)536 void DualModeController::HciRemoteNameRequest(
537     UNUSED_ATTR const vector<uint8_t>& args) {
538   LogCommand("Remote Name Request");
539   SendCommandStatusSuccess(HCI_RMT_NAME_REQUEST);
540 }
541 
HciLeSetEventMask(const vector<uint8_t> & args)542 void DualModeController::HciLeSetEventMask(const vector<uint8_t>& args) {
543   LogCommand("LE SetEventMask");
544   le_event_mask_ = args;
545   SendCommandCompleteSuccess(HCI_BLE_SET_EVENT_MASK);
546 }
547 
HciLeReadBufferSize(UNUSED_ATTR const vector<uint8_t> & args)548 void DualModeController::HciLeReadBufferSize(
549     UNUSED_ATTR const vector<uint8_t>& args) {
550   std::unique_ptr<EventPacket> command_complete =
551       EventPacket::CreateCommandCompleteLeReadBufferSize(
552           kSuccessStatus, properties_.GetLeDataPacketLength(),
553           properties_.GetTotalNumLeDataPackets());
554   send_event_(std::move(command_complete));
555 }
556 
HciLeReadLocalSupportedFeatures(UNUSED_ATTR const vector<uint8_t> & args)557 void DualModeController::HciLeReadLocalSupportedFeatures(
558     UNUSED_ATTR const vector<uint8_t>& args) {
559   std::unique_ptr<EventPacket> command_complete =
560       EventPacket::CreateCommandCompleteLeReadLocalSupportedFeatures(
561           kSuccessStatus, properties_.GetLeLocalSupportedFeatures());
562   send_event_(std::move(command_complete));
563 }
564 
HciLeSetRandomAddress(const vector<uint8_t> & args)565 void DualModeController::HciLeSetRandomAddress(const vector<uint8_t>& args) {
566   LogCommand("LE SetRandomAddress");
567   CHECK(args.size() == 7);
568   vector<uint8_t> new_addr = {args[1], args[2], args[3],
569                               args[4], args[5], args[6]};
570   CHECK(le_random_address_.FromVector(new_addr));
571   SendCommandCompleteSuccess(HCI_BLE_WRITE_RANDOM_ADDR);
572 }
573 
HciLeSetAdvertisingParameters(UNUSED_ATTR const vector<uint8_t> & args)574 void DualModeController::HciLeSetAdvertisingParameters(
575     UNUSED_ATTR const vector<uint8_t>& args) {
576   LogCommand("LE SetAdvertisingParameters");
577   SendCommandCompleteSuccess(HCI_BLE_WRITE_ADV_PARAMS);
578 }
579 
HciLeSetAdvertisingData(UNUSED_ATTR const vector<uint8_t> & args)580 void DualModeController::HciLeSetAdvertisingData(
581     UNUSED_ATTR const vector<uint8_t>& args) {
582   LogCommand("LE SetAdvertisingData");
583   SendCommandCompleteSuccess(HCI_BLE_WRITE_ADV_DATA);
584 }
585 
HciLeSetScanParameters(const vector<uint8_t> & args)586 void DualModeController::HciLeSetScanParameters(const vector<uint8_t>& args) {
587   LogCommand("LE SetScanParameters");
588   CHECK(args.size() == 8);
589   le_scan_type_ = args[1];
590   le_scan_interval_ = args[2] | (args[3] << 8);
591   le_scan_window_ = args[4] | (args[5] << 8);
592   own_address_type_ = args[6];
593   scanning_filter_policy_ = args[7];
594   SendCommandCompleteSuccess(HCI_BLE_WRITE_SCAN_PARAMS);
595 }
596 
HciLeSetScanEnable(const vector<uint8_t> & args)597 void DualModeController::HciLeSetScanEnable(const vector<uint8_t>& args) {
598   LogCommand("LE SetScanEnable");
599   CHECK(args.size() == 3);
600   CHECK(args[0] == 2);
601   le_scan_enable_ = args[1];
602   filter_duplicates_ = args[2];
603   SendCommandCompleteSuccess(HCI_BLE_WRITE_SCAN_ENABLE);
604 }
605 
HciLeReadWhiteListSize(UNUSED_ATTR const vector<uint8_t> & args)606 void DualModeController::HciLeReadWhiteListSize(
607     UNUSED_ATTR const vector<uint8_t>& args) {
608   std::unique_ptr<EventPacket> command_complete =
609       EventPacket::CreateCommandCompleteLeReadWhiteListSize(
610           kSuccessStatus, properties_.GetLeWhiteListSize());
611   send_event_(std::move(command_complete));
612 }
613 
HciLeRand(UNUSED_ATTR const vector<uint8_t> & args)614 void DualModeController::HciLeRand(UNUSED_ATTR const vector<uint8_t>& args) {
615   uint64_t random_val = rand();
616   std::unique_ptr<EventPacket> command_complete =
617       EventPacket::CreateCommandCompleteLeRand(kSuccessStatus, random_val);
618   send_event_(std::move(command_complete));
619 }
620 
HciLeReadSupportedStates(UNUSED_ATTR const vector<uint8_t> & args)621 void DualModeController::HciLeReadSupportedStates(
622     UNUSED_ATTR const vector<uint8_t>& args) {
623   std::unique_ptr<EventPacket> command_complete =
624       EventPacket::CreateCommandCompleteLeReadSupportedStates(
625           kSuccessStatus, properties_.GetLeSupportedStates());
626   send_event_(std::move(command_complete));
627 }
628 
HciBleVendorSleepMode(UNUSED_ATTR const vector<uint8_t> & args)629 void DualModeController::HciBleVendorSleepMode(
630     UNUSED_ATTR const vector<uint8_t>& args) {
631   SendCommandCompleteOnlyStatus(HCI_GRP_VENDOR_SPECIFIC | 0x27,
632                                 kUnknownHciCommand);
633 }
634 
HciBleVendorCap(UNUSED_ATTR const vector<uint8_t> & args)635 void DualModeController::HciBleVendorCap(
636     UNUSED_ATTR const vector<uint8_t>& args) {
637   std::unique_ptr<EventPacket> command_complete =
638       EventPacket::CreateCommandCompleteLeVendorCap(
639           kSuccessStatus, properties_.GetLeVendorCap());
640   send_event_(std::move(command_complete));
641 }
642 
HciBleVendorMultiAdv(UNUSED_ATTR const vector<uint8_t> & args)643 void DualModeController::HciBleVendorMultiAdv(
644     UNUSED_ATTR const vector<uint8_t>& args) {
645   SendCommandCompleteOnlyStatus(HCI_BLE_MULTI_ADV_OCF, kUnknownHciCommand);
646 }
647 
HciBleVendor155(UNUSED_ATTR const vector<uint8_t> & args)648 void DualModeController::HciBleVendor155(
649     UNUSED_ATTR const vector<uint8_t>& args) {
650   SendCommandCompleteOnlyStatus(HCI_GRP_VENDOR_SPECIFIC | 0x155,
651                                 kUnknownHciCommand);
652 }
653 
HciBleVendor157(UNUSED_ATTR const vector<uint8_t> & args)654 void DualModeController::HciBleVendor157(
655     UNUSED_ATTR const vector<uint8_t>& args) {
656   SendCommandCompleteOnlyStatus(HCI_GRP_VENDOR_SPECIFIC | 0x157,
657                                 kUnknownHciCommand);
658 }
659 
HciBleEnergyInfo(UNUSED_ATTR const vector<uint8_t> & args)660 void DualModeController::HciBleEnergyInfo(
661     UNUSED_ATTR const vector<uint8_t>& args) {
662   SendCommandCompleteOnlyStatus(HCI_BLE_ENERGY_INFO_OCF, kUnknownHciCommand);
663 }
664 
HciBleExtendedScanParams(UNUSED_ATTR const vector<uint8_t> & args)665 void DualModeController::HciBleExtendedScanParams(
666     UNUSED_ATTR const vector<uint8_t>& args) {
667   SendCommandCompleteOnlyStatus(HCI_BLE_EXTENDED_SCAN_PARAMS_OCF,
668                                 kUnknownHciCommand);
669 }
670 
Properties(const std::string & file_name)671 DualModeController::Properties::Properties(const std::string& file_name)
672     : acl_data_packet_size_(1024),
673       sco_data_packet_size_(255),
674       num_acl_data_packets_(10),
675       num_sco_data_packets_(10),
676       version_(4),
677       revision_(1),
678       lmp_pal_version_(0),
679       manufacturer_name_(0),
680       lmp_pal_subversion_(0),
681       le_data_packet_length_(27),
682       num_le_data_packets_(15),
683       le_white_list_size_(15) {
684   std::string properties_raw;
685 
686   local_extended_features_ = {0xffffffffffffffff, 0x7};
687 
688   CHECK(address_.FromString("01:02:03:04:05:06"));
689   local_name_ = "DefaultName";
690 
691   supported_codecs_ = {1};
692   vendor_specific_codecs_ = {};
693 
694   for (int i = 0; i < 64; i++) local_supported_commands_.push_back(0xff);
695 
696   le_supported_features_ = 0x1f;
697   le_supported_states_ = 0x3ffffffffff;
698   le_vendor_cap_ = {0x05, 0x01, 0x00, 0x04, 0x80, 0x01, 0x10,
699                     0x01, 0x60, 0x00, 0x0a, 0x00, 0x01, 0x01};
700 
701   LOG_INFO(LOG_TAG, "Reading controller properties from %s.",
702            file_name.c_str());
703   if (!base::ReadFileToString(base::FilePath(file_name), &properties_raw)) {
704     LOG_ERROR(LOG_TAG, "Error reading controller properties from file.");
705     return;
706   }
707 
708   std::unique_ptr<base::Value> properties_value_ptr =
709       base::JSONReader::Read(properties_raw);
710   if (properties_value_ptr.get() == nullptr)
711     LOG_INFO(LOG_TAG,
712              "Error controller properties may consist of ill-formed JSON.");
713 
714   // Get the underlying base::Value object, which is of type
715   // base::Value::TYPE_DICTIONARY, and read it into member variables.
716   base::Value& properties_dictionary = *(properties_value_ptr.get());
717   base::JSONValueConverter<DualModeController::Properties> converter;
718 
719   if (!converter.Convert(properties_dictionary, this))
720     LOG_INFO(LOG_TAG,
721              "Error converting JSON properties into Properties object.");
722 }
723 
724 // static
RegisterJSONConverter(base::JSONValueConverter<DualModeController::Properties> * converter)725 void DualModeController::Properties::RegisterJSONConverter(
726     base::JSONValueConverter<DualModeController::Properties>* converter) {
727 // TODO(dennischeng): Use RegisterIntField() here?
728 #define REGISTER_UINT8_T(field_name, field) \
729   converter->RegisterCustomField<uint8_t>(  \
730       field_name, &DualModeController::Properties::field, &ParseUint8t);
731 #define REGISTER_UINT16_T(field_name, field) \
732   converter->RegisterCustomField<uint16_t>(  \
733       field_name, &DualModeController::Properties::field, &ParseUint16t);
734   REGISTER_UINT16_T("AclDataPacketSize", acl_data_packet_size_);
735   REGISTER_UINT8_T("ScoDataPacketSize", sco_data_packet_size_);
736   REGISTER_UINT16_T("NumAclDataPackets", num_acl_data_packets_);
737   REGISTER_UINT16_T("NumScoDataPackets", num_sco_data_packets_);
738   REGISTER_UINT8_T("Version", version_);
739   REGISTER_UINT16_T("Revision", revision_);
740   REGISTER_UINT8_T("LmpPalVersion", lmp_pal_version_);
741   REGISTER_UINT16_T("ManufacturerName", manufacturer_name_);
742   REGISTER_UINT16_T("LmpPalSubversion", lmp_pal_subversion_);
743 #undef REGISTER_UINT8_T
744 #undef REGISTER_UINT16_T
745 }
746 
747 }  // namespace test_vendor_lib
748