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 #include "dual_mode_controller.h"
18 
19 #include <memory>
20 
21 #include <base/files/file_util.h>
22 #include <base/json/json_reader.h>
23 #include <base/values.h>
24 
25 #include "os/log.h"
26 #include "packet/raw_builder.h"
27 
28 namespace gd_hci = ::bluetooth::hci;
29 using gd_hci::ErrorCode;
30 using gd_hci::LoopbackMode;
31 using gd_hci::OpCode;
32 using std::vector;
33 
34 namespace test_vendor_lib {
35 constexpr char DualModeController::kControllerPropertiesFile[];
36 constexpr uint16_t DualModeController::kSecurityManagerNumKeys;
37 constexpr uint16_t kNumCommandPackets = 0x01;
38 constexpr uint16_t kLeMaximumAdvertisingDataLength = 256;
39 constexpr uint16_t kLeMaximumDataLength = 64;
40 constexpr uint16_t kLeMaximumDataTime = 0x148;
41 
42 // Device methods.
Initialize(const std::vector<std::string> & args)43 void DualModeController::Initialize(const std::vector<std::string>& args) {
44   if (args.size() < 2) return;
45 
46   Address addr{};
47   if (Address::FromString(args[1], addr)) {
48     properties_.SetAddress(addr);
49   } else {
50     LOG_ALWAYS_FATAL("Invalid address: %s", args[1].c_str());
51   }
52 };
53 
GetTypeString() const54 std::string DualModeController::GetTypeString() const {
55   return "Simulated Bluetooth Controller";
56 }
57 
IncomingPacket(model::packets::LinkLayerPacketView incoming)58 void DualModeController::IncomingPacket(
59     model::packets::LinkLayerPacketView incoming) {
60   link_layer_controller_.IncomingPacket(incoming);
61 }
62 
TimerTick()63 void DualModeController::TimerTick() {
64   link_layer_controller_.TimerTick();
65 }
66 
SendCommandCompleteUnknownOpCodeEvent(uint16_t command_opcode) const67 void DualModeController::SendCommandCompleteUnknownOpCodeEvent(uint16_t command_opcode) const {
68   std::unique_ptr<bluetooth::packet::RawBuilder> raw_builder_ptr =
69       std::make_unique<bluetooth::packet::RawBuilder>();
70   raw_builder_ptr->AddOctets1(kNumCommandPackets);
71   raw_builder_ptr->AddOctets2(command_opcode);
72   raw_builder_ptr->AddOctets1(
73       static_cast<uint8_t>(ErrorCode::UNKNOWN_HCI_COMMAND));
74 
75   auto packet = gd_hci::EventBuilder::Create(
76       gd_hci::EventCode::COMMAND_COMPLETE, std::move(raw_builder_ptr));
77   send_event_(std::move(packet));
78 }
79 
DualModeController(const std::string & properties_filename,uint16_t num_keys)80 DualModeController::DualModeController(const std::string& properties_filename, uint16_t num_keys)
81     : Device(properties_filename), security_manager_(num_keys) {
82   loopback_mode_ = LoopbackMode::NO_LOOPBACK;
83 
84   Address public_address{};
85   ASSERT(Address::FromString("3C:5A:B4:04:05:06", public_address));
86   properties_.SetAddress(public_address);
87 
88   link_layer_controller_.RegisterRemoteChannel(
89       [this](std::shared_ptr<model::packets::LinkLayerPacketBuilder> packet,
90              Phy::Type phy_type) {
91         DualModeController::SendLinkLayerPacket(packet, phy_type);
92       });
93 
94   std::array<uint8_t, 64> supported_commands;
95   for (size_t i = 0; i < 64; i++) {
96     supported_commands[i] = 0;
97   }
98 
99 #define SET_HANDLER(name, method)                                  \
100   active_hci_commands_[OpCode::name] = [this](CommandView param) { \
101     method(std::move(param));                                      \
102   };
103 
104 #define SET_SUPPORTED(name, method)                                          \
105   SET_HANDLER(name, method);                                                 \
106   {                                                                          \
107     uint16_t index = (uint16_t)bluetooth::hci::OpCodeIndex::name;            \
108     uint16_t byte_index = index / 10;                                        \
109     uint8_t bit = 1 << (index % 10);                                         \
110     if (byte_index < 36) {                                                   \
111       supported_commands[byte_index] = supported_commands[byte_index] | bit; \
112     }                                                                        \
113   }
114 
115   SET_SUPPORTED(RESET, Reset);
116   SET_SUPPORTED(READ_BUFFER_SIZE, ReadBufferSize);
117   SET_SUPPORTED(HOST_BUFFER_SIZE, HostBufferSize);
118   SET_SUPPORTED(SNIFF_SUBRATING, SniffSubrating);
119   SET_SUPPORTED(READ_ENCRYPTION_KEY_SIZE, ReadEncryptionKeySize);
120   SET_SUPPORTED(READ_LOCAL_VERSION_INFORMATION, ReadLocalVersionInformation);
121   SET_SUPPORTED(READ_BD_ADDR, ReadBdAddr);
122   SET_HANDLER(READ_LOCAL_SUPPORTED_COMMANDS, ReadLocalSupportedCommands);
123   SET_SUPPORTED(READ_LOCAL_SUPPORTED_FEATURES, ReadLocalSupportedFeatures);
124   SET_SUPPORTED(READ_LOCAL_SUPPORTED_CODECS_V1, ReadLocalSupportedCodecs);
125   SET_SUPPORTED(READ_LOCAL_EXTENDED_FEATURES, ReadLocalExtendedFeatures);
126   SET_SUPPORTED(READ_REMOTE_EXTENDED_FEATURES, ReadRemoteExtendedFeatures);
127   SET_SUPPORTED(SWITCH_ROLE, SwitchRole);
128   SET_SUPPORTED(READ_REMOTE_SUPPORTED_FEATURES, ReadRemoteSupportedFeatures);
129   SET_SUPPORTED(READ_CLOCK_OFFSET, ReadClockOffset);
130   SET_SUPPORTED(IO_CAPABILITY_REQUEST_REPLY, IoCapabilityRequestReply);
131   SET_SUPPORTED(USER_CONFIRMATION_REQUEST_REPLY, UserConfirmationRequestReply);
132   SET_SUPPORTED(USER_CONFIRMATION_REQUEST_NEGATIVE_REPLY,
133                 UserConfirmationRequestNegativeReply);
134   SET_SUPPORTED(USER_PASSKEY_REQUEST_REPLY, UserPasskeyRequestReply);
135   SET_SUPPORTED(USER_PASSKEY_REQUEST_NEGATIVE_REPLY,
136                 UserPasskeyRequestNegativeReply);
137   SET_SUPPORTED(PIN_CODE_REQUEST_REPLY, PinCodeRequestReply);
138   SET_SUPPORTED(PIN_CODE_REQUEST_NEGATIVE_REPLY, PinCodeRequestNegativeReply);
139   SET_SUPPORTED(REMOTE_OOB_DATA_REQUEST_REPLY, RemoteOobDataRequestReply);
140   SET_SUPPORTED(REMOTE_OOB_DATA_REQUEST_NEGATIVE_REPLY,
141                 RemoteOobDataRequestNegativeReply);
142   SET_SUPPORTED(IO_CAPABILITY_REQUEST_NEGATIVE_REPLY,
143                 IoCapabilityRequestNegativeReply);
144   SET_SUPPORTED(REMOTE_OOB_EXTENDED_DATA_REQUEST_REPLY,
145                 RemoteOobExtendedDataRequestReply);
146   SET_SUPPORTED(READ_INQUIRY_RESPONSE_TRANSMIT_POWER_LEVEL,
147                 ReadInquiryResponseTransmitPowerLevel);
148   SET_SUPPORTED(SEND_KEYPRESS_NOTIFICATION, SendKeypressNotification);
149   SET_HANDLER(SET_EVENT_MASK_PAGE_2, SetEventMaskPage2);
150   SET_SUPPORTED(READ_LOCAL_OOB_DATA, ReadLocalOobData);
151   SET_SUPPORTED(READ_LOCAL_OOB_EXTENDED_DATA, ReadLocalOobExtendedData);
152   SET_SUPPORTED(WRITE_SIMPLE_PAIRING_MODE, WriteSimplePairingMode);
153   SET_SUPPORTED(WRITE_LE_HOST_SUPPORT, WriteLeHostSupport);
154   SET_SUPPORTED(WRITE_SECURE_CONNECTIONS_HOST_SUPPORT,
155                 WriteSecureConnectionsHostSupport);
156   SET_SUPPORTED(SET_EVENT_MASK, SetEventMask);
157   SET_SUPPORTED(READ_INQUIRY_MODE, ReadInquiryMode);
158   SET_SUPPORTED(WRITE_INQUIRY_MODE, WriteInquiryMode);
159   SET_SUPPORTED(READ_PAGE_SCAN_TYPE, ReadPageScanType);
160   SET_SUPPORTED(WRITE_PAGE_SCAN_TYPE, WritePageScanType);
161   SET_SUPPORTED(WRITE_INQUIRY_SCAN_TYPE, WriteInquiryScanType);
162   SET_SUPPORTED(READ_INQUIRY_SCAN_TYPE, ReadInquiryScanType);
163   SET_SUPPORTED(AUTHENTICATION_REQUESTED, AuthenticationRequested);
164   SET_SUPPORTED(SET_CONNECTION_ENCRYPTION, SetConnectionEncryption);
165   SET_SUPPORTED(CHANGE_CONNECTION_LINK_KEY, ChangeConnectionLinkKey);
166   SET_SUPPORTED(CENTRAL_LINK_KEY, CentralLinkKey);
167   SET_SUPPORTED(WRITE_AUTHENTICATION_ENABLE, WriteAuthenticationEnable);
168   SET_SUPPORTED(READ_AUTHENTICATION_ENABLE, ReadAuthenticationEnable);
169   SET_SUPPORTED(WRITE_CLASS_OF_DEVICE, WriteClassOfDevice);
170   SET_SUPPORTED(READ_PAGE_TIMEOUT, ReadPageTimeout);
171   SET_SUPPORTED(WRITE_PAGE_TIMEOUT, WritePageTimeout);
172   SET_SUPPORTED(WRITE_LINK_SUPERVISION_TIMEOUT, WriteLinkSupervisionTimeout);
173   SET_SUPPORTED(HOLD_MODE, HoldMode);
174   SET_SUPPORTED(SNIFF_MODE, SniffMode);
175   SET_SUPPORTED(EXIT_SNIFF_MODE, ExitSniffMode);
176   SET_SUPPORTED(QOS_SETUP, QosSetup);
177   SET_SUPPORTED(READ_DEFAULT_LINK_POLICY_SETTINGS,
178                 ReadDefaultLinkPolicySettings);
179   SET_SUPPORTED(WRITE_DEFAULT_LINK_POLICY_SETTINGS,
180                 WriteDefaultLinkPolicySettings);
181   SET_SUPPORTED(FLOW_SPECIFICATION, FlowSpecification);
182   SET_SUPPORTED(WRITE_LINK_POLICY_SETTINGS, WriteLinkPolicySettings);
183   SET_SUPPORTED(CHANGE_CONNECTION_PACKET_TYPE, ChangeConnectionPacketType);
184   SET_SUPPORTED(WRITE_LOCAL_NAME, WriteLocalName);
185   SET_SUPPORTED(READ_LOCAL_NAME, ReadLocalName);
186   SET_SUPPORTED(WRITE_EXTENDED_INQUIRY_RESPONSE, WriteExtendedInquiryResponse);
187   SET_SUPPORTED(REFRESH_ENCRYPTION_KEY, RefreshEncryptionKey);
188   SET_SUPPORTED(WRITE_VOICE_SETTING, WriteVoiceSetting);
189   SET_SUPPORTED(READ_NUMBER_OF_SUPPORTED_IAC, ReadNumberOfSupportedIac);
190   SET_SUPPORTED(READ_CURRENT_IAC_LAP, ReadCurrentIacLap);
191   SET_SUPPORTED(WRITE_CURRENT_IAC_LAP, WriteCurrentIacLap);
192   SET_SUPPORTED(READ_PAGE_SCAN_ACTIVITY, ReadPageScanActivity);
193   SET_SUPPORTED(WRITE_PAGE_SCAN_ACTIVITY, WritePageScanActivity);
194   SET_SUPPORTED(READ_INQUIRY_SCAN_ACTIVITY, ReadInquiryScanActivity);
195   SET_SUPPORTED(WRITE_INQUIRY_SCAN_ACTIVITY, WriteInquiryScanActivity);
196   SET_SUPPORTED(READ_SCAN_ENABLE, ReadScanEnable);
197   SET_SUPPORTED(WRITE_SCAN_ENABLE, WriteScanEnable);
198   SET_SUPPORTED(SET_EVENT_FILTER, SetEventFilter);
199   SET_SUPPORTED(INQUIRY, Inquiry);
200   SET_SUPPORTED(INQUIRY_CANCEL, InquiryCancel);
201   SET_SUPPORTED(ACCEPT_CONNECTION_REQUEST, AcceptConnectionRequest);
202   SET_SUPPORTED(REJECT_CONNECTION_REQUEST, RejectConnectionRequest);
203   SET_SUPPORTED(LINK_KEY_REQUEST_REPLY, LinkKeyRequestReply);
204   SET_SUPPORTED(LINK_KEY_REQUEST_NEGATIVE_REPLY, LinkKeyRequestNegativeReply);
205   SET_SUPPORTED(DELETE_STORED_LINK_KEY, DeleteStoredLinkKey);
206   SET_SUPPORTED(REMOTE_NAME_REQUEST, RemoteNameRequest);
207   SET_SUPPORTED(LE_SET_EVENT_MASK, LeSetEventMask);
208   SET_SUPPORTED(LE_READ_BUFFER_SIZE_V1, LeReadBufferSize);
209   SET_SUPPORTED(LE_READ_LOCAL_SUPPORTED_FEATURES, LeReadLocalSupportedFeatures);
210   SET_SUPPORTED(LE_SET_RANDOM_ADDRESS, LeSetRandomAddress);
211   SET_SUPPORTED(LE_SET_ADVERTISING_PARAMETERS, LeSetAdvertisingParameters);
212   SET_SUPPORTED(LE_READ_ADVERTISING_PHYSICAL_CHANNEL_TX_POWER,
213                 LeReadAdvertisingPhysicalChannelTxPower);
214   SET_SUPPORTED(LE_SET_ADVERTISING_DATA, LeSetAdvertisingData);
215   SET_SUPPORTED(LE_SET_SCAN_RESPONSE_DATA, LeSetScanResponseData);
216   SET_SUPPORTED(LE_SET_ADVERTISING_ENABLE, LeSetAdvertisingEnable);
217   SET_SUPPORTED(LE_SET_SCAN_PARAMETERS, LeSetScanParameters);
218   SET_SUPPORTED(LE_SET_SCAN_ENABLE, LeSetScanEnable);
219   SET_SUPPORTED(LE_CREATE_CONNECTION, LeCreateConnection);
220   SET_SUPPORTED(CREATE_CONNECTION, CreateConnection);
221   SET_SUPPORTED(CREATE_CONNECTION_CANCEL, CreateConnectionCancel);
222   SET_SUPPORTED(DISCONNECT, Disconnect);
223   SET_SUPPORTED(LE_CREATE_CONNECTION_CANCEL, LeConnectionCancel);
224   SET_SUPPORTED(LE_READ_CONNECT_LIST_SIZE, LeReadConnectListSize);
225   SET_SUPPORTED(LE_CLEAR_CONNECT_LIST, LeClearConnectList);
226   SET_SUPPORTED(LE_ADD_DEVICE_TO_CONNECT_LIST, LeAddDeviceToConnectList);
227   SET_SUPPORTED(LE_REMOVE_DEVICE_FROM_CONNECT_LIST,
228                 LeRemoveDeviceFromConnectList);
229   SET_SUPPORTED(LE_RAND, LeRand);
230   SET_SUPPORTED(LE_READ_SUPPORTED_STATES, LeReadSupportedStates);
231   SET_HANDLER(LE_GET_VENDOR_CAPABILITIES, LeVendorCap);
232   SET_HANDLER(LE_MULTI_ADVT, LeVendorMultiAdv);
233   SET_HANDLER(LE_ADV_FILTER, LeAdvertisingFilter);
234   SET_HANDLER(LE_ENERGY_INFO, LeEnergyInfo);
235   SET_SUPPORTED(LE_SET_EXTENDED_ADVERTISING_RANDOM_ADDRESS,
236                 LeSetExtendedAdvertisingRandomAddress);
237   SET_SUPPORTED(LE_SET_EXTENDED_ADVERTISING_PARAMETERS,
238                 LeSetExtendedAdvertisingParameters);
239   SET_SUPPORTED(LE_SET_EXTENDED_ADVERTISING_DATA, LeSetExtendedAdvertisingData);
240   SET_SUPPORTED(LE_SET_EXTENDED_ADVERTISING_SCAN_RESPONSE,
241                 LeSetExtendedAdvertisingScanResponse);
242   SET_SUPPORTED(LE_SET_EXTENDED_ADVERTISING_ENABLE,
243                 LeSetExtendedAdvertisingEnable);
244   SET_SUPPORTED(LE_READ_MAXIMUM_ADVERTISING_DATA_LENGTH,
245                 LeReadMaximumAdvertisingDataLength);
246   SET_SUPPORTED(LE_READ_NUMBER_OF_SUPPORTED_ADVERTISING_SETS,
247                 LeReadNumberOfSupportedAdvertisingSets);
248   SET_SUPPORTED(LE_REMOVE_ADVERTISING_SET, LeRemoveAdvertisingSet);
249   SET_SUPPORTED(LE_CLEAR_ADVERTISING_SETS, LeClearAdvertisingSets);
250   SET_SUPPORTED(LE_READ_REMOTE_FEATURES, LeReadRemoteFeatures);
251   SET_SUPPORTED(READ_REMOTE_VERSION_INFORMATION, ReadRemoteVersionInformation);
252   SET_SUPPORTED(LE_CONNECTION_UPDATE, LeConnectionUpdate);
253   SET_SUPPORTED(LE_START_ENCRYPTION, LeStartEncryption);
254   SET_SUPPORTED(LE_LONG_TERM_KEY_REQUEST_REPLY, LeLongTermKeyRequestReply);
255   SET_SUPPORTED(LE_LONG_TERM_KEY_REQUEST_NEGATIVE_REPLY,
256                 LeLongTermKeyRequestNegativeReply);
257   SET_SUPPORTED(LE_ADD_DEVICE_TO_RESOLVING_LIST, LeAddDeviceToResolvingList);
258   SET_SUPPORTED(LE_REMOVE_DEVICE_FROM_RESOLVING_LIST,
259                 LeRemoveDeviceFromResolvingList);
260   SET_SUPPORTED(LE_CLEAR_RESOLVING_LIST, LeClearResolvingList);
261   SET_SUPPORTED(LE_READ_RESOLVING_LIST_SIZE, LeReadResolvingListSize);
262   SET_SUPPORTED(LE_READ_MAXIMUM_DATA_LENGTH, LeReadMaximumDataLength);
263 
264   SET_SUPPORTED(LE_SET_EXTENDED_SCAN_PARAMETERS, LeSetExtendedScanParameters);
265   SET_SUPPORTED(LE_SET_EXTENDED_SCAN_ENABLE, LeSetExtendedScanEnable);
266   SET_SUPPORTED(LE_EXTENDED_CREATE_CONNECTION, LeExtendedCreateConnection);
267   SET_SUPPORTED(LE_SET_PRIVACY_MODE, LeSetPrivacyMode);
268   SET_SUPPORTED(LE_READ_SUGGESTED_DEFAULT_DATA_LENGTH,
269                 LeReadSuggestedDefaultDataLength);
270   // ISO Commands
271   SET_SUPPORTED(LE_READ_ISO_TX_SYNC, LeReadIsoTxSync);
272   SET_SUPPORTED(LE_SET_CIG_PARAMETERS, LeSetCigParameters);
273   SET_SUPPORTED(LE_CREATE_CIS, LeCreateCis);
274   SET_SUPPORTED(LE_REMOVE_CIG, LeRemoveCig);
275   SET_SUPPORTED(LE_ACCEPT_CIS_REQUEST, LeAcceptCisRequest);
276   SET_SUPPORTED(LE_REJECT_CIS_REQUEST, LeRejectCisRequest);
277   SET_SUPPORTED(LE_CREATE_BIG, LeCreateBig);
278   SET_SUPPORTED(LE_TERMINATE_BIG, LeTerminateBig);
279   SET_SUPPORTED(LE_BIG_CREATE_SYNC, LeBigCreateSync);
280   SET_SUPPORTED(LE_BIG_TERMINATE_SYNC, LeBigTerminateSync);
281   SET_SUPPORTED(LE_REQUEST_PEER_SCA, LeRequestPeerSca);
282   SET_SUPPORTED(LE_SETUP_ISO_DATA_PATH, LeSetupIsoDataPath);
283   SET_SUPPORTED(LE_REMOVE_ISO_DATA_PATH, LeRemoveIsoDataPath);
284   // Testing Commands
285   SET_SUPPORTED(READ_LOOPBACK_MODE, ReadLoopbackMode);
286   SET_SUPPORTED(WRITE_LOOPBACK_MODE, WriteLoopbackMode);
287 
288   SET_SUPPORTED(READ_CLASS_OF_DEVICE, ReadClassOfDevice);
289   SET_SUPPORTED(READ_VOICE_SETTING, ReadVoiceSetting);
290   SET_SUPPORTED(READ_CONNECTION_ACCEPT_TIMEOUT, ReadConnectionAcceptTimeout);
291   SET_SUPPORTED(WRITE_CONNECTION_ACCEPT_TIMEOUT, WriteConnectionAcceptTimeout);
292   SET_SUPPORTED(LE_SET_ADDRESS_RESOLUTION_ENABLE, LeSetAddressResolutionEnable);
293   SET_SUPPORTED(LE_SET_RESOLVABLE_PRIVATE_ADDRESS_TIMEOUT, LeSetResovalablePrivateAddressTimeout);
294 #undef SET_HANDLER
295 #undef SET_SUPPORTED
296   properties_.SetSupportedCommands(supported_commands);
297 }
298 
SniffSubrating(CommandView command)299 void DualModeController::SniffSubrating(CommandView command) {
300   auto command_view = gd_hci::SniffSubratingView::Create(
301       gd_hci::ConnectionManagementCommandView::Create(
302           gd_hci::AclCommandView::Create(command)));
303   ASSERT(command_view.IsValid());
304 
305   send_event_(gd_hci::SniffSubratingCompleteBuilder::Create(
306       kNumCommandPackets, ErrorCode::SUCCESS,
307       command_view.GetConnectionHandle()));
308 }
309 
RegisterTaskScheduler(std::function<AsyncTaskId (std::chrono::milliseconds,const TaskCallback &)> oneshot_scheduler)310 void DualModeController::RegisterTaskScheduler(
311     std::function<AsyncTaskId(std::chrono::milliseconds, const TaskCallback&)> oneshot_scheduler) {
312   link_layer_controller_.RegisterTaskScheduler(oneshot_scheduler);
313 }
314 
RegisterPeriodicTaskScheduler(std::function<AsyncTaskId (std::chrono::milliseconds,std::chrono::milliseconds,const TaskCallback &)> periodic_scheduler)315 void DualModeController::RegisterPeriodicTaskScheduler(
316     std::function<AsyncTaskId(std::chrono::milliseconds, std::chrono::milliseconds, const TaskCallback&)>
317         periodic_scheduler) {
318   link_layer_controller_.RegisterPeriodicTaskScheduler(periodic_scheduler);
319 }
320 
RegisterTaskCancel(std::function<void (AsyncTaskId)> task_cancel)321 void DualModeController::RegisterTaskCancel(std::function<void(AsyncTaskId)> task_cancel) {
322   link_layer_controller_.RegisterTaskCancel(task_cancel);
323 }
324 
HandleAcl(std::shared_ptr<std::vector<uint8_t>> packet)325 void DualModeController::HandleAcl(std::shared_ptr<std::vector<uint8_t>> packet) {
326   bluetooth::hci::PacketView<bluetooth::hci::kLittleEndian> raw_packet(packet);
327   auto acl_packet = bluetooth::hci::AclView::Create(raw_packet);
328   ASSERT(acl_packet.IsValid());
329   if (loopback_mode_ == LoopbackMode::ENABLE_LOCAL) {
330     uint16_t handle = acl_packet.GetHandle();
331 
332     std::vector<bluetooth::hci::CompletedPackets> completed_packets;
333     bluetooth::hci::CompletedPackets cp;
334     cp.connection_handle_ = handle;
335     cp.host_num_of_completed_packets_ = kNumCommandPackets;
336     completed_packets.push_back(cp);
337     send_event_(bluetooth::hci::NumberOfCompletedPacketsBuilder::Create(
338         completed_packets));
339     return;
340   }
341 
342   link_layer_controller_.SendAclToRemote(acl_packet);
343 }
344 
HandleSco(std::shared_ptr<std::vector<uint8_t>> packet)345 void DualModeController::HandleSco(std::shared_ptr<std::vector<uint8_t>> packet) {
346   bluetooth::hci::PacketView<bluetooth::hci::kLittleEndian> raw_packet(packet);
347   auto sco_packet = bluetooth::hci::ScoView::Create(raw_packet);
348   if (loopback_mode_ == LoopbackMode::ENABLE_LOCAL) {
349     uint16_t handle = sco_packet.GetHandle();
350     auto sco_builder = bluetooth::hci::ScoBuilder::Create(
351         handle, sco_packet.GetPacketStatusFlag(), sco_packet.GetData());
352     send_sco_(std::move(sco_builder));
353     std::vector<bluetooth::hci::CompletedPackets> completed_packets;
354     bluetooth::hci::CompletedPackets cp;
355     cp.connection_handle_ = handle;
356     cp.host_num_of_completed_packets_ = kNumCommandPackets;
357     completed_packets.push_back(cp);
358     send_event_(bluetooth::hci::NumberOfCompletedPacketsBuilder::Create(
359         completed_packets));
360     return;
361   }
362 }
363 
HandleIso(std::shared_ptr<std::vector<uint8_t>> packet)364 void DualModeController::HandleIso(
365     std::shared_ptr<std::vector<uint8_t>> packet) {
366   bluetooth::hci::PacketView<bluetooth::hci::kLittleEndian> raw_packet(packet);
367   auto iso = bluetooth::hci::IsoView::Create(raw_packet);
368   ASSERT(iso.IsValid());
369   link_layer_controller_.HandleIso(iso);
370 }
371 
HandleCommand(std::shared_ptr<std::vector<uint8_t>> packet)372 void DualModeController::HandleCommand(std::shared_ptr<std::vector<uint8_t>> packet) {
373   bluetooth::hci::PacketView<bluetooth::hci::kLittleEndian> raw_packet(packet);
374   auto command_packet = bluetooth::hci::CommandView::Create(raw_packet);
375   ASSERT(command_packet.IsValid());
376   auto op = command_packet.GetOpCode();
377 
378   if (loopback_mode_ == LoopbackMode::ENABLE_LOCAL &&
379       // Loopback exceptions.
380       op != OpCode::RESET &&
381       op != OpCode::SET_CONTROLLER_TO_HOST_FLOW_CONTROL &&
382       op != OpCode::HOST_BUFFER_SIZE &&
383       op != OpCode::HOST_NUM_COMPLETED_PACKETS &&
384       op != OpCode::READ_BUFFER_SIZE && op != OpCode::READ_LOOPBACK_MODE &&
385       op != OpCode::WRITE_LOOPBACK_MODE) {
386     std::unique_ptr<bluetooth::packet::RawBuilder> raw_builder_ptr =
387         std::make_unique<bluetooth::packet::RawBuilder>(255);
388     raw_builder_ptr->AddOctets(*packet);
389     send_event_(bluetooth::hci::LoopbackCommandBuilder::Create(
390         std::move(raw_builder_ptr)));
391   } else if (active_hci_commands_.count(op) > 0) {
392     active_hci_commands_[op](command_packet);
393   } else {
394     uint16_t opcode = static_cast<uint16_t>(op);
395     SendCommandCompleteUnknownOpCodeEvent(opcode);
396     LOG_INFO("Unknown command, opcode: 0x%04X, OGF: 0x%04X, OCF: 0x%04X",
397              opcode, (opcode & 0xFC00) >> 10, opcode & 0x03FF);
398   }
399 }
400 
RegisterEventChannel(const std::function<void (std::shared_ptr<std::vector<uint8_t>>)> & callback)401 void DualModeController::RegisterEventChannel(
402     const std::function<void(std::shared_ptr<std::vector<uint8_t>>)>& callback) {
403   send_event_ =
404       [callback](std::shared_ptr<bluetooth::hci::EventBuilder> event) {
405         auto bytes = std::make_shared<std::vector<uint8_t>>();
406         bluetooth::packet::BitInserter bit_inserter(*bytes);
407         bytes->reserve(event->size());
408         event->Serialize(bit_inserter);
409         callback(std::move(bytes));
410       };
411   link_layer_controller_.RegisterEventChannel(send_event_);
412 }
413 
RegisterAclChannel(const std::function<void (std::shared_ptr<std::vector<uint8_t>>)> & callback)414 void DualModeController::RegisterAclChannel(
415     const std::function<void(std::shared_ptr<std::vector<uint8_t>>)>& callback) {
416   send_acl_ = [callback](std::shared_ptr<bluetooth::hci::AclBuilder> acl_data) {
417     auto bytes = std::make_shared<std::vector<uint8_t>>();
418     bluetooth::packet::BitInserter bit_inserter(*bytes);
419     bytes->reserve(acl_data->size());
420     acl_data->Serialize(bit_inserter);
421     callback(std::move(bytes));
422   };
423   link_layer_controller_.RegisterAclChannel(send_acl_);
424 }
425 
RegisterScoChannel(const std::function<void (std::shared_ptr<std::vector<uint8_t>>)> & callback)426 void DualModeController::RegisterScoChannel(
427     const std::function<void(std::shared_ptr<std::vector<uint8_t>>)>& callback) {
428   send_sco_ = [callback](std::shared_ptr<bluetooth::hci::ScoBuilder> sco_data) {
429     auto bytes = std::make_shared<std::vector<uint8_t>>();
430     bluetooth::packet::BitInserter bit_inserter(*bytes);
431     bytes->reserve(sco_data->size());
432     sco_data->Serialize(bit_inserter);
433     callback(std::move(bytes));
434   };
435   link_layer_controller_.RegisterScoChannel(send_sco_);
436 }
437 
RegisterIsoChannel(const std::function<void (std::shared_ptr<std::vector<uint8_t>>)> & callback)438 void DualModeController::RegisterIsoChannel(
439     const std::function<void(std::shared_ptr<std::vector<uint8_t>>)>&
440         callback) {
441   send_iso_ = [callback](std::shared_ptr<bluetooth::hci::IsoBuilder> iso_data) {
442     auto bytes = std::make_shared<std::vector<uint8_t>>();
443     bluetooth::packet::BitInserter bit_inserter(*bytes);
444     bytes->reserve(iso_data->size());
445     iso_data->Serialize(bit_inserter);
446     callback(std::move(bytes));
447   };
448   link_layer_controller_.RegisterIsoChannel(send_iso_);
449 }
450 
Reset(CommandView command)451 void DualModeController::Reset(CommandView command) {
452   auto command_view = gd_hci::ResetView::Create(command);
453   ASSERT(command_view.IsValid());
454   link_layer_controller_.Reset();
455   if (loopback_mode_ == LoopbackMode::ENABLE_LOCAL) {
456     loopback_mode_ = LoopbackMode::NO_LOOPBACK;
457   }
458 
459   send_event_(bluetooth::hci::ResetCompleteBuilder::Create(kNumCommandPackets,
460                                                            ErrorCode::SUCCESS));
461 }
462 
ReadBufferSize(CommandView command)463 void DualModeController::ReadBufferSize(CommandView command) {
464   auto command_view = gd_hci::ReadBufferSizeView::Create(command);
465   ASSERT(command_view.IsValid());
466 
467   auto packet = bluetooth::hci::ReadBufferSizeCompleteBuilder::Create(
468       kNumCommandPackets, ErrorCode::SUCCESS,
469       properties_.GetAclDataPacketSize(),
470       properties_.GetSynchronousDataPacketSize(),
471       properties_.GetTotalNumAclDataPackets(),
472       properties_.GetTotalNumSynchronousDataPackets());
473   send_event_(std::move(packet));
474 }
475 
ReadEncryptionKeySize(CommandView command)476 void DualModeController::ReadEncryptionKeySize(CommandView command) {
477   auto command_view = gd_hci::ReadEncryptionKeySizeView::Create(
478       gd_hci::SecurityCommandView::Create(command));
479   ASSERT(command_view.IsValid());
480 
481   auto packet = bluetooth::hci::ReadEncryptionKeySizeCompleteBuilder::Create(
482       kNumCommandPackets, ErrorCode::SUCCESS,
483       command_view.GetConnectionHandle(), properties_.GetEncryptionKeySize());
484   send_event_(std::move(packet));
485 }
486 
HostBufferSize(CommandView command)487 void DualModeController::HostBufferSize(CommandView command) {
488   auto command_view = gd_hci::HostBufferSizeView::Create(command);
489   ASSERT(command_view.IsValid());
490   auto packet = bluetooth::hci::HostBufferSizeCompleteBuilder::Create(
491       kNumCommandPackets, ErrorCode::SUCCESS);
492   send_event_(std::move(packet));
493 }
494 
ReadLocalVersionInformation(CommandView command)495 void DualModeController::ReadLocalVersionInformation(CommandView command) {
496   auto command_view = gd_hci::ReadLocalVersionInformationView::Create(command);
497   ASSERT(command_view.IsValid());
498 
499   bluetooth::hci::LocalVersionInformation local_version_information;
500   local_version_information.hci_version_ =
501       static_cast<bluetooth::hci::HciVersion>(properties_.GetVersion());
502   local_version_information.hci_revision_ = properties_.GetRevision();
503   local_version_information.lmp_version_ =
504       static_cast<bluetooth::hci::LmpVersion>(properties_.GetLmpPalVersion());
505   local_version_information.manufacturer_name_ =
506       properties_.GetManufacturerName();
507   local_version_information.lmp_subversion_ = properties_.GetLmpPalSubversion();
508   auto packet =
509       bluetooth::hci::ReadLocalVersionInformationCompleteBuilder::Create(
510           kNumCommandPackets, ErrorCode::SUCCESS, local_version_information);
511   send_event_(std::move(packet));
512 }
513 
ReadRemoteVersionInformation(CommandView command)514 void DualModeController::ReadRemoteVersionInformation(CommandView command) {
515   auto command_view = gd_hci::ReadRemoteVersionInformationView::Create(
516       gd_hci::ConnectionManagementCommandView::Create(
517           gd_hci::AclCommandView::Create(command)));
518   ASSERT(command_view.IsValid());
519 
520   auto status = link_layer_controller_.SendCommandToRemoteByHandle(
521       OpCode::READ_REMOTE_VERSION_INFORMATION, command.GetPayload(),
522       command_view.GetConnectionHandle());
523 
524   auto packet =
525       bluetooth::hci::ReadRemoteVersionInformationStatusBuilder::Create(
526           status, kNumCommandPackets);
527   send_event_(std::move(packet));
528 }
529 
ReadBdAddr(CommandView command)530 void DualModeController::ReadBdAddr(CommandView command) {
531   auto command_view = gd_hci::ReadBdAddrView::Create(command);
532   ASSERT(command_view.IsValid());
533   auto packet = bluetooth::hci::ReadBdAddrCompleteBuilder::Create(
534       kNumCommandPackets, ErrorCode::SUCCESS, properties_.GetAddress());
535   send_event_(std::move(packet));
536 }
537 
ReadLocalSupportedCommands(CommandView command)538 void DualModeController::ReadLocalSupportedCommands(CommandView command) {
539   auto command_view = gd_hci::ReadLocalSupportedCommandsView::Create(command);
540   ASSERT(command_view.IsValid());
541 
542   std::array<uint8_t, 64> supported_commands{};
543   supported_commands.fill(0x00);
544   size_t len = properties_.GetSupportedCommands().size();
545   if (len > 64) {
546     len = 64;
547   }
548   std::copy_n(properties_.GetSupportedCommands().begin(), len,
549               supported_commands.begin());
550 
551   auto packet =
552       bluetooth::hci::ReadLocalSupportedCommandsCompleteBuilder::Create(
553           kNumCommandPackets, ErrorCode::SUCCESS, supported_commands);
554   send_event_(std::move(packet));
555 }
556 
ReadLocalSupportedFeatures(CommandView command)557 void DualModeController::ReadLocalSupportedFeatures(CommandView command) {
558   auto command_view = gd_hci::ReadLocalSupportedFeaturesView::Create(command);
559   ASSERT(command_view.IsValid());
560   auto packet =
561       bluetooth::hci::ReadLocalSupportedFeaturesCompleteBuilder::Create(
562           kNumCommandPackets, ErrorCode::SUCCESS,
563           properties_.GetSupportedFeatures());
564   send_event_(std::move(packet));
565 }
566 
ReadLocalSupportedCodecs(CommandView command)567 void DualModeController::ReadLocalSupportedCodecs(CommandView command) {
568   auto command_view = gd_hci::ReadLocalSupportedCodecsV1View::Create(command);
569   ASSERT(command_view.IsValid());
570   auto packet =
571       bluetooth::hci::ReadLocalSupportedCodecsV1CompleteBuilder::Create(
572           kNumCommandPackets, ErrorCode::SUCCESS,
573           properties_.GetSupportedCodecs(),
574           properties_.GetVendorSpecificCodecs());
575   send_event_(std::move(packet));
576 }
577 
ReadLocalExtendedFeatures(CommandView command)578 void DualModeController::ReadLocalExtendedFeatures(CommandView command) {
579   auto command_view = gd_hci::ReadLocalExtendedFeaturesView::Create(command);
580   ASSERT(command_view.IsValid());
581   uint8_t page_number = command_view.GetPageNumber();
582 
583   auto pakcet =
584       bluetooth::hci::ReadLocalExtendedFeaturesCompleteBuilder::Create(
585           kNumCommandPackets, ErrorCode::SUCCESS, page_number,
586           properties_.GetExtendedFeaturesMaximumPageNumber(),
587           properties_.GetExtendedFeatures(page_number));
588   send_event_(std::move(pakcet));
589 }
590 
ReadRemoteExtendedFeatures(CommandView command)591 void DualModeController::ReadRemoteExtendedFeatures(CommandView command) {
592   auto command_view = gd_hci::ReadRemoteExtendedFeaturesView::Create(
593       gd_hci::ConnectionManagementCommandView::Create(
594           gd_hci::AclCommandView::Create(command)));
595   ASSERT(command_view.IsValid());
596 
597   auto status = link_layer_controller_.SendCommandToRemoteByHandle(
598       OpCode::READ_REMOTE_EXTENDED_FEATURES, command_view.GetPayload(),
599       command_view.GetConnectionHandle());
600 
601   auto packet = bluetooth::hci::ReadRemoteExtendedFeaturesStatusBuilder::Create(
602       status, kNumCommandPackets);
603   send_event_(std::move(packet));
604 }
605 
SwitchRole(CommandView command)606 void DualModeController::SwitchRole(CommandView command) {
607   auto command_view = gd_hci::SwitchRoleView::Create(
608       gd_hci::ConnectionManagementCommandView::Create(
609           gd_hci::AclCommandView::Create(command)));
610   ASSERT(command_view.IsValid());
611 
612   auto status = link_layer_controller_.SwitchRole(
613       command_view.GetBdAddr(), static_cast<uint8_t>(command_view.GetRole()));
614 
615   auto packet = bluetooth::hci::SwitchRoleStatusBuilder::Create(
616       status, kNumCommandPackets);
617   send_event_(std::move(packet));
618 }
619 
ReadRemoteSupportedFeatures(CommandView command)620 void DualModeController::ReadRemoteSupportedFeatures(CommandView command) {
621   auto command_view = gd_hci::ReadRemoteSupportedFeaturesView::Create(
622       gd_hci::ConnectionManagementCommandView::Create(
623           gd_hci::AclCommandView::Create(command)));
624   ASSERT(command_view.IsValid());
625 
626   auto status = link_layer_controller_.SendCommandToRemoteByHandle(
627       OpCode::READ_REMOTE_SUPPORTED_FEATURES, command_view.GetPayload(),
628       command_view.GetConnectionHandle());
629 
630   auto packet =
631       bluetooth::hci::ReadRemoteSupportedFeaturesStatusBuilder::Create(
632           status, kNumCommandPackets);
633   send_event_(std::move(packet));
634 }
635 
ReadClockOffset(CommandView command)636 void DualModeController::ReadClockOffset(CommandView command) {
637   auto command_view = gd_hci::ReadClockOffsetView::Create(
638       gd_hci::ConnectionManagementCommandView::Create(
639           gd_hci::AclCommandView::Create(command)));
640   ASSERT(command_view.IsValid());
641 
642   uint16_t handle = command_view.GetConnectionHandle();
643 
644   auto status = link_layer_controller_.SendCommandToRemoteByHandle(
645       OpCode::READ_CLOCK_OFFSET, command_view.GetPayload(), handle);
646 
647   auto packet = bluetooth::hci::ReadClockOffsetStatusBuilder::Create(
648       status, kNumCommandPackets);
649   send_event_(std::move(packet));
650 }
651 
IoCapabilityRequestReply(CommandView command)652 void DualModeController::IoCapabilityRequestReply(CommandView command) {
653   auto command_view = gd_hci::IoCapabilityRequestReplyView::Create(
654       gd_hci::SecurityCommandView::Create(command));
655   ASSERT(command_view.IsValid());
656 
657   Address peer = command_view.GetBdAddr();
658   uint8_t io_capability = static_cast<uint8_t>(command_view.GetIoCapability());
659   uint8_t oob_data_present_flag =
660       static_cast<uint8_t>(command_view.GetOobPresent());
661   uint8_t authentication_requirements =
662       static_cast<uint8_t>(command_view.GetAuthenticationRequirements());
663 
664   auto status = link_layer_controller_.IoCapabilityRequestReply(
665       peer, io_capability, oob_data_present_flag, authentication_requirements);
666   auto packet = bluetooth::hci::IoCapabilityRequestReplyCompleteBuilder::Create(
667       kNumCommandPackets, status, peer);
668 
669   send_event_(std::move(packet));
670 }
671 
UserConfirmationRequestReply(CommandView command)672 void DualModeController::UserConfirmationRequestReply(CommandView command) {
673   auto command_view = gd_hci::UserConfirmationRequestReplyView::Create(
674       gd_hci::SecurityCommandView::Create(command));
675   ASSERT(command_view.IsValid());
676 
677   Address peer = command_view.GetBdAddr();
678 
679   auto status = link_layer_controller_.UserConfirmationRequestReply(peer);
680   auto packet =
681       bluetooth::hci::UserConfirmationRequestReplyCompleteBuilder::Create(
682           kNumCommandPackets, status, peer);
683 
684   send_event_(std::move(packet));
685 }
686 
UserConfirmationRequestNegativeReply(CommandView command)687 void DualModeController::UserConfirmationRequestNegativeReply(
688     CommandView command) {
689   auto command_view = gd_hci::UserConfirmationRequestNegativeReplyView::Create(
690       gd_hci::SecurityCommandView::Create(command));
691   ASSERT(command_view.IsValid());
692 
693   Address peer = command_view.GetBdAddr();
694 
695   auto status =
696       link_layer_controller_.UserConfirmationRequestNegativeReply(peer);
697   auto packet =
698       bluetooth::hci::UserConfirmationRequestNegativeReplyCompleteBuilder::
699           Create(kNumCommandPackets, status, peer);
700 
701   send_event_(std::move(packet));
702 }
703 
PinCodeRequestReply(CommandView command)704 void DualModeController::PinCodeRequestReply(CommandView command) {
705   auto command_view = gd_hci::PinCodeRequestReplyView::Create(
706       gd_hci::SecurityCommandView::Create(command));
707   ASSERT(command_view.IsValid());
708   LOG_INFO("%s", properties_.GetAddress().ToString().c_str());
709 
710   Address peer = command_view.GetBdAddr();
711   uint8_t pin_length = command_view.GetPinCodeLength();
712   std::array<uint8_t, 16> pin = command_view.GetPinCode();
713   ErrorCode status = ErrorCode::INVALID_HCI_COMMAND_PARAMETERS;
714   if (pin_length >= 1 && pin_length <= 0x10) {
715     status = link_layer_controller_.PinCodeRequestReply(
716         peer, std::vector<uint8_t>(pin.begin(), pin.begin() + pin_length));
717   }
718 
719   send_event_(bluetooth::hci::PinCodeRequestReplyCompleteBuilder::Create(
720       kNumCommandPackets, status, peer));
721 }
722 
PinCodeRequestNegativeReply(CommandView command)723 void DualModeController::PinCodeRequestNegativeReply(CommandView command) {
724   auto command_view = gd_hci::PinCodeRequestNegativeReplyView::Create(
725       gd_hci::SecurityCommandView::Create(command));
726   ASSERT(command_view.IsValid());
727   LOG_INFO("%s", properties_.GetAddress().ToString().c_str());
728 
729   Address peer = command_view.GetBdAddr();
730 
731   auto status = link_layer_controller_.PinCodeRequestNegativeReply(peer);
732   auto packet =
733       bluetooth::hci::PinCodeRequestNegativeReplyCompleteBuilder::Create(
734           kNumCommandPackets, status, peer);
735 
736   send_event_(std::move(packet));
737 }
738 
UserPasskeyRequestReply(CommandView command)739 void DualModeController::UserPasskeyRequestReply(CommandView command) {
740   auto command_view = gd_hci::UserPasskeyRequestReplyView::Create(
741       gd_hci::SecurityCommandView::Create(command));
742   ASSERT(command_view.IsValid());
743 
744   Address peer = command_view.GetBdAddr();
745   uint32_t numeric_value = command_view.GetNumericValue();
746 
747   auto status =
748       link_layer_controller_.UserPasskeyRequestReply(peer, numeric_value);
749   auto packet = bluetooth::hci::UserPasskeyRequestReplyCompleteBuilder::Create(
750       kNumCommandPackets, status, peer);
751 
752   send_event_(std::move(packet));
753 }
754 
UserPasskeyRequestNegativeReply(CommandView command)755 void DualModeController::UserPasskeyRequestNegativeReply(CommandView command) {
756   auto command_view = gd_hci::UserPasskeyRequestNegativeReplyView::Create(
757       gd_hci::SecurityCommandView::Create(command));
758   ASSERT(command_view.IsValid());
759 
760   Address peer = command_view.GetBdAddr();
761 
762   auto status = link_layer_controller_.UserPasskeyRequestNegativeReply(peer);
763   auto packet =
764       bluetooth::hci::UserPasskeyRequestNegativeReplyCompleteBuilder::Create(
765           kNumCommandPackets, status, peer);
766 
767   send_event_(std::move(packet));
768 }
769 
RemoteOobDataRequestReply(CommandView command)770 void DualModeController::RemoteOobDataRequestReply(CommandView command) {
771   auto command_view = gd_hci::RemoteOobDataRequestReplyView::Create(
772       gd_hci::SecurityCommandView::Create(command));
773   ASSERT(command_view.IsValid());
774 
775   Address peer = command_view.GetBdAddr();
776 
777   auto status = link_layer_controller_.RemoteOobDataRequestReply(
778       peer, command_view.GetC(), command_view.GetR());
779 
780   send_event_(bluetooth::hci::RemoteOobDataRequestReplyCompleteBuilder::Create(
781       kNumCommandPackets, status, peer));
782 }
783 
RemoteOobDataRequestNegativeReply(CommandView command)784 void DualModeController::RemoteOobDataRequestNegativeReply(
785     CommandView command) {
786   auto command_view = gd_hci::RemoteOobDataRequestNegativeReplyView::Create(
787       gd_hci::SecurityCommandView::Create(command));
788   ASSERT(command_view.IsValid());
789 
790   Address peer = command_view.GetBdAddr();
791 
792   auto status = link_layer_controller_.RemoteOobDataRequestNegativeReply(peer);
793   auto packet =
794       bluetooth::hci::RemoteOobDataRequestNegativeReplyCompleteBuilder::Create(
795           kNumCommandPackets, status, peer);
796 
797   send_event_(std::move(packet));
798 }
799 
IoCapabilityRequestNegativeReply(CommandView command)800 void DualModeController::IoCapabilityRequestNegativeReply(CommandView command) {
801   auto command_view = gd_hci::IoCapabilityRequestNegativeReplyView::Create(
802       gd_hci::SecurityCommandView::Create(command));
803   ASSERT(command_view.IsValid());
804 
805   Address peer = command_view.GetBdAddr();
806   ErrorCode reason = command_view.GetReason();
807 
808   auto status =
809       link_layer_controller_.IoCapabilityRequestNegativeReply(peer, reason);
810   auto packet =
811       bluetooth::hci::IoCapabilityRequestNegativeReplyCompleteBuilder::Create(
812           kNumCommandPackets, status, peer);
813 
814   send_event_(std::move(packet));
815 }
816 
RemoteOobExtendedDataRequestReply(CommandView command)817 void DualModeController::RemoteOobExtendedDataRequestReply(
818     CommandView command) {
819   auto command_view = gd_hci::RemoteOobExtendedDataRequestReplyView::Create(
820       gd_hci::SecurityCommandView::Create(command));
821   ASSERT(command_view.IsValid());
822 
823   Address peer = command_view.GetBdAddr();
824 
825   auto status = link_layer_controller_.RemoteOobExtendedDataRequestReply(
826       peer, command_view.GetC192(), command_view.GetR192(),
827       command_view.GetC256(), command_view.GetR256());
828 
829   send_event_(
830       bluetooth::hci::RemoteOobExtendedDataRequestReplyCompleteBuilder::Create(
831           kNumCommandPackets, status, peer));
832 }
833 
ReadInquiryResponseTransmitPowerLevel(CommandView command)834 void DualModeController::ReadInquiryResponseTransmitPowerLevel(
835     CommandView command) {
836   auto command_view = gd_hci::ReadInquiryResponseTransmitPowerLevelView::Create(
837       gd_hci::DiscoveryCommandView::Create(command));
838   ASSERT(command_view.IsValid());
839 
840   uint8_t tx_power = 20;  // maximum
841   auto packet =
842       bluetooth::hci::ReadInquiryResponseTransmitPowerLevelCompleteBuilder::
843           Create(kNumCommandPackets, ErrorCode::SUCCESS, tx_power);
844   send_event_(std::move(packet));
845 }
846 
SendKeypressNotification(CommandView command)847 void DualModeController::SendKeypressNotification(CommandView command) {
848   auto command_view = gd_hci::SendKeypressNotificationView::Create(
849       gd_hci::SecurityCommandView::Create(command));
850   ASSERT(command_view.IsValid());
851 
852   auto peer = command_view.GetBdAddr();
853 
854   auto status = link_layer_controller_.SendKeypressNotification(
855       peer, command_view.GetNotificationType());
856   send_event_(bluetooth::hci::SendKeypressNotificationCompleteBuilder::Create(
857       kNumCommandPackets, status, peer));
858 }
859 
SetEventMaskPage2(CommandView command)860 void DualModeController::SetEventMaskPage2(CommandView command) {
861   auto payload =
862       std::make_unique<bluetooth::packet::RawBuilder>(std::vector<uint8_t>(
863           {static_cast<uint8_t>(bluetooth::hci::ErrorCode::SUCCESS)}));
864   send_event_(bluetooth::hci::CommandCompleteBuilder::Create(
865       kNumCommandPackets, command.GetOpCode(), std::move(payload)));
866 }
867 
ReadLocalOobData(CommandView command)868 void DualModeController::ReadLocalOobData(CommandView command) {
869   auto command_view = gd_hci::ReadLocalOobDataView::Create(
870       gd_hci::SecurityCommandView::Create(command));
871   link_layer_controller_.ReadLocalOobData();
872 }
873 
ReadLocalOobExtendedData(CommandView command)874 void DualModeController::ReadLocalOobExtendedData(CommandView command) {
875   auto command_view = gd_hci::ReadLocalOobExtendedDataView::Create(
876       gd_hci::SecurityCommandView::Create(command));
877   link_layer_controller_.ReadLocalOobExtendedData();
878 }
879 
WriteSimplePairingMode(CommandView command)880 void DualModeController::WriteSimplePairingMode(CommandView command) {
881   auto command_view = gd_hci::WriteSimplePairingModeView::Create(
882       gd_hci::SecurityCommandView::Create(command));
883   ASSERT(command_view.IsValid());
884 
885   auto enabled = command_view.GetSimplePairingMode() == gd_hci::Enable::ENABLED;
886   properties_.SetSecureSimplePairingSupport(enabled);
887   auto packet = bluetooth::hci::WriteSimplePairingModeCompleteBuilder::Create(
888       kNumCommandPackets, ErrorCode::SUCCESS);
889   send_event_(std::move(packet));
890 }
891 
ChangeConnectionPacketType(CommandView command)892 void DualModeController::ChangeConnectionPacketType(CommandView command) {
893   auto command_view = gd_hci::ChangeConnectionPacketTypeView::Create(
894       gd_hci::ConnectionManagementCommandView::Create(
895           gd_hci::AclCommandView::Create(command)));
896   ASSERT(command_view.IsValid());
897 
898   uint16_t handle = command_view.GetConnectionHandle();
899   uint16_t packet_type = static_cast<uint16_t>(command_view.GetPacketType());
900 
901   auto status =
902       link_layer_controller_.ChangeConnectionPacketType(handle, packet_type);
903 
904   auto packet = bluetooth::hci::ChangeConnectionPacketTypeStatusBuilder::Create(
905       status, kNumCommandPackets);
906   send_event_(std::move(packet));
907 }
908 
WriteLeHostSupport(CommandView command)909 void DualModeController::WriteLeHostSupport(CommandView command) {
910   auto command_view = gd_hci::WriteLeHostSupportView::Create(command);
911   ASSERT(command_view.IsValid());
912   auto le_support =
913       command_view.GetLeSupportedHost() == gd_hci::Enable::ENABLED;
914   properties_.SetLeHostSupport(le_support);
915   auto packet = bluetooth::hci::WriteLeHostSupportCompleteBuilder::Create(
916       kNumCommandPackets, ErrorCode::SUCCESS);
917   send_event_(std::move(packet));
918 }
919 
WriteSecureConnectionsHostSupport(CommandView command)920 void DualModeController::WriteSecureConnectionsHostSupport(
921     CommandView command) {
922   auto command_view = gd_hci::WriteSecureConnectionsHostSupportView::Create(
923       gd_hci::SecurityCommandView::Create(command));
924   ASSERT(command_view.IsValid());
925   properties_.SetSecureConnections(
926       command_view.GetSecureConnectionsHostSupport() ==
927       bluetooth::hci::Enable::ENABLED);
928   auto packet =
929       bluetooth::hci::WriteSecureConnectionsHostSupportCompleteBuilder::Create(
930           kNumCommandPackets, ErrorCode::SUCCESS);
931   send_event_(std::move(packet));
932 }
933 
SetEventMask(CommandView command)934 void DualModeController::SetEventMask(CommandView command) {
935   auto command_view = gd_hci::SetEventMaskView::Create(command);
936   ASSERT(command_view.IsValid());
937   properties_.SetEventMask(command_view.GetEventMask());
938   auto packet = bluetooth::hci::SetEventMaskCompleteBuilder::Create(
939       kNumCommandPackets, ErrorCode::SUCCESS);
940   send_event_(std::move(packet));
941 }
942 
ReadInquiryMode(CommandView command)943 void DualModeController::ReadInquiryMode(CommandView command) {
944   auto command_view = gd_hci::ReadInquiryModeView::Create(
945       gd_hci::DiscoveryCommandView::Create(command));
946   ASSERT(command_view.IsValid());
947   gd_hci::InquiryMode inquiry_mode = gd_hci::InquiryMode::STANDARD;
948   auto packet = bluetooth::hci::ReadInquiryModeCompleteBuilder::Create(
949       kNumCommandPackets, ErrorCode::SUCCESS, inquiry_mode);
950   send_event_(std::move(packet));
951 }
952 
WriteInquiryMode(CommandView command)953 void DualModeController::WriteInquiryMode(CommandView command) {
954   auto command_view = gd_hci::WriteInquiryModeView::Create(
955       gd_hci::DiscoveryCommandView::Create(command));
956   ASSERT(command_view.IsValid());
957   link_layer_controller_.SetInquiryMode(
958       static_cast<uint8_t>(command_view.GetInquiryMode()));
959   auto packet = bluetooth::hci::WriteInquiryModeCompleteBuilder::Create(
960       kNumCommandPackets, ErrorCode::SUCCESS);
961   send_event_(std::move(packet));
962 }
963 
ReadPageScanType(CommandView command)964 void DualModeController::ReadPageScanType(CommandView command) {
965   auto command_view = gd_hci::ReadPageScanTypeView::Create(
966       gd_hci::DiscoveryCommandView::Create(command));
967   ASSERT(command_view.IsValid());
968   gd_hci::PageScanType page_scan_type = gd_hci::PageScanType::STANDARD;
969   auto packet = bluetooth::hci::ReadPageScanTypeCompleteBuilder::Create(
970       kNumCommandPackets, ErrorCode::SUCCESS, page_scan_type);
971   send_event_(std::move(packet));
972 }
973 
WritePageScanType(CommandView command)974 void DualModeController::WritePageScanType(CommandView command) {
975   auto command_view = gd_hci::WritePageScanTypeView::Create(
976       gd_hci::DiscoveryCommandView::Create(command));
977   ASSERT(command_view.IsValid());
978   auto packet = bluetooth::hci::WritePageScanTypeCompleteBuilder::Create(
979       kNumCommandPackets, ErrorCode::SUCCESS);
980   send_event_(std::move(packet));
981 }
982 
ReadInquiryScanType(CommandView command)983 void DualModeController::ReadInquiryScanType(CommandView command) {
984   auto command_view = gd_hci::ReadInquiryScanTypeView::Create(
985       gd_hci::DiscoveryCommandView::Create(command));
986   ASSERT(command_view.IsValid());
987   gd_hci::InquiryScanType inquiry_scan_type = gd_hci::InquiryScanType::STANDARD;
988   auto packet = bluetooth::hci::ReadInquiryScanTypeCompleteBuilder::Create(
989       kNumCommandPackets, ErrorCode::SUCCESS, inquiry_scan_type);
990   send_event_(std::move(packet));
991 }
992 
WriteInquiryScanType(CommandView command)993 void DualModeController::WriteInquiryScanType(CommandView command) {
994   auto command_view = gd_hci::WriteInquiryScanTypeView::Create(
995       gd_hci::DiscoveryCommandView::Create(command));
996   ASSERT(command_view.IsValid());
997   auto packet = bluetooth::hci::WriteInquiryScanTypeCompleteBuilder::Create(
998       kNumCommandPackets, ErrorCode::SUCCESS);
999   send_event_(std::move(packet));
1000 }
1001 
AuthenticationRequested(CommandView command)1002 void DualModeController::AuthenticationRequested(CommandView command) {
1003   auto command_view = gd_hci::AuthenticationRequestedView::Create(
1004       gd_hci::ConnectionManagementCommandView::Create(
1005           gd_hci::AclCommandView::Create(command)));
1006   ASSERT(command_view.IsValid());
1007   uint16_t handle = command_view.GetConnectionHandle();
1008   auto status = link_layer_controller_.AuthenticationRequested(handle);
1009 
1010   auto packet = bluetooth::hci::AuthenticationRequestedStatusBuilder::Create(
1011       status, kNumCommandPackets);
1012   send_event_(std::move(packet));
1013 }
1014 
SetConnectionEncryption(CommandView command)1015 void DualModeController::SetConnectionEncryption(CommandView command) {
1016   auto command_view = gd_hci::SetConnectionEncryptionView::Create(
1017       gd_hci::ConnectionManagementCommandView::Create(
1018           gd_hci::AclCommandView::Create(command)));
1019   ASSERT(command_view.IsValid());
1020   uint16_t handle = command_view.GetConnectionHandle();
1021   uint8_t encryption_enable =
1022       static_cast<uint8_t>(command_view.GetEncryptionEnable());
1023   auto status =
1024       link_layer_controller_.SetConnectionEncryption(handle, encryption_enable);
1025 
1026   auto packet = bluetooth::hci::SetConnectionEncryptionStatusBuilder::Create(
1027       status, kNumCommandPackets);
1028   send_event_(std::move(packet));
1029 }
1030 
ChangeConnectionLinkKey(CommandView command)1031 void DualModeController::ChangeConnectionLinkKey(CommandView command) {
1032   auto command_view = gd_hci::ChangeConnectionLinkKeyView::Create(
1033       gd_hci::ConnectionManagementCommandView::Create(
1034           gd_hci::AclCommandView::Create(command)));
1035   ASSERT(command_view.IsValid());
1036   uint16_t handle = command_view.GetConnectionHandle();
1037 
1038   auto status = link_layer_controller_.ChangeConnectionLinkKey(handle);
1039 
1040   auto packet = bluetooth::hci::ChangeConnectionLinkKeyStatusBuilder::Create(
1041       status, kNumCommandPackets);
1042   send_event_(std::move(packet));
1043 }
1044 
CentralLinkKey(CommandView command)1045 void DualModeController::CentralLinkKey(CommandView command) {
1046   auto command_view = gd_hci::CentralLinkKeyView::Create(
1047       gd_hci::ConnectionManagementCommandView::Create(
1048           gd_hci::AclCommandView::Create(command)));
1049   ASSERT(command_view.IsValid());
1050   uint8_t key_flag = static_cast<uint8_t>(command_view.GetKeyFlag());
1051 
1052   auto status = link_layer_controller_.CentralLinkKey(key_flag);
1053 
1054   auto packet = bluetooth::hci::CentralLinkKeyStatusBuilder::Create(
1055       status, kNumCommandPackets);
1056   send_event_(std::move(packet));
1057 }
1058 
WriteAuthenticationEnable(CommandView command)1059 void DualModeController::WriteAuthenticationEnable(CommandView command) {
1060   auto command_view = gd_hci::WriteAuthenticationEnableView::Create(
1061       gd_hci::SecurityCommandView::Create(command));
1062   ASSERT(command_view.IsValid());
1063   properties_.SetAuthenticationEnable(
1064       static_cast<uint8_t>(command_view.GetAuthenticationEnable()));
1065   auto packet =
1066       bluetooth::hci::WriteAuthenticationEnableCompleteBuilder::Create(
1067           kNumCommandPackets, ErrorCode::SUCCESS);
1068   send_event_(std::move(packet));
1069 }
1070 
ReadAuthenticationEnable(CommandView command)1071 void DualModeController::ReadAuthenticationEnable(CommandView command) {
1072   auto command_view = gd_hci::ReadAuthenticationEnableView::Create(command);
1073   ASSERT(command_view.IsValid());
1074   auto packet = bluetooth::hci::ReadAuthenticationEnableCompleteBuilder::Create(
1075       kNumCommandPackets, ErrorCode::SUCCESS,
1076       static_cast<bluetooth::hci::AuthenticationEnable>(
1077           properties_.GetAuthenticationEnable()));
1078   send_event_(std::move(packet));
1079 }
1080 
WriteClassOfDevice(CommandView command)1081 void DualModeController::WriteClassOfDevice(CommandView command) {
1082   auto command_view = gd_hci::WriteClassOfDeviceView::Create(
1083       gd_hci::DiscoveryCommandView::Create(command));
1084   ASSERT(command_view.IsValid());
1085   ClassOfDevice class_of_device = command_view.GetClassOfDevice();
1086   properties_.SetClassOfDevice(class_of_device.cod[0], class_of_device.cod[1],
1087                                class_of_device.cod[2]);
1088   auto packet = bluetooth::hci::WriteClassOfDeviceCompleteBuilder::Create(
1089       kNumCommandPackets, ErrorCode::SUCCESS);
1090   send_event_(std::move(packet));
1091 }
1092 
ReadPageTimeout(CommandView command)1093 void DualModeController::ReadPageTimeout(CommandView command) {
1094   auto command_view = gd_hci::ReadPageTimeoutView::Create(
1095       gd_hci::DiscoveryCommandView::Create(command));
1096   ASSERT(command_view.IsValid());
1097   uint16_t page_timeout = 0x2000;
1098   auto packet = bluetooth::hci::ReadPageTimeoutCompleteBuilder::Create(
1099       kNumCommandPackets, ErrorCode::SUCCESS, page_timeout);
1100   send_event_(std::move(packet));
1101 }
1102 
WritePageTimeout(CommandView command)1103 void DualModeController::WritePageTimeout(CommandView command) {
1104   auto command_view = gd_hci::WritePageTimeoutView::Create(
1105       gd_hci::DiscoveryCommandView::Create(command));
1106   ASSERT(command_view.IsValid());
1107   auto packet = bluetooth::hci::WritePageTimeoutCompleteBuilder::Create(
1108       kNumCommandPackets, ErrorCode::SUCCESS);
1109   send_event_(std::move(packet));
1110 }
1111 
HoldMode(CommandView command)1112 void DualModeController::HoldMode(CommandView command) {
1113   auto command_view = gd_hci::HoldModeView::Create(
1114       gd_hci::ConnectionManagementCommandView::Create(
1115           gd_hci::AclCommandView::Create(command)));
1116   ASSERT(command_view.IsValid());
1117   uint16_t handle = command_view.GetConnectionHandle();
1118   uint16_t hold_mode_max_interval = command_view.GetHoldModeMaxInterval();
1119   uint16_t hold_mode_min_interval = command_view.GetHoldModeMinInterval();
1120 
1121   auto status = link_layer_controller_.HoldMode(handle, hold_mode_max_interval,
1122                                                 hold_mode_min_interval);
1123 
1124   auto packet =
1125       bluetooth::hci::HoldModeStatusBuilder::Create(status, kNumCommandPackets);
1126   send_event_(std::move(packet));
1127 }
1128 
SniffMode(CommandView command)1129 void DualModeController::SniffMode(CommandView command) {
1130   auto command_view = gd_hci::SniffModeView::Create(
1131       gd_hci::ConnectionManagementCommandView::Create(
1132           gd_hci::AclCommandView::Create(command)));
1133   ASSERT(command_view.IsValid());
1134   uint16_t handle = command_view.GetConnectionHandle();
1135   uint16_t sniff_max_interval = command_view.GetSniffMaxInterval();
1136   uint16_t sniff_min_interval = command_view.GetSniffMinInterval();
1137   uint16_t sniff_attempt = command_view.GetSniffAttempt();
1138   uint16_t sniff_timeout = command_view.GetSniffTimeout();
1139 
1140   auto status = link_layer_controller_.SniffMode(handle, sniff_max_interval,
1141                                                  sniff_min_interval,
1142                                                  sniff_attempt, sniff_timeout);
1143 
1144   auto packet = bluetooth::hci::SniffModeStatusBuilder::Create(
1145       status, kNumCommandPackets);
1146   send_event_(std::move(packet));
1147 }
1148 
ExitSniffMode(CommandView command)1149 void DualModeController::ExitSniffMode(CommandView command) {
1150   auto command_view = gd_hci::ExitSniffModeView::Create(
1151       gd_hci::ConnectionManagementCommandView::Create(
1152           gd_hci::AclCommandView::Create(command)));
1153   ASSERT(command_view.IsValid());
1154 
1155   auto status =
1156       link_layer_controller_.ExitSniffMode(command_view.GetConnectionHandle());
1157 
1158   auto packet = bluetooth::hci::ExitSniffModeStatusBuilder::Create(
1159       status, kNumCommandPackets);
1160   send_event_(std::move(packet));
1161 }
1162 
QosSetup(CommandView command)1163 void DualModeController::QosSetup(CommandView command) {
1164   auto command_view = gd_hci::QosSetupView::Create(
1165       gd_hci::ConnectionManagementCommandView::Create(
1166           gd_hci::AclCommandView::Create(command)));
1167   ASSERT(command_view.IsValid());
1168   uint16_t handle = command_view.GetConnectionHandle();
1169   uint8_t service_type = static_cast<uint8_t>(command_view.GetServiceType());
1170   uint32_t token_rate = command_view.GetTokenRate();
1171   uint32_t peak_bandwidth = command_view.GetPeakBandwidth();
1172   uint32_t latency = command_view.GetLatency();
1173   uint32_t delay_variation = command_view.GetDelayVariation();
1174 
1175   auto status =
1176       link_layer_controller_.QosSetup(handle, service_type, token_rate,
1177                                       peak_bandwidth, latency, delay_variation);
1178 
1179   auto packet =
1180       bluetooth::hci::QosSetupStatusBuilder::Create(status, kNumCommandPackets);
1181   send_event_(std::move(packet));
1182 }
1183 
ReadDefaultLinkPolicySettings(CommandView command)1184 void DualModeController::ReadDefaultLinkPolicySettings(CommandView command) {
1185   auto command_view = gd_hci::ReadDefaultLinkPolicySettingsView::Create(
1186       gd_hci::ConnectionManagementCommandView::Create(
1187           gd_hci::AclCommandView::Create(command)));
1188   ASSERT(command_view.IsValid());
1189   uint16_t settings = link_layer_controller_.ReadDefaultLinkPolicySettings();
1190   auto packet =
1191       bluetooth::hci::ReadDefaultLinkPolicySettingsCompleteBuilder::Create(
1192           kNumCommandPackets, ErrorCode::SUCCESS, settings);
1193   send_event_(std::move(packet));
1194 }
1195 
WriteDefaultLinkPolicySettings(CommandView command)1196 void DualModeController::WriteDefaultLinkPolicySettings(CommandView command) {
1197   auto command_view = gd_hci::WriteDefaultLinkPolicySettingsView::Create(
1198       gd_hci::ConnectionManagementCommandView::Create(
1199           gd_hci::AclCommandView::Create(command)));
1200   ASSERT(command_view.IsValid());
1201   ErrorCode status = link_layer_controller_.WriteDefaultLinkPolicySettings(
1202       command_view.GetDefaultLinkPolicySettings());
1203   auto packet =
1204       bluetooth::hci::WriteDefaultLinkPolicySettingsCompleteBuilder::Create(
1205           kNumCommandPackets, status);
1206   send_event_(std::move(packet));
1207 }
1208 
FlowSpecification(CommandView command)1209 void DualModeController::FlowSpecification(CommandView command) {
1210   auto command_view = gd_hci::FlowSpecificationView::Create(
1211       gd_hci::ConnectionManagementCommandView::Create(
1212           gd_hci::AclCommandView::Create(command)));
1213   ASSERT(command_view.IsValid());
1214   uint16_t handle = command_view.GetConnectionHandle();
1215   uint8_t flow_direction =
1216       static_cast<uint8_t>(command_view.GetFlowDirection());
1217   uint8_t service_type = static_cast<uint8_t>(command_view.GetServiceType());
1218   uint32_t token_rate = command_view.GetTokenRate();
1219   uint32_t token_bucket_size = command_view.GetTokenBucketSize();
1220   uint32_t peak_bandwidth = command_view.GetPeakBandwidth();
1221   uint32_t access_latency = command_view.GetAccessLatency();
1222 
1223   auto status = link_layer_controller_.FlowSpecification(
1224       handle, flow_direction, service_type, token_rate, token_bucket_size,
1225       peak_bandwidth, access_latency);
1226 
1227   auto packet = bluetooth::hci::FlowSpecificationStatusBuilder::Create(
1228       status, kNumCommandPackets);
1229   send_event_(std::move(packet));
1230 }
1231 
WriteLinkPolicySettings(CommandView command)1232 void DualModeController::WriteLinkPolicySettings(CommandView command) {
1233   auto command_view = gd_hci::WriteLinkPolicySettingsView::Create(
1234       gd_hci::ConnectionManagementCommandView::Create(
1235           gd_hci::AclCommandView::Create(command)));
1236   ASSERT(command_view.IsValid());
1237 
1238   uint16_t handle = command_view.GetConnectionHandle();
1239   uint16_t settings = command_view.GetLinkPolicySettings();
1240 
1241   auto status =
1242       link_layer_controller_.WriteLinkPolicySettings(handle, settings);
1243 
1244   auto packet = bluetooth::hci::WriteLinkPolicySettingsCompleteBuilder::Create(
1245       kNumCommandPackets, status, handle);
1246   send_event_(std::move(packet));
1247 }
1248 
WriteLinkSupervisionTimeout(CommandView command)1249 void DualModeController::WriteLinkSupervisionTimeout(CommandView command) {
1250   auto command_view = gd_hci::WriteLinkSupervisionTimeoutView::Create(
1251       gd_hci::ConnectionManagementCommandView::Create(
1252           gd_hci::AclCommandView::Create(command)));
1253   ASSERT(command_view.IsValid());
1254 
1255   uint16_t handle = command_view.GetConnectionHandle();
1256   uint16_t timeout = command_view.GetLinkSupervisionTimeout();
1257 
1258   auto status =
1259       link_layer_controller_.WriteLinkSupervisionTimeout(handle, timeout);
1260   auto packet =
1261       bluetooth::hci::WriteLinkSupervisionTimeoutCompleteBuilder::Create(
1262           kNumCommandPackets, status, handle);
1263   send_event_(std::move(packet));
1264 }
1265 
ReadLocalName(CommandView command)1266 void DualModeController::ReadLocalName(CommandView command) {
1267   auto command_view = gd_hci::ReadLocalNameView::Create(command);
1268   ASSERT(command_view.IsValid());
1269 
1270   std::array<uint8_t, 248> local_name{};
1271   local_name.fill(0x00);
1272   size_t len = properties_.GetName().size();
1273   if (len > 247) {
1274     len = 247;  // one byte for NULL octet (0x00)
1275   }
1276   std::copy_n(properties_.GetName().begin(), len, local_name.begin());
1277 
1278   auto packet = bluetooth::hci::ReadLocalNameCompleteBuilder::Create(
1279       kNumCommandPackets, ErrorCode::SUCCESS, local_name);
1280   send_event_(std::move(packet));
1281 }
1282 
WriteLocalName(CommandView command)1283 void DualModeController::WriteLocalName(CommandView command) {
1284   auto command_view = gd_hci::WriteLocalNameView::Create(command);
1285   ASSERT(command_view.IsValid());
1286   const auto local_name = command_view.GetLocalName();
1287   std::vector<uint8_t> name_vec(248);
1288   for (size_t i = 0; i < 248; i++) {
1289     name_vec[i] = local_name[i];
1290   }
1291   properties_.SetName(name_vec);
1292   auto packet = bluetooth::hci::WriteLocalNameCompleteBuilder::Create(
1293       kNumCommandPackets, ErrorCode::SUCCESS);
1294   send_event_(std::move(packet));
1295 }
1296 
WriteExtendedInquiryResponse(CommandView command)1297 void DualModeController::WriteExtendedInquiryResponse(CommandView command) {
1298   auto command_view = gd_hci::WriteExtendedInquiryResponseView::Create(command);
1299   ASSERT(command_view.IsValid());
1300   properties_.SetExtendedInquiryData(std::vector<uint8_t>(
1301       command_view.GetPayload().begin() + 1, command_view.GetPayload().end()));
1302   auto packet =
1303       bluetooth::hci::WriteExtendedInquiryResponseCompleteBuilder::Create(
1304           kNumCommandPackets, ErrorCode::SUCCESS);
1305   send_event_(std::move(packet));
1306 }
1307 
RefreshEncryptionKey(CommandView command)1308 void DualModeController::RefreshEncryptionKey(CommandView command) {
1309   auto command_view = gd_hci::RefreshEncryptionKeyView::Create(
1310       gd_hci::SecurityCommandView::Create(command));
1311   ASSERT(command_view.IsValid());
1312   uint16_t handle = command_view.GetConnectionHandle();
1313   auto status_packet =
1314       bluetooth::hci::RefreshEncryptionKeyStatusBuilder::Create(
1315           ErrorCode::SUCCESS, kNumCommandPackets);
1316   send_event_(std::move(status_packet));
1317   // TODO: Support this in the link layer
1318   auto complete_packet =
1319       bluetooth::hci::EncryptionKeyRefreshCompleteBuilder::Create(
1320           ErrorCode::SUCCESS, handle);
1321   send_event_(std::move(complete_packet));
1322 }
1323 
WriteVoiceSetting(CommandView command)1324 void DualModeController::WriteVoiceSetting(CommandView command) {
1325   auto command_view = gd_hci::WriteVoiceSettingView::Create(command);
1326   ASSERT(command_view.IsValid());
1327 
1328   properties_.SetVoiceSetting(command_view.GetVoiceSetting());
1329 
1330   auto packet = bluetooth::hci::WriteVoiceSettingCompleteBuilder::Create(
1331       kNumCommandPackets, ErrorCode::SUCCESS);
1332   send_event_(std::move(packet));
1333 }
1334 
ReadNumberOfSupportedIac(CommandView command)1335 void DualModeController::ReadNumberOfSupportedIac(CommandView command) {
1336   auto command_view = gd_hci::ReadNumberOfSupportedIacView::Create(
1337       gd_hci::DiscoveryCommandView::Create(command));
1338   ASSERT(command_view.IsValid());
1339   uint8_t num_support_iac = 0x1;
1340   auto packet = bluetooth::hci::ReadNumberOfSupportedIacCompleteBuilder::Create(
1341       kNumCommandPackets, ErrorCode::SUCCESS, num_support_iac);
1342   send_event_(std::move(packet));
1343 }
1344 
ReadCurrentIacLap(CommandView command)1345 void DualModeController::ReadCurrentIacLap(CommandView command) {
1346   auto command_view = gd_hci::ReadCurrentIacLapView::Create(
1347       gd_hci::DiscoveryCommandView::Create(command));
1348   ASSERT(command_view.IsValid());
1349   gd_hci::Lap lap;
1350   lap.lap_ = 0x30;
1351   auto packet = bluetooth::hci::ReadCurrentIacLapCompleteBuilder::Create(
1352       kNumCommandPackets, ErrorCode::SUCCESS, {lap});
1353   send_event_(std::move(packet));
1354 }
1355 
WriteCurrentIacLap(CommandView command)1356 void DualModeController::WriteCurrentIacLap(CommandView command) {
1357   auto command_view = gd_hci::WriteCurrentIacLapView::Create(
1358       gd_hci::DiscoveryCommandView::Create(command));
1359   ASSERT(command_view.IsValid());
1360   auto packet = bluetooth::hci::WriteCurrentIacLapCompleteBuilder::Create(
1361       kNumCommandPackets, ErrorCode::SUCCESS);
1362   send_event_(std::move(packet));
1363 }
1364 
ReadPageScanActivity(CommandView command)1365 void DualModeController::ReadPageScanActivity(CommandView command) {
1366   auto command_view = gd_hci::ReadPageScanActivityView::Create(
1367       gd_hci::DiscoveryCommandView::Create(command));
1368   ASSERT(command_view.IsValid());
1369   uint16_t interval = 0x1000;
1370   uint16_t window = 0x0012;
1371   auto packet = bluetooth::hci::ReadPageScanActivityCompleteBuilder::Create(
1372       kNumCommandPackets, ErrorCode::SUCCESS, interval, window);
1373   send_event_(std::move(packet));
1374 }
1375 
WritePageScanActivity(CommandView command)1376 void DualModeController::WritePageScanActivity(CommandView command) {
1377   auto command_view = gd_hci::WritePageScanActivityView::Create(
1378       gd_hci::DiscoveryCommandView::Create(command));
1379   ASSERT(command_view.IsValid());
1380   auto packet = bluetooth::hci::WritePageScanActivityCompleteBuilder::Create(
1381       kNumCommandPackets, ErrorCode::SUCCESS);
1382   send_event_(std::move(packet));
1383 }
1384 
ReadInquiryScanActivity(CommandView command)1385 void DualModeController::ReadInquiryScanActivity(CommandView command) {
1386   auto command_view = gd_hci::ReadInquiryScanActivityView::Create(
1387       gd_hci::DiscoveryCommandView::Create(command));
1388   ASSERT(command_view.IsValid());
1389   uint16_t interval = 0x1000;
1390   uint16_t window = 0x0012;
1391   auto packet = bluetooth::hci::ReadInquiryScanActivityCompleteBuilder::Create(
1392       kNumCommandPackets, ErrorCode::SUCCESS, interval, window);
1393   send_event_(std::move(packet));
1394 }
1395 
WriteInquiryScanActivity(CommandView command)1396 void DualModeController::WriteInquiryScanActivity(CommandView command) {
1397   auto command_view = gd_hci::WriteInquiryScanActivityView::Create(
1398       gd_hci::DiscoveryCommandView::Create(command));
1399   ASSERT(command_view.IsValid());
1400   auto packet = bluetooth::hci::WriteInquiryScanActivityCompleteBuilder::Create(
1401       kNumCommandPackets, ErrorCode::SUCCESS);
1402   send_event_(std::move(packet));
1403 }
1404 
ReadScanEnable(CommandView command)1405 void DualModeController::ReadScanEnable(CommandView command) {
1406   auto command_view = gd_hci::ReadScanEnableView::Create(
1407       gd_hci::DiscoveryCommandView::Create(command));
1408   ASSERT(command_view.IsValid());
1409   auto packet = bluetooth::hci::ReadScanEnableCompleteBuilder::Create(
1410       kNumCommandPackets, ErrorCode::SUCCESS, gd_hci::ScanEnable::NO_SCANS);
1411   send_event_(std::move(packet));
1412 }
1413 
WriteScanEnable(CommandView command)1414 void DualModeController::WriteScanEnable(CommandView command) {
1415   auto command_view = gd_hci::WriteScanEnableView::Create(
1416       gd_hci::DiscoveryCommandView::Create(command));
1417   ASSERT(command_view.IsValid());
1418   link_layer_controller_.SetInquiryScanEnable(
1419       command_view.GetScanEnable() ==
1420           gd_hci::ScanEnable::INQUIRY_AND_PAGE_SCAN ||
1421       command_view.GetScanEnable() == gd_hci::ScanEnable::INQUIRY_SCAN_ONLY);
1422   link_layer_controller_.SetPageScanEnable(
1423       command_view.GetScanEnable() ==
1424           gd_hci::ScanEnable::INQUIRY_AND_PAGE_SCAN ||
1425       command_view.GetScanEnable() == gd_hci::ScanEnable::PAGE_SCAN_ONLY);
1426   auto packet = bluetooth::hci::WriteScanEnableCompleteBuilder::Create(
1427       kNumCommandPackets, ErrorCode::SUCCESS);
1428   send_event_(std::move(packet));
1429 }
1430 
SetEventFilter(CommandView command)1431 void DualModeController::SetEventFilter(CommandView command) {
1432   auto command_view = gd_hci::SetEventFilterView::Create(command);
1433   ASSERT(command_view.IsValid());
1434   auto packet = bluetooth::hci::SetEventFilterCompleteBuilder::Create(
1435       kNumCommandPackets, ErrorCode::SUCCESS);
1436   send_event_(std::move(packet));
1437 }
1438 
Inquiry(CommandView command)1439 void DualModeController::Inquiry(CommandView command) {
1440   auto command_view = gd_hci::InquiryView::Create(
1441       gd_hci::DiscoveryCommandView::Create(command));
1442   ASSERT(command_view.IsValid());
1443   link_layer_controller_.SetInquiryLAP(command_view.GetLap().lap_);
1444   link_layer_controller_.SetInquiryMaxResponses(command_view.GetNumResponses());
1445   link_layer_controller_.StartInquiry(
1446       std::chrono::milliseconds(command_view.GetInquiryLength() * 1280));
1447 
1448   auto packet = bluetooth::hci::InquiryStatusBuilder::Create(
1449       ErrorCode::SUCCESS, kNumCommandPackets);
1450   send_event_(std::move(packet));
1451 }
1452 
InquiryCancel(CommandView command)1453 void DualModeController::InquiryCancel(CommandView command) {
1454   auto command_view = gd_hci::InquiryCancelView::Create(
1455       gd_hci::DiscoveryCommandView::Create(command));
1456   ASSERT(command_view.IsValid());
1457   link_layer_controller_.InquiryCancel();
1458   auto packet = bluetooth::hci::InquiryCancelCompleteBuilder::Create(
1459       kNumCommandPackets, ErrorCode::SUCCESS);
1460   send_event_(std::move(packet));
1461 }
1462 
AcceptConnectionRequest(CommandView command)1463 void DualModeController::AcceptConnectionRequest(CommandView command) {
1464   auto command_view = gd_hci::AcceptConnectionRequestView::Create(
1465       gd_hci::ConnectionManagementCommandView::Create(
1466           gd_hci::AclCommandView::Create(command)));
1467   ASSERT(command_view.IsValid());
1468   Address addr = command_view.GetBdAddr();
1469   bool try_role_switch = command_view.GetRole() ==
1470                          gd_hci::AcceptConnectionRequestRole::BECOME_CENTRAL;
1471   auto status =
1472       link_layer_controller_.AcceptConnectionRequest(addr, try_role_switch);
1473   auto packet = bluetooth::hci::AcceptConnectionRequestStatusBuilder::Create(
1474       status, kNumCommandPackets);
1475   send_event_(std::move(packet));
1476 }
1477 
RejectConnectionRequest(CommandView command)1478 void DualModeController::RejectConnectionRequest(CommandView command) {
1479   auto command_view = gd_hci::RejectConnectionRequestView::Create(
1480       gd_hci::ConnectionManagementCommandView::Create(
1481           gd_hci::AclCommandView::Create(command)));
1482   ASSERT(command_view.IsValid());
1483   Address addr = command_view.GetBdAddr();
1484   uint8_t reason = static_cast<uint8_t>(command_view.GetReason());
1485   auto status = link_layer_controller_.RejectConnectionRequest(addr, reason);
1486   auto packet = bluetooth::hci::RejectConnectionRequestStatusBuilder::Create(
1487       status, kNumCommandPackets);
1488   send_event_(std::move(packet));
1489 }
1490 
LinkKeyRequestReply(CommandView command)1491 void DualModeController::LinkKeyRequestReply(CommandView command) {
1492   auto command_view = gd_hci::LinkKeyRequestReplyView::Create(
1493       gd_hci::SecurityCommandView::Create(command));
1494   ASSERT(command_view.IsValid());
1495   Address addr = command_view.GetBdAddr();
1496   auto key = command_view.GetLinkKey();
1497   auto status = link_layer_controller_.LinkKeyRequestReply(addr, key);
1498   auto packet = bluetooth::hci::LinkKeyRequestReplyCompleteBuilder::Create(
1499       kNumCommandPackets, status);
1500   send_event_(std::move(packet));
1501 }
1502 
LinkKeyRequestNegativeReply(CommandView command)1503 void DualModeController::LinkKeyRequestNegativeReply(CommandView command) {
1504   auto command_view = gd_hci::LinkKeyRequestNegativeReplyView::Create(
1505       gd_hci::SecurityCommandView::Create(command));
1506   ASSERT(command_view.IsValid());
1507   Address addr = command_view.GetBdAddr();
1508   auto status = link_layer_controller_.LinkKeyRequestNegativeReply(addr);
1509   auto packet =
1510       bluetooth::hci::LinkKeyRequestNegativeReplyCompleteBuilder::Create(
1511           kNumCommandPackets, status, addr);
1512   send_event_(std::move(packet));
1513 }
1514 
DeleteStoredLinkKey(CommandView command)1515 void DualModeController::DeleteStoredLinkKey(CommandView command) {
1516   auto command_view = gd_hci::DeleteStoredLinkKeyView::Create(
1517       gd_hci::SecurityCommandView::Create(command));
1518   ASSERT(command_view.IsValid());
1519 
1520   uint16_t deleted_keys = 0;
1521 
1522   auto flag = command_view.GetDeleteAllFlag();
1523   if (flag == gd_hci::DeleteStoredLinkKeyDeleteAllFlag::SPECIFIED_BD_ADDR) {
1524     Address addr = command_view.GetBdAddr();
1525     deleted_keys = security_manager_.DeleteKey(addr);
1526   }
1527 
1528   if (flag == gd_hci::DeleteStoredLinkKeyDeleteAllFlag::ALL) {
1529     security_manager_.DeleteAllKeys();
1530   }
1531 
1532   auto packet = bluetooth::hci::DeleteStoredLinkKeyCompleteBuilder::Create(
1533       kNumCommandPackets, ErrorCode::SUCCESS, deleted_keys);
1534 
1535   send_event_(std::move(packet));
1536 }
1537 
RemoteNameRequest(CommandView command)1538 void DualModeController::RemoteNameRequest(CommandView command) {
1539   auto command_view = gd_hci::RemoteNameRequestView::Create(
1540       gd_hci::DiscoveryCommandView::Create(command));
1541   ASSERT(command_view.IsValid());
1542 
1543   Address remote_addr = command_view.GetBdAddr();
1544 
1545   auto status = link_layer_controller_.SendCommandToRemoteByAddress(
1546       OpCode::REMOTE_NAME_REQUEST, command_view.GetPayload(), remote_addr);
1547 
1548   auto packet = bluetooth::hci::RemoteNameRequestStatusBuilder::Create(
1549       status, kNumCommandPackets);
1550   send_event_(std::move(packet));
1551 }
1552 
LeSetEventMask(CommandView command)1553 void DualModeController::LeSetEventMask(CommandView command) {
1554   auto command_view = gd_hci::LeSetEventMaskView::Create(command);
1555   ASSERT(command_view.IsValid());
1556   properties_.SetLeEventMask(command_view.GetLeEventMask());
1557   auto packet = bluetooth::hci::LeSetEventMaskCompleteBuilder::Create(
1558       kNumCommandPackets, ErrorCode::SUCCESS);
1559   send_event_(std::move(packet));
1560 }
1561 
LeReadBufferSize(CommandView command)1562 void DualModeController::LeReadBufferSize(CommandView command) {
1563   auto command_view = gd_hci::LeReadBufferSizeV1View::Create(command);
1564   ASSERT(command_view.IsValid());
1565 
1566   bluetooth::hci::LeBufferSize le_buffer_size;
1567   le_buffer_size.le_data_packet_length_ = properties_.GetLeDataPacketLength();
1568   le_buffer_size.total_num_le_packets_ = properties_.GetTotalNumLeDataPackets();
1569 
1570   auto packet = bluetooth::hci::LeReadBufferSizeV1CompleteBuilder::Create(
1571       kNumCommandPackets, ErrorCode::SUCCESS, le_buffer_size);
1572   send_event_(std::move(packet));
1573 }
1574 
LeSetAddressResolutionEnable(CommandView command)1575 void DualModeController::LeSetAddressResolutionEnable(CommandView command) {
1576     // NOP
1577     auto payload =
1578       std::make_unique<bluetooth::packet::RawBuilder>(std::vector<uint8_t>(
1579           {static_cast<uint8_t>(bluetooth::hci::ErrorCode::SUCCESS)}));
1580   send_event_(bluetooth::hci::CommandCompleteBuilder::Create(
1581       kNumCommandPackets, command.GetOpCode(), std::move(payload)));
1582 }
1583 
LeSetResovalablePrivateAddressTimeout(CommandView command)1584 void DualModeController::LeSetResovalablePrivateAddressTimeout(CommandView command) {
1585     // NOP
1586     auto payload =
1587       std::make_unique<bluetooth::packet::RawBuilder>(std::vector<uint8_t>(
1588           {static_cast<uint8_t>(bluetooth::hci::ErrorCode::SUCCESS)}));
1589   send_event_(bluetooth::hci::CommandCompleteBuilder::Create(
1590       kNumCommandPackets, command.GetOpCode(), std::move(payload)));
1591 }
1592 
LeReadLocalSupportedFeatures(CommandView command)1593 void DualModeController::LeReadLocalSupportedFeatures(CommandView command) {
1594   auto command_view = gd_hci::LeReadLocalSupportedFeaturesView::Create(command);
1595   ASSERT(command_view.IsValid());
1596   auto packet =
1597       bluetooth::hci::LeReadLocalSupportedFeaturesCompleteBuilder::Create(
1598           kNumCommandPackets, ErrorCode::SUCCESS,
1599           properties_.GetLeSupportedFeatures());
1600   send_event_(std::move(packet));
1601 }
1602 
LeSetRandomAddress(CommandView command)1603 void DualModeController::LeSetRandomAddress(CommandView command) {
1604   auto command_view = gd_hci::LeSetRandomAddressView::Create(
1605       gd_hci::LeAdvertisingCommandView::Create(command));
1606   ASSERT(command_view.IsValid());
1607   properties_.SetLeAddress(command_view.GetRandomAddress());
1608   auto packet = bluetooth::hci::LeSetRandomAddressCompleteBuilder::Create(
1609       kNumCommandPackets, ErrorCode::SUCCESS);
1610   send_event_(std::move(packet));
1611 }
1612 
LeSetAdvertisingParameters(CommandView command)1613 void DualModeController::LeSetAdvertisingParameters(CommandView command) {
1614   auto command_view = gd_hci::LeSetAdvertisingParametersView::Create(
1615       gd_hci::LeAdvertisingCommandView::Create(command));
1616   ASSERT(command_view.IsValid());
1617   auto peer_address = command_view.GetPeerAddress();
1618   auto type = command_view.GetAdvtType();
1619   if (type != bluetooth::hci::AdvertisingType::ADV_DIRECT_IND &&
1620       type != bluetooth::hci::AdvertisingType::ADV_DIRECT_IND_LOW) {
1621     peer_address = Address::kEmpty;
1622   }
1623   properties_.SetLeAdvertisingParameters(
1624       command_view.GetIntervalMin(), command_view.GetIntervalMax(),
1625       static_cast<uint8_t>(type),
1626       static_cast<uint8_t>(command_view.GetOwnAddressType()),
1627       static_cast<uint8_t>(command_view.GetPeerAddressType()), peer_address,
1628       command_view.GetChannelMap(),
1629       static_cast<uint8_t>(command_view.GetFilterPolicy()));
1630 
1631   auto packet =
1632       bluetooth::hci::LeSetAdvertisingParametersCompleteBuilder::Create(
1633           kNumCommandPackets, ErrorCode::SUCCESS);
1634   send_event_(std::move(packet));
1635 }
1636 
LeReadAdvertisingPhysicalChannelTxPower(CommandView command)1637 void DualModeController::LeReadAdvertisingPhysicalChannelTxPower(
1638     CommandView command) {
1639   auto command_view =
1640       gd_hci::LeReadAdvertisingPhysicalChannelTxPowerView::Create(
1641           gd_hci::LeAdvertisingCommandView::Create(command));
1642   ASSERT(command_view.IsValid());
1643   auto packet =
1644       bluetooth::hci::LeReadAdvertisingPhysicalChannelTxPowerCompleteBuilder::
1645           Create(kNumCommandPackets, ErrorCode::SUCCESS,
1646                  properties_.GetLeAdvertisingPhysicalChannelTxPower());
1647   send_event_(std::move(packet));
1648 }
1649 
LeSetAdvertisingData(CommandView command)1650 void DualModeController::LeSetAdvertisingData(CommandView command) {
1651   auto command_view = gd_hci::LeSetAdvertisingDataView::Create(
1652       gd_hci::LeAdvertisingCommandView::Create(command));
1653   auto payload = command.GetPayload();
1654   auto data_size = *payload.begin();
1655   auto first_data = payload.begin() + 1;
1656   std::vector<uint8_t> payload_bytes{first_data, first_data + data_size};
1657   ASSERT_LOG(command_view.IsValid(), "%s command.size() = %zu",
1658              gd_hci::OpCodeText(command.GetOpCode()).c_str(), command.size());
1659   ASSERT(command_view.GetPayload().size() == 32);
1660   properties_.SetLeAdvertisement(payload_bytes);
1661   auto packet = bluetooth::hci::LeSetAdvertisingDataCompleteBuilder::Create(
1662       kNumCommandPackets, ErrorCode::SUCCESS);
1663   send_event_(std::move(packet));
1664 }
1665 
LeSetScanResponseData(CommandView command)1666 void DualModeController::LeSetScanResponseData(CommandView command) {
1667   auto command_view = gd_hci::LeSetScanResponseDataView::Create(
1668       gd_hci::LeAdvertisingCommandView::Create(command));
1669   ASSERT(command_view.IsValid());
1670   ASSERT(command_view.GetPayload().size() == 32);
1671   properties_.SetLeScanResponse(std::vector<uint8_t>(
1672       command_view.GetPayload().begin() + 1, command_view.GetPayload().end()));
1673   auto packet = bluetooth::hci::LeSetScanResponseDataCompleteBuilder::Create(
1674       kNumCommandPackets, ErrorCode::SUCCESS);
1675   send_event_(std::move(packet));
1676 }
1677 
LeSetAdvertisingEnable(CommandView command)1678 void DualModeController::LeSetAdvertisingEnable(CommandView command) {
1679   auto command_view = gd_hci::LeSetAdvertisingEnableView::Create(
1680       gd_hci::LeAdvertisingCommandView::Create(command));
1681   ASSERT(command_view.IsValid());
1682   auto status = link_layer_controller_.SetLeAdvertisingEnable(
1683       command_view.GetAdvertisingEnable() == gd_hci::Enable::ENABLED);
1684   send_event_(bluetooth::hci::LeSetAdvertisingEnableCompleteBuilder::Create(
1685       kNumCommandPackets, status));
1686 }
1687 
LeSetScanParameters(CommandView command)1688 void DualModeController::LeSetScanParameters(CommandView command) {
1689   auto command_view = gd_hci::LeSetScanParametersView::Create(
1690       gd_hci::LeScanningCommandView::Create(command));
1691   ASSERT(command_view.IsValid());
1692   link_layer_controller_.SetLeScanType(
1693       static_cast<uint8_t>(command_view.GetLeScanType()));
1694   link_layer_controller_.SetLeScanInterval(command_view.GetLeScanInterval());
1695   link_layer_controller_.SetLeScanWindow(command_view.GetLeScanWindow());
1696   link_layer_controller_.SetLeAddressType(command_view.GetOwnAddressType());
1697   link_layer_controller_.SetLeScanFilterPolicy(
1698       static_cast<uint8_t>(command_view.GetScanningFilterPolicy()));
1699   auto packet = bluetooth::hci::LeSetScanParametersCompleteBuilder::Create(
1700       kNumCommandPackets, ErrorCode::SUCCESS);
1701   send_event_(std::move(packet));
1702 }
1703 
LeSetScanEnable(CommandView command)1704 void DualModeController::LeSetScanEnable(CommandView command) {
1705   auto command_view = gd_hci::LeSetScanEnableView::Create(
1706       gd_hci::LeScanningCommandView::Create(command));
1707   ASSERT(command_view.IsValid());
1708   if (command_view.GetLeScanEnable() == gd_hci::Enable::ENABLED) {
1709     link_layer_controller_.SetLeScanEnable(gd_hci::OpCode::LE_SET_SCAN_ENABLE);
1710   } else {
1711     link_layer_controller_.SetLeScanEnable(gd_hci::OpCode::NONE);
1712   }
1713   link_layer_controller_.SetLeFilterDuplicates(
1714       command_view.GetFilterDuplicates() == gd_hci::Enable::ENABLED);
1715   auto packet = bluetooth::hci::LeSetScanEnableCompleteBuilder::Create(
1716       kNumCommandPackets, ErrorCode::SUCCESS);
1717   send_event_(std::move(packet));
1718 }
1719 
LeCreateConnection(CommandView command)1720 void DualModeController::LeCreateConnection(CommandView command) {
1721   auto command_view = gd_hci::LeCreateConnectionView::Create(
1722       gd_hci::LeConnectionManagementCommandView::Create(
1723           gd_hci::AclCommandView::Create(command)));
1724   ASSERT(command_view.IsValid());
1725   link_layer_controller_.SetLeScanInterval(command_view.GetLeScanInterval());
1726   link_layer_controller_.SetLeScanWindow(command_view.GetLeScanWindow());
1727   uint8_t initiator_filter_policy =
1728       static_cast<uint8_t>(command_view.GetInitiatorFilterPolicy());
1729   link_layer_controller_.SetLeInitiatorFilterPolicy(initiator_filter_policy);
1730 
1731   if (initiator_filter_policy == 0) {  // Connect list not used
1732     uint8_t peer_address_type =
1733         static_cast<uint8_t>(command_view.GetPeerAddressType());
1734     Address peer_address = command_view.GetPeerAddress();
1735     link_layer_controller_.SetLePeerAddressType(peer_address_type);
1736     link_layer_controller_.SetLePeerAddress(peer_address);
1737   }
1738   link_layer_controller_.SetLeAddressType(command_view.GetOwnAddressType());
1739   link_layer_controller_.SetLeConnectionIntervalMin(
1740       command_view.GetConnIntervalMin());
1741   link_layer_controller_.SetLeConnectionIntervalMax(
1742       command_view.GetConnIntervalMax());
1743   link_layer_controller_.SetLeConnectionLatency(command_view.GetConnLatency());
1744   link_layer_controller_.SetLeSupervisionTimeout(
1745       command_view.GetSupervisionTimeout());
1746   link_layer_controller_.SetLeMinimumCeLength(
1747       command_view.GetMinimumCeLength());
1748   link_layer_controller_.SetLeMaximumCeLength(
1749       command_view.GetMaximumCeLength());
1750 
1751   auto status = link_layer_controller_.SetLeConnect(true);
1752 
1753   auto packet = bluetooth::hci::LeCreateConnectionStatusBuilder::Create(
1754       status, kNumCommandPackets);
1755   send_event_(std::move(packet));
1756 }
1757 
LeConnectionUpdate(CommandView command)1758 void DualModeController::LeConnectionUpdate(CommandView command) {
1759   auto command_view = gd_hci::LeConnectionUpdateView::Create(
1760       gd_hci::LeConnectionManagementCommandView::Create(
1761           gd_hci::AclCommandView::Create(command)));
1762   ASSERT(command_view.IsValid());
1763   ErrorCode status = link_layer_controller_.LeConnectionUpdate(command_view);
1764 
1765   auto status_packet = bluetooth::hci::LeConnectionUpdateStatusBuilder::Create(
1766       status, kNumCommandPackets);
1767   send_event_(std::move(status_packet));
1768 }
1769 
CreateConnection(CommandView command)1770 void DualModeController::CreateConnection(CommandView command) {
1771   auto command_view = gd_hci::CreateConnectionView::Create(
1772       gd_hci::ConnectionManagementCommandView::Create(
1773           gd_hci::AclCommandView::Create(command)));
1774   ASSERT(command_view.IsValid());
1775 
1776   Address address = command_view.GetBdAddr();
1777   uint16_t packet_type = command_view.GetPacketType();
1778   uint8_t page_scan_mode =
1779       static_cast<uint8_t>(command_view.GetPageScanRepetitionMode());
1780   uint16_t clock_offset =
1781       (command_view.GetClockOffsetValid() == gd_hci::ClockOffsetValid::VALID
1782            ? command_view.GetClockOffset()
1783            : 0);
1784   uint8_t allow_role_switch =
1785       static_cast<uint8_t>(command_view.GetAllowRoleSwitch());
1786 
1787   auto status = link_layer_controller_.CreateConnection(
1788       address, packet_type, page_scan_mode, clock_offset, allow_role_switch);
1789 
1790   auto packet = bluetooth::hci::CreateConnectionStatusBuilder::Create(
1791       status, kNumCommandPackets);
1792   send_event_(std::move(packet));
1793 }
1794 
CreateConnectionCancel(CommandView command)1795 void DualModeController::CreateConnectionCancel(CommandView command) {
1796   auto command_view = gd_hci::CreateConnectionCancelView::Create(
1797       gd_hci::ConnectionManagementCommandView::Create(
1798           gd_hci::AclCommandView::Create(command)));
1799   ASSERT(command_view.IsValid());
1800 
1801   Address address = command_view.GetBdAddr();
1802 
1803   auto status = link_layer_controller_.CreateConnectionCancel(address);
1804 
1805   auto packet = bluetooth::hci::CreateConnectionCancelCompleteBuilder::Create(
1806       kNumCommandPackets, status, address);
1807   send_event_(std::move(packet));
1808 }
1809 
Disconnect(CommandView command)1810 void DualModeController::Disconnect(CommandView command) {
1811   auto command_view = gd_hci::DisconnectView::Create(
1812       gd_hci::ConnectionManagementCommandView::Create(
1813           gd_hci::AclCommandView::Create(command)));
1814   ASSERT(command_view.IsValid());
1815 
1816   uint16_t handle = command_view.GetConnectionHandle();
1817   uint8_t reason = static_cast<uint8_t>(command_view.GetReason());
1818 
1819   auto status = link_layer_controller_.Disconnect(handle, reason);
1820 
1821   auto packet = bluetooth::hci::DisconnectStatusBuilder::Create(
1822       status, kNumCommandPackets);
1823   send_event_(std::move(packet));
1824 }
1825 
LeConnectionCancel(CommandView command)1826 void DualModeController::LeConnectionCancel(CommandView command) {
1827   auto command_view = gd_hci::LeCreateConnectionCancelView::Create(
1828       gd_hci::LeConnectionManagementCommandView::Create(
1829           gd_hci::AclCommandView::Create(command)));
1830   ASSERT(command_view.IsValid());
1831   ErrorCode status = link_layer_controller_.SetLeConnect(false);
1832   send_event_(bluetooth::hci::LeCreateConnectionCancelCompleteBuilder::Create(
1833       kNumCommandPackets, status));
1834 
1835   send_event_(bluetooth::hci::LeConnectionCompleteBuilder::Create(
1836       ErrorCode::UNKNOWN_CONNECTION, kReservedHandle,
1837       bluetooth::hci::Role::CENTRAL,
1838       bluetooth::hci::AddressType::PUBLIC_DEVICE_ADDRESS,
1839       bluetooth::hci::Address(), 1 /* connection_interval */,
1840       2 /* connection_latency */, 3 /* supervision_timeout*/,
1841       static_cast<bluetooth::hci::ClockAccuracy>(0x00)));
1842 }
1843 
LeReadConnectListSize(CommandView command)1844 void DualModeController::LeReadConnectListSize(CommandView command) {
1845   auto command_view = gd_hci::LeReadConnectListSizeView::Create(
1846       gd_hci::LeConnectionManagementCommandView::Create(
1847           gd_hci::AclCommandView::Create(command)));
1848   ASSERT(command_view.IsValid());
1849   auto packet = bluetooth::hci::LeReadConnectListSizeCompleteBuilder::Create(
1850       kNumCommandPackets, ErrorCode::SUCCESS,
1851       properties_.GetLeConnectListSize());
1852   send_event_(std::move(packet));
1853 }
1854 
LeClearConnectList(CommandView command)1855 void DualModeController::LeClearConnectList(CommandView command) {
1856   auto command_view = gd_hci::LeClearConnectListView::Create(
1857       gd_hci::LeConnectionManagementCommandView::Create(
1858           gd_hci::AclCommandView::Create(command)));
1859   ASSERT(command_view.IsValid());
1860   link_layer_controller_.LeConnectListClear();
1861   auto packet = bluetooth::hci::LeClearConnectListCompleteBuilder::Create(
1862       kNumCommandPackets, ErrorCode::SUCCESS);
1863   send_event_(std::move(packet));
1864 }
1865 
LeAddDeviceToConnectList(CommandView command)1866 void DualModeController::LeAddDeviceToConnectList(CommandView command) {
1867   auto command_view = gd_hci::LeAddDeviceToConnectListView::Create(
1868       gd_hci::LeConnectionManagementCommandView::Create(
1869           gd_hci::AclCommandView::Create(command)));
1870   ASSERT(command_view.IsValid());
1871 
1872   uint8_t addr_type = static_cast<uint8_t>(command_view.GetAddressType());
1873   Address address = command_view.GetAddress();
1874   ErrorCode result =
1875       link_layer_controller_.LeConnectListAddDevice(address, addr_type);
1876   auto packet = bluetooth::hci::LeAddDeviceToConnectListCompleteBuilder::Create(
1877       kNumCommandPackets, result);
1878   send_event_(std::move(packet));
1879 }
1880 
LeRemoveDeviceFromConnectList(CommandView command)1881 void DualModeController::LeRemoveDeviceFromConnectList(CommandView command) {
1882   auto command_view = gd_hci::LeRemoveDeviceFromConnectListView::Create(
1883       gd_hci::LeConnectionManagementCommandView::Create(
1884           gd_hci::AclCommandView::Create(command)));
1885   ASSERT(command_view.IsValid());
1886 
1887   uint8_t addr_type = static_cast<uint8_t>(command_view.GetAddressType());
1888   Address address = command_view.GetAddress();
1889   link_layer_controller_.LeConnectListRemoveDevice(address, addr_type);
1890   auto packet =
1891       bluetooth::hci::LeRemoveDeviceFromConnectListCompleteBuilder::Create(
1892           kNumCommandPackets, ErrorCode::SUCCESS);
1893   send_event_(std::move(packet));
1894 }
1895 
LeClearResolvingList(CommandView command)1896 void DualModeController::LeClearResolvingList(CommandView command) {
1897   auto command_view = gd_hci::LeClearResolvingListView::Create(
1898       gd_hci::LeSecurityCommandView::Create(command));
1899   ASSERT(command_view.IsValid());
1900   link_layer_controller_.LeResolvingListClear();
1901   auto packet = bluetooth::hci::LeClearResolvingListCompleteBuilder::Create(
1902       kNumCommandPackets, ErrorCode::SUCCESS);
1903   send_event_(std::move(packet));
1904 }
1905 
LeReadResolvingListSize(CommandView command)1906 void DualModeController::LeReadResolvingListSize(CommandView command) {
1907   auto command_view = gd_hci::LeReadResolvingListSizeView::Create(
1908       gd_hci::LeSecurityCommandView::Create(command));
1909   ASSERT(command_view.IsValid());
1910   auto packet = bluetooth::hci::LeReadResolvingListSizeCompleteBuilder::Create(
1911       kNumCommandPackets, ErrorCode::SUCCESS,
1912       properties_.GetLeResolvingListSize());
1913   send_event_(std::move(packet));
1914 }
1915 
LeReadMaximumDataLength(CommandView command)1916 void DualModeController::LeReadMaximumDataLength(CommandView command) {
1917   auto command_view = gd_hci::LeReadMaximumDataLengthView::Create(
1918       gd_hci::LeSecurityCommandView::Create(command));
1919   ASSERT(command_view.IsValid());
1920   bluetooth::hci::LeMaximumDataLength data_length;
1921   data_length.supported_max_rx_octets_ = kLeMaximumDataLength;
1922   data_length.supported_max_rx_time_ = kLeMaximumDataTime;
1923   data_length.supported_max_tx_octets_ = kLeMaximumDataLength + 10;
1924   data_length.supported_max_tx_time_ = kLeMaximumDataTime + 10;
1925   send_event_(bluetooth::hci::LeReadMaximumDataLengthCompleteBuilder::Create(
1926       kNumCommandPackets, ErrorCode::SUCCESS, data_length));
1927 }
1928 
LeReadSuggestedDefaultDataLength(CommandView command)1929 void DualModeController::LeReadSuggestedDefaultDataLength(CommandView command) {
1930   auto command_view = gd_hci::LeReadSuggestedDefaultDataLengthView::Create(
1931       gd_hci::LeConnectionManagementCommandView::Create(
1932           gd_hci::AclCommandView::Create(command)));
1933   ASSERT(command_view.IsValid());
1934   send_event_(bluetooth::hci::LeReadSuggestedDefaultDataLengthCompleteBuilder::Create(
1935       kNumCommandPackets, ErrorCode::SUCCESS, kLeMaximumDataLength, kLeMaximumDataTime));
1936 }
1937 
LeAddDeviceToResolvingList(CommandView command)1938 void DualModeController::LeAddDeviceToResolvingList(CommandView command) {
1939   auto command_view = gd_hci::LeAddDeviceToResolvingListView::Create(
1940       gd_hci::LeSecurityCommandView::Create(command));
1941   ASSERT(command_view.IsValid());
1942 
1943   uint8_t addr_type =
1944       static_cast<uint8_t>(command_view.GetPeerIdentityAddressType());
1945   Address address = command_view.GetPeerIdentityAddress();
1946   std::array<uint8_t, LinkLayerController::kIrk_size> peerIrk =
1947       command_view.GetPeerIrk();
1948   std::array<uint8_t, LinkLayerController::kIrk_size> localIrk =
1949       command_view.GetLocalIrk();
1950 
1951   auto status = link_layer_controller_.LeResolvingListAddDevice(
1952       address, addr_type, peerIrk, localIrk);
1953   auto packet =
1954       bluetooth::hci::LeAddDeviceToResolvingListCompleteBuilder::Create(
1955           kNumCommandPackets, status);
1956   send_event_(std::move(packet));
1957 }
1958 
LeRemoveDeviceFromResolvingList(CommandView command)1959 void DualModeController::LeRemoveDeviceFromResolvingList(CommandView command) {
1960   auto command_view = gd_hci::LeRemoveDeviceFromResolvingListView::Create(
1961       gd_hci::LeSecurityCommandView::Create(command));
1962   ASSERT(command_view.IsValid());
1963 
1964   uint8_t addr_type =
1965       static_cast<uint8_t>(command_view.GetPeerIdentityAddressType());
1966   Address address = command_view.GetPeerIdentityAddress();
1967   link_layer_controller_.LeResolvingListRemoveDevice(address, addr_type);
1968   auto packet =
1969       bluetooth::hci::LeRemoveDeviceFromResolvingListCompleteBuilder::Create(
1970           kNumCommandPackets, ErrorCode::SUCCESS);
1971   send_event_(std::move(packet));
1972 }
1973 
LeSetExtendedScanParameters(CommandView command)1974 void DualModeController::LeSetExtendedScanParameters(CommandView command) {
1975   auto command_view = gd_hci::LeSetExtendedScanParametersView::Create(
1976       gd_hci::LeScanningCommandView::Create(command));
1977   ASSERT(command_view.IsValid());
1978   auto parameters = command_view.GetParameters();
1979   // Multiple phys are not supported.
1980   ASSERT(command_view.GetScanningPhys() == 1);
1981   ASSERT(parameters.size() == 1);
1982 
1983   auto status = ErrorCode::SUCCESS;
1984   if (link_layer_controller_.GetLeScanEnable() == OpCode::NONE) {
1985     link_layer_controller_.SetLeScanType(
1986         static_cast<uint8_t>(parameters[0].le_scan_type_));
1987     link_layer_controller_.SetLeScanInterval(parameters[0].le_scan_interval_);
1988     link_layer_controller_.SetLeScanWindow(parameters[0].le_scan_window_);
1989     link_layer_controller_.SetLeAddressType(command_view.GetOwnAddressType());
1990     link_layer_controller_.SetLeScanFilterPolicy(
1991         static_cast<uint8_t>(command_view.GetScanningFilterPolicy()));
1992   } else {
1993     status = ErrorCode::COMMAND_DISALLOWED;
1994   }
1995   send_event_(
1996       bluetooth::hci::LeSetExtendedScanParametersCompleteBuilder::Create(
1997           kNumCommandPackets, status));
1998 }
1999 
LeSetExtendedScanEnable(CommandView command)2000 void DualModeController::LeSetExtendedScanEnable(CommandView command) {
2001   auto command_view = gd_hci::LeSetExtendedScanEnableView::Create(
2002       gd_hci::LeScanningCommandView::Create(command));
2003   ASSERT(command_view.IsValid());
2004   if (command_view.GetEnable() == gd_hci::Enable::ENABLED) {
2005     link_layer_controller_.SetLeScanEnable(
2006         gd_hci::OpCode::LE_SET_EXTENDED_SCAN_ENABLE);
2007   } else {
2008     link_layer_controller_.SetLeScanEnable(gd_hci::OpCode::NONE);
2009   }
2010   link_layer_controller_.SetLeFilterDuplicates(
2011       command_view.GetFilterDuplicates() == gd_hci::FilterDuplicates::ENABLED);
2012   auto packet = bluetooth::hci::LeSetExtendedScanEnableCompleteBuilder::Create(
2013       kNumCommandPackets, ErrorCode::SUCCESS);
2014   send_event_(std::move(packet));
2015 }
2016 
LeExtendedCreateConnection(CommandView command)2017 void DualModeController::LeExtendedCreateConnection(CommandView command) {
2018   auto command_view = gd_hci::LeExtendedCreateConnectionView::Create(
2019       gd_hci::LeConnectionManagementCommandView::Create(
2020           gd_hci::AclCommandView::Create(command)));
2021   ASSERT(command_view.IsValid());
2022   ASSERT_LOG(command_view.GetInitiatingPhys() == 1, "Only LE_1M is supported");
2023   auto params = command_view.GetPhyScanParameters();
2024   link_layer_controller_.SetLeScanInterval(params[0].scan_interval_);
2025   link_layer_controller_.SetLeScanWindow(params[0].scan_window_);
2026   auto initiator_filter_policy = command_view.GetInitiatorFilterPolicy();
2027   link_layer_controller_.SetLeInitiatorFilterPolicy(
2028       static_cast<uint8_t>(initiator_filter_policy));
2029 
2030   if (initiator_filter_policy ==
2031       gd_hci::InitiatorFilterPolicy::USE_PEER_ADDRESS) {
2032     link_layer_controller_.SetLePeerAddressType(
2033         static_cast<uint8_t>(command_view.GetPeerAddressType()));
2034     link_layer_controller_.SetLePeerAddress(command_view.GetPeerAddress());
2035   }
2036   link_layer_controller_.SetLeAddressType(command_view.GetOwnAddressType());
2037   link_layer_controller_.SetLeConnectionIntervalMin(
2038       params[0].conn_interval_min_);
2039   link_layer_controller_.SetLeConnectionIntervalMax(
2040       params[0].conn_interval_max_);
2041   link_layer_controller_.SetLeConnectionLatency(params[0].conn_latency_);
2042   link_layer_controller_.SetLeSupervisionTimeout(
2043       params[0].supervision_timeout_);
2044   link_layer_controller_.SetLeMinimumCeLength(params[0].min_ce_length_);
2045   link_layer_controller_.SetLeMaximumCeLength(params[0].max_ce_length_);
2046 
2047   auto status = link_layer_controller_.SetLeConnect(true);
2048 
2049   send_event_(bluetooth::hci::LeExtendedCreateConnectionStatusBuilder::Create(
2050       status, kNumCommandPackets));
2051 }
2052 
LeSetPrivacyMode(CommandView command)2053 void DualModeController::LeSetPrivacyMode(CommandView command) {
2054   auto command_view = gd_hci::LeSetPrivacyModeView::Create(
2055       gd_hci::LeSecurityCommandView::Create(command));
2056   ASSERT(command_view.IsValid());
2057 
2058   uint8_t peer_identity_address_type =
2059       static_cast<uint8_t>(command_view.GetPeerIdentityAddressType());
2060   Address peer_identity_address = command_view.GetPeerIdentityAddress();
2061   uint8_t privacy_mode = static_cast<uint8_t>(command_view.GetPrivacyMode());
2062 
2063   if (link_layer_controller_.LeResolvingListContainsDevice(
2064           peer_identity_address, peer_identity_address_type)) {
2065     link_layer_controller_.LeSetPrivacyMode(
2066         peer_identity_address_type, peer_identity_address, privacy_mode);
2067   }
2068 
2069   auto packet = bluetooth::hci::LeSetPrivacyModeCompleteBuilder::Create(
2070       kNumCommandPackets, ErrorCode::SUCCESS);
2071   send_event_(std::move(packet));
2072 }
2073 
LeReadIsoTxSync(CommandView command)2074 void DualModeController::LeReadIsoTxSync(CommandView command) {
2075   auto iso_command_view = gd_hci::LeIsoCommandView::Create(command);
2076   ASSERT(iso_command_view.IsValid());
2077   auto command_view =
2078       gd_hci::LeReadIsoTxSyncView::Create(std::move(iso_command_view));
2079   ASSERT(command_view.IsValid());
2080   link_layer_controller_.LeReadIsoTxSync(command_view.GetConnectionHandle());
2081 }
2082 
LeSetCigParameters(CommandView command)2083 void DualModeController::LeSetCigParameters(CommandView command) {
2084   auto iso_command_view = gd_hci::LeIsoCommandView::Create(command);
2085   ASSERT(iso_command_view.IsValid());
2086   auto command_view =
2087       gd_hci::LeSetCigParametersView::Create(std::move(iso_command_view));
2088   ASSERT(command_view.IsValid());
2089   link_layer_controller_.LeSetCigParameters(
2090       command_view.GetCigId(), command_view.GetSduIntervalMToS(),
2091       command_view.GetSduIntervalSToM(),
2092       command_view.GetPeripheralsClockAccuracy(), command_view.GetPacking(),
2093       command_view.GetFraming(), command_view.GetMaxTransportLatencyMToS(),
2094       command_view.GetMaxTransportLatencySToM(), command_view.GetCisConfig());
2095 }
2096 
LeCreateCis(CommandView command)2097 void DualModeController::LeCreateCis(CommandView command) {
2098   auto iso_command_view = gd_hci::LeIsoCommandView::Create(command);
2099   ASSERT(iso_command_view.IsValid());
2100   auto command_view =
2101       gd_hci::LeCreateCisView::Create(std::move(iso_command_view));
2102   ASSERT(command_view.IsValid());
2103   ErrorCode status =
2104       link_layer_controller_.LeCreateCis(command_view.GetCisConfig());
2105   send_event_(bluetooth::hci::LeCreateCisStatusBuilder::Create(
2106       status, kNumCommandPackets));
2107 }
2108 
LeRemoveCig(CommandView command)2109 void DualModeController::LeRemoveCig(CommandView command) {
2110   auto iso_command_view = gd_hci::LeIsoCommandView::Create(command);
2111   ASSERT(iso_command_view.IsValid());
2112   auto command_view =
2113       gd_hci::LeRemoveCigView::Create(std::move(iso_command_view));
2114   ASSERT(command_view.IsValid());
2115   uint8_t cig = command_view.GetCigId();
2116   ErrorCode status = link_layer_controller_.LeRemoveCig(cig);
2117   send_event_(bluetooth::hci::LeRemoveCigCompleteBuilder::Create(
2118       kNumCommandPackets, status, cig));
2119 }
2120 
LeAcceptCisRequest(CommandView command)2121 void DualModeController::LeAcceptCisRequest(CommandView command) {
2122   auto iso_command_view = gd_hci::LeIsoCommandView::Create(command);
2123   ASSERT(iso_command_view.IsValid());
2124   auto command_view =
2125       gd_hci::LeAcceptCisRequestView::Create(std::move(iso_command_view));
2126   ASSERT(command_view.IsValid());
2127   ErrorCode status = link_layer_controller_.LeAcceptCisRequest(
2128       command_view.GetConnectionHandle());
2129   send_event_(bluetooth::hci::LeAcceptCisRequestStatusBuilder::Create(
2130       status, kNumCommandPackets));
2131 }
2132 
LeRejectCisRequest(CommandView command)2133 void DualModeController::LeRejectCisRequest(CommandView command) {
2134   auto iso_command_view = gd_hci::LeIsoCommandView::Create(command);
2135   ASSERT(iso_command_view.IsValid());
2136   auto command_view =
2137       gd_hci::LeRejectCisRequestView::Create(std::move(iso_command_view));
2138   ASSERT(command_view.IsValid());
2139   link_layer_controller_.LeRejectCisRequest(command_view.GetConnectionHandle(),
2140                                             command_view.GetReason());
2141 }
2142 
LeCreateBig(CommandView command)2143 void DualModeController::LeCreateBig(CommandView command) {
2144   auto iso_command_view = gd_hci::LeIsoCommandView::Create(command);
2145   ASSERT(iso_command_view.IsValid());
2146   auto command_view =
2147       gd_hci::LeCreateBigView::Create(std::move(iso_command_view));
2148   ASSERT(command_view.IsValid());
2149   ErrorCode status = link_layer_controller_.LeCreateBig(
2150       command_view.GetBigHandle(), command_view.GetAdvertisingHandle(),
2151       command_view.GetNumBis(), command_view.GetSduInterval(),
2152       command_view.GetMaxSdu(), command_view.GetMaxTransportLatency(),
2153       command_view.GetRtn(), command_view.GetPhy(), command_view.GetPacking(),
2154       command_view.GetFraming(), command_view.GetEncryption(),
2155       command_view.GetBroadcastCode());
2156   send_event_(bluetooth::hci::LeCreateBigStatusBuilder::Create(
2157       status, kNumCommandPackets));
2158 }
2159 
LeTerminateBig(CommandView command)2160 void DualModeController::LeTerminateBig(CommandView command) {
2161   auto iso_command_view = gd_hci::LeIsoCommandView::Create(command);
2162   ASSERT(iso_command_view.IsValid());
2163   auto command_view =
2164       gd_hci::LeTerminateBigView::Create(std::move(iso_command_view));
2165   ASSERT(command_view.IsValid());
2166   ErrorCode status = link_layer_controller_.LeTerminateBig(
2167       command_view.GetBigHandle(), command_view.GetReason());
2168   send_event_(bluetooth::hci::LeTerminateBigStatusBuilder::Create(
2169       status, kNumCommandPackets));
2170 }
2171 
LeBigCreateSync(CommandView command)2172 void DualModeController::LeBigCreateSync(CommandView command) {
2173   auto iso_command_view = gd_hci::LeIsoCommandView::Create(command);
2174   ASSERT(iso_command_view.IsValid());
2175   auto command_view =
2176       gd_hci::LeBigCreateSyncView::Create(std::move(iso_command_view));
2177   ASSERT(command_view.IsValid());
2178   ErrorCode status = link_layer_controller_.LeBigCreateSync(
2179       command_view.GetBigHandle(), command_view.GetSyncHandle(),
2180       command_view.GetEncryption(), command_view.GetBroadcastCode(),
2181       command_view.GetMse(), command_view.GetBigSyncTimeout(),
2182       command_view.GetBis());
2183   send_event_(bluetooth::hci::LeBigCreateSyncStatusBuilder::Create(
2184       status, kNumCommandPackets));
2185 }
2186 
LeBigTerminateSync(CommandView command)2187 void DualModeController::LeBigTerminateSync(CommandView command) {
2188   auto iso_command_view = gd_hci::LeIsoCommandView::Create(command);
2189   ASSERT(iso_command_view.IsValid());
2190   auto command_view =
2191       gd_hci::LeBigTerminateSyncView::Create(std::move(iso_command_view));
2192   ASSERT(command_view.IsValid());
2193   link_layer_controller_.LeBigTerminateSync(command_view.GetBigHandle());
2194 }
2195 
LeRequestPeerSca(CommandView command)2196 void DualModeController::LeRequestPeerSca(CommandView command) {
2197   auto command_view = gd_hci::LeRequestPeerScaView::Create(std::move(command));
2198   ASSERT(command_view.IsValid());
2199   ErrorCode status = link_layer_controller_.LeRequestPeerSca(
2200       command_view.GetConnectionHandle());
2201   send_event_(bluetooth::hci::LeRequestPeerScaStatusBuilder::Create(
2202       status, kNumCommandPackets));
2203 }
2204 
LeSetupIsoDataPath(CommandView command)2205 void DualModeController::LeSetupIsoDataPath(CommandView command) {
2206   auto iso_command_view = gd_hci::LeIsoCommandView::Create(command);
2207   ASSERT(iso_command_view.IsValid());
2208   auto command_view =
2209       gd_hci::LeSetupIsoDataPathView::Create(std::move(iso_command_view));
2210   ASSERT(command_view.IsValid());
2211   link_layer_controller_.LeSetupIsoDataPath(
2212       command_view.GetConnectionHandle(), command_view.GetDataPathDirection(),
2213       command_view.GetDataPathId(), command_view.GetCodecId(),
2214       command_view.GetControllerDelay(), command_view.GetCodecConfiguration());
2215 }
2216 
LeRemoveIsoDataPath(CommandView command)2217 void DualModeController::LeRemoveIsoDataPath(CommandView command) {
2218   auto iso_command_view = gd_hci::LeIsoCommandView::Create(command);
2219   ASSERT(iso_command_view.IsValid());
2220   auto command_view =
2221       gd_hci::LeRemoveIsoDataPathView::Create(std::move(iso_command_view));
2222   ASSERT(command_view.IsValid());
2223   link_layer_controller_.LeRemoveIsoDataPath(
2224       command_view.GetConnectionHandle(), command_view.GetDataPathDirection());
2225 }
2226 
LeReadRemoteFeatures(CommandView command)2227 void DualModeController::LeReadRemoteFeatures(CommandView command) {
2228   auto command_view = gd_hci::LeReadRemoteFeaturesView::Create(
2229       gd_hci::LeConnectionManagementCommandView::Create(
2230           gd_hci::AclCommandView::Create(command)));
2231   ASSERT(command_view.IsValid());
2232 
2233   uint16_t handle = command_view.GetConnectionHandle();
2234 
2235   auto status = link_layer_controller_.SendCommandToRemoteByHandle(
2236       OpCode::LE_READ_REMOTE_FEATURES, command_view.GetPayload(), handle);
2237 
2238   auto packet = bluetooth::hci::LeReadRemoteFeaturesStatusBuilder::Create(
2239       status, kNumCommandPackets);
2240   send_event_(std::move(packet));
2241 }
2242 
LeRand(CommandView command)2243 void DualModeController::LeRand(CommandView command) {
2244   auto command_view = gd_hci::LeRandView::Create(
2245       gd_hci::LeSecurityCommandView::Create(command));
2246   ASSERT(command_view.IsValid());
2247   uint64_t random_val = 0;
2248   for (size_t rand_bytes = 0; rand_bytes < sizeof(uint64_t); rand_bytes += sizeof(RAND_MAX)) {
2249     random_val = (random_val << (8 * sizeof(RAND_MAX))) | random();
2250   }
2251 
2252   auto packet = bluetooth::hci::LeRandCompleteBuilder::Create(
2253       kNumCommandPackets, ErrorCode::SUCCESS, random_val);
2254   send_event_(std::move(packet));
2255 }
2256 
LeReadSupportedStates(CommandView command)2257 void DualModeController::LeReadSupportedStates(CommandView command) {
2258   auto command_view = gd_hci::LeReadSupportedStatesView::Create(command);
2259   ASSERT(command_view.IsValid());
2260   auto packet = bluetooth::hci::LeReadSupportedStatesCompleteBuilder::Create(
2261       kNumCommandPackets, ErrorCode::SUCCESS,
2262       properties_.GetLeSupportedStates());
2263   send_event_(std::move(packet));
2264 }
2265 
LeVendorCap(CommandView command)2266 void DualModeController::LeVendorCap(CommandView command) {
2267   auto command_view = gd_hci::LeGetVendorCapabilitiesView::Create(
2268       gd_hci::VendorCommandView::Create(command));
2269   ASSERT(command_view.IsValid());
2270   vector<uint8_t> caps = properties_.GetLeVendorCap();
2271   if (caps.size() == 0) {
2272     SendCommandCompleteUnknownOpCodeEvent(
2273         static_cast<uint16_t>(OpCode::LE_GET_VENDOR_CAPABILITIES));
2274     return;
2275   }
2276 
2277   std::unique_ptr<bluetooth::packet::RawBuilder> raw_builder_ptr =
2278       std::make_unique<bluetooth::packet::RawBuilder>();
2279   raw_builder_ptr->AddOctets1(static_cast<uint8_t>(ErrorCode::SUCCESS));
2280   raw_builder_ptr->AddOctets(properties_.GetLeVendorCap());
2281 
2282   auto packet = bluetooth::hci::CommandCompleteBuilder::Create(
2283       kNumCommandPackets, OpCode::LE_GET_VENDOR_CAPABILITIES,
2284       std::move(raw_builder_ptr));
2285   send_event_(std::move(packet));
2286 }
2287 
LeVendorMultiAdv(CommandView command)2288 void DualModeController::LeVendorMultiAdv(CommandView command) {
2289   auto command_view = gd_hci::LeMultiAdvtView::Create(
2290       gd_hci::LeAdvertisingCommandView::Create(command));
2291   ASSERT(command_view.IsValid());
2292   SendCommandCompleteUnknownOpCodeEvent(
2293       static_cast<uint16_t>(OpCode::LE_MULTI_ADVT));
2294 }
2295 
LeAdvertisingFilter(CommandView command)2296 void DualModeController::LeAdvertisingFilter(CommandView command) {
2297   auto command_view = gd_hci::LeAdvFilterView::Create(
2298       gd_hci::LeScanningCommandView::Create(command));
2299   ASSERT(command_view.IsValid());
2300   SendCommandCompleteUnknownOpCodeEvent(
2301       static_cast<uint16_t>(OpCode::LE_ADV_FILTER));
2302 }
2303 
LeEnergyInfo(CommandView command)2304 void DualModeController::LeEnergyInfo(CommandView command) {
2305   auto command_view = gd_hci::LeEnergyInfoView::Create(
2306       gd_hci::VendorCommandView::Create(command));
2307   ASSERT(command_view.IsValid());
2308   SendCommandCompleteUnknownOpCodeEvent(
2309       static_cast<uint16_t>(OpCode::LE_ENERGY_INFO));
2310 }
2311 
LeSetExtendedAdvertisingRandomAddress(CommandView command)2312 void DualModeController::LeSetExtendedAdvertisingRandomAddress(
2313     CommandView command) {
2314   auto command_view = gd_hci::LeSetExtendedAdvertisingRandomAddressView::Create(
2315       gd_hci::LeAdvertisingCommandView::Create(command));
2316   ASSERT(command_view.IsValid());
2317   link_layer_controller_.SetLeExtendedAddress(
2318       command_view.GetAdvertisingHandle(),
2319       command_view.GetAdvertisingRandomAddress());
2320   send_event_(
2321       bluetooth::hci::LeSetExtendedAdvertisingRandomAddressCompleteBuilder::
2322           Create(kNumCommandPackets, ErrorCode::SUCCESS));
2323 }
2324 
LeSetExtendedAdvertisingParameters(CommandView command)2325 void DualModeController::LeSetExtendedAdvertisingParameters(
2326     CommandView command) {
2327   auto command_view =
2328       gd_hci::LeSetExtendedAdvertisingLegacyParametersView::Create(
2329           gd_hci::LeAdvertisingCommandView::Create(command));
2330   // TODO: Support non-legacy parameters
2331   ASSERT(command_view.IsValid());
2332   link_layer_controller_.SetLeExtendedAdvertisingParameters(
2333       command_view.GetAdvertisingHandle(),
2334       command_view.GetPrimaryAdvertisingIntervalMin(),
2335       command_view.GetPrimaryAdvertisingIntervalMax(),
2336       command_view.GetAdvertisingEventLegacyProperties(),
2337       command_view.GetOwnAddressType(), command_view.GetPeerAddressType(),
2338       command_view.GetPeerAddress(), command_view.GetAdvertisingFilterPolicy());
2339 
2340   send_event_(
2341       bluetooth::hci::LeSetExtendedAdvertisingParametersCompleteBuilder::Create(
2342           kNumCommandPackets, ErrorCode::SUCCESS, 0xa5));
2343 }
2344 
LeSetExtendedAdvertisingData(CommandView command)2345 void DualModeController::LeSetExtendedAdvertisingData(CommandView command) {
2346   auto command_view = gd_hci::LeSetExtendedAdvertisingDataView::Create(
2347       gd_hci::LeAdvertisingCommandView::Create(command));
2348   ASSERT(command_view.IsValid());
2349   auto raw_command_view = gd_hci::LeSetExtendedAdvertisingDataRawView::Create(
2350       gd_hci::LeAdvertisingCommandView::Create(command));
2351   ASSERT(raw_command_view.IsValid());
2352   link_layer_controller_.SetLeExtendedAdvertisingData(
2353       command_view.GetAdvertisingHandle(),
2354       raw_command_view.GetAdvertisingData());
2355   auto packet =
2356       bluetooth::hci::LeSetExtendedAdvertisingDataCompleteBuilder::Create(
2357           kNumCommandPackets, ErrorCode::SUCCESS);
2358   send_event_(std::move(packet));
2359 }
2360 
LeSetExtendedAdvertisingScanResponse(CommandView command)2361 void DualModeController::LeSetExtendedAdvertisingScanResponse(
2362     CommandView command) {
2363   auto command_view = gd_hci::LeSetExtendedAdvertisingScanResponseView::Create(
2364       gd_hci::LeAdvertisingCommandView::Create(command));
2365   ASSERT(command_view.IsValid());
2366   properties_.SetLeScanResponse(std::vector<uint8_t>(
2367       command_view.GetPayload().begin() + 1, command_view.GetPayload().end()));
2368   send_event_(
2369       bluetooth::hci::LeSetExtendedAdvertisingScanResponseCompleteBuilder::
2370           Create(kNumCommandPackets, ErrorCode::SUCCESS));
2371 }
2372 
LeSetExtendedAdvertisingEnable(CommandView command)2373 void DualModeController::LeSetExtendedAdvertisingEnable(CommandView command) {
2374   auto command_view = gd_hci::LeSetExtendedAdvertisingEnableView::Create(
2375       gd_hci::LeAdvertisingCommandView::Create(command));
2376   ASSERT(command_view.IsValid());
2377   auto enabled_sets = command_view.GetEnabledSets();
2378   ErrorCode status = ErrorCode::SUCCESS;
2379   if (enabled_sets.size() == 0) {
2380     link_layer_controller_.LeDisableAdvertisingSets();
2381   } else {
2382     status = link_layer_controller_.SetLeExtendedAdvertisingEnable(
2383         command_view.GetEnable(), command_view.GetEnabledSets());
2384   }
2385   send_event_(
2386       bluetooth::hci::LeSetExtendedAdvertisingEnableCompleteBuilder::Create(
2387           kNumCommandPackets, status));
2388 }
2389 
LeReadMaximumAdvertisingDataLength(CommandView command)2390 void DualModeController::LeReadMaximumAdvertisingDataLength(
2391     CommandView command) {
2392   auto command_view = gd_hci::LeReadMaximumAdvertisingDataLengthView::Create(
2393       gd_hci::LeAdvertisingCommandView::Create(command));
2394   ASSERT(command_view.IsValid());
2395   send_event_(
2396       bluetooth::hci::LeReadMaximumAdvertisingDataLengthCompleteBuilder::Create(
2397           kNumCommandPackets, ErrorCode::SUCCESS,
2398           kLeMaximumAdvertisingDataLength));
2399 }
2400 
LeReadNumberOfSupportedAdvertisingSets(CommandView command)2401 void DualModeController::LeReadNumberOfSupportedAdvertisingSets(
2402     CommandView command) {
2403   auto command_view =
2404       gd_hci::LeReadNumberOfSupportedAdvertisingSetsView::Create(
2405           gd_hci::LeAdvertisingCommandView::Create(command));
2406   ASSERT(command_view.IsValid());
2407   send_event_(
2408       bluetooth::hci::LeReadNumberOfSupportedAdvertisingSetsCompleteBuilder::
2409           Create(
2410               kNumCommandPackets, ErrorCode::SUCCESS,
2411               link_layer_controller_.LeReadNumberOfSupportedAdvertisingSets()));
2412 }
2413 
LeRemoveAdvertisingSet(CommandView command)2414 void DualModeController::LeRemoveAdvertisingSet(CommandView command) {
2415   auto command_view = gd_hci::LeRemoveAdvertisingSetView::Create(
2416       gd_hci::LeAdvertisingCommandView::Create(command));
2417   ASSERT(command_view.IsValid());
2418   auto status = link_layer_controller_.LeRemoveAdvertisingSet(
2419       command_view.GetAdvertisingHandle());
2420   send_event_(bluetooth::hci::LeRemoveAdvertisingSetCompleteBuilder::Create(
2421       kNumCommandPackets, status));
2422 }
2423 
LeClearAdvertisingSets(CommandView command)2424 void DualModeController::LeClearAdvertisingSets(CommandView command) {
2425   auto command_view = gd_hci::LeClearAdvertisingSetsView::Create(
2426       gd_hci::LeAdvertisingCommandView::Create(command));
2427   ASSERT(command_view.IsValid());
2428   auto status = link_layer_controller_.LeClearAdvertisingSets();
2429   send_event_(bluetooth::hci::LeClearAdvertisingSetsCompleteBuilder::Create(
2430       kNumCommandPackets, status));
2431 }
2432 
LeExtendedScanParams(CommandView command)2433 void DualModeController::LeExtendedScanParams(CommandView command) {
2434   auto command_view = gd_hci::LeExtendedScanParamsView::Create(
2435       gd_hci::LeScanningCommandView::Create(command));
2436   ASSERT(command_view.IsValid());
2437   SendCommandCompleteUnknownOpCodeEvent(
2438       static_cast<uint16_t>(OpCode::LE_EXTENDED_SCAN_PARAMS));
2439 }
2440 
LeStartEncryption(CommandView command)2441 void DualModeController::LeStartEncryption(CommandView command) {
2442   auto command_view = gd_hci::LeStartEncryptionView::Create(
2443       gd_hci::LeSecurityCommandView::Create(command));
2444   ASSERT(command_view.IsValid());
2445 
2446   ErrorCode status = link_layer_controller_.LeEnableEncryption(
2447       command_view.GetConnectionHandle(), command_view.GetRand(),
2448       command_view.GetEdiv(), command_view.GetLtk());
2449 
2450   send_event_(bluetooth::hci::LeStartEncryptionStatusBuilder::Create(
2451       status, kNumCommandPackets));
2452 }
2453 
LeLongTermKeyRequestReply(CommandView command)2454 void DualModeController::LeLongTermKeyRequestReply(CommandView command) {
2455   auto command_view = gd_hci::LeLongTermKeyRequestReplyView::Create(
2456       gd_hci::LeSecurityCommandView::Create(command));
2457   ASSERT(command_view.IsValid());
2458 
2459   uint16_t handle = command_view.GetConnectionHandle();
2460   ErrorCode status = link_layer_controller_.LeLongTermKeyRequestReply(
2461       handle, command_view.GetLongTermKey());
2462 
2463   send_event_(bluetooth::hci::LeLongTermKeyRequestReplyCompleteBuilder::Create(
2464       kNumCommandPackets, status, handle));
2465 }
2466 
LeLongTermKeyRequestNegativeReply(CommandView command)2467 void DualModeController::LeLongTermKeyRequestNegativeReply(
2468     CommandView command) {
2469   auto command_view = gd_hci::LeLongTermKeyRequestNegativeReplyView::Create(
2470       gd_hci::LeSecurityCommandView::Create(command));
2471   ASSERT(command_view.IsValid());
2472 
2473   uint16_t handle = command_view.GetConnectionHandle();
2474   ErrorCode status =
2475       link_layer_controller_.LeLongTermKeyRequestNegativeReply(handle);
2476 
2477   send_event_(
2478       bluetooth::hci::LeLongTermKeyRequestNegativeReplyCompleteBuilder::Create(
2479           kNumCommandPackets, status, handle));
2480 }
2481 
ReadClassOfDevice(CommandView command)2482 void DualModeController::ReadClassOfDevice(CommandView command) {
2483   auto command_view = gd_hci::ReadClassOfDeviceView::Create(
2484       gd_hci::DiscoveryCommandView::Create(command));
2485   ASSERT(command_view.IsValid());
2486 
2487   auto packet = bluetooth::hci::ReadClassOfDeviceCompleteBuilder::Create(
2488       kNumCommandPackets, ErrorCode::SUCCESS, properties_.GetClassOfDevice());
2489   send_event_(std::move(packet));
2490 }
2491 
ReadVoiceSetting(CommandView command)2492 void DualModeController::ReadVoiceSetting(CommandView command) {
2493   auto command_view = gd_hci::ReadVoiceSettingView::Create(command);
2494   ASSERT(command_view.IsValid());
2495 
2496   auto packet = bluetooth::hci::ReadVoiceSettingCompleteBuilder::Create(
2497       kNumCommandPackets, ErrorCode::SUCCESS, properties_.GetVoiceSetting());
2498   send_event_(std::move(packet));
2499 }
2500 
ReadConnectionAcceptTimeout(CommandView command)2501 void DualModeController::ReadConnectionAcceptTimeout(CommandView command) {
2502   auto command_view = gd_hci::ReadConnectionAcceptTimeoutView::Create(
2503       gd_hci::ConnectionManagementCommandView::Create(
2504           gd_hci::AclCommandView::Create(command)));
2505   ASSERT(command_view.IsValid());
2506 
2507   auto packet =
2508       bluetooth::hci::ReadConnectionAcceptTimeoutCompleteBuilder::Create(
2509           kNumCommandPackets, ErrorCode::SUCCESS,
2510           properties_.GetConnectionAcceptTimeout());
2511   send_event_(std::move(packet));
2512 }
2513 
WriteConnectionAcceptTimeout(CommandView command)2514 void DualModeController::WriteConnectionAcceptTimeout(CommandView command) {
2515   auto command_view = gd_hci::WriteConnectionAcceptTimeoutView::Create(
2516       gd_hci::ConnectionManagementCommandView::Create(
2517           gd_hci::AclCommandView::Create(command)));
2518   ASSERT(command_view.IsValid());
2519 
2520   properties_.SetConnectionAcceptTimeout(command_view.GetConnAcceptTimeout());
2521 
2522   auto packet =
2523       bluetooth::hci::WriteConnectionAcceptTimeoutCompleteBuilder::Create(
2524           kNumCommandPackets, ErrorCode::SUCCESS);
2525   send_event_(std::move(packet));
2526 }
2527 
ReadLoopbackMode(CommandView command)2528 void DualModeController::ReadLoopbackMode(CommandView command) {
2529   auto command_view = gd_hci::ReadLoopbackModeView::Create(command);
2530   ASSERT(command_view.IsValid());
2531   auto packet = bluetooth::hci::ReadLoopbackModeCompleteBuilder::Create(
2532       kNumCommandPackets, ErrorCode::SUCCESS,
2533       static_cast<LoopbackMode>(loopback_mode_));
2534   send_event_(std::move(packet));
2535 }
2536 
WriteLoopbackMode(CommandView command)2537 void DualModeController::WriteLoopbackMode(CommandView command) {
2538   auto command_view = gd_hci::WriteLoopbackModeView::Create(command);
2539   ASSERT(command_view.IsValid());
2540   loopback_mode_ = command_view.GetLoopbackMode();
2541   // ACL channel
2542   uint16_t acl_handle = 0x123;
2543   auto packet_acl = bluetooth::hci::ConnectionCompleteBuilder::Create(
2544       ErrorCode::SUCCESS, acl_handle, properties_.GetAddress(),
2545       bluetooth::hci::LinkType::ACL, bluetooth::hci::Enable::DISABLED);
2546   send_event_(std::move(packet_acl));
2547   // SCO channel
2548   uint16_t sco_handle = 0x345;
2549   auto packet_sco = bluetooth::hci::ConnectionCompleteBuilder::Create(
2550       ErrorCode::SUCCESS, sco_handle, properties_.GetAddress(),
2551       bluetooth::hci::LinkType::SCO, bluetooth::hci::Enable::DISABLED);
2552   send_event_(std::move(packet_sco));
2553   auto packet = bluetooth::hci::WriteLoopbackModeCompleteBuilder::Create(
2554       kNumCommandPackets, ErrorCode::SUCCESS);
2555   send_event_(std::move(packet));
2556 }
2557 
SetAddress(Address address)2558 void DualModeController::SetAddress(Address address) {
2559   properties_.SetAddress(address);
2560 }
2561 
2562 }  // namespace test_vendor_lib
2563