• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2017 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 #pragma once
18 
19 #include <algorithm>
20 #include <chrono>
21 #include <map>
22 #include <set>
23 #include <vector>
24 
25 #include "hci/address.h"
26 #include "hci/hci_packets.h"
27 #include "include/phy.h"
28 #include "model/controller/acl_connection_handler.h"
29 #include "model/controller/controller_properties.h"
30 #include "model/controller/le_advertiser.h"
31 #include "packets/link_layer_packets.h"
32 
33 extern "C" {
34 struct LinkManager;
35 }
36 
37 #include "lmp.h"
38 
39 namespace rootcanal {
40 
41 using ::bluetooth::hci::Address;
42 using ::bluetooth::hci::AddressType;
43 using ::bluetooth::hci::AuthenticationEnable;
44 using ::bluetooth::hci::ClassOfDevice;
45 using ::bluetooth::hci::ErrorCode;
46 using ::bluetooth::hci::FilterAcceptListAddressType;
47 using ::bluetooth::hci::OpCode;
48 using ::bluetooth::hci::PageScanRepetitionMode;
49 
50 // Create an address with type Public Device Address or Random Device Address.
51 AddressWithType PeerDeviceAddress(Address address,
52                                   PeerAddressType peer_address_type);
53 // Create an address with type Public Identity Address or Random Identity
54 // address.
55 AddressWithType PeerIdentityAddress(Address address,
56                                     PeerAddressType peer_address_type);
57 
58 class LinkLayerController {
59  public:
60   static constexpr size_t kIrkSize = 16;
61   static constexpr size_t kLtkSize = 16;
62   static constexpr size_t kLocalNameSize = 248;
63   static constexpr size_t kExtendedInquiryResponseSize = 240;
64 
65   // Generate a resolvable private address using the specified IRK.
66   static Address generate_rpa(
67       std::array<uint8_t, LinkLayerController::kIrkSize> irk);
68 
69   LinkLayerController(const Address& address,
70                       const ControllerProperties& properties);
71   ~LinkLayerController();
72 
73   ErrorCode SendCommandToRemoteByAddress(
74       OpCode opcode, bluetooth::packet::PacketView<true> args,
75       const Address& own_address, const Address& peer_address);
76   ErrorCode SendLeCommandToRemoteByAddress(OpCode opcode,
77                                            const Address& own_address,
78                                            const Address& peer_address);
79   ErrorCode SendCommandToRemoteByHandle(
80       OpCode opcode, bluetooth::packet::PacketView<true> args, uint16_t handle);
81   ErrorCode SendScoToRemote(bluetooth::hci::ScoView sco_packet);
82   ErrorCode SendAclToRemote(bluetooth::hci::AclView acl_packet);
83 
84   void ForwardToLm(bluetooth::hci::CommandView command);
85 
86   std::vector<bluetooth::hci::Lap> const& ReadCurrentIacLap() const;
87   void WriteCurrentIacLap(std::vector<bluetooth::hci::Lap> iac_lap);
88 
89   ErrorCode AcceptConnectionRequest(const Address& addr, bool try_role_switch);
90   void MakePeripheralConnection(const Address& addr, bool try_role_switch);
91   ErrorCode RejectConnectionRequest(const Address& addr, uint8_t reason);
92   void RejectPeripheralConnection(const Address& addr, uint8_t reason);
93   ErrorCode CreateConnection(const Address& addr, uint16_t packet_type,
94                              uint8_t page_scan_mode, uint16_t clock_offset,
95                              uint8_t allow_role_switch);
96   ErrorCode CreateConnectionCancel(const Address& addr);
97 
98   // Disconnect a link.
99   // \p host_reason is taken from the Disconnect command, and sent over
100   // to the remote as disconnect error. \p controller_reason is the code
101   // used in the DisconnectionComplete event.
102   ErrorCode Disconnect(uint16_t handle, ErrorCode host_reason,
103                        ErrorCode controller_reason =
104                            ErrorCode::CONNECTION_TERMINATED_BY_LOCAL_HOST);
105 
106   // Internal task scheduler.
107   // This scheduler is driven by the tick function only,
108   // hence the precision of the scheduler is within a tick period.
109   class Task;
110   using TaskId = uint32_t;
111   using TaskCallback = std::function<void(void)>;
112   static constexpr TaskId kInvalidTaskId = 0;
113 
114   /// Schedule a task to be executed \p delay ms in the future.
115   TaskId ScheduleTask(std::chrono::milliseconds delay,
116                       TaskCallback task_callback);
117 
118   /// Schedule a task to be executed every \p period ms starting
119   /// \p delay ms in the future. Note that the task will be executed
120   /// at most once per \ref Tick() invocation, hence the period
121   /// cannot be lower than the \ref Tick() period.
122   TaskId SchedulePeriodicTask(std::chrono::milliseconds delay,
123                               std::chrono::milliseconds period,
124                               TaskCallback task_callback);
125 
126   /// Cancel the selected task.
127   void CancelScheduledTask(TaskId task_id);
128 
129   // Execute tasks that are pending at the current time.
130   void RunPendingTasks();
131 
132  private:
133   void SendDisconnectionCompleteEvent(uint16_t handle, ErrorCode reason);
134 
135  public:
136   const Address& GetAddress() const;
137 
138   void IncomingPacket(model::packets::LinkLayerPacketView incoming,
139                       int8_t rssi);
140 
141   void Tick();
142 
143   void Close();
144 
145   // Set the callbacks for sending packets to the HCI.
146   void RegisterEventChannel(
147       const std::function<void(std::shared_ptr<bluetooth::hci::EventBuilder>)>&
148           send_event);
149 
150   void RegisterAclChannel(
151       const std::function<void(std::shared_ptr<bluetooth::hci::AclBuilder>)>&
152           send_acl);
153 
154   void RegisterScoChannel(
155       const std::function<void(std::shared_ptr<bluetooth::hci::ScoBuilder>)>&
156           send_sco);
157 
158   void RegisterIsoChannel(
159       const std::function<void(std::shared_ptr<bluetooth::hci::IsoBuilder>)>&
160           send_iso);
161 
162   void RegisterRemoteChannel(
163       const std::function<
164           void(std::shared_ptr<model::packets::LinkLayerPacketBuilder>,
165                Phy::Type, int8_t)>& send_to_remote);
166 
167   void Reset();
168 
169   void LeAdvertising();
170   void LeScanning();
171   void LeSynchronization();
172 
173   void LeConnectionUpdateComplete(uint16_t handle, uint16_t interval_min,
174                                   uint16_t interval_max, uint16_t latency,
175                                   uint16_t supervision_timeout);
176   ErrorCode LeConnectionUpdate(uint16_t handle, uint16_t interval_min,
177                                uint16_t interval_max, uint16_t latency,
178                                uint16_t supervision_timeout);
179   ErrorCode LeRemoteConnectionParameterRequestReply(
180       uint16_t connection_handle, uint16_t interval_min, uint16_t interval_max,
181       uint16_t timeout, uint16_t latency, uint16_t minimum_ce_length,
182       uint16_t maximum_ce_length);
183   ErrorCode LeRemoteConnectionParameterRequestNegativeReply(
184       uint16_t connection_handle, bluetooth::hci::ErrorCode reason);
185   uint16_t HandleLeConnection(AddressWithType addr, AddressWithType own_addr,
186                               bluetooth::hci::Role role,
187                               uint16_t connection_interval,
188                               uint16_t connection_latency,
189                               uint16_t supervision_timeout,
190                               bool send_le_channel_selection_algorithm_event);
191 
192   bool ResolvingListBusy();
193   bool FilterAcceptListBusy();
194 
195   bool LeFilterAcceptListContainsDevice(
196       FilterAcceptListAddressType address_type, Address address);
197   bool LeFilterAcceptListContainsDevice(AddressWithType address);
198 
199   bool LePeriodicAdvertiserListContainsDevice(
200       bluetooth::hci::AdvertiserAddressType advertiser_address_type,
201       Address advertiser_address, uint8_t advertising_sid);
202 
203   enum IrkSelection {
204     Peer,  // Use Peer IRK for RPA resolution or generation.
205     Local  // Use Local IRK for RPA resolution or generation.
206   };
207 
208   // If the selected address is a Resolvable Private Address, then
209   // resolve the address using the resolving list. If the address cannot
210   // be resolved none is returned. If the address is not a Resolvable
211   // Private Address, the original address is returned.
212   std::optional<AddressWithType> ResolvePrivateAddress(AddressWithType address,
213                                                        IrkSelection irk);
214 
215   // Generate a Resolvable Private for the selected peer.
216   // If the address is not found in the resolving list none is returned.
217   // `local` indicates whether to use the local (true) or peer (false) IRK when
218   // generating the Resolvable Private Address.
219   std::optional<AddressWithType> GenerateResolvablePrivateAddress(
220       AddressWithType address, IrkSelection irk);
221 
222   // Check if the selected address matches one of the controller's device
223   // addresses (public or random static).
IsLocalPublicOrRandomAddress(AddressWithType address)224   bool IsLocalPublicOrRandomAddress(AddressWithType address) {
225     switch (address.GetAddressType()) {
226       case AddressType::PUBLIC_DEVICE_ADDRESS:
227         return address.GetAddress() == address_;
228       case AddressType::RANDOM_DEVICE_ADDRESS:
229         return address.GetAddress() == random_address_;
230       default:
231         return false;
232     }
233   }
234 
235   void LeReadIsoTxSync(uint16_t handle);
236   void LeSetCigParameters(
237       uint8_t cig_id, uint32_t sdu_interval_m_to_s,
238       uint32_t sdu_interval_s_to_m,
239       bluetooth::hci::ClockAccuracy clock_accuracy,
240       bluetooth::hci::Packing packing, bluetooth::hci::Enable framing,
241       uint16_t max_transport_latency_m_to_s,
242       uint16_t max_transport_latency_s_to_m,
243       std::vector<bluetooth::hci::CisParametersConfig> cis_config);
244   bluetooth::hci::ErrorCode LeCreateCis(
245       std::vector<bluetooth::hci::CreateCisConfig> cis_config);
246   bluetooth::hci::ErrorCode LeRemoveCig(uint8_t cig_id);
247   bluetooth::hci::ErrorCode LeAcceptCisRequest(uint16_t handle);
248   bluetooth::hci::ErrorCode LeRejectCisRequest(
249       uint16_t handle, bluetooth::hci::ErrorCode reason);
250   bluetooth::hci::ErrorCode LeCreateBig(
251       uint8_t big_handle, uint8_t advertising_handle, uint8_t num_bis,
252       uint32_t sdu_interval, uint16_t max_sdu, uint16_t max_transport_latency,
253       uint8_t rtn, bluetooth::hci::SecondaryPhyType phy,
254       bluetooth::hci::Packing packing, bluetooth::hci::Enable framing,
255       bluetooth::hci::Enable encryption,
256       std::array<uint8_t, 16> broadcast_code);
257   bluetooth::hci::ErrorCode LeTerminateBig(uint8_t big_handle,
258                                            bluetooth::hci::ErrorCode reason);
259   bluetooth::hci::ErrorCode LeBigCreateSync(
260       uint8_t big_handle, uint16_t sync_handle,
261       bluetooth::hci::Enable encryption, std::array<uint8_t, 16> broadcast_code,
262       uint8_t mse, uint16_t big_syunc_timeout, std::vector<uint8_t> bis);
263   void LeBigTerminateSync(uint8_t big_handle);
264   bluetooth::hci::ErrorCode LeRequestPeerSca(uint16_t request_handle);
265   void LeSetupIsoDataPath(uint16_t connection_handle,
266                           bluetooth::hci::DataPathDirection data_path_direction,
267                           uint8_t data_path_id, uint64_t codec_id,
268                           uint32_t controller_Delay,
269                           std::vector<uint8_t> codec_configuration);
270   void LeRemoveIsoDataPath(
271       uint16_t connection_handle,
272       bluetooth::hci::RemoveDataPathDirection remove_data_path_direction);
273 
274   void HandleLeEnableEncryption(uint16_t handle, std::array<uint8_t, 8> rand,
275                                 uint16_t ediv,
276                                 std::array<uint8_t, kLtkSize> ltk);
277 
278   ErrorCode LeEnableEncryption(uint16_t handle, std::array<uint8_t, 8> rand,
279                                uint16_t ediv,
280                                std::array<uint8_t, kLtkSize> ltk);
281 
282   ErrorCode LeLongTermKeyRequestReply(uint16_t handle,
283                                       std::array<uint8_t, kLtkSize> ltk);
284 
285   ErrorCode LeLongTermKeyRequestNegativeReply(uint16_t handle);
286 
287   uint8_t LeReadNumberOfSupportedAdvertisingSets();
288 
289   // Classic
290   void StartInquiry(std::chrono::milliseconds timeout);
291   void InquiryCancel();
292   void InquiryTimeout();
293   void SetInquiryMode(uint8_t mode);
294   void SetInquiryLAP(uint64_t lap);
295   void SetInquiryMaxResponses(uint8_t max);
296   void Inquiry();
297 
GetInquiryScanEnable()298   bool GetInquiryScanEnable() const { return inquiry_scan_enable_; }
299   void SetInquiryScanEnable(bool enable);
300 
GetPageScanEnable()301   bool GetPageScanEnable() const { return page_scan_enable_; }
302   void SetPageScanEnable(bool enable);
303 
GetPageTimeout()304   uint16_t GetPageTimeout() const { return page_timeout_; }
305   void SetPageTimeout(uint16_t page_timeout);
306 
307   ErrorCode ChangeConnectionPacketType(uint16_t handle, uint16_t types);
308   ErrorCode ChangeConnectionLinkKey(uint16_t handle);
309   ErrorCode CentralLinkKey(uint8_t key_flag);
310   ErrorCode HoldMode(uint16_t handle, uint16_t hold_mode_max_interval,
311                      uint16_t hold_mode_min_interval);
312   ErrorCode SniffMode(uint16_t handle, uint16_t sniff_max_interval,
313                       uint16_t sniff_min_interval, uint16_t sniff_attempt,
314                       uint16_t sniff_timeout);
315   ErrorCode ExitSniffMode(uint16_t handle);
316   ErrorCode QosSetup(uint16_t handle, uint8_t service_type, uint32_t token_rate,
317                      uint32_t peak_bandwidth, uint32_t latency,
318                      uint32_t delay_variation);
319   ErrorCode RoleDiscovery(uint16_t handle, bluetooth::hci::Role* role);
320   ErrorCode SwitchRole(Address bd_addr, bluetooth::hci::Role role);
321   ErrorCode ReadLinkPolicySettings(uint16_t handle, uint16_t* settings);
322   ErrorCode WriteLinkPolicySettings(uint16_t handle, uint16_t settings);
323   ErrorCode FlowSpecification(uint16_t handle, uint8_t flow_direction,
324                               uint8_t service_type, uint32_t token_rate,
325                               uint32_t token_bucket_size,
326                               uint32_t peak_bandwidth, uint32_t access_latency);
327   ErrorCode WriteLinkSupervisionTimeout(uint16_t handle, uint16_t timeout);
328   ErrorCode WriteDefaultLinkPolicySettings(uint16_t settings);
329   void CheckExpiringConnection(uint16_t handle);
330   uint16_t ReadDefaultLinkPolicySettings() const;
331 
332   void ReadLocalOobData();
333   void ReadLocalOobExtendedData();
334 
335   ErrorCode AddScoConnection(uint16_t connection_handle, uint16_t packet_type,
336                              ScoDatapath datapath);
337   ErrorCode SetupSynchronousConnection(
338       uint16_t connection_handle, uint32_t transmit_bandwidth,
339       uint32_t receive_bandwidth, uint16_t max_latency, uint16_t voice_setting,
340       uint8_t retransmission_effort, uint16_t packet_types,
341       ScoDatapath datapath);
342   ErrorCode AcceptSynchronousConnection(
343       Address bd_addr, uint32_t transmit_bandwidth, uint32_t receive_bandwidth,
344       uint16_t max_latency, uint16_t voice_setting,
345       uint8_t retransmission_effort, uint16_t packet_types);
346   ErrorCode RejectSynchronousConnection(Address bd_addr, uint16_t reason);
347 
348   bool HasAclConnection();
349 
350   void HandleIso(bluetooth::hci::IsoView iso);
351 
352   // BR/EDR Commands
353 
354   // HCI Read Rssi command (Vol 4, Part E § 7.5.4).
355   ErrorCode ReadRssi(uint16_t connection_handle, int8_t* rssi);
356 
357   // LE Commands
358 
359   // HCI LE Set Random Address command (Vol 4, Part E § 7.8.4).
360   ErrorCode LeSetRandomAddress(Address random_address);
361 
362   // HCI LE Set Resolvable Private Address Timeout command
363   // (Vol 4, Part E § 7.8.45).
364   ErrorCode LeSetResolvablePrivateAddressTimeout(uint16_t rpa_timeout);
365 
366   // HCI LE Read Phy command (Vol 4, Part E § 7.8.47).
367   ErrorCode LeReadPhy(uint16_t connection_handle,
368                       bluetooth::hci::PhyType* tx_phy,
369                       bluetooth::hci::PhyType* rx_phy);
370 
371   // HCI LE Set Default Phy command (Vol 4, Part E § 7.8.48).
372   ErrorCode LeSetDefaultPhy(bool all_phys_no_transmit_preference,
373                             bool all_phys_no_receive_preference,
374                             uint8_t tx_phys, uint8_t rx_phys);
375 
376   // HCI LE Set Phy command (Vol 4, Part E § 7.8.49).
377   ErrorCode LeSetPhy(uint16_t connection_handle,
378                      bool all_phys_no_transmit_preference,
379                      bool all_phys_no_receive_preference, uint8_t tx_phys,
380                      uint8_t rx_phys, bluetooth::hci::PhyOptions phy_options);
381 
382   // HCI LE Set Host Feature command (Vol 4, Part E § 7.8.115).
383   ErrorCode LeSetHostFeature(uint8_t bit_number, uint8_t bit_value);
384 
385   // LE Filter Accept List
386 
387   // HCI command LE_Clear_Filter_Accept_List (Vol 4, Part E § 7.8.15).
388   ErrorCode LeClearFilterAcceptList();
389 
390   // HCI command LE_Add_Device_To_Filter_Accept_List (Vol 4, Part E § 7.8.16).
391   ErrorCode LeAddDeviceToFilterAcceptList(
392       FilterAcceptListAddressType address_type, Address address);
393 
394   // HCI command LE_Remove_Device_From_Filter_Accept_List (Vol 4, Part E
395   // § 7.8.17).
396   ErrorCode LeRemoveDeviceFromFilterAcceptList(
397       FilterAcceptListAddressType address_type, Address address);
398 
399   // LE Address Resolving
400 
401   // HCI command LE_Add_Device_To_Resolving_List (Vol 4, Part E § 7.8.38).
402   ErrorCode LeAddDeviceToResolvingList(
403       PeerAddressType peer_identity_address_type, Address peer_identity_address,
404       std::array<uint8_t, kIrkSize> peer_irk,
405       std::array<uint8_t, kIrkSize> local_irk);
406 
407   // HCI command LE_Remove_Device_From_Resolving_List (Vol 4, Part E § 7.8.39).
408   ErrorCode LeRemoveDeviceFromResolvingList(
409       PeerAddressType peer_identity_address_type,
410       Address peer_identity_address);
411 
412   // HCI command LE_Clear_Resolving_List (Vol 4, Part E § 7.8.40).
413   ErrorCode LeClearResolvingList();
414 
415   // HCI command LE_Read_Peer_Resolvable_Address (Vol 4, Part E § 7.8.42).
416   ErrorCode LeReadPeerResolvableAddress(
417       PeerAddressType peer_identity_address_type, Address peer_identity_address,
418       Address* peer_resolvable_address);
419 
420   // HCI command LE_Read_Local_Resolvable_Address (Vol 4, Part E § 7.8.43).
421   ErrorCode LeReadLocalResolvableAddress(
422       PeerAddressType peer_identity_address_type, Address peer_identity_address,
423       Address* local_resolvable_address);
424 
425   // HCI command LE_Set_Address_Resolution_Enable (Vol 4, Part E § 7.8.44).
426   ErrorCode LeSetAddressResolutionEnable(bool enable);
427 
428   // HCI command LE_Set_Privacy_Mode (Vol 4, Part E § 7.8.77).
429   ErrorCode LeSetPrivacyMode(PeerAddressType peer_identity_address_type,
430                              Address peer_identity_address,
431                              bluetooth::hci::PrivacyMode privacy_mode);
432 
433   // Legacy Advertising
434 
435   // HCI command LE_Set_Advertising_Parameters (Vol 4, Part E § 7.8.5).
436   ErrorCode LeSetAdvertisingParameters(
437       uint16_t advertising_interval_min, uint16_t advertising_interval_max,
438       bluetooth::hci::AdvertisingType advertising_type,
439       bluetooth::hci::OwnAddressType own_address_type,
440       bluetooth::hci::PeerAddressType peer_address_type, Address peer_address,
441       uint8_t advertising_channel_map,
442       bluetooth::hci::AdvertisingFilterPolicy advertising_filter_policy);
443 
444   // HCI command LE_Set_Advertising_Data (Vol 4, Part E § 7.8.7).
445   ErrorCode LeSetAdvertisingData(const std::vector<uint8_t>& advertising_data);
446 
447   // HCI command LE_Set_Scan_Response_Data (Vol 4, Part E § 7.8.8).
448   ErrorCode LeSetScanResponseData(
449       const std::vector<uint8_t>& scan_response_data);
450 
451   // HCI command LE_Advertising_Enable (Vol 4, Part E § 7.8.9).
452   ErrorCode LeSetAdvertisingEnable(bool advertising_enable);
453 
454   // Extended Advertising
455 
456   // HCI command LE_Set_Advertising_Set_Random_Address (Vol 4, Part E § 7.8.52).
457   ErrorCode LeSetAdvertisingSetRandomAddress(uint8_t advertising_handle,
458                                              Address random_address);
459 
460   // HCI command LE_Set_Advertising_Parameters (Vol 4, Part E § 7.8.53).
461   ErrorCode LeSetExtendedAdvertisingParameters(
462       uint8_t advertising_handle,
463       AdvertisingEventProperties advertising_event_properties,
464       uint16_t primary_advertising_interval_min,
465       uint16_t primary_advertising_interval_max,
466       uint8_t primary_advertising_channel_map,
467       bluetooth::hci::OwnAddressType own_address_type,
468       bluetooth::hci::PeerAddressType peer_address_type, Address peer_address,
469       bluetooth::hci::AdvertisingFilterPolicy advertising_filter_policy,
470       uint8_t advertising_tx_power,
471       bluetooth::hci::PrimaryPhyType primary_advertising_phy,
472       uint8_t secondary_max_skip,
473       bluetooth::hci::SecondaryPhyType secondary_advertising_phy,
474       uint8_t advertising_sid, bool scan_request_notification_enable);
475 
476   // HCI command LE_Set_Extended_Advertising_Data (Vol 4, Part E § 7.8.54).
477   ErrorCode LeSetExtendedAdvertisingData(
478       uint8_t advertising_handle, bluetooth::hci::Operation operation,
479       bluetooth::hci::FragmentPreference fragment_preference,
480       const std::vector<uint8_t>& advertising_data);
481 
482   // HCI command LE_Set_Extended_Scan_Response_Data (Vol 4, Part E § 7.8.55).
483   ErrorCode LeSetExtendedScanResponseData(
484       uint8_t advertising_handle, bluetooth::hci::Operation operation,
485       bluetooth::hci::FragmentPreference fragment_preference,
486       const std::vector<uint8_t>& scan_response_data);
487 
488   // HCI command LE_Set_Extended_Advertising_Enable (Vol 4, Part E § 7.8.56).
489   ErrorCode LeSetExtendedAdvertisingEnable(
490       bool enable, const std::vector<bluetooth::hci::EnabledSet>& sets);
491 
492   // HCI command LE_Remove_Advertising_Set (Vol 4, Part E § 7.8.59).
493   ErrorCode LeRemoveAdvertisingSet(uint8_t advertising_handle);
494 
495   // HCI command LE_Clear_Advertising_Sets (Vol 4, Part E § 7.8.60).
496   ErrorCode LeClearAdvertisingSets();
497 
498   // Legacy Scanning
499 
500   // HCI command LE_Set_Scan_Parameters (Vol 4, Part E § 7.8.10).
501   ErrorCode LeSetScanParameters(
502       bluetooth::hci::LeScanType scan_type, uint16_t scan_interval,
503       uint16_t scan_window, bluetooth::hci::OwnAddressType own_address_type,
504       bluetooth::hci::LeScanningFilterPolicy scanning_filter_policy);
505 
506   // HCI command LE_Set_Scan_Enable (Vol 4, Part E § 7.8.11).
507   ErrorCode LeSetScanEnable(bool enable, bool filter_duplicates);
508 
509   // Extended Scanning
510 
511   // HCI command LE_Set_Extended_Scan_Parameters (Vol 4, Part E § 7.8.64).
512   ErrorCode LeSetExtendedScanParameters(
513       bluetooth::hci::OwnAddressType own_address_type,
514       bluetooth::hci::LeScanningFilterPolicy scanning_filter_policy,
515       uint8_t scanning_phys,
516       std::vector<bluetooth::hci::PhyScanParameters> scanning_phy_parameters);
517 
518   // HCI command LE_Set_Extended_Scan_Enable (Vol 4, Part E § 7.8.65).
519   ErrorCode LeSetExtendedScanEnable(
520       bool enable, bluetooth::hci::FilterDuplicates filter_duplicates,
521       uint16_t duration, uint16_t period);
522 
523   // Legacy Connection
524 
525   // HCI LE Create Connection command (Vol 4, Part E § 7.8.12).
526   ErrorCode LeCreateConnection(
527       uint16_t scan_interval, uint16_t scan_window,
528       bluetooth::hci::InitiatorFilterPolicy initiator_filter_policy,
529       AddressWithType peer_address,
530       bluetooth::hci::OwnAddressType own_address_type,
531       uint16_t connection_interval_min, uint16_t connection_interval_max,
532       uint16_t max_latency, uint16_t supervision_timeout,
533       uint16_t min_ce_length, uint16_t max_ce_length);
534 
535   // HCI LE Create Connection Cancel command (Vol 4, Part E § 7.8.12).
536   ErrorCode LeCreateConnectionCancel();
537 
538   // Extended Connection
539 
540   // HCI LE Extended Create Connection command (Vol 4, Part E § 7.8.66).
541   ErrorCode LeExtendedCreateConnection(
542       bluetooth::hci::InitiatorFilterPolicy initiator_filter_policy,
543       bluetooth::hci::OwnAddressType own_address_type,
544       AddressWithType peer_address, uint8_t initiating_phys,
545       std::vector<bluetooth::hci::LeCreateConnPhyScanParameters>
546           initiating_phy_parameters);
547 
548   // Periodic Advertising
549 
550   // HCI LE Set Periodic Advertising Parameters command (Vol 4, Part E
551   // § 7.8.61).
552   ErrorCode LeSetPeriodicAdvertisingParameters(
553       uint8_t advertising_handle, uint16_t periodic_advertising_interval_min,
554       uint16_t periodic_advertising_interval_max, bool include_tx_power);
555 
556   // HCI LE Set Periodic Advertising Data command (Vol 4, Part E § 7.8.62).
557   ErrorCode LeSetPeriodicAdvertisingData(
558       uint8_t advertising_handle, bluetooth::hci::Operation operation,
559       const std::vector<uint8_t>& advertising_data);
560 
561   // HCI LE Set Periodic Advertising Enable command (Vol 4, Part E § 7.8.63).
562   ErrorCode LeSetPeriodicAdvertisingEnable(bool enable, bool include_adi,
563                                            uint8_t advertising_handle);
564 
565   // Periodic Sync
566 
567   // HCI LE Periodic Advertising Create Sync command (Vol 4, Part E § 7.8.67).
568   ErrorCode LePeriodicAdvertisingCreateSync(
569       bluetooth::hci::PeriodicAdvertisingOptions options,
570       uint8_t advertising_sid,
571       bluetooth::hci::AdvertiserAddressType advertiser_address_type,
572       Address advertiser_address, uint16_t skip, uint16_t sync_timeout,
573       uint8_t sync_cte_type);
574 
575   // HCI LE Periodic Advertising Create Sync Cancel command (Vol 4, Part E
576   // § 7.8.68).
577   ErrorCode LePeriodicAdvertisingCreateSyncCancel();
578 
579   // HCI LE Periodic Advertising Terminate Sync command (Vol 4, Part E
580   // § 7.8.69).
581   ErrorCode LePeriodicAdvertisingTerminateSync(uint16_t sync_handle);
582 
583   // Periodic Advertiser List
584 
585   // HCI LE Add Device To Periodic Advertiser List command (Vol 4, Part E
586   // § 7.8.70).
587   ErrorCode LeAddDeviceToPeriodicAdvertiserList(
588       bluetooth::hci::AdvertiserAddressType advertiser_address_type,
589       Address advertiser_address, uint8_t advertising_sid);
590 
591   // HCI LE Remove Device From Periodic Advertiser List command
592   // (Vol 4, Part E § 7.8.71).
593   ErrorCode LeRemoveDeviceFromPeriodicAdvertiserList(
594       bluetooth::hci::AdvertiserAddressType advertiser_address_type,
595       Address advertiser_address, uint8_t advertising_sid);
596 
597   // HCI LE Clear Periodic Advertiser List command (Vol 4, Part E § 7.8.72).
598   ErrorCode LeClearPeriodicAdvertiserList();
599 
600  protected:
601   void SendLinkLayerPacket(
602       std::unique_ptr<model::packets::LinkLayerPacketBuilder> packet,
603       int8_t tx_power = 0);
604   void SendLeLinkLayerPacket(
605       std::unique_ptr<model::packets::LinkLayerPacketBuilder> packet,
606       int8_t tx_power = 0);
607 
608   void IncomingAclPacket(model::packets::LinkLayerPacketView incoming,
609                          int8_t rssi);
610   void IncomingScoPacket(model::packets::LinkLayerPacketView incoming);
611   void IncomingDisconnectPacket(model::packets::LinkLayerPacketView incoming);
612   void IncomingEncryptConnection(model::packets::LinkLayerPacketView incoming);
613   void IncomingEncryptConnectionResponse(
614       model::packets::LinkLayerPacketView incoming);
615   void IncomingInquiryPacket(model::packets::LinkLayerPacketView incoming,
616                              uint8_t rssi);
617   void IncomingInquiryResponsePacket(
618       model::packets::LinkLayerPacketView incoming);
619   void IncomingLmpPacket(model::packets::LinkLayerPacketView incoming);
620   void IncomingIsoPacket(model::packets::LinkLayerPacketView incoming);
621   void IncomingIsoConnectionRequestPacket(
622       model::packets::LinkLayerPacketView incoming);
623   void IncomingIsoConnectionResponsePacket(
624       model::packets::LinkLayerPacketView incoming);
625 
626   void ScanIncomingLeLegacyAdvertisingPdu(
627       model::packets::LeLegacyAdvertisingPduView& pdu, uint8_t rssi);
628   void ScanIncomingLeExtendedAdvertisingPdu(
629       model::packets::LeExtendedAdvertisingPduView& pdu, uint8_t rssi);
630   void ConnectIncomingLeLegacyAdvertisingPdu(
631       model::packets::LeLegacyAdvertisingPduView& pdu);
632   void ConnectIncomingLeExtendedAdvertisingPdu(
633       model::packets::LeExtendedAdvertisingPduView& pdu);
634 
635   void IncomingLeLegacyAdvertisingPdu(
636       model::packets::LinkLayerPacketView incoming, uint8_t rssi);
637   void IncomingLeExtendedAdvertisingPdu(
638       model::packets::LinkLayerPacketView incoming, uint8_t rssi);
639   void IncomingLePeriodicAdvertisingPdu(
640       model::packets::LinkLayerPacketView incoming, uint8_t rssi);
641 
642   void IncomingLeConnectPacket(model::packets::LinkLayerPacketView incoming);
643   void IncomingLeConnectCompletePacket(
644       model::packets::LinkLayerPacketView incoming);
645   void IncomingLeConnectionParameterRequest(
646       model::packets::LinkLayerPacketView incoming);
647   void IncomingLeConnectionParameterUpdate(
648       model::packets::LinkLayerPacketView incoming);
649   void IncomingLeEncryptConnection(
650       model::packets::LinkLayerPacketView incoming);
651   void IncomingLeEncryptConnectionResponse(
652       model::packets::LinkLayerPacketView incoming);
653   void IncomingLeReadRemoteFeatures(
654       model::packets::LinkLayerPacketView incoming);
655   void IncomingLeReadRemoteFeaturesResponse(
656       model::packets::LinkLayerPacketView incoming);
657 
658   void ProcessIncomingLegacyScanRequest(
659       AddressWithType scanning_address,
660       AddressWithType resolved_scanning_address,
661       AddressWithType advertising_address);
662   void ProcessIncomingExtendedScanRequest(
663       ExtendedAdvertiser const& advertiser, AddressWithType scanning_address,
664       AddressWithType resolved_scanning_address,
665       AddressWithType advertising_address);
666 
667   bool ProcessIncomingLegacyConnectRequest(
668       model::packets::LeConnectView const& connect_ind);
669   bool ProcessIncomingExtendedConnectRequest(
670       ExtendedAdvertiser& advertiser,
671       model::packets::LeConnectView const& connect_ind);
672 
673   void IncomingLeScanPacket(model::packets::LinkLayerPacketView incoming);
674 
675   void IncomingLeScanResponsePacket(
676       model::packets::LinkLayerPacketView incoming, uint8_t rssi);
677   void IncomingPagePacket(model::packets::LinkLayerPacketView incoming);
678   void IncomingPageRejectPacket(model::packets::LinkLayerPacketView incoming);
679   void IncomingPageResponsePacket(model::packets::LinkLayerPacketView incoming);
680   void IncomingReadRemoteLmpFeatures(
681       model::packets::LinkLayerPacketView incoming);
682   void IncomingReadRemoteLmpFeaturesResponse(
683       model::packets::LinkLayerPacketView incoming);
684   void IncomingReadRemoteSupportedFeatures(
685       model::packets::LinkLayerPacketView incoming);
686   void IncomingReadRemoteSupportedFeaturesResponse(
687       model::packets::LinkLayerPacketView incoming);
688   void IncomingReadRemoteExtendedFeatures(
689       model::packets::LinkLayerPacketView incoming);
690   void IncomingReadRemoteExtendedFeaturesResponse(
691       model::packets::LinkLayerPacketView incoming);
692   void IncomingReadRemoteVersion(model::packets::LinkLayerPacketView incoming);
693   void IncomingReadRemoteVersionResponse(
694       model::packets::LinkLayerPacketView incoming);
695   void IncomingReadClockOffset(model::packets::LinkLayerPacketView incoming);
696   void IncomingReadClockOffsetResponse(
697       model::packets::LinkLayerPacketView incoming);
698   void IncomingRemoteNameRequest(model::packets::LinkLayerPacketView incoming);
699   void IncomingRemoteNameRequestResponse(
700       model::packets::LinkLayerPacketView incoming);
701 
702   void IncomingScoConnectionRequest(
703       model::packets::LinkLayerPacketView incoming);
704   void IncomingScoConnectionResponse(
705       model::packets::LinkLayerPacketView incoming);
706   void IncomingScoDisconnect(model::packets::LinkLayerPacketView incoming);
707 
708   void IncomingPingRequest(model::packets::LinkLayerPacketView incoming);
709   void IncomingRoleSwitchRequest(model::packets::LinkLayerPacketView incoming);
710   void IncomingRoleSwitchResponse(model::packets::LinkLayerPacketView incoming);
711 
712   void IncomingLlPhyReq(model::packets::LinkLayerPacketView incoming);
713   void IncomingLlPhyRsp(model::packets::LinkLayerPacketView incoming);
714   void IncomingLlPhyUpdateInd(model::packets::LinkLayerPacketView incoming);
715 
716  public:
717   bool IsEventUnmasked(bluetooth::hci::EventCode event) const;
718   bool IsLeEventUnmasked(bluetooth::hci::SubeventCode subevent) const;
719 
720   // TODO
721   // The Clock Offset should be specific to an ACL connection.
722   // Returning a proper value is not that important.
723   // NOLINTNEXTLINE(readability-convert-member-functions-to-static)
GetClockOffset()724   uint32_t GetClockOffset() const { return 0; }
725 
726   // TODO
727   // The Page Scan Repetition Mode should be specific to an ACL connection or
728   // a paging session.
GetPageScanRepetitionMode()729   PageScanRepetitionMode GetPageScanRepetitionMode() const {
730     return page_scan_repetition_mode_;
731   }
732 
733   // TODO
734   // The Encryption Key Size should be specific to an ACL connection.
GetEncryptionKeySize()735   uint8_t GetEncryptionKeySize() const { return min_encryption_key_size_; }
736 
GetScoFlowControlEnable()737   bool GetScoFlowControlEnable() const { return sco_flow_control_enable_; }
738 
GetAuthenticationEnable()739   AuthenticationEnable GetAuthenticationEnable() {
740     return authentication_enable_;
741   }
742 
GetLocalName()743   std::array<uint8_t, kLocalNameSize> const& GetLocalName() {
744     return local_name_;
745   }
746 
GetLeSupportedFeatures()747   uint64_t GetLeSupportedFeatures() const {
748     return properties_.le_features | le_host_supported_features_;
749   }
750 
GetConnectionAcceptTimeout()751   uint16_t GetConnectionAcceptTimeout() const {
752     return connection_accept_timeout_;
753   }
754 
GetVoiceSetting()755   uint16_t GetVoiceSetting() const { return voice_setting_; }
GetClassOfDevice()756   const ClassOfDevice& GetClassOfDevice() const { return class_of_device_; }
757 
GetMaxLmpFeaturesPageNumber()758   uint8_t GetMaxLmpFeaturesPageNumber() {
759     return properties_.lmp_features.size() - 1;
760   }
761 
762   uint64_t GetLmpFeatures(uint8_t page_number = 0) {
763     return page_number == 1 ? host_supported_features_
764                             : properties_.lmp_features[page_number];
765   }
766 
767   void SetLocalName(std::vector<uint8_t> const& local_name);
768   void SetLocalName(std::array<uint8_t, kLocalNameSize> const& local_name);
769   void SetExtendedInquiryResponse(
770       std::vector<uint8_t> const& extended_inquiry_response);
771 
SetClassOfDevice(ClassOfDevice class_of_device)772   void SetClassOfDevice(ClassOfDevice class_of_device) {
773     class_of_device_ = class_of_device;
774   }
775 
SetClassOfDevice(uint32_t class_of_device)776   void SetClassOfDevice(uint32_t class_of_device) {
777     class_of_device_.cod[0] = class_of_device & UINT8_MAX;
778     class_of_device_.cod[1] = (class_of_device >> 8) & UINT8_MAX;
779     class_of_device_.cod[2] = (class_of_device >> 16) & UINT8_MAX;
780   }
781 
SetAuthenticationEnable(AuthenticationEnable enable)782   void SetAuthenticationEnable(AuthenticationEnable enable) {
783     authentication_enable_ = enable;
784   }
785 
SetScoFlowControlEnable(bool enable)786   void SetScoFlowControlEnable(bool enable) {
787     sco_flow_control_enable_ = enable;
788   }
SetVoiceSetting(uint16_t voice_setting)789   void SetVoiceSetting(uint16_t voice_setting) {
790     voice_setting_ = voice_setting;
791   }
SetEventMask(uint64_t event_mask)792   void SetEventMask(uint64_t event_mask) { event_mask_ = event_mask; }
793 
SetEventMaskPage2(uint64_t event_mask)794   void SetEventMaskPage2(uint64_t event_mask) {
795     event_mask_page_2_ = event_mask;
796   }
SetLeEventMask(uint64_t le_event_mask)797   void SetLeEventMask(uint64_t le_event_mask) {
798     le_event_mask_ = le_event_mask;
799   }
800 
801   void SetLeHostSupport(bool enable);
802   void SetSecureSimplePairingSupport(bool enable);
803   void SetSecureConnectionsSupport(bool enable);
804 
SetConnectionAcceptTimeout(uint16_t timeout)805   void SetConnectionAcceptTimeout(uint16_t timeout) {
806     connection_accept_timeout_ = timeout;
807   }
808 
LegacyAdvertising()809   bool LegacyAdvertising() const { return legacy_advertising_in_use_; }
ExtendedAdvertising()810   bool ExtendedAdvertising() const { return extended_advertising_in_use_; }
811 
SelectLegacyAdvertising()812   bool SelectLegacyAdvertising() {
813     if (extended_advertising_in_use_) {
814       return false;
815     }
816     legacy_advertising_in_use_ = true;
817     return true;
818   }
819 
SelectExtendedAdvertising()820   bool SelectExtendedAdvertising() {
821     if (legacy_advertising_in_use_) {
822       return false;
823     }
824     extended_advertising_in_use_ = true;
825     return true;
826   }
827 
GetLeSuggestedMaxTxOctets()828   uint16_t GetLeSuggestedMaxTxOctets() const {
829     return le_suggested_max_tx_octets_;
830   }
GetLeSuggestedMaxTxTime()831   uint16_t GetLeSuggestedMaxTxTime() const { return le_suggested_max_tx_time_; }
832 
SetLeSuggestedMaxTxOctets(uint16_t max_tx_octets)833   void SetLeSuggestedMaxTxOctets(uint16_t max_tx_octets) {
834     le_suggested_max_tx_octets_ = max_tx_octets;
835   }
SetLeSuggestedMaxTxTime(uint16_t max_tx_time)836   void SetLeSuggestedMaxTxTime(uint16_t max_tx_time) {
837     le_suggested_max_tx_time_ = max_tx_time;
838   }
839 
840   TaskId StartScoStream(Address address);
841 
842  private:
843   const Address& address_;
844   const ControllerProperties& properties_;
845 
846   // Host Supported Features (Vol 2, Part C § 3.3 Feature Mask Definition).
847   // Page 1 of the LMP feature mask.
848   uint64_t host_supported_features_{0};
849   bool le_host_support_{false};
850   bool secure_simple_pairing_host_support_{false};
851   bool secure_connections_host_support_{false};
852 
853   // Le Host Supported Features (Vol 4, Part E § 7.8.3).
854   // Specifies the bits indicating Host support.
855   uint64_t le_host_supported_features_{0};
856   bool connected_isochronous_stream_host_support_{false};
857   bool connection_subrating_host_support_{false};
858 
859   // LE Random Address (Vol 4, Part E § 7.8.4).
860   Address random_address_{Address::kEmpty};
861 
862   // HCI configuration parameters.
863   //
864   // Provide the current HCI Configuration Parameters as defined in section
865   // Vol 4, Part E § 6 of the core specification.
866 
867   // Scan Enable (Vol 4, Part E § 6.1).
868   bool page_scan_enable_{false};
869   bool inquiry_scan_enable_{false};
870 
871   // Inquiry Scan Interval and Window
872   // (Vol 4, Part E § 6.2, 6.3).
873   uint16_t inquiry_scan_interval_{0x1000};
874   uint16_t inquiry_scan_window_{0x0012};
875 
876   // Page Timeout (Vol 4, Part E § 6.6).
877   uint16_t page_timeout_{0x2000};
878 
879   // Connection Accept Timeout (Vol 4, Part E § 6.7).
880   uint16_t connection_accept_timeout_{0x1FA0};
881 
882   // Page Scan Interval and Window
883   // (Vol 4, Part E § 6.8, 6.9).
884   uint16_t page_scan_interval_{0x0800};
885   uint16_t page_scan_window_{0x0012};
886 
887   // Voice Setting (Vol 4, Part E § 6.12).
888   uint16_t voice_setting_{0x0060};
889 
890   // Authentication Enable (Vol 4, Part E § 6.16).
891   AuthenticationEnable authentication_enable_{
892       AuthenticationEnable::NOT_REQUIRED};
893 
894   // Default Link Policy Settings (Vol 4, Part E § 6.18).
895   uint8_t default_link_policy_settings_{0x0000};
896 
897   // Synchronous Flow Control Enable (Vol 4, Part E § 6.22).
898   bool sco_flow_control_enable_{false};
899 
900   // Local Name (Vol 4, Part E § 6.23).
901   std::array<uint8_t, kLocalNameSize> local_name_{};
902 
903   // Extended Inquiry Response (Vol 4, Part E § 6.24).
904   std::array<uint8_t, kExtendedInquiryResponseSize>
905       extended_inquiry_response_{};
906 
907   // Class of Device (Vol 4, Part E § 6.26).
908   ClassOfDevice class_of_device_{{0, 0, 0}};
909 
910   // Other configuration parameters.
911 
912   // Current IAC LAP (Vol 4, Part E § 7.3.44).
913   std::vector<bluetooth::hci::Lap> current_iac_lap_list_{};
914 
915   // Min Encryption Key Size (Vol 4, Part E § 7.3.102).
916   uint8_t min_encryption_key_size_{16};
917 
918   // Event Mask (Vol 4, Part E § 7.3.1) and
919   // Event Mask Page 2 (Vol 4, Part E § 7.3.69) and
920   // LE Event Mask (Vol 4, Part E § 7.8.1).
921   uint64_t event_mask_{0x00001fffffffffff};
922   uint64_t event_mask_page_2_{0x0};
923   uint64_t le_event_mask_{0x01f};
924 
925   // Suggested Default Data Length (Vol 4, Part E § 7.8.34).
926   uint16_t le_suggested_max_tx_octets_{0x001b};
927   uint16_t le_suggested_max_tx_time_{0x0148};
928 
929   // Resolvable Private Address Timeout (Vol 4, Part E § 7.8.45).
930   std::chrono::seconds resolvable_private_address_timeout_{0x0384};
931 
932   // Page Scan Repetition Mode (Vol 2 Part B § 8.3.1 Page Scan substate).
933   // The Page Scan Repetition Mode depends on the selected Page Scan Interval.
934   PageScanRepetitionMode page_scan_repetition_mode_{PageScanRepetitionMode::R0};
935 
936   AclConnectionHandler connections_;
937 
938   // Callbacks to send packets back to the HCI.
939   std::function<void(std::shared_ptr<bluetooth::hci::AclBuilder>)> send_acl_;
940   std::function<void(std::shared_ptr<bluetooth::hci::EventBuilder>)>
941       send_event_;
942   std::function<void(std::shared_ptr<bluetooth::hci::ScoBuilder>)> send_sco_;
943   std::function<void(std::shared_ptr<bluetooth::hci::IsoBuilder>)> send_iso_;
944 
945   // Callback to send packets to remote devices.
946   std::function<void(std::shared_ptr<model::packets::LinkLayerPacketBuilder>,
947                      Phy::Type phy_type, int8_t tx_power)>
948       send_to_remote_;
949 
950   uint32_t oob_id_{1};
951   uint32_t key_id_{1};
952 
953   struct FilterAcceptListEntry {
954     FilterAcceptListAddressType address_type;
955     Address address;
956   };
957 
958   std::vector<FilterAcceptListEntry> le_filter_accept_list_;
959 
960   struct ResolvingListEntry {
961     PeerAddressType peer_identity_address_type;
962     Address peer_identity_address;
963     std::array<uint8_t, kIrkSize> peer_irk;
964     std::array<uint8_t, kIrkSize> local_irk;
965     bluetooth::hci::PrivacyMode privacy_mode;
966 
967     // Resolvable Private Address being used by the local device.
968     // It is the last resolvable private address generated for
969     // this identity address.
970     std::optional<Address> local_resolvable_address;
971     // Resolvable Private Address being used by the peer device.
972     // It is the last resolvable private address received that resolved
973     // to this identity address.
974     std::optional<Address> peer_resolvable_address;
975   };
976 
977   std::vector<ResolvingListEntry> le_resolving_list_;
978   bool le_resolving_list_enabled_{false};
979 
980   // Flag set when any legacy advertising command has been received
981   // since the last power-on-reset.
982   // From Vol 4, Part E § 3.1.1 Legacy and extended advertising,
983   // extended advertising are rejected when this bit is set.
984   bool legacy_advertising_in_use_{false};
985 
986   // Flag set when any extended advertising command has been received
987   // since the last power-on-reset.
988   // From Vol 4, Part E § 3.1.1 Legacy and extended advertising,
989   // legacy advertising are rejected when this bit is set.
990   bool extended_advertising_in_use_{false};
991 
992   // Legacy advertising state.
993   LegacyAdvertiser legacy_advertiser_{};
994 
995   // Extended advertising sets.
996   std::unordered_map<uint8_t, ExtendedAdvertiser> extended_advertisers_{};
997 
998   // Local phy preferences, defaults to LE 1M Phy.
999   uint8_t default_tx_phys_{0x1};
1000   uint8_t default_rx_phys_{0x1};
1001   uint8_t requested_tx_phys_{0x1};
1002   uint8_t requested_rx_phys_{0x1};
1003 
1004   struct PeriodicAdvertiserListEntry {
1005     bluetooth::hci::AdvertiserAddressType advertiser_address_type;
1006     Address advertiser_address;
1007     uint8_t advertising_sid;
1008   };
1009 
1010   std::vector<PeriodicAdvertiserListEntry> le_periodic_advertiser_list_;
1011 
1012   struct Scanner {
1013     bool scan_enable;
1014     std::chrono::steady_clock::duration period;
1015     std::chrono::steady_clock::duration duration;
1016     bluetooth::hci::FilterDuplicates filter_duplicates;
1017     bluetooth::hci::OwnAddressType own_address_type;
1018     bluetooth::hci::LeScanningFilterPolicy scan_filter_policy;
1019 
1020     struct PhyParameters {
1021       bool enabled;
1022       bluetooth::hci::LeScanType scan_type;
1023       uint16_t scan_interval;
1024       uint16_t scan_window;
1025     };
1026 
1027     PhyParameters le_1m_phy;
1028     PhyParameters le_coded_phy;
1029 
1030     // Save information about the advertising PDU being scanned.
1031     bool connectable_scan_response;
1032     std::optional<AddressWithType> pending_scan_request{};
1033 
1034     // Time keeping
1035     std::optional<std::chrono::steady_clock::time_point> timeout;
1036     std::optional<std::chrono::steady_clock::time_point> periodical_timeout;
1037 
1038     // Packet History
1039     std::vector<model::packets::LinkLayerPacketView> history;
1040 
IsEnabledScanner1041     bool IsEnabled() const { return scan_enable; }
1042 
IsPacketInHistoryScanner1043     bool IsPacketInHistory(model::packets::LinkLayerPacketView packet) const {
1044       return std::any_of(
1045           history.begin(), history.end(),
1046           [packet](model::packets::LinkLayerPacketView const& a) {
1047             return a.size() == packet.size() &&
1048                    std::equal(a.begin(), a.end(), packet.begin());
1049           });
1050     }
1051 
AddPacketToHistoryScanner1052     void AddPacketToHistory(model::packets::LinkLayerPacketView packet) {
1053       history.push_back(packet);
1054     }
1055   };
1056 
1057   // Legacy and extended scanning properties.
1058   // Legacy and extended scanning are disambiguated by the use
1059   // of legacy_advertising_in_use_ and extended_advertising_in_use_ flags.
1060   // Only one type of advertising may be used during a controller session.
1061   Scanner scanner_{};
1062 
1063   struct Initiator {
1064     bool connect_enable;
1065     bluetooth::hci::InitiatorFilterPolicy initiator_filter_policy;
1066     bluetooth::hci::AddressWithType peer_address{};
1067     bluetooth::hci::OwnAddressType own_address_type;
1068 
1069     struct PhyParameters {
1070       bool enabled;
1071       uint16_t scan_interval;
1072       uint16_t scan_window;
1073       uint16_t connection_interval_min;
1074       uint16_t connection_interval_max;
1075       uint16_t max_latency;
1076       uint16_t supervision_timeout;
1077       uint16_t min_ce_length;
1078       uint16_t max_ce_length;
1079     };
1080 
1081     PhyParameters le_1m_phy;
1082     PhyParameters le_2m_phy;
1083     PhyParameters le_coded_phy;
1084 
1085     // Save information about the ongoing connection.
1086     Address initiating_address{};  // TODO: AddressWithType
1087     std::optional<AddressWithType> pending_connect_request{};
1088 
IsEnabledInitiator1089     bool IsEnabled() const { return connect_enable; }
DisableInitiator1090     void Disable() { connect_enable = false; }
1091   };
1092 
1093   // Legacy and extended initiating properties.
1094   // Legacy and extended initiating are disambiguated by the use
1095   // of legacy_advertising_in_use_ and extended_advertising_in_use_ flags.
1096   // Only one type of advertising may be used during a controller session.
1097   Initiator initiator_{};
1098 
1099   struct Synchronizing {
1100     bluetooth::hci::PeriodicAdvertisingOptions options{};
1101     bluetooth::hci::AdvertiserAddressType advertiser_address_type{};
1102     Address advertiser_address{};
1103     uint8_t advertising_sid{};
1104     std::chrono::steady_clock::duration sync_timeout{};
1105   };
1106 
1107   struct Synchronized {
1108     bluetooth::hci::AdvertiserAddressType advertiser_address_type;
1109     Address advertiser_address;
1110     uint8_t advertising_sid;
1111     uint16_t sync_handle;
1112     std::chrono::steady_clock::duration sync_timeout;
1113     std::chrono::steady_clock::time_point timeout;
1114   };
1115 
1116   // Periodic advertising synchronizing and synchronized states.
1117   // Contains information for the currently established syncs, and the
1118   // pending sync.
1119   std::optional<Synchronizing> synchronizing_{};
1120   std::unordered_map<uint16_t, Synchronized> synchronized_{};
1121 
1122   // Classic state
1123   std::unique_ptr<const LinkManager, void (*)(const LinkManager*)> lm_;
1124   struct LinkManagerOps ops_;
1125 
1126   TaskId page_timeout_task_id_ = kInvalidTaskId;
1127 
1128   std::chrono::steady_clock::time_point last_inquiry_;
1129   model::packets::InquiryType inquiry_mode_{
1130       model::packets::InquiryType::STANDARD};
1131   TaskId inquiry_timer_task_id_ = kInvalidTaskId;
1132   uint64_t inquiry_lap_{};
1133   uint8_t inquiry_max_responses_{};
1134 
1135  public:
1136   // Type of scheduled tasks.
1137   class Task {
1138    public:
Task(std::chrono::steady_clock::time_point time,std::chrono::milliseconds period,TaskCallback callback,TaskId task_id)1139     Task(std::chrono::steady_clock::time_point time,
1140          std::chrono::milliseconds period, TaskCallback callback,
1141          TaskId task_id)
1142         : time(time),
1143           periodic(true),
1144           period(period),
1145           callback(std::move(callback)),
1146           task_id(task_id) {}
1147 
Task(std::chrono::steady_clock::time_point time,TaskCallback callback,TaskId task_id)1148     Task(std::chrono::steady_clock::time_point time, TaskCallback callback,
1149          TaskId task_id)
1150         : time(time),
1151           periodic(false),
1152           callback(std::move(callback)),
1153           task_id(task_id) {}
1154 
1155     // Operators needed to be in a collection
1156     bool operator<(const Task& another) const {
1157       return std::make_pair(time, task_id) <
1158              std::make_pair(another.time, another.task_id);
1159     }
1160 
1161     // These fields should no longer be public if the class ever becomes
1162     // public or gets more complex
1163     std::chrono::steady_clock::time_point time;
1164     const bool periodic;
1165     std::chrono::milliseconds period{};
1166     TaskCallback callback;
1167     TaskId task_id;
1168   };
1169 
1170  private:
1171   // List currently pending tasks.
1172   std::set<Task> task_queue_{};
1173   TaskId task_counter_{0};
1174 
1175   // Return the next valid unused task identifier.
1176   TaskId NextTaskId();
1177 };
1178 
1179 }  // namespace rootcanal
1180