1 /*
2  * Copyright 2019 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 #include "hci/le_scanning_manager.h"
17 
18 #include <bluetooth/log.h>
19 #include <com_android_bluetooth_flags.h>
20 
21 #include <memory>
22 #include <unordered_map>
23 
24 #include "hci/acl_manager.h"
25 #include "hci/controller.h"
26 #include "hci/event_checkers.h"
27 #include "hci/hci_layer.h"
28 #include "hci/hci_packets.h"
29 #include "hci/le_periodic_sync_manager.h"
30 #include "hci/le_scanning_interface.h"
31 #include "hci/le_scanning_reassembler.h"
32 #include "module.h"
33 #include "os/handler.h"
34 #include "os/log.h"
35 #include "os/system_properties.h"
36 #include "storage/storage_module.h"
37 
38 namespace bluetooth {
39 namespace hci {
40 
41 constexpr uint16_t kLeScanWindowMin = 0x0004;
42 constexpr uint16_t kLeScanWindowMax = 0x4000;
43 constexpr int64_t kLeScanRssiMin = -127;
44 constexpr int64_t kLeScanRssiMax = 20;
45 constexpr int64_t kLeScanRssiUnknown = 127;
46 constexpr int64_t kLeRxPathLossCompMin = -128;
47 constexpr int64_t kLeRxPathLossCompMax = 127;
48 constexpr uint16_t kDefaultLeExtendedScanWindow = 4800;
49 constexpr uint16_t kLeExtendedScanWindowMax = 0xFFFF;
50 constexpr uint16_t kLeScanIntervalMin = 0x0004;
51 constexpr uint16_t kLeScanIntervalMax = 0x4000;
52 constexpr uint16_t kDefaultLeExtendedScanInterval = 4800;
53 constexpr uint16_t kLeExtendedScanIntervalMax = 0xFFFF;
54 
55 constexpr uint8_t kScannableBit = 1;
56 constexpr uint8_t kDirectedBit = 2;
57 constexpr uint8_t kScanResponseBit = 3;
58 constexpr uint8_t kLegacyBit = 4;
59 constexpr uint8_t kDataStatusBits = 5;
60 
61 // system properties
62 const std::string kLeRxPathLossCompProperty = "bluetooth.hardware.radio.le_rx_path_loss_comp_db";
63 
__anon85f029fa0102() 64 const ModuleFactory LeScanningManager::Factory = ModuleFactory([]() { return new LeScanningManager(); });
65 
66 enum class ScanApiType {
67   LEGACY = 1,
68   ANDROID_HCI = 2,
69   EXTENDED = 3,
70 };
71 
72 struct Scanner {
73   Uuid app_uuid;
74   bool in_use;
75 };
76 
77 class NullScanningCallback : public ScanningCallback {
OnScannerRegistered(const Uuid,ScannerId,ScanningStatus)78   void OnScannerRegistered(
79       const Uuid /* app_uuid */, ScannerId /* scanner_id */, ScanningStatus /* status */) override {
80     log::info("OnScannerRegistered in NullScanningCallback");
81   }
OnSetScannerParameterComplete(ScannerId,ScanningStatus)82   void OnSetScannerParameterComplete(
83       ScannerId /* scanner_id */, ScanningStatus /* status */) override {
84     log::info("OnSetScannerParameterComplete in NullScanningCallback");
85   }
OnScanResult(uint16_t,uint8_t,Address,uint8_t,uint8_t,uint8_t,int8_t,int8_t,uint16_t,std::vector<uint8_t>)86   void OnScanResult(
87       uint16_t /* event_type */,
88       uint8_t /* address_type */,
89       Address /* address */,
90       uint8_t /* primary_phy */,
91       uint8_t /* secondary_phy */,
92       uint8_t /* advertising_sid */,
93       int8_t /* tx_power */,
94       int8_t /* rssi */,
95       uint16_t /* periodic_advertising_interval */,
96       std::vector<uint8_t> /* advertising_data */) override {
97     log::info("OnScanResult in NullScanningCallback");
98   }
OnTrackAdvFoundLost(AdvertisingFilterOnFoundOnLostInfo)99   void OnTrackAdvFoundLost(
100       AdvertisingFilterOnFoundOnLostInfo /* on_found_on_lost_info */) override {
101     log::info("OnTrackAdvFoundLost in NullScanningCallback");
102   }
OnBatchScanReports(int,int,int,int,std::vector<uint8_t>)103   void OnBatchScanReports(
104       int /* client_if */,
105       int /* status */,
106       int /* report_format */,
107       int /* num_records */,
108       std::vector<uint8_t> /* data */) override {
109     log::info("OnBatchScanReports in NullScanningCallback");
110   }
OnBatchScanThresholdCrossed(int)111   void OnBatchScanThresholdCrossed(int /* client_if */) override {
112     log::info("OnBatchScanThresholdCrossed in NullScanningCallback");
113   }
OnTimeout()114   void OnTimeout() override {
115     log::info("OnTimeout in NullScanningCallback");
116   }
OnFilterEnable(Enable,uint8_t)117   void OnFilterEnable(Enable /* enable */, uint8_t /* status */) override {
118     log::info("OnFilterEnable in NullScanningCallback");
119   }
OnFilterParamSetup(uint8_t,ApcfAction,uint8_t)120   void OnFilterParamSetup(
121       uint8_t /* available_spaces */, ApcfAction /* action */, uint8_t /* status */) override {
122     log::info("OnFilterParamSetup in NullScanningCallback");
123   }
OnFilterConfigCallback(ApcfFilterType,uint8_t,ApcfAction,uint8_t)124   void OnFilterConfigCallback(
125       ApcfFilterType /* filter_type */,
126       uint8_t /* available_spaces */,
127       ApcfAction /* action */,
128       uint8_t /* status */) override {
129     log::info("OnFilterConfigCallback in NullScanningCallback");
130   }
OnPeriodicSyncStarted(int,uint8_t,uint16_t,uint8_t,AddressWithType,uint8_t,uint16_t)131   void OnPeriodicSyncStarted(
132       int /* reg_id */,
133       uint8_t /* status */,
134       uint16_t /* sync_handle */,
135       uint8_t /* advertising_sid */,
136       AddressWithType /* address_with_type */,
137       uint8_t /* phy */,
138       uint16_t /* interval */) override {
139     log::info("OnPeriodicSyncStarted in NullScanningCallback");
140   };
OnPeriodicSyncReport(uint16_t,int8_t,int8_t,uint8_t,std::vector<uint8_t>)141   void OnPeriodicSyncReport(
142       uint16_t /* sync_handle */,
143       int8_t /* tx_power */,
144       int8_t /* rssi */,
145       uint8_t /* status */,
146       std::vector<uint8_t> /* data */) override {
147     log::info("OnPeriodicSyncReport in NullScanningCallback");
148   };
OnPeriodicSyncLost(uint16_t)149   void OnPeriodicSyncLost(uint16_t /* sync_handle */) override {
150     log::info("OnPeriodicSyncLost in NullScanningCallback");
151   };
OnPeriodicSyncTransferred(int,uint8_t,Address)152   void OnPeriodicSyncTransferred(
153       int /* pa_source */, uint8_t /* status */, Address /* address */) override {
154     log::info("OnPeriodicSyncTransferred in NullScanningCallback");
155   };
OnBigInfoReport(uint16_t,bool)156   void OnBigInfoReport(uint16_t /* sync_handle */, bool /* encrypted */) {
157     log::info("OnBigInfoReport in NullScanningCallback");
158   };
159 };
160 
161 enum class BatchScanState {
162   ERROR_STATE = 0,
163   ENABLE_CALLED = 1,
164   ENABLED_STATE = 2,
165   DISABLE_CALLED = 3,
166   DISABLED_STATE = 4,
167 };
168 
169 #define BTM_BLE_BATCH_SCAN_MODE_DISABLE 0
170 #define BTM_BLE_BATCH_SCAN_MODE_PASS 1
171 #define BTM_BLE_BATCH_SCAN_MODE_ACTI 2
172 #define BTM_BLE_BATCH_SCAN_MODE_PASS_ACTI 3
173 
174 struct BatchScanConfig {
175   BatchScanState current_state;
176   BatchScanMode scan_mode;
177   uint32_t scan_interval;
178   uint32_t scan_window;
179   BatchScanDiscardRule discard_rule;
180   ScannerId ref_value;
181 };
182 
183 struct LeScanningManager::impl : public LeAddressManagerCallback {
implbluetooth::hci::LeScanningManager::impl184   impl(Module* module) : module_(module), le_scanning_interface_(nullptr) {}
185 
~implbluetooth::hci::LeScanningManager::impl186   ~impl() {
187     if (address_manager_registered_) {
188       le_address_manager_->Unregister(this);
189     }
190   }
191 
startbluetooth::hci::LeScanningManager::impl192   void start(
193       os::Handler* handler,
194       HciLayer* hci_layer,
195       Controller* controller,
196       AclManager* acl_manager,
197       storage::StorageModule* storage_module) {
198     module_handler_ = handler;
199     hci_layer_ = hci_layer;
200     controller_ = controller;
201     acl_manager_ = acl_manager;
202     storage_module_ = storage_module;
203     le_address_manager_ = acl_manager->GetLeAddressManager();
204     le_scanning_interface_ = hci_layer_->GetLeScanningInterface(
205         module_handler_->BindOn(this, &LeScanningManager::impl::handle_scan_results));
206     periodic_sync_manager_.Init(le_scanning_interface_, module_handler_);
207     /* Check to see if the opcode is supported and C19 (support for extended advertising). */
208     if (controller_->IsSupported(OpCode::LE_SET_EXTENDED_SCAN_PARAMETERS) &&
209         controller->SupportsBleExtendedAdvertising()) {
210       api_type_ = ScanApiType::EXTENDED;
211       interval_ms_ = kDefaultLeExtendedScanInterval;
212       window_ms_ = kDefaultLeExtendedScanWindow;
213       phy_ = static_cast<uint8_t>(PhyType::LE_1M);
214     } else if (controller_->IsSupported(OpCode::LE_EXTENDED_SCAN_PARAMS)) {
215       api_type_ = ScanApiType::ANDROID_HCI;
216     } else {
217       api_type_ = ScanApiType::LEGACY;
218     }
219     is_filter_supported_ = controller_->IsSupported(OpCode::LE_ADV_FILTER);
220     if (is_filter_supported_) {
221       le_scanning_interface_->EnqueueCommand(
222           LeAdvFilterReadExtendedFeaturesBuilder::Create(),
223           module_handler_->BindOnceOn(this, &impl::on_apcf_read_extended_features_complete));
224     }
225     is_batch_scan_supported_ = controller->IsSupported(OpCode::LE_BATCH_SCAN);
226     is_periodic_advertising_sync_transfer_sender_supported_ =
227         controller_->SupportsBlePeriodicAdvertisingSyncTransferSender();
228     total_num_of_advt_tracked_ = controller->GetVendorCapabilities().total_num_of_advt_tracked_;
229     if (is_batch_scan_supported_) {
230       hci_layer_->RegisterVendorSpecificEventHandler(
231           VseSubeventCode::BLE_THRESHOLD,
232           handler->BindOn(this, &LeScanningManager::impl::on_storage_threshold_breach));
233       hci_layer_->RegisterVendorSpecificEventHandler(
234           VseSubeventCode::BLE_TRACKING,
235           handler->BindOn(this, &LeScanningManager::impl::on_advertisement_tracking));
236     }
237     scanners_ = std::vector<Scanner>(kMaxAppNum + 1);
238     for (size_t i = 0; i < scanners_.size(); i++) {
239       scanners_[i].app_uuid = Uuid::kEmpty;
240       scanners_[i].in_use = false;
241     }
242     batch_scan_config_.current_state = BatchScanState::DISABLED_STATE;
243     batch_scan_config_.ref_value = kInvalidScannerId;
244     le_rx_path_loss_comp_ = get_rx_path_loss_compensation();
245   }
246 
stopbluetooth::hci::LeScanningManager::impl247   void stop() {
248     for (auto subevent_code : LeScanningEvents) {
249       hci_layer_->UnregisterLeEventHandler(subevent_code);
250     }
251     if (is_batch_scan_supported_) {
252       // TODO implete vse module
253       // hci_layer_->UnregisterVesEventHandler(VseSubeventCode::BLE_THRESHOLD);
254       // hci_layer_->UnregisterVesEventHandler(VseSubeventCode::BLE_TRACKING);
255     }
256     batch_scan_config_.current_state = BatchScanState::DISABLED_STATE;
257     batch_scan_config_.ref_value = kInvalidScannerId;
258     scanning_callbacks_ = &null_scanning_callback_;
259     periodic_sync_manager_.SetScanningCallback(scanning_callbacks_);
260   }
261 
handle_scan_resultsbluetooth::hci::LeScanningManager::impl262   void handle_scan_results(LeMetaEventView event) {
263     switch (event.GetSubeventCode()) {
264       case SubeventCode::ADVERTISING_REPORT:
265         handle_advertising_report(LeAdvertisingReportRawView::Create(event));
266         break;
267       case SubeventCode::DIRECTED_ADVERTISING_REPORT:
268         handle_directed_advertising_report(LeDirectedAdvertisingReportView::Create(event));
269         break;
270       case SubeventCode::EXTENDED_ADVERTISING_REPORT:
271         handle_extended_advertising_report(LeExtendedAdvertisingReportRawView::Create(event));
272         break;
273       case SubeventCode::PERIODIC_ADVERTISING_SYNC_ESTABLISHED:
274         LePeriodicAdvertisingSyncEstablishedView::Create(event);
275         periodic_sync_manager_.HandleLePeriodicAdvertisingSyncEstablished(
276             LePeriodicAdvertisingSyncEstablishedView::Create(event));
277         break;
278       case SubeventCode::PERIODIC_ADVERTISING_REPORT:
279         periodic_sync_manager_.HandleLePeriodicAdvertisingReport(LePeriodicAdvertisingReportView::Create(event));
280         break;
281       case SubeventCode::PERIODIC_ADVERTISING_SYNC_LOST:
282         periodic_sync_manager_.HandleLePeriodicAdvertisingSyncLost(LePeriodicAdvertisingSyncLostView::Create(event));
283         break;
284       case SubeventCode::PERIODIC_ADVERTISING_SYNC_TRANSFER_RECEIVED:
285         periodic_sync_manager_.HandleLePeriodicAdvertisingSyncTransferReceived(
286             LePeriodicAdvertisingSyncTransferReceivedView::Create(event));
287         break;
288       case SubeventCode::SCAN_TIMEOUT:
289         scanning_callbacks_->OnTimeout();
290         break;
291       case SubeventCode::BIG_INFO_ADVERTISING_REPORT:
292         periodic_sync_manager_.HandleLeBigInfoAdvertisingReport(
293             LeBigInfoAdvertisingReportView::Create(event));
294         break;
295       default:
296         log::fatal("Unknown advertising subevent {}", SubeventCodeText(event.GetSubeventCode()));
297     }
298   }
299 
300   struct ExtendedEventTypeOptions {
301     bool connectable{false};
302     bool scannable{false};
303     bool directed{false};
304     bool scan_response{false};
305     bool legacy{false};
306     bool continuing{false};
307     bool truncated{false};
308   };
309 
get_rx_path_loss_compensationbluetooth::hci::LeScanningManager::impl310   int8_t get_rx_path_loss_compensation() {
311     int8_t compensation = 0;
312     auto compensation_prop = os::GetSystemProperty(kLeRxPathLossCompProperty);
313     if (compensation_prop) {
314       auto compensation_number = common::Int64FromString(compensation_prop.value());
315       if (compensation_number) {
316         int64_t number = compensation_number.value();
317         if (number < kLeRxPathLossCompMin || number > kLeRxPathLossCompMax) {
318           log::error("Invalid number for rx path loss compensation: {}", number);
319         } else {
320           compensation = number;
321         }
322       }
323     }
324     log::info("Rx path loss compensation: {}", compensation);
325     return compensation;
326   }
327 
get_rssi_after_calibrationbluetooth::hci::LeScanningManager::impl328   int8_t get_rssi_after_calibration(int8_t rssi) {
329     if (le_rx_path_loss_comp_ == 0 || rssi == kLeScanRssiUnknown) {
330       return rssi;
331     }
332     int8_t calibrated_rssi = rssi;
333     int64_t number = rssi + le_rx_path_loss_comp_;
334     if (number < kLeScanRssiMin || number > kLeScanRssiMax) {
335       log::error("Invalid number for calibrated rssi: {}", number);
336     } else {
337       calibrated_rssi = number;
338     }
339     return calibrated_rssi;
340   }
341 
transform_to_extended_event_typebluetooth::hci::LeScanningManager::impl342   uint16_t transform_to_extended_event_type(ExtendedEventTypeOptions o) {
343     return (o.connectable ? 0x0001 << 0 : 0) | (o.scannable ? 0x0001 << 1 : 0) |
344            (o.directed ? 0x0001 << 2 : 0) | (o.scan_response ? 0x0001 << 3 : 0) |
345            (o.legacy ? 0x0001 << 4 : 0) | (o.continuing ? 0x0001 << 5 : 0) |
346            (o.truncated ? 0x0001 << 6 : 0);
347   }
348 
handle_advertising_reportbluetooth::hci::LeScanningManager::impl349   void handle_advertising_report(LeAdvertisingReportRawView event_view) {
350     if (!event_view.IsValid()) {
351       log::info("Dropping invalid advertising event");
352       return;
353     }
354     std::vector<LeAdvertisingResponseRaw> reports = event_view.GetResponses();
355     if (reports.empty()) {
356       log::info("Zero results in advertising event");
357       return;
358     }
359 
360     for (LeAdvertisingResponseRaw report : reports) {
361       uint16_t extended_event_type = 0;
362       switch (report.event_type_) {
363         case AdvertisingEventType::ADV_IND:
364           extended_event_type = transform_to_extended_event_type(
365               {.connectable = true, .scannable = true, .legacy = true});
366           break;
367         case AdvertisingEventType::ADV_DIRECT_IND:
368           extended_event_type = transform_to_extended_event_type(
369               {.connectable = true, .directed = true, .legacy = true});
370           break;
371         case AdvertisingEventType::ADV_SCAN_IND:
372           extended_event_type =
373               transform_to_extended_event_type({.scannable = true, .legacy = true});
374           break;
375         case AdvertisingEventType::ADV_NONCONN_IND:
376           extended_event_type = transform_to_extended_event_type({.legacy = true});
377           break;
378         case AdvertisingEventType::SCAN_RESPONSE:
379           if (com::android::bluetooth::flags::fix_nonconnectable_scannable_advertisement()) {
380             // We don't know if the initial advertising report was connectable or not.
381             // LeScanningReassembler fixes the connectable field.
382             extended_event_type = transform_to_extended_event_type(
383                 {.scannable = true, .scan_response = true, .legacy = true});
384           } else {
385             extended_event_type = transform_to_extended_event_type(
386                 {.connectable = true, .scannable = true, .scan_response = true, .legacy = true});
387           }
388           break;
389         default:
390           log::warn("Unsupported event type:{}", (uint16_t)report.event_type_);
391           return;
392       }
393 
394       process_advertising_package_content(
395           extended_event_type,
396           (uint8_t)report.address_type_,
397           report.address_,
398           (uint8_t)PrimaryPhyType::LE_1M,
399           (uint8_t)SecondaryPhyType::NO_PACKETS,
400           kAdvertisingDataInfoNotPresent,
401           kTxPowerInformationNotPresent,
402           report.rssi_,
403           kNotPeriodicAdvertisement,
404           report.advertising_data_);
405     }
406   }
407 
handle_directed_advertising_reportbluetooth::hci::LeScanningManager::impl408   void handle_directed_advertising_report(LeDirectedAdvertisingReportView /*event_view*/) {
409     log::warn("HCI Directed Advertising Report events are not supported");
410   }
411 
handle_extended_advertising_reportbluetooth::hci::LeScanningManager::impl412   void handle_extended_advertising_report(LeExtendedAdvertisingReportRawView event_view) {
413     if (!event_view.IsValid()) {
414       log::info("Dropping invalid advertising event");
415       return;
416     }
417 
418     std::vector<LeExtendedAdvertisingResponseRaw> reports = event_view.GetResponses();
419     if (reports.empty()) {
420       log::info("Zero results in advertising event");
421       return;
422     }
423 
424     for (LeExtendedAdvertisingResponseRaw& report : reports) {
425       uint16_t event_type = report.connectable_ | (report.scannable_ << kScannableBit) |
426                             (report.directed_ << kDirectedBit) | (report.scan_response_ << kScanResponseBit) |
427                             (report.legacy_ << kLegacyBit) | ((uint16_t)report.data_status_ << kDataStatusBits);
428       process_advertising_package_content(
429           event_type,
430           (uint8_t)report.address_type_,
431           report.address_,
432           (uint8_t)report.primary_phy_,
433           (uint8_t)report.secondary_phy_,
434           report.advertising_sid_,
435           report.tx_power_,
436           report.rssi_,
437           report.periodic_advertising_interval_,
438           report.advertising_data_);
439     }
440   }
441 
process_advertising_package_contentbluetooth::hci::LeScanningManager::impl442   void process_advertising_package_content(
443       uint16_t event_type,
444       uint8_t address_type,
445       Address address,
446       uint8_t primary_phy,
447       uint8_t secondary_phy,
448       uint8_t advertising_sid,
449       int8_t tx_power,
450       int8_t rssi,
451       uint16_t periodic_advertising_interval,
452       const std::vector<uint8_t>& advertising_data) {
453     // When using the vendor command Le Set Extended Params to
454     // configure a filter accept list based e.g. on the service UUIDs
455     // found in the report, we ignore the scan responses as we cannot be
456     // certain that they will not be dropped by the filter.
457     // TODO(b/275754998): Improve the decision on what to do with scan responses: Only when used
458     // with hardware-filtering features should we ignore waiting for scan response, and make sure
459     // scan responses are still reported too.
460     scanning_reassembler_.SetIgnoreScanResponses(
461         le_scan_type_ == LeScanType::PASSIVE ||
462         filter_policy_ == LeScanningFilterPolicy::FILTER_ACCEPT_LIST_ONLY);
463 
464     std::optional<LeScanningReassembler::CompleteAdvertisingData> processed_report =
465         scanning_reassembler_.ProcessAdvertisingReport(
466             event_type, address_type, address, advertising_sid, advertising_data);
467 
468     if (processed_report.has_value()) {
469       switch (address_type) {
470         case (uint8_t)AddressType::PUBLIC_DEVICE_ADDRESS:
471         case (uint8_t)AddressType::PUBLIC_IDENTITY_ADDRESS:
472           address_type = (uint8_t)AddressType::PUBLIC_DEVICE_ADDRESS;
473           break;
474         case (uint8_t)AddressType::RANDOM_DEVICE_ADDRESS:
475         case (uint8_t)AddressType::RANDOM_IDENTITY_ADDRESS:
476           address_type = (uint8_t)AddressType::RANDOM_DEVICE_ADDRESS;
477           break;
478       }
479 
480       const uint16_t result_event_type =
481           com::android::bluetooth::flags::fix_nonconnectable_scannable_advertisement()
482               ? processed_report->extended_event_type
483               : event_type;
484 
485       scanning_callbacks_->OnScanResult(
486           result_event_type,
487           address_type,
488           address,
489           primary_phy,
490           secondary_phy,
491           advertising_sid,
492           tx_power,
493           get_rssi_after_calibration(rssi),
494           periodic_advertising_interval,
495           std::move(processed_report->data));
496     }
497   }
498 
configure_scanbluetooth::hci::LeScanningManager::impl499   void configure_scan() {
500     std::vector<PhyScanParameters> parameter_vector;
501     for (int i = 0; i < 7; i++) {
502       if ((phy_ & 1 << i) != 0) {
503         PhyScanParameters phy_scan_parameters;
504         phy_scan_parameters.le_scan_window_ = window_ms_;
505         phy_scan_parameters.le_scan_interval_ = interval_ms_;
506         phy_scan_parameters.le_scan_type_ = le_scan_type_;
507         parameter_vector.push_back(phy_scan_parameters);
508       }
509     }
510     uint8_t phys_in_use = phy_;
511 
512     // The Host shall not issue set scan parameter command when scanning is enabled
513     stop_scan();
514 
515     if (le_address_manager_->GetAddressPolicy() != LeAddressManager::USE_PUBLIC_ADDRESS) {
516       own_address_type_ = OwnAddressType::RANDOM_DEVICE_ADDRESS;
517     } else {
518       own_address_type_ = OwnAddressType::PUBLIC_DEVICE_ADDRESS;
519     }
520 
521     switch (api_type_) {
522       case ScanApiType::EXTENDED:
523         le_scanning_interface_->EnqueueCommand(
524             LeSetExtendedScanParametersBuilder::Create(
525                 own_address_type_, filter_policy_, phys_in_use, parameter_vector),
526             module_handler_->BindOnceOn(this, &impl::on_set_scan_parameter_complete));
527         break;
528       case ScanApiType::ANDROID_HCI:
529         le_scanning_interface_->EnqueueCommand(
530             LeExtendedScanParamsBuilder::Create(
531                 le_scan_type_, interval_ms_, window_ms_, own_address_type_, filter_policy_),
532             module_handler_->BindOnceOn(this, &impl::on_set_scan_parameter_complete));
533 
534         break;
535       case ScanApiType::LEGACY:
536         le_scanning_interface_->EnqueueCommand(
537 
538             LeSetScanParametersBuilder::Create(
539                 le_scan_type_, interval_ms_, window_ms_, own_address_type_, filter_policy_),
540             module_handler_->BindOnceOn(this, &impl::on_set_scan_parameter_complete));
541         break;
542     }
543   }
544 
register_scannerbluetooth::hci::LeScanningManager::impl545   void register_scanner(const Uuid app_uuid) {
546     for (uint8_t i = 1; i <= kMaxAppNum; i++) {
547       if (scanners_[i].in_use && scanners_[i].app_uuid == app_uuid) {
548         log::error("Application already registered {}", app_uuid.ToString());
549         scanning_callbacks_->OnScannerRegistered(app_uuid, 0x00, ScanningCallback::ScanningStatus::INTERNAL_ERROR);
550         return;
551       }
552     }
553 
554     // valid value of scanner id : 1 ~ kMaxAppNum
555     for (uint8_t i = 1; i <= kMaxAppNum; i++) {
556       if (!scanners_[i].in_use) {
557         scanners_[i].app_uuid = app_uuid;
558         scanners_[i].in_use = true;
559         scanning_callbacks_->OnScannerRegistered(app_uuid, i, ScanningCallback::ScanningStatus::SUCCESS);
560         return;
561       }
562     }
563 
564     log::error("Unable to register scanner, max client reached:{}", kMaxAppNum);
565     scanning_callbacks_->OnScannerRegistered(app_uuid, 0x00, ScanningCallback::ScanningStatus::NO_RESOURCES);
566   }
567 
unregister_scannerbluetooth::hci::LeScanningManager::impl568   void unregister_scanner(ScannerId scanner_id) {
569     if (scanner_id <= 0 || scanner_id > kMaxAppNum) {
570       log::warn("Invalid scanner id");
571       return;
572     }
573 
574     if (scanners_[scanner_id].in_use) {
575       scanners_[scanner_id].in_use = false;
576       scanners_[scanner_id].app_uuid = Uuid::kEmpty;
577       log::debug("Unregister scanner successful, scannerId={}", scanner_id);
578     } else {
579       log::warn("Unregister scanner with unused scanner id");
580     }
581   }
582 
scanbluetooth::hci::LeScanningManager::impl583   void scan(bool start) {
584     // On-resume flag should always be reset if there is an explicit start/stop call.
585     scan_on_resume_ = false;
586     if (start) {
587       configure_scan();
588       start_scan();
589     } else {
590       if (address_manager_registered_) {
591         le_address_manager_->Unregister(this);
592         address_manager_registered_ = false;
593         paused_ = false;
594       }
595       stop_scan();
596     }
597   }
598 
start_scanbluetooth::hci::LeScanningManager::impl599   void start_scan() {
600     // If we receive start_scan during paused, set scan_on_resume_ to true
601     if (paused_ && address_manager_registered_) {
602       scan_on_resume_ = true;
603       return;
604     }
605     is_scanning_ = true;
606     if (!address_manager_registered_) {
607       le_address_manager_->Register(this);
608       address_manager_registered_ = true;
609     }
610 
611     switch (api_type_) {
612       case ScanApiType::EXTENDED:
613         le_scanning_interface_->EnqueueCommand(
614             LeSetExtendedScanEnableBuilder::Create(
615                 Enable::ENABLED,
616 #if TARGET_FLOSS
617                 FilterDuplicates::ENABLED /* filter duplicates */,
618 #else
619                 FilterDuplicates::DISABLED /* filter duplicates */,
620 #endif
621                 0,
622                 0),
623             module_handler_->BindOnce(check_complete<LeSetExtendedScanEnableCompleteView>));
624         break;
625       case ScanApiType::ANDROID_HCI:
626       case ScanApiType::LEGACY:
627         le_scanning_interface_->EnqueueCommand(
628             LeSetScanEnableBuilder::Create(
629                 Enable::ENABLED, Enable::DISABLED /* filter duplicates */),
630             module_handler_->BindOnce(check_complete<LeSetScanEnableCompleteView>));
631         break;
632     }
633   }
634 
stop_scanbluetooth::hci::LeScanningManager::impl635   void stop_scan() {
636     if (!is_scanning_) {
637       log::info("Scanning already stopped, return!");
638       return;
639     }
640     is_scanning_ = false;
641 
642     switch (api_type_) {
643       case ScanApiType::EXTENDED:
644         le_scanning_interface_->EnqueueCommand(
645             LeSetExtendedScanEnableBuilder::Create(
646                 Enable::DISABLED,
647 #if TARGET_FLOSS
648                 FilterDuplicates::ENABLED /* filter duplicates */,
649 #else
650                 FilterDuplicates::DISABLED /* filter duplicates */,
651 #endif
652                 0,
653                 0),
654             module_handler_->BindOnce(check_complete<LeSetExtendedScanEnableCompleteView>));
655         break;
656       case ScanApiType::ANDROID_HCI:
657       case ScanApiType::LEGACY:
658         le_scanning_interface_->EnqueueCommand(
659             LeSetScanEnableBuilder::Create(
660                 Enable::DISABLED, Enable::DISABLED /* filter duplicates */),
661             module_handler_->BindOnce(check_complete<LeSetScanEnableCompleteView>));
662         break;
663     }
664   }
665 
set_scan_parametersbluetooth::hci::LeScanningManager::impl666   void set_scan_parameters(
667       ScannerId scanner_id,
668       LeScanType scan_type,
669       uint16_t scan_interval,
670       uint16_t scan_window,
671       uint8_t scan_phy) {
672     uint32_t max_scan_interval = kLeScanIntervalMax;
673     uint32_t max_scan_window = kLeScanWindowMax;
674     if (api_type_ == ScanApiType::EXTENDED) {
675       max_scan_interval = kLeExtendedScanIntervalMax;
676       max_scan_window = kLeExtendedScanWindowMax;
677     }
678 
679     if (scan_type != LeScanType::ACTIVE && scan_type != LeScanType::PASSIVE) {
680       log::error("Invalid scan type");
681       scanning_callbacks_->OnSetScannerParameterComplete(
682           scanner_id, ScanningCallback::ScanningStatus::ILLEGAL_PARAMETER);
683       return;
684     }
685     if (scan_interval > max_scan_interval || scan_interval < kLeScanIntervalMin) {
686       log::error("Invalid scan_interval {}", scan_interval);
687       scanning_callbacks_->OnSetScannerParameterComplete(
688           scanner_id, ScanningCallback::ScanningStatus::ILLEGAL_PARAMETER);
689       return;
690     }
691     if (scan_window > max_scan_window || scan_window < kLeScanWindowMin) {
692       log::error("Invalid scan_window {}", scan_window);
693       scanning_callbacks_->OnSetScannerParameterComplete(
694           scanner_id, ScanningCallback::ScanningStatus::ILLEGAL_PARAMETER);
695       return;
696     }
697     le_scan_type_ = scan_type;
698     interval_ms_ = scan_interval;
699     window_ms_ = scan_window;
700     if (com::android::bluetooth::flags::phy_to_native()) phy_ = scan_phy;
701     scanning_callbacks_->OnSetScannerParameterComplete(scanner_id, ScanningCallback::SUCCESS);
702   }
703 
set_scan_filter_policybluetooth::hci::LeScanningManager::impl704   void set_scan_filter_policy(LeScanningFilterPolicy filter_policy) {
705     filter_policy_ = filter_policy;
706   }
707 
scan_filter_enablebluetooth::hci::LeScanningManager::impl708   void scan_filter_enable(bool enable) {
709     if (!is_filter_supported_) {
710       log::warn("Advertising filter is not supported");
711       return;
712     }
713 
714     Enable apcf_enable = enable ? Enable::ENABLED : Enable::DISABLED;
715     le_scanning_interface_->EnqueueCommand(
716         LeAdvFilterEnableBuilder::Create(apcf_enable),
717         module_handler_->BindOnceOn(this, &impl::on_advertising_filter_complete));
718   }
719 
is_bondedbluetooth::hci::LeScanningManager::impl720   bool is_bonded(Address target_address) {
721     for (auto device : storage_module_->GetBondedDevices()) {
722       if (device.GetAddress() == target_address) {
723         log::debug("Addresses match!");
724         return true;
725       }
726     }
727     log::debug("Addresse DON'Ts match!");
728     return false;
729   }
730 
scan_filter_parameter_setupbluetooth::hci::LeScanningManager::impl731   void scan_filter_parameter_setup(
732       ApcfAction action, uint8_t filter_index, AdvertisingFilterParameter advertising_filter_parameter) {
733     if (!is_filter_supported_) {
734       log::warn("Advertising filter is not supported");
735       return;
736     }
737 
738     auto entry = remove_me_later_map_.find(filter_index);
739     switch (action) {
740       case ApcfAction::ADD:
741         le_scanning_interface_->EnqueueCommand(
742             LeAdvFilterAddFilteringParametersBuilder::Create(
743                 filter_index,
744                 advertising_filter_parameter.feature_selection,
745                 advertising_filter_parameter.list_logic_type,
746                 advertising_filter_parameter.filter_logic_type,
747                 advertising_filter_parameter.rssi_high_thresh,
748                 advertising_filter_parameter.delivery_mode,
749                 advertising_filter_parameter.onfound_timeout,
750                 advertising_filter_parameter.onfound_timeout_cnt,
751                 advertising_filter_parameter.rssi_low_thresh,
752                 advertising_filter_parameter.onlost_timeout,
753                 advertising_filter_parameter.num_of_tracking_entries),
754             module_handler_->BindOnceOn(this, &impl::on_advertising_filter_complete));
755         break;
756       case ApcfAction::DELETE:
757         tracker_id_map_.erase(filter_index);
758         le_scanning_interface_->EnqueueCommand(
759             LeAdvFilterDeleteFilteringParametersBuilder::Create(filter_index),
760             module_handler_->BindOnceOn(this, &impl::on_advertising_filter_complete));
761 
762         // IRK Scanning
763         if (entry != remove_me_later_map_.end()) {
764           // Don't want to remove for a bonded device
765           if (!is_bonded(entry->second.GetAddress())) {
766             le_address_manager_->RemoveDeviceFromResolvingList(
767                 static_cast<PeerAddressType>(entry->second.GetAddressType()), entry->second.GetAddress());
768           }
769           remove_me_later_map_.erase(filter_index);
770         }
771 
772         break;
773       case ApcfAction::CLEAR:
774         le_scanning_interface_->EnqueueCommand(
775             LeAdvFilterClearFilteringParametersBuilder::Create(),
776             module_handler_->BindOnceOn(this, &impl::on_advertising_filter_complete));
777 
778         // IRK Scanning
779         if (entry != remove_me_later_map_.end()) {
780           // Don't want to remove for a bonded device
781           if (!is_bonded(entry->second.GetAddress())) {
782             le_address_manager_->RemoveDeviceFromResolvingList(
783                 static_cast<PeerAddressType>(entry->second.GetAddressType()), entry->second.GetAddress());
784           }
785           remove_me_later_map_.erase(filter_index);
786         }
787 
788         break;
789       default:
790         log::error("Unknown action type: {}", (uint16_t)action);
791         break;
792     }
793   }
794 
scan_filter_addbluetooth::hci::LeScanningManager::impl795   void scan_filter_add(uint8_t filter_index, std::vector<AdvertisingPacketContentFilterCommand> filters) {
796     if (!is_filter_supported_) {
797       log::warn("Advertising filter is not supported");
798       return;
799     }
800 
801     ApcfAction apcf_action = ApcfAction::ADD;
802     for (auto filter : filters) {
803       /* If data is passed, both mask and data have to be the same length */
804       if (filter.data.size() != filter.data_mask.size() && filter.data.size() != 0 && filter.data_mask.size() != 0) {
805         log::error("data and data_mask are of different size");
806         continue;
807       }
808 
809       switch (filter.filter_type) {
810         case ApcfFilterType::BROADCASTER_ADDRESS: {
811           update_address_filter(apcf_action, filter_index, filter.address, filter.application_address_type, filter.irk);
812           break;
813         }
814         case ApcfFilterType::SERVICE_UUID:
815         case ApcfFilterType::SERVICE_SOLICITATION_UUID: {
816           update_uuid_filter(apcf_action, filter_index, filter.filter_type, filter.uuid, filter.uuid_mask);
817           break;
818         }
819         case ApcfFilterType::LOCAL_NAME: {
820           update_local_name_filter(apcf_action, filter_index, filter.name);
821           break;
822         }
823         case ApcfFilterType::MANUFACTURER_DATA: {
824           update_manufacturer_data_filter(
825               apcf_action, filter_index, filter.company, filter.company_mask, filter.data, filter.data_mask);
826           break;
827         }
828         case ApcfFilterType::SERVICE_DATA: {
829           update_service_data_filter(apcf_action, filter_index, filter.data, filter.data_mask);
830           break;
831         }
832         case ApcfFilterType::TRANSPORT_DISCOVERY_DATA: {
833           update_transport_discovery_data_filter(
834               apcf_action,
835               filter_index,
836               filter.org_id,
837               filter.tds_flags,
838               filter.tds_flags_mask,
839               filter.data,
840               filter.data_mask,
841               filter.meta_data_type,
842               filter.meta_data);
843           break;
844         }
845         case ApcfFilterType::AD_TYPE: {
846           update_ad_type_filter(apcf_action, filter_index, filter.ad_type, filter.data, filter.data_mask);
847           break;
848         }
849         default:
850           log::error("Unknown filter type: {}", (uint16_t)filter.filter_type);
851           break;
852       }
853     }
854   }
855 
856   std::unordered_map<uint8_t, AddressWithType> remove_me_later_map_;
857 
update_address_filterbluetooth::hci::LeScanningManager::impl858   void update_address_filter(
859       ApcfAction action,
860       uint8_t filter_index,
861       Address address,
862       ApcfApplicationAddressType address_type,
863       std::array<uint8_t, 16> irk) {
864     if (action != ApcfAction::CLEAR) {
865       /*
866        * The vendor command (APCF Filtering 0x0157) takes Public (0) or Random (1)
867        * or Addresses type not applicable (2).
868        *
869        * Advertising results have four types:
870        *     -  Public = 0
871        *     -  Random = 1
872        *     -  Public ID = 2
873        *     -  Random ID = 3
874        *
875        * e.g. specifying PUBLIC (0) will only return results with a public
876        * address. It will ignore resolved addresses, since they return PUBLIC
877        * IDENTITY (2). For this, Addresses type not applicable (0x02) must be specified.
878        * This should also cover if the RPA is derived from RANDOM STATIC.
879        */
880       le_scanning_interface_->EnqueueCommand(
881           LeAdvFilterBroadcasterAddressBuilder::Create(
882               action, filter_index, address, ApcfApplicationAddressType::NOT_APPLICABLE),
883           module_handler_->BindOnceOn(this, &impl::on_advertising_filter_complete));
884       if (!is_empty_128bit(irk)) {
885         // If an entry exists for this filter index, replace data because the filter has been
886         // updated.
887         auto entry = remove_me_later_map_.find(filter_index);
888         // IRK Scanning
889         if (entry != remove_me_later_map_.end()) {
890           // Don't want to remove for a bonded device
891           if (!is_bonded(entry->second.GetAddress())) {
892             le_address_manager_->RemoveDeviceFromResolvingList(
893                 static_cast<PeerAddressType>(entry->second.GetAddressType()), entry->second.GetAddress());
894           }
895           remove_me_later_map_.erase(filter_index);
896         }
897 
898         // Now replace it with a new one
899         std::array<uint8_t, 16> empty_irk;
900         le_address_manager_->AddDeviceToResolvingList(
901             static_cast<PeerAddressType>(address_type), address, irk, empty_irk);
902         remove_me_later_map_.emplace(filter_index, AddressWithType(address, static_cast<AddressType>(address_type)));
903       }
904     } else {
905       le_scanning_interface_->EnqueueCommand(
906           LeAdvFilterClearBroadcasterAddressBuilder::Create(filter_index),
907           module_handler_->BindOnceOn(this, &impl::on_advertising_filter_complete));
908       auto entry = remove_me_later_map_.find(filter_index);
909       if (entry != remove_me_later_map_.end()) {
910         // TODO(optedoblivion): If not bonded
911         le_address_manager_->RemoveDeviceFromResolvingList(static_cast<PeerAddressType>(address_type), address);
912         remove_me_later_map_.erase(filter_index);
913       }
914     }
915   }
916 
is_empty_128bitbluetooth::hci::LeScanningManager::impl917   bool is_empty_128bit(const std::array<uint8_t, 16> data) {
918     for (int i = 0; i < 16; i++) {
919       if (data[i] != (uint8_t)0) {
920         return false;
921       }
922     }
923     return true;
924   }
925 
update_uuid_filterbluetooth::hci::LeScanningManager::impl926   void update_uuid_filter(
927       ApcfAction action, uint8_t filter_index, ApcfFilterType filter_type, Uuid uuid, Uuid uuid_mask) {
928     std::vector<uint8_t> combined_data = {};
929     if (action != ApcfAction::CLEAR) {
930       uint8_t uuid_len = uuid.GetShortestRepresentationSize();
931       if (uuid_len == Uuid::kNumBytes16) {
932         uint16_t data = uuid.As16Bit();
933         combined_data.push_back((uint8_t)data);
934         combined_data.push_back((uint8_t)(data >> 8));
935       } else if (uuid_len == Uuid::kNumBytes32) {
936         uint32_t data = uuid.As32Bit();
937         combined_data.push_back((uint8_t)data);
938         combined_data.push_back((uint8_t)(data >> 8));
939         combined_data.push_back((uint8_t)(data >> 16));
940         combined_data.push_back((uint8_t)(data >> 24));
941       } else if (uuid_len == Uuid::kNumBytes128) {
942         auto data = uuid.To128BitLE();
943         combined_data.insert(combined_data.end(), data.begin(), data.end());
944       } else {
945         log::error("illegal UUID length: {}", (uint16_t)uuid_len);
946         return;
947       }
948 
949       if (!uuid_mask.IsEmpty()) {
950         if (uuid_len == Uuid::kNumBytes16) {
951           uint16_t data = uuid_mask.As16Bit();
952           combined_data.push_back((uint8_t)data);
953           combined_data.push_back((uint8_t)(data >> 8));
954         } else if (uuid_len == Uuid::kNumBytes32) {
955           uint32_t data = uuid_mask.As32Bit();
956           combined_data.push_back((uint8_t)data);
957           combined_data.push_back((uint8_t)(data >> 8));
958           combined_data.push_back((uint8_t)(data >> 16));
959           combined_data.push_back((uint8_t)(data >> 24));
960         } else if (uuid_len == Uuid::kNumBytes128) {
961           auto data = uuid_mask.To128BitLE();
962           combined_data.insert(combined_data.end(), data.begin(), data.end());
963         }
964       } else {
965         std::vector<uint8_t> data(uuid_len, 0xFF);
966         combined_data.insert(combined_data.end(), data.begin(), data.end());
967       }
968     }
969 
970     if (filter_type == ApcfFilterType::SERVICE_UUID) {
971       le_scanning_interface_->EnqueueCommand(
972           LeAdvFilterServiceUuidBuilder::Create(action, filter_index, combined_data),
973           module_handler_->BindOnceOn(this, &impl::on_advertising_filter_complete));
974     } else {
975       le_scanning_interface_->EnqueueCommand(
976           LeAdvFilterSolicitationUuidBuilder::Create(action, filter_index, combined_data),
977           module_handler_->BindOnceOn(this, &impl::on_advertising_filter_complete));
978     }
979   }
980 
update_local_name_filterbluetooth::hci::LeScanningManager::impl981   void update_local_name_filter(ApcfAction action, uint8_t filter_index, std::vector<uint8_t> name) {
982     le_scanning_interface_->EnqueueCommand(
983         LeAdvFilterLocalNameBuilder::Create(action, filter_index, name),
984         module_handler_->BindOnceOn(this, &impl::on_advertising_filter_complete));
985   }
986 
update_manufacturer_data_filterbluetooth::hci::LeScanningManager::impl987   void update_manufacturer_data_filter(
988       ApcfAction action,
989       uint8_t filter_index,
990       uint16_t company_id,
991       uint16_t company_id_mask,
992       std::vector<uint8_t> data,
993       std::vector<uint8_t> data_mask) {
994     if (data.size() != data_mask.size()) {
995       log::error("manufacturer data mask should have the same length as manufacturer data");
996       return;
997     }
998     std::vector<uint8_t> combined_data = {};
999     if (action != ApcfAction::CLEAR) {
1000       combined_data.push_back((uint8_t)company_id);
1001       combined_data.push_back((uint8_t)(company_id >> 8));
1002       if (data.size() != 0) {
1003         combined_data.insert(combined_data.end(), data.begin(), data.end());
1004       }
1005       if (company_id_mask != 0) {
1006         combined_data.push_back((uint8_t)company_id_mask);
1007         combined_data.push_back((uint8_t)(company_id_mask >> 8));
1008       } else {
1009         combined_data.push_back(0xFF);
1010         combined_data.push_back(0xFF);
1011       }
1012       if (data_mask.size() != 0) {
1013         combined_data.insert(combined_data.end(), data_mask.begin(), data_mask.end());
1014       }
1015     }
1016 
1017     le_scanning_interface_->EnqueueCommand(
1018         LeAdvFilterManufacturerDataBuilder::Create(action, filter_index, combined_data),
1019         module_handler_->BindOnceOn(this, &impl::on_advertising_filter_complete));
1020   }
1021 
update_service_data_filterbluetooth::hci::LeScanningManager::impl1022   void update_service_data_filter(
1023       ApcfAction action, uint8_t filter_index, std::vector<uint8_t> data, std::vector<uint8_t> data_mask) {
1024     if (data.size() != data_mask.size()) {
1025       log::error("service data mask should have the same length as service data");
1026       return;
1027     }
1028     std::vector<uint8_t> combined_data = {};
1029     if (action != ApcfAction::CLEAR && data.size() != 0) {
1030       combined_data.insert(combined_data.end(), data.begin(), data.end());
1031       combined_data.insert(combined_data.end(), data_mask.begin(), data_mask.end());
1032     }
1033 
1034     le_scanning_interface_->EnqueueCommand(
1035         LeAdvFilterServiceDataBuilder::Create(action, filter_index, combined_data),
1036         module_handler_->BindOnceOn(this, &impl::on_advertising_filter_complete));
1037   }
1038 
update_transport_discovery_data_filterbluetooth::hci::LeScanningManager::impl1039   void update_transport_discovery_data_filter(
1040       ApcfAction action,
1041       uint8_t filter_index,
1042       uint8_t org_id,
1043       uint8_t tds_flags,
1044       uint8_t tds_flags_mask,
1045       std::vector<uint8_t> transport_data,
1046       std::vector<uint8_t> transport_data_mask,
1047       ApcfMetaDataType meta_data_type,
1048       std::vector<uint8_t> meta_data) {
1049     LocalVersionInformation local_version_information = controller_->GetLocalVersionInformation();
1050 
1051     // In QTI controller, transport discovery data filter are supported by default. Check is added
1052     // to keep backward compatibility.
1053     if (!is_transport_discovery_data_filter_supported_ &&
1054         !(local_version_information.manufacturer_name_ == LMP_COMPID_QTI)) {
1055       log::warn("transport discovery data filter isn't supported");
1056       return;
1057     }
1058 
1059     log::info(
1060         "org id: {}, tds_flags: {}, tds_flags_mask: {}, transport_data size: {}, "
1061         "transport_data_mask size: {}, meta_data_type: {}, meta_data size: {}",
1062         org_id,
1063         tds_flags,
1064         tds_flags_mask,
1065         transport_data.size(),
1066         transport_data_mask.size(),
1067         (uint8_t)meta_data_type,
1068         meta_data.size());
1069 
1070     // 0x02 Wi-Fi Alliance Neighbor Awareness Networking & meta_data_type is 0x01 for NAN Hash.
1071     if (org_id == 0x02) {
1072       // meta data contains WIFI NAN hash, reverse it before sending controller.
1073       switch (meta_data_type) {
1074         case ApcfMetaDataType::WIFI_NAN_HASH:
1075           std::reverse(meta_data.begin(), meta_data.end());
1076           break;
1077         default:
1078           break;
1079       }
1080     }
1081 
1082     if (is_transport_discovery_data_filter_supported_) {
1083       le_scanning_interface_->EnqueueCommand(
1084           LeAdvFilterTransportDiscoveryDataBuilder::Create(
1085               action,
1086               filter_index,
1087               org_id,
1088               tds_flags,
1089               tds_flags_mask,
1090               transport_data,
1091               transport_data_mask,
1092               meta_data_type,
1093               meta_data),
1094           module_handler_->BindOnceOn(this, &impl::on_advertising_filter_complete));
1095     } else {
1096       // In QTI controller, transport discovery data filter are supported by default.
1097       // keeping old version for backward compatibility
1098       std::vector<uint8_t> combined_data = {};
1099       if (action != ApcfAction::CLEAR) {
1100         combined_data.push_back((uint8_t)org_id);
1101         combined_data.push_back((uint8_t)tds_flags);
1102         combined_data.push_back((uint8_t)tds_flags_mask);
1103         if (org_id == 0x02 && meta_data_type == ApcfMetaDataType::WIFI_NAN_HASH) {
1104           // meta data contains WIFI NAN hash
1105           combined_data.insert(combined_data.end(), meta_data.begin(), meta_data.end());
1106         }
1107       }
1108       le_scanning_interface_->EnqueueCommand(
1109           LeAdvFilterTransportDiscoveryDataOldBuilder::Create(action, filter_index, combined_data),
1110           module_handler_->BindOnceOn(this, &impl::on_advertising_filter_complete));
1111     }
1112   }
1113 
update_ad_type_filterbluetooth::hci::LeScanningManager::impl1114   void update_ad_type_filter(
1115       ApcfAction action,
1116       uint8_t filter_index,
1117       uint8_t ad_type,
1118       std::vector<uint8_t> data,
1119       std::vector<uint8_t> data_mask) {
1120     if (!is_ad_type_filter_supported_) {
1121       log::error("AD type filter isn't supported");
1122       return;
1123     }
1124 
1125     if (data.size() != data_mask.size()) {
1126       log::error("ad type mask should have the same length as ad type data");
1127       return;
1128     }
1129     std::vector<uint8_t> combined_data = {};
1130     if (action != ApcfAction::CLEAR) {
1131       combined_data.push_back((uint8_t)ad_type);
1132       combined_data.push_back((uint8_t)(data.size()));
1133       if (data.size() != 0) {
1134         combined_data.insert(combined_data.end(), data.begin(), data.end());
1135         combined_data.insert(combined_data.end(), data_mask.begin(), data_mask.end());
1136       }
1137     }
1138 
1139     le_scanning_interface_->EnqueueCommand(
1140         LeAdvFilterADTypeBuilder::Create(action, filter_index, combined_data),
1141         module_handler_->BindOnceOn(this, &impl::on_advertising_filter_complete));
1142   }
1143 
batch_scan_set_storage_parameterbluetooth::hci::LeScanningManager::impl1144   void batch_scan_set_storage_parameter(
1145       uint8_t batch_scan_full_max,
1146       uint8_t batch_scan_truncated_max,
1147       uint8_t batch_scan_notify_threshold,
1148       ScannerId scanner_id) {
1149     if (!is_batch_scan_supported_) {
1150       log::warn("Batch scan is not supported");
1151       return;
1152     }
1153     // scanner id for OnBatchScanThresholdCrossed
1154     batch_scan_config_.ref_value = scanner_id;
1155 
1156     if (batch_scan_config_.current_state == BatchScanState::ERROR_STATE ||
1157         batch_scan_config_.current_state == BatchScanState::DISABLED_STATE ||
1158         batch_scan_config_.current_state == BatchScanState::DISABLE_CALLED) {
1159       batch_scan_config_.current_state = BatchScanState::ENABLE_CALLED;
1160       le_scanning_interface_->EnqueueCommand(
1161           LeBatchScanEnableBuilder::Create(Enable::ENABLED),
1162           module_handler_->BindOnceOn(this, &impl::on_batch_scan_enable_complete));
1163     }
1164 
1165     le_scanning_interface_->EnqueueCommand(
1166         LeBatchScanSetStorageParametersBuilder::Create(
1167             batch_scan_full_max, batch_scan_truncated_max, batch_scan_notify_threshold),
1168         module_handler_->BindOnceOn(this, &impl::on_batch_scan_complete));
1169   }
1170 
batch_scan_enablebluetooth::hci::LeScanningManager::impl1171   void batch_scan_enable(
1172       BatchScanMode scan_mode,
1173       uint32_t duty_cycle_scan_window_slots,
1174       uint32_t duty_cycle_scan_interval_slots,
1175       BatchScanDiscardRule batch_scan_discard_rule) {
1176     if (!is_batch_scan_supported_) {
1177       log::warn("Batch scan is not supported");
1178       return;
1179     }
1180 
1181     if (batch_scan_config_.current_state == BatchScanState::ERROR_STATE ||
1182         batch_scan_config_.current_state == BatchScanState::DISABLED_STATE ||
1183         batch_scan_config_.current_state == BatchScanState::DISABLE_CALLED) {
1184       batch_scan_config_.current_state = BatchScanState::ENABLE_CALLED;
1185       le_scanning_interface_->EnqueueCommand(
1186           LeBatchScanEnableBuilder::Create(Enable::ENABLED),
1187           module_handler_->BindOnceOn(this, &impl::on_batch_scan_enable_complete));
1188     }
1189 
1190     batch_scan_config_.scan_mode = scan_mode;
1191     batch_scan_config_.scan_interval = duty_cycle_scan_interval_slots;
1192     batch_scan_config_.scan_window = duty_cycle_scan_window_slots;
1193     batch_scan_config_.discard_rule = batch_scan_discard_rule;
1194     /* This command starts batch scanning, if enabled */
1195     batch_scan_set_scan_parameter(
1196         scan_mode, duty_cycle_scan_window_slots, duty_cycle_scan_interval_slots, batch_scan_discard_rule);
1197   }
1198 
batch_scan_disablebluetooth::hci::LeScanningManager::impl1199   void batch_scan_disable() {
1200     if (!is_batch_scan_supported_) {
1201       log::warn("Batch scan is not supported");
1202       return;
1203     }
1204     batch_scan_config_.current_state = BatchScanState::DISABLE_CALLED;
1205     batch_scan_set_scan_parameter(
1206         BatchScanMode::DISABLE,
1207         batch_scan_config_.scan_window,
1208         batch_scan_config_.scan_interval,
1209         batch_scan_config_.discard_rule);
1210   }
1211 
batch_scan_set_scan_parameterbluetooth::hci::LeScanningManager::impl1212   void batch_scan_set_scan_parameter(
1213       BatchScanMode scan_mode,
1214       uint32_t duty_cycle_scan_window_slots,
1215       uint32_t duty_cycle_scan_interval_slots,
1216       BatchScanDiscardRule batch_scan_discard_rule) {
1217     if (!is_batch_scan_supported_) {
1218       log::warn("Batch scan is not supported");
1219       return;
1220     }
1221     PeerAddressType own_address_type = PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS;
1222     if (own_address_type_ == OwnAddressType::RANDOM_DEVICE_ADDRESS ||
1223         own_address_type_ == OwnAddressType::RESOLVABLE_OR_RANDOM_ADDRESS) {
1224       own_address_type = PeerAddressType::RANDOM_DEVICE_OR_IDENTITY_ADDRESS;
1225     }
1226     uint8_t truncated_mode_enabled = 0x00;
1227     uint8_t full_mode_enabled = 0x00;
1228     if (scan_mode == BatchScanMode::TRUNCATED || scan_mode == BatchScanMode::TRUNCATED_AND_FULL) {
1229       truncated_mode_enabled = 0x01;
1230     }
1231     if (scan_mode == BatchScanMode::FULL || scan_mode == BatchScanMode::TRUNCATED_AND_FULL) {
1232       full_mode_enabled = 0x01;
1233     }
1234 
1235     if (scan_mode == BatchScanMode::DISABLE) {
1236       le_scanning_interface_->EnqueueCommand(
1237           LeBatchScanSetScanParametersBuilder::Create(
1238               truncated_mode_enabled,
1239               full_mode_enabled,
1240               duty_cycle_scan_window_slots,
1241               duty_cycle_scan_interval_slots,
1242               own_address_type,
1243               batch_scan_discard_rule),
1244           module_handler_->BindOnceOn(this, &impl::on_batch_scan_disable_complete));
1245     } else {
1246       le_scanning_interface_->EnqueueCommand(
1247           LeBatchScanSetScanParametersBuilder::Create(
1248               truncated_mode_enabled,
1249               full_mode_enabled,
1250               duty_cycle_scan_window_slots,
1251               duty_cycle_scan_interval_slots,
1252               own_address_type,
1253               batch_scan_discard_rule),
1254           module_handler_->BindOnceOn(this, &impl::on_batch_scan_complete));
1255     }
1256   }
1257 
batch_scan_read_resultsbluetooth::hci::LeScanningManager::impl1258   void batch_scan_read_results(ScannerId scanner_id, uint16_t total_num_of_records, BatchScanMode scan_mode) {
1259     if (!is_batch_scan_supported_) {
1260       log::warn("Batch scan is not supported");
1261       int status = static_cast<int>(ErrorCode::UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE);
1262       scanning_callbacks_->OnBatchScanReports(scanner_id, status, 0, 0, {});
1263       return;
1264     }
1265 
1266     if (scan_mode != BatchScanMode::FULL && scan_mode != BatchScanMode::TRUNCATED) {
1267       log::warn("Invalid scan mode {}", (uint16_t)scan_mode);
1268       int status = static_cast<int>(ErrorCode::INVALID_HCI_COMMAND_PARAMETERS);
1269       scanning_callbacks_->OnBatchScanReports(scanner_id, status, 0, 0, {});
1270       return;
1271     }
1272 
1273     if (batch_scan_result_cache_.find(scanner_id) == batch_scan_result_cache_.end()) {
1274       std::vector<uint8_t> empty_data = {};
1275       batch_scan_result_cache_.emplace(scanner_id, empty_data);
1276     }
1277 
1278     le_scanning_interface_->EnqueueCommand(
1279         LeBatchScanReadResultParametersBuilder::Create(static_cast<BatchScanDataRead>(scan_mode)),
1280         module_handler_->BindOnceOn(this, &impl::on_batch_scan_read_result_complete, scanner_id, total_num_of_records));
1281   }
1282 
start_syncbluetooth::hci::LeScanningManager::impl1283   void start_sync(
1284       uint8_t sid, const AddressWithType& address_with_type, uint16_t skip, uint16_t timeout, int request_id) {
1285     if (!is_periodic_advertising_sync_transfer_sender_supported_) {
1286       log::warn("PAST sender not supported on this device");
1287       int status = static_cast<int>(ErrorCode::UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE);
1288       scanning_callbacks_->OnPeriodicSyncStarted(request_id, status, -1, sid, address_with_type, 0, 0);
1289       return;
1290     }
1291     PeriodicSyncStates request{
1292         .request_id = request_id,
1293         .advertiser_sid = sid,
1294         .address_with_type = address_with_type,
1295         .sync_handle = 0,
1296         .sync_state = PeriodicSyncState::PERIODIC_SYNC_STATE_IDLE,
1297     };
1298     periodic_sync_manager_.StartSync(request, skip, timeout);
1299   }
1300 
stop_syncbluetooth::hci::LeScanningManager::impl1301   void stop_sync(uint16_t handle) {
1302     if (!is_periodic_advertising_sync_transfer_sender_supported_) {
1303       log::warn("PAST sender not supported on this device");
1304       return;
1305     }
1306     periodic_sync_manager_.StopSync(handle);
1307   }
1308 
cancel_create_syncbluetooth::hci::LeScanningManager::impl1309   void cancel_create_sync(uint8_t sid, const Address& address) {
1310     if (!is_periodic_advertising_sync_transfer_sender_supported_) {
1311       log::warn("PAST sender not supported on this device");
1312       return;
1313     }
1314     periodic_sync_manager_.CancelCreateSync(sid, address);
1315   }
1316 
transfer_syncbluetooth::hci::LeScanningManager::impl1317   void transfer_sync(
1318       const Address& address,
1319       uint16_t connection_handle,
1320       uint16_t service_data,
1321       uint16_t sync_handle,
1322       int pa_source) {
1323     if (!is_periodic_advertising_sync_transfer_sender_supported_) {
1324       log::warn("PAST sender not supported on this device");
1325       int status = static_cast<int>(ErrorCode::UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE);
1326       scanning_callbacks_->OnPeriodicSyncTransferred(pa_source, status, address);
1327       return;
1328     }
1329     if (connection_handle == 0xFFFF) {
1330       log::error("[PAST]: Invalid connection handle or no LE ACL link");
1331       int status = static_cast<int>(ErrorCode::UNKNOWN_CONNECTION);
1332       scanning_callbacks_->OnPeriodicSyncTransferred(pa_source, status, address);
1333       return;
1334     }
1335     periodic_sync_manager_.TransferSync(address, service_data, sync_handle, pa_source, connection_handle);
1336   }
1337 
transfer_set_infobluetooth::hci::LeScanningManager::impl1338   void transfer_set_info(
1339       const Address& address,
1340       uint16_t connection_handle,
1341       uint16_t service_data,
1342       uint8_t adv_handle,
1343       int pa_source) {
1344     if (!is_periodic_advertising_sync_transfer_sender_supported_) {
1345       log::warn("PAST sender not supported on this device");
1346       int status = static_cast<int>(ErrorCode::UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE);
1347       scanning_callbacks_->OnPeriodicSyncTransferred(pa_source, status, address);
1348       return;
1349     }
1350     if (connection_handle == 0xFFFF) {
1351       log::error("[PAST]:Invalid connection handle or no LE ACL link");
1352       int status = static_cast<int>(ErrorCode::UNKNOWN_CONNECTION);
1353       scanning_callbacks_->OnPeriodicSyncTransferred(pa_source, status, address);
1354       return;
1355     }
1356     periodic_sync_manager_.SyncSetInfo(address, service_data, adv_handle, pa_source, connection_handle);
1357   }
1358 
sync_tx_parametersbluetooth::hci::LeScanningManager::impl1359   void sync_tx_parameters(const Address& address, uint8_t mode, uint16_t skip, uint16_t timeout, int reg_id) {
1360     if (!is_periodic_advertising_sync_transfer_sender_supported_) {
1361       log::warn("PAST sender not supported on this device");
1362       int status = static_cast<int>(ErrorCode::UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE);
1363       AddressWithType address_with_type(address, AddressType::RANDOM_DEVICE_ADDRESS);
1364       scanning_callbacks_->OnPeriodicSyncStarted(reg_id, status, -1, -1, address_with_type, 0, 0);
1365       return;
1366     }
1367     periodic_sync_manager_.SyncTxParameters(address, mode, skip, timeout, reg_id);
1368   }
1369 
track_advertiserbluetooth::hci::LeScanningManager::impl1370   void track_advertiser(uint8_t filter_index, ScannerId scanner_id) {
1371     if (total_num_of_advt_tracked_ <= 0) {
1372       log::warn("advertisement tracking is not supported");
1373       AdvertisingFilterOnFoundOnLostInfo on_found_on_lost_info = {};
1374       on_found_on_lost_info.scanner_id = scanner_id;
1375       on_found_on_lost_info.advertiser_info_present = AdvtInfoPresent::NO_ADVT_INFO_PRESENT;
1376       scanning_callbacks_->OnTrackAdvFoundLost(on_found_on_lost_info);
1377       return;
1378     } else if (tracker_id_map_.size() >= total_num_of_advt_tracked_) {
1379       AdvertisingFilterOnFoundOnLostInfo on_found_on_lost_info = {};
1380       on_found_on_lost_info.scanner_id = scanner_id;
1381       on_found_on_lost_info.advertiser_info_present = AdvtInfoPresent::NO_ADVT_INFO_PRESENT;
1382       scanning_callbacks_->OnTrackAdvFoundLost(on_found_on_lost_info);
1383       return;
1384     }
1385     log::info(
1386         "track_advertiser scanner_id {}, filter_index {}",
1387         (uint16_t)scanner_id,
1388         (uint16_t)filter_index);
1389     tracker_id_map_[filter_index] = scanner_id;
1390   }
1391 
register_scanning_callbackbluetooth::hci::LeScanningManager::impl1392   void register_scanning_callback(ScanningCallback* scanning_callbacks) {
1393     scanning_callbacks_ = scanning_callbacks;
1394     periodic_sync_manager_.SetScanningCallback(scanning_callbacks_);
1395   }
1396 
is_ad_type_filter_supportedbluetooth::hci::LeScanningManager::impl1397   bool is_ad_type_filter_supported() {
1398     return is_ad_type_filter_supported_;
1399   }
1400 
on_set_scan_parameter_completebluetooth::hci::LeScanningManager::impl1401   void on_set_scan_parameter_complete(CommandCompleteView view) {
1402     switch (view.GetCommandOpCode()) {
1403       case (OpCode::LE_SET_SCAN_PARAMETERS): {
1404         auto status_view = LeSetScanParametersCompleteView::Create(view);
1405         log::assert_that(status_view.IsValid(), "assert failed: status_view.IsValid()");
1406         if (status_view.GetStatus() != ErrorCode::SUCCESS) {
1407           log::info(
1408               "Receive set scan parameter complete with error code {}",
1409               ErrorCodeText(status_view.GetStatus()));
1410         }
1411       } break;
1412       case (OpCode::LE_EXTENDED_SCAN_PARAMS): {
1413         auto status_view = LeExtendedScanParamsCompleteView::Create(view);
1414         log::assert_that(status_view.IsValid(), "assert failed: status_view.IsValid()");
1415         if (status_view.GetStatus() != ErrorCode::SUCCESS) {
1416           log::info(
1417               "Receive extended scan parameter complete with error code {}",
1418               ErrorCodeText(status_view.GetStatus()));
1419         }
1420       } break;
1421       case (OpCode::LE_SET_EXTENDED_SCAN_PARAMETERS): {
1422         auto status_view = LeSetExtendedScanParametersCompleteView::Create(view);
1423         log::assert_that(status_view.IsValid(), "assert failed: status_view.IsValid()");
1424         if (status_view.GetStatus() != ErrorCode::SUCCESS) {
1425           log::info(
1426               "Receive set extended scan parameter complete with error code {}",
1427               ErrorCodeText(status_view.GetStatus()));
1428         }
1429       } break;
1430       default:
1431         log::fatal("Unhandled event {}", OpCodeText(view.GetCommandOpCode()));
1432     }
1433   }
1434 
on_advertising_filter_completebluetooth::hci::LeScanningManager::impl1435   void on_advertising_filter_complete(CommandCompleteView view) {
1436     log::assert_that(view.IsValid(), "assert failed: view.IsValid()");
1437     auto status_view = LeAdvFilterCompleteView::Create(view);
1438     log::assert_that(status_view.IsValid(), "assert failed: status_view.IsValid()");
1439     if (status_view.GetStatus() != ErrorCode::SUCCESS) {
1440       log::info(
1441           "Got a Command complete {}, status {}",
1442           OpCodeText(view.GetCommandOpCode()),
1443           ErrorCodeText(status_view.GetStatus()));
1444     }
1445 
1446     ApcfOpcode apcf_opcode = status_view.GetApcfOpcode();
1447     switch (apcf_opcode) {
1448       case ApcfOpcode::ENABLE: {
1449         auto complete_view = LeAdvFilterEnableCompleteView::Create(status_view);
1450         log::assert_that(complete_view.IsValid(), "assert failed: complete_view.IsValid()");
1451         scanning_callbacks_->OnFilterEnable(complete_view.GetApcfEnable(), (uint8_t)complete_view.GetStatus());
1452       } break;
1453       case ApcfOpcode::SET_FILTERING_PARAMETERS: {
1454         auto complete_view = LeAdvFilterSetFilteringParametersCompleteView::Create(status_view);
1455         log::assert_that(complete_view.IsValid(), "assert failed: complete_view.IsValid()");
1456         scanning_callbacks_->OnFilterParamSetup(
1457             complete_view.GetApcfAvailableSpaces(), complete_view.GetApcfAction(), (uint8_t)complete_view.GetStatus());
1458       } break;
1459       case ApcfOpcode::BROADCASTER_ADDRESS: {
1460         auto complete_view = LeAdvFilterBroadcasterAddressCompleteView::Create(status_view);
1461         log::assert_that(complete_view.IsValid(), "assert failed: complete_view.IsValid()");
1462         scanning_callbacks_->OnFilterConfigCallback(
1463             ApcfFilterType::BROADCASTER_ADDRESS,
1464             complete_view.GetApcfAvailableSpaces(),
1465             complete_view.GetApcfAction(),
1466             (uint8_t)complete_view.GetStatus());
1467       } break;
1468       case ApcfOpcode::SERVICE_UUID: {
1469         auto complete_view = LeAdvFilterServiceUuidCompleteView::Create(status_view);
1470         log::assert_that(complete_view.IsValid(), "assert failed: complete_view.IsValid()");
1471         scanning_callbacks_->OnFilterConfigCallback(
1472             ApcfFilterType::SERVICE_UUID,
1473             complete_view.GetApcfAvailableSpaces(),
1474             complete_view.GetApcfAction(),
1475             (uint8_t)complete_view.GetStatus());
1476       } break;
1477       case ApcfOpcode::SERVICE_SOLICITATION_UUID: {
1478         auto complete_view = LeAdvFilterSolicitationUuidCompleteView::Create(status_view);
1479         log::assert_that(complete_view.IsValid(), "assert failed: complete_view.IsValid()");
1480         scanning_callbacks_->OnFilterConfigCallback(
1481             ApcfFilterType::SERVICE_SOLICITATION_UUID,
1482             complete_view.GetApcfAvailableSpaces(),
1483             complete_view.GetApcfAction(),
1484             (uint8_t)complete_view.GetStatus());
1485       } break;
1486       case ApcfOpcode::LOCAL_NAME: {
1487         auto complete_view = LeAdvFilterLocalNameCompleteView::Create(status_view);
1488         log::assert_that(complete_view.IsValid(), "assert failed: complete_view.IsValid()");
1489         scanning_callbacks_->OnFilterConfigCallback(
1490             ApcfFilterType::LOCAL_NAME,
1491             complete_view.GetApcfAvailableSpaces(),
1492             complete_view.GetApcfAction(),
1493             (uint8_t)complete_view.GetStatus());
1494       } break;
1495       case ApcfOpcode::MANUFACTURER_DATA: {
1496         auto complete_view = LeAdvFilterManufacturerDataCompleteView::Create(status_view);
1497         log::assert_that(complete_view.IsValid(), "assert failed: complete_view.IsValid()");
1498         scanning_callbacks_->OnFilterConfigCallback(
1499             ApcfFilterType::MANUFACTURER_DATA,
1500             complete_view.GetApcfAvailableSpaces(),
1501             complete_view.GetApcfAction(),
1502             (uint8_t)complete_view.GetStatus());
1503       } break;
1504       case ApcfOpcode::SERVICE_DATA: {
1505         auto complete_view = LeAdvFilterServiceDataCompleteView::Create(status_view);
1506         log::assert_that(complete_view.IsValid(), "assert failed: complete_view.IsValid()");
1507         scanning_callbacks_->OnFilterConfigCallback(
1508             ApcfFilterType::SERVICE_DATA,
1509             complete_view.GetApcfAvailableSpaces(),
1510             complete_view.GetApcfAction(),
1511             (uint8_t)complete_view.GetStatus());
1512       } break;
1513       case ApcfOpcode::TRANSPORT_DISCOVERY_DATA: {
1514         auto complete_view = LeAdvFilterTransportDiscoveryDataCompleteView::Create(status_view);
1515         log::assert_that(complete_view.IsValid(), "assert failed: complete_view.IsValid()");
1516         scanning_callbacks_->OnFilterConfigCallback(
1517             ApcfFilterType::TRANSPORT_DISCOVERY_DATA,
1518             complete_view.GetApcfAvailableSpaces(),
1519             complete_view.GetApcfAction(),
1520             (uint8_t)complete_view.GetStatus());
1521       } break;
1522       case ApcfOpcode::AD_TYPE: {
1523         auto complete_view = LeAdvFilterADTypeCompleteView::Create(status_view);
1524         log::assert_that(complete_view.IsValid(), "assert failed: complete_view.IsValid()");
1525         scanning_callbacks_->OnFilterConfigCallback(
1526             ApcfFilterType::AD_TYPE,
1527             complete_view.GetApcfAvailableSpaces(),
1528             complete_view.GetApcfAction(),
1529             (uint8_t)complete_view.GetStatus());
1530       } break;
1531       default:
1532         log::warn("Unexpected event type {}", OpCodeText(view.GetCommandOpCode()));
1533     }
1534   }
1535 
on_apcf_read_extended_features_completebluetooth::hci::LeScanningManager::impl1536   void on_apcf_read_extended_features_complete(CommandCompleteView view) {
1537     log::assert_that(view.IsValid(), "assert failed: view.IsValid()");
1538     auto status_view = LeAdvFilterCompleteView::Create(view);
1539     if (!status_view.IsValid()) {
1540       log::warn("Can not get valid LeAdvFilterCompleteView, return");
1541       return;
1542     }
1543     if (status_view.GetStatus() != ErrorCode::SUCCESS) {
1544       log::warn(
1545           "Got a Command complete {}, status {}",
1546           OpCodeText(view.GetCommandOpCode()),
1547           ErrorCodeText(status_view.GetStatus()));
1548       return;
1549     }
1550     auto complete_view = LeAdvFilterReadExtendedFeaturesCompleteView::Create(status_view);
1551     log::assert_that(complete_view.IsValid(), "assert failed: complete_view.IsValid()");
1552     is_transport_discovery_data_filter_supported_ =
1553         complete_view.GetTransportDiscoveryDataFilter() == 1;
1554     is_ad_type_filter_supported_ = complete_view.GetAdTypeFilter() == 1;
1555     log::info(
1556         "set is_ad_type_filter_supported_ to {} & is_transport_discovery_data_filter_supported_ to "
1557         "{}",
1558         is_ad_type_filter_supported_,
1559         is_transport_discovery_data_filter_supported_);
1560   }
1561 
on_batch_scan_completebluetooth::hci::LeScanningManager::impl1562   void on_batch_scan_complete(CommandCompleteView view) {
1563     log::assert_that(view.IsValid(), "assert failed: view.IsValid()");
1564     auto status_view = LeBatchScanCompleteView::Create(view);
1565     log::assert_that(status_view.IsValid(), "assert failed: status_view.IsValid()");
1566     if (status_view.GetStatus() != ErrorCode::SUCCESS) {
1567       log::info(
1568           "Got a Command complete {}, status {}, batch_scan_opcode {}",
1569           OpCodeText(view.GetCommandOpCode()),
1570           ErrorCodeText(status_view.GetStatus()),
1571           BatchScanOpcodeText(status_view.GetBatchScanOpcode()));
1572     }
1573   }
1574 
on_batch_scan_enable_completebluetooth::hci::LeScanningManager::impl1575   void on_batch_scan_enable_complete(CommandCompleteView view) {
1576     log::assert_that(view.IsValid(), "assert failed: view.IsValid()");
1577     auto status_view = LeBatchScanCompleteView::Create(view);
1578     log::assert_that(status_view.IsValid(), "assert failed: status_view.IsValid()");
1579     auto complete_view = LeBatchScanEnableCompleteView::Create(status_view);
1580     log::assert_that(complete_view.IsValid(), "assert failed: complete_view.IsValid()");
1581     if (status_view.GetStatus() != ErrorCode::SUCCESS) {
1582       log::info(
1583           "Got batch scan enable complete, status {}", ErrorCodeText(status_view.GetStatus()));
1584       batch_scan_config_.current_state = BatchScanState::ERROR_STATE;
1585     } else {
1586       batch_scan_config_.current_state = BatchScanState::ENABLED_STATE;
1587     }
1588   }
1589 
on_batch_scan_disable_completebluetooth::hci::LeScanningManager::impl1590   void on_batch_scan_disable_complete(CommandCompleteView view) {
1591     log::assert_that(view.IsValid(), "assert failed: view.IsValid()");
1592     auto status_view = LeBatchScanCompleteView::Create(view);
1593     log::assert_that(status_view.IsValid(), "assert failed: status_view.IsValid()");
1594     auto complete_view = LeBatchScanSetScanParametersCompleteView::Create(status_view);
1595     log::assert_that(complete_view.IsValid(), "assert failed: complete_view.IsValid()");
1596     log::assert_that(
1597         status_view.GetStatus() == ErrorCode::SUCCESS,
1598         "assert failed: status_view.GetStatus() == ErrorCode::SUCCESS");
1599     batch_scan_config_.current_state = BatchScanState::DISABLED_STATE;
1600   }
1601 
on_batch_scan_read_result_completebluetooth::hci::LeScanningManager::impl1602   void on_batch_scan_read_result_complete(
1603       ScannerId scanner_id, uint16_t total_num_of_records, CommandCompleteView view) {
1604     log::assert_that(view.IsValid(), "assert failed: view.IsValid()");
1605     auto status_view = LeBatchScanCompleteView::Create(view);
1606     log::assert_that(status_view.IsValid(), "assert failed: status_view.IsValid()");
1607     auto complete_view = LeBatchScanReadResultParametersCompleteRawView::Create(status_view);
1608     log::assert_that(complete_view.IsValid(), "assert failed: complete_view.IsValid()");
1609     if (complete_view.GetStatus() != ErrorCode::SUCCESS) {
1610       log::info(
1611           "Got batch scan read result complete, status {}", ErrorCodeText(status_view.GetStatus()));
1612     }
1613     uint8_t num_of_records = complete_view.GetNumOfRecords();
1614     auto report_format = complete_view.GetBatchScanDataRead();
1615     if (num_of_records == 0) {
1616       scanning_callbacks_->OnBatchScanReports(
1617           scanner_id, 0x00, (int)report_format, total_num_of_records, batch_scan_result_cache_[scanner_id]);
1618       batch_scan_result_cache_.erase(scanner_id);
1619     } else {
1620       auto raw_data = complete_view.GetRawData();
1621       batch_scan_result_cache_[scanner_id].insert(
1622           batch_scan_result_cache_[scanner_id].end(), raw_data.begin(), raw_data.end());
1623       total_num_of_records += num_of_records;
1624       batch_scan_read_results(scanner_id, total_num_of_records, static_cast<BatchScanMode>(report_format));
1625     }
1626   }
1627 
on_storage_threshold_breachbluetooth::hci::LeScanningManager::impl1628   void on_storage_threshold_breach(VendorSpecificEventView /* event */) {
1629     if (batch_scan_config_.ref_value == kInvalidScannerId) {
1630       log::warn("storage threshold was not set !!");
1631       return;
1632     }
1633     scanning_callbacks_->OnBatchScanThresholdCrossed(static_cast<int>(batch_scan_config_.ref_value));
1634   }
1635 
on_advertisement_trackingbluetooth::hci::LeScanningManager::impl1636   void on_advertisement_tracking(VendorSpecificEventView event) {
1637     auto view = LEAdvertisementTrackingEventView::Create(event);
1638     log::assert_that(view.IsValid(), "assert failed: view.IsValid()");
1639     uint8_t filter_index = view.GetApcfFilterIndex();
1640     if (tracker_id_map_.find(filter_index) == tracker_id_map_.end()) {
1641       log::warn("Advertisement track for filter_index {} is not register", (uint16_t)filter_index);
1642       return;
1643     }
1644     AdvertisingFilterOnFoundOnLostInfo on_found_on_lost_info = {};
1645     on_found_on_lost_info.scanner_id = tracker_id_map_[filter_index];
1646     on_found_on_lost_info.filter_index = filter_index;
1647     on_found_on_lost_info.advertiser_state = view.GetAdvertiserState();
1648     on_found_on_lost_info.advertiser_address = view.GetAdvertiserAddress();
1649     on_found_on_lost_info.advertiser_address_type = view.GetAdvertiserAddressType();
1650     on_found_on_lost_info.advertiser_info_present = view.GetAdvtInfoPresent();
1651     /* Extract the adv info details */
1652     if (on_found_on_lost_info.advertiser_info_present == AdvtInfoPresent::ADVT_INFO_PRESENT) {
1653       auto info_view = LEAdvertisementTrackingWithInfoEventView::Create(view);
1654       log::assert_that(info_view.IsValid(), "assert failed: info_view.IsValid()");
1655       on_found_on_lost_info.tx_power = info_view.GetTxPower();
1656       on_found_on_lost_info.rssi = info_view.GetRssi();
1657       on_found_on_lost_info.time_stamp = info_view.GetTimestamp();
1658       auto adv_data = info_view.GetAdvPacket();
1659       on_found_on_lost_info.adv_packet.reserve(adv_data.size());
1660       on_found_on_lost_info.adv_packet.insert(on_found_on_lost_info.adv_packet.end(), adv_data.begin(), adv_data.end());
1661       auto scan_rsp_data = info_view.GetScanResponse();
1662       on_found_on_lost_info.scan_response.reserve(scan_rsp_data.size());
1663       on_found_on_lost_info.scan_response.insert(
1664           on_found_on_lost_info.scan_response.end(), scan_rsp_data.begin(), scan_rsp_data.end());
1665     }
1666     scanning_callbacks_->OnTrackAdvFoundLost(on_found_on_lost_info);
1667   }
1668 
OnPausebluetooth::hci::LeScanningManager::impl1669   void OnPause() override {
1670     if (!address_manager_registered_) {
1671       log::warn("Unregistered!");
1672       return;
1673     }
1674     paused_ = true;
1675     scan_on_resume_ = is_scanning_;
1676     stop_scan();
1677     ack_pause();
1678   }
1679 
ack_pausebluetooth::hci::LeScanningManager::impl1680   void ack_pause() {
1681     le_address_manager_->AckPause(this);
1682   }
1683 
OnResumebluetooth::hci::LeScanningManager::impl1684   void OnResume() override {
1685     if (!address_manager_registered_) {
1686       log::warn("Unregistered!");
1687       return;
1688     }
1689     paused_ = false;
1690     if (scan_on_resume_ == true) {
1691       scan_on_resume_ = false;
1692       start_scan();
1693     }
1694     le_address_manager_->AckResume(this);
1695   }
1696 
1697   ScanApiType api_type_;
1698 
1699   Module* module_;
1700   os::Handler* module_handler_;
1701   HciLayer* hci_layer_;
1702   Controller* controller_;
1703   AclManager* acl_manager_;
1704   storage::StorageModule* storage_module_;
1705   LeScanningInterface* le_scanning_interface_;
1706   LeAddressManager* le_address_manager_;
1707   bool address_manager_registered_ = false;
1708   NullScanningCallback null_scanning_callback_;
1709   ScanningCallback* scanning_callbacks_ = &null_scanning_callback_;
1710   PeriodicSyncManager periodic_sync_manager_{&null_scanning_callback_};
1711   std::vector<Scanner> scanners_;
1712   bool is_scanning_ = false;
1713   bool scan_on_resume_ = false;
1714   bool paused_ = false;
1715   LeScanningReassembler scanning_reassembler_;
1716   bool is_filter_supported_ = false;
1717   bool is_ad_type_filter_supported_ = false;
1718   bool is_batch_scan_supported_ = false;
1719   bool is_periodic_advertising_sync_transfer_sender_supported_ = false;
1720   bool is_transport_discovery_data_filter_supported_ = false;
1721 
1722   LeScanType le_scan_type_ = LeScanType::ACTIVE;
1723   uint32_t interval_ms_{1000};
1724   uint16_t window_ms_{1000};
1725   uint8_t phy_{(uint8_t)PhyType::LE_1M};
1726   OwnAddressType own_address_type_{OwnAddressType::PUBLIC_DEVICE_ADDRESS};
1727   LeScanningFilterPolicy filter_policy_{LeScanningFilterPolicy::ACCEPT_ALL};
1728   BatchScanConfig batch_scan_config_;
1729   std::map<ScannerId, std::vector<uint8_t>> batch_scan_result_cache_;
1730   std::unordered_map<uint8_t, ScannerId> tracker_id_map_;
1731   uint16_t total_num_of_advt_tracked_ = 0x00;
1732   int8_t le_rx_path_loss_comp_ = 0;
1733 };
1734 
LeScanningManager()1735 LeScanningManager::LeScanningManager() {
1736   pimpl_ = std::make_unique<impl>(this);
1737 }
1738 
ListDependencies(ModuleList * list) const1739 void LeScanningManager::ListDependencies(ModuleList* list) const {
1740   list->add<HciLayer>();
1741   list->add<Controller>();
1742   list->add<AclManager>();
1743   list->add<storage::StorageModule>();
1744 }
1745 
Start()1746 void LeScanningManager::Start() {
1747   pimpl_->start(
1748       GetHandler(),
1749       GetDependency<HciLayer>(),
1750       GetDependency<Controller>(),
1751       GetDependency<AclManager>(),
1752       GetDependency<storage::StorageModule>());
1753 }
1754 
Stop()1755 void LeScanningManager::Stop() {
1756   pimpl_->stop();
1757   pimpl_.reset();
1758 }
1759 
ToString() const1760 std::string LeScanningManager::ToString() const {
1761   return "Le Scanning Manager";
1762 }
1763 
RegisterScanner(Uuid app_uuid)1764 void LeScanningManager::RegisterScanner(Uuid app_uuid) {
1765   CallOn(pimpl_.get(), &impl::register_scanner, app_uuid);
1766 }
1767 
Unregister(ScannerId scanner_id)1768 void LeScanningManager::Unregister(ScannerId scanner_id) {
1769   CallOn(pimpl_.get(), &impl::unregister_scanner, scanner_id);
1770 }
1771 
Scan(bool start)1772 void LeScanningManager::Scan(bool start) {
1773   CallOn(pimpl_.get(), &impl::scan, start);
1774 }
1775 
SetScanParameters(ScannerId scanner_id,LeScanType scan_type,uint16_t scan_interval,uint16_t scan_window,uint8_t scan_phy)1776 void LeScanningManager::SetScanParameters(
1777     ScannerId scanner_id,
1778     LeScanType scan_type,
1779     uint16_t scan_interval,
1780     uint16_t scan_window,
1781     uint8_t scan_phy) {
1782   CallOn(
1783       pimpl_.get(),
1784       &impl::set_scan_parameters,
1785       scanner_id,
1786       scan_type,
1787       scan_interval,
1788       scan_window,
1789       scan_phy);
1790 }
1791 
SetScanFilterPolicy(LeScanningFilterPolicy filter_policy)1792 void LeScanningManager::SetScanFilterPolicy(LeScanningFilterPolicy filter_policy) {
1793   CallOn(pimpl_.get(), &impl::set_scan_filter_policy, filter_policy);
1794 }
1795 
ScanFilterEnable(bool enable)1796 void LeScanningManager::ScanFilterEnable(bool enable) {
1797   CallOn(pimpl_.get(), &impl::scan_filter_enable, enable);
1798 }
1799 
ScanFilterParameterSetup(ApcfAction action,uint8_t filter_index,AdvertisingFilterParameter advertising_filter_parameter)1800 void LeScanningManager::ScanFilterParameterSetup(
1801     ApcfAction action, uint8_t filter_index, AdvertisingFilterParameter advertising_filter_parameter) {
1802   CallOn(pimpl_.get(), &impl::scan_filter_parameter_setup, action, filter_index, advertising_filter_parameter);
1803 }
1804 
ScanFilterAdd(uint8_t filter_index,std::vector<AdvertisingPacketContentFilterCommand> filters)1805 void LeScanningManager::ScanFilterAdd(
1806     uint8_t filter_index, std::vector<AdvertisingPacketContentFilterCommand> filters) {
1807   CallOn(pimpl_.get(), &impl::scan_filter_add, filter_index, filters);
1808 }
1809 
BatchScanConifgStorage(uint8_t batch_scan_full_max,uint8_t batch_scan_truncated_max,uint8_t batch_scan_notify_threshold,ScannerId scanner_id)1810 void LeScanningManager::BatchScanConifgStorage(
1811     uint8_t batch_scan_full_max,
1812     uint8_t batch_scan_truncated_max,
1813     uint8_t batch_scan_notify_threshold,
1814     ScannerId scanner_id) {
1815   CallOn(
1816       pimpl_.get(),
1817       &impl::batch_scan_set_storage_parameter,
1818       batch_scan_full_max,
1819       batch_scan_truncated_max,
1820       batch_scan_notify_threshold,
1821       scanner_id);
1822 }
1823 
BatchScanEnable(BatchScanMode scan_mode,uint32_t duty_cycle_scan_window_slots,uint32_t duty_cycle_scan_interval_slots,BatchScanDiscardRule batch_scan_discard_rule)1824 void LeScanningManager::BatchScanEnable(
1825     BatchScanMode scan_mode,
1826     uint32_t duty_cycle_scan_window_slots,
1827     uint32_t duty_cycle_scan_interval_slots,
1828     BatchScanDiscardRule batch_scan_discard_rule) {
1829   CallOn(
1830       pimpl_.get(),
1831       &impl::batch_scan_enable,
1832       scan_mode,
1833       duty_cycle_scan_window_slots,
1834       duty_cycle_scan_interval_slots,
1835       batch_scan_discard_rule);
1836 }
1837 
BatchScanDisable()1838 void LeScanningManager::BatchScanDisable() {
1839   CallOn(pimpl_.get(), &impl::batch_scan_disable);
1840 }
1841 
BatchScanReadReport(ScannerId scanner_id,BatchScanMode scan_mode)1842 void LeScanningManager::BatchScanReadReport(ScannerId scanner_id, BatchScanMode scan_mode) {
1843   CallOn(pimpl_.get(), &impl::batch_scan_read_results, scanner_id, 0, scan_mode);
1844 }
1845 
StartSync(uint8_t sid,const AddressWithType & address_with_type,uint16_t skip,uint16_t timeout,int reg_id)1846 void LeScanningManager::StartSync(
1847     uint8_t sid, const AddressWithType& address_with_type, uint16_t skip, uint16_t timeout, int reg_id) {
1848   CallOn(pimpl_.get(), &impl::start_sync, sid, address_with_type, skip, timeout, reg_id);
1849 }
1850 
StopSync(uint16_t handle)1851 void LeScanningManager::StopSync(uint16_t handle) {
1852   CallOn(pimpl_.get(), &impl::stop_sync, handle);
1853 }
1854 
CancelCreateSync(uint8_t sid,const Address & address)1855 void LeScanningManager::CancelCreateSync(uint8_t sid, const Address& address) {
1856   CallOn(pimpl_.get(), &impl::cancel_create_sync, sid, address);
1857 }
1858 
TransferSync(const Address & address,uint16_t handle,uint16_t service_data,uint16_t sync_handle,int pa_source)1859 void LeScanningManager::TransferSync(
1860     const Address& address,
1861     uint16_t handle,
1862     uint16_t service_data,
1863     uint16_t sync_handle,
1864     int pa_source) {
1865   CallOn(pimpl_.get(), &impl::transfer_sync, address, handle, service_data, sync_handle, pa_source);
1866 }
1867 
TransferSetInfo(const Address & address,uint16_t handle,uint16_t service_data,uint8_t adv_handle,int pa_source)1868 void LeScanningManager::TransferSetInfo(
1869     const Address& address,
1870     uint16_t handle,
1871     uint16_t service_data,
1872     uint8_t adv_handle,
1873     int pa_source) {
1874   CallOn(
1875       pimpl_.get(), &impl::transfer_set_info, address, handle, service_data, adv_handle, pa_source);
1876 }
1877 
SyncTxParameters(const Address & address,uint8_t mode,uint16_t skip,uint16_t timeout,int reg_id)1878 void LeScanningManager::SyncTxParameters(
1879     const Address& address, uint8_t mode, uint16_t skip, uint16_t timeout, int reg_id) {
1880   CallOn(pimpl_.get(), &impl::sync_tx_parameters, address, mode, skip, timeout, reg_id);
1881 }
1882 
TrackAdvertiser(uint8_t filter_index,ScannerId scanner_id)1883 void LeScanningManager::TrackAdvertiser(uint8_t filter_index, ScannerId scanner_id) {
1884   CallOn(pimpl_.get(), &impl::track_advertiser, filter_index, scanner_id);
1885 }
1886 
RegisterScanningCallback(ScanningCallback * scanning_callback)1887 void LeScanningManager::RegisterScanningCallback(ScanningCallback* scanning_callback) {
1888   CallOn(pimpl_.get(), &impl::register_scanning_callback, scanning_callback);
1889 }
1890 
IsAdTypeFilterSupported() const1891 bool LeScanningManager::IsAdTypeFilterSupported() const {
1892   return pimpl_->is_ad_type_filter_supported();
1893 }
1894 
1895 }  // namespace hci
1896 }  // namespace bluetooth
1897