1//
2//  Copyright (C) 2016 The Android Open Source Project
3//
4//  Licensed under the Apache License, Version 2.0 (the "License");
5//  you may not use this file except in compliance with the License.
6//  You may obtain a copy of the License at:
7//
8//  http://www.apache.org/licenses/LICENSE-2.0
9//
10//  Unless required by applicable law or agreed to in writing, software
11//  distributed under the License is distributed on an "AS IS" BASIS,
12//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13//  See the License for the specific language governing permissions and
14//  limitations under the License.
15//
16
17#pragma once
18
19#include <atomic>
20#include <functional>
21#include <map>
22#include <mutex>
23
24#include <base/macros.h>
25
26#include "service/bluetooth_instance.h"
27#include "service/common/bluetooth/advertise_data.h"
28#include "service/common/bluetooth/advertise_settings.h"
29#include "service/common/bluetooth/low_energy_constants.h"
30#include "service/common/bluetooth/scan_filter.h"
31#include "service/common/bluetooth/scan_result.h"
32#include "service/common/bluetooth/scan_settings.h"
33#include "service/common/bluetooth/uuid.h"
34#include "service/hal/bluetooth_gatt_interface.h"
35
36namespace bluetooth {
37
38class Adapter;
39
40// A LowEnergyScanner represents an application's handle to perform various
41// Bluetooth Low Energy GAP operations. Instances cannot be created directly and
42// should be obtained through the factory.
43class LowEnergyScanner : private hal::BluetoothGattInterface::ScannerObserver,
44                         public BluetoothInstance {
45 public:
46  // The Delegate interface is used to notify asynchronous events related to LE
47  // scan.
48  class Delegate {
49   public:
50    Delegate() = default;
51    virtual ~Delegate() = default;
52
53    // Called asynchronously to notify the delegate of nearby BLE advertisers
54    // found during a device scan.
55    virtual void OnScanResult(LowEnergyScanner* client,
56                              const ScanResult& scan_result) = 0;
57
58   private:
59    DISALLOW_COPY_AND_ASSIGN(Delegate);
60  };
61
62  // The destructor automatically unregisters this client instance from the
63  // stack.
64  ~LowEnergyScanner() override;
65
66  // Assigns a delegate to this instance. |delegate| must out-live this
67  // LowEnergyClient instance.
68  void SetDelegate(Delegate* delegate);
69
70  // Initiates a BLE device scan for this client using the given |settings| and
71  // |filters|. See the documentation for ScanSettings and ScanFilter for how
72  // these parameters can be configured. Return true on success, false
73  // otherwise. Please see logs for details in case of error.
74  bool StartScan(const ScanSettings& settings,
75                 const std::vector<ScanFilter>& filters);
76
77  // Stops an ongoing BLE device scan for this client.
78  bool StopScan();
79
80  // Returns the current scan settings.
81  const ScanSettings& scan_settings() const { return scan_settings_; }
82
83  // BluetoothInstace overrides:
84  const UUID& GetAppIdentifier() const override;
85  int GetInstanceId() const override;
86
87  void ScanResultCallback(hal::BluetoothGattInterface* gatt_iface,
88                          const RawAddress& bda, int rssi,
89                          std::vector<uint8_t> adv_data) override;
90
91 private:
92  friend class LowEnergyScannerFactory;
93
94  // Constructor shouldn't be called directly as instances are meant to be
95  // obtained from the factory.
96  LowEnergyScanner(Adapter& adapter, const UUID& uuid, int scanner_id);
97
98  // Calls and clears the pending callbacks.
99  void InvokeAndClearStartCallback(BLEStatus status);
100  void InvokeAndClearStopCallback(BLEStatus status);
101
102  // Raw pointer to the Bluetooth Adapter.
103  Adapter& adapter_;
104
105  // See getters above for documentation.
106  UUID app_identifier_;
107  int scanner_id_;
108
109  // Protects device scan related members below.
110  std::mutex scan_fields_lock_;
111
112  // Current scan settings.
113  ScanSettings scan_settings_;
114
115  // If true, then this client have a BLE device scan in progress.
116  std::atomic_bool scan_started_;
117
118  // Raw handle to the Delegate, which must outlive this LowEnergyScanner
119  // instance.
120  std::mutex delegate_mutex_;
121  Delegate* delegate_;
122
123  DISALLOW_COPY_AND_ASSIGN(LowEnergyScanner);
124};
125
126// LowEnergyScannerFactory is used to register and obtain a per-application
127// LowEnergyScanner instance. Users should call RegisterInstance to obtain their
128// own unique LowEnergyScanner instance that has been registered with the
129// Bluetooth stack.
130class LowEnergyScannerFactory
131    : private hal::BluetoothGattInterface::ScannerObserver,
132      public BluetoothInstanceFactory {
133 public:
134  // Don't construct/destruct directly except in tests. Instead, obtain a handle
135  // from an Adapter instance.
136  explicit LowEnergyScannerFactory(Adapter& adapter);
137  ~LowEnergyScannerFactory() override;
138
139  // BluetoothInstanceFactory override:
140  bool RegisterInstance(const UUID& app_uuid,
141                        const RegisterCallback& callback) override;
142
143 private:
144  friend class LowEnergyScanner;
145
146  // BluetoothGattInterface::ScannerObserver overrides:
147  void RegisterScannerCallback(const RegisterCallback& callback,
148                               const UUID& app_uuid, uint8_t scanner_id,
149                               uint8_t status);
150
151  // Map of pending calls to register.
152  std::mutex pending_calls_lock_;
153  std::unordered_set<UUID> pending_calls_;
154
155  // Raw pointer to the Adapter that owns this factory.
156  Adapter& adapter_;
157
158  DISALLOW_COPY_AND_ASSIGN(LowEnergyScannerFactory);
159};
160
161}  // namespace bluetooth
162