OSDN Git Service

Merge "service: Add OnScanResult Delegate event."
[android-x86/system-bt.git] / service / low_energy_client.h
1 //
2 //  Copyright (C) 2015 Google, Inc.
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
36 namespace bluetooth {
37
38 class Adapter;
39
40 // A LowEnergyClient 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.
43 class LowEnergyClient : private hal::BluetoothGattInterface::ClientObserver,
44                         public BluetoothInstance {
45  public:
46   // The Delegate interface is used to notify asynchronous events related to BLE
47   // GAP operations.
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(LowEnergyClient* 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   ~LowEnergyClient() override;
65
66   // Assigns a delegate to this instance. |delegate| must out-live this
67   // LowEnergyClient instance.
68   void SetDelegate(Delegate* delegate);
69
70   // Callback type used to return the result of asynchronous operations below.
71   using StatusCallback = std::function<void(BLEStatus)>;
72
73   // Initiates a BLE device scan for this client using the given |settings| and
74   // |filters|. See the documentation for ScanSettings and ScanFilter for how
75   // these parameters can be configured. Return true on success, false
76   // otherwise. Please see logs for details in case of error.
77   bool StartScan(const ScanSettings& settings,
78                  const std::vector<ScanFilter>& filters);
79
80   // Stops an ongoing BLE device scan for this client.
81   bool StopScan();
82
83   // Starts advertising based on the given advertising and scan response
84   // data and the provided |settings|. Reports the result of the operation in
85   // |callback|. Return true on success, false otherwise. Please see logs for
86   // details in case of error.
87   bool StartAdvertising(const AdvertiseSettings& settings,
88                         const AdvertiseData& advertise_data,
89                         const AdvertiseData& scan_response,
90                         const StatusCallback& callback);
91
92   // Stops advertising if it was already started. Reports the result of the
93   // operation in |callback|.
94   bool StopAdvertising(const StatusCallback& callback);
95
96   // Returns true if advertising has been started.
97   bool IsAdvertisingStarted() const;
98
99   // Returns the state of pending advertising operations.
100   bool IsStartingAdvertising() const;
101   bool IsStoppingAdvertising() const;
102
103   // Returns the current advertising settings.
104   const AdvertiseSettings& advertise_settings() const {
105    return advertise_settings_;
106   }
107
108   // Returns the current scan settings.
109   const ScanSettings& scan_settings() const { return scan_settings_; }
110
111   // BluetoothClientInstace overrides:
112   const UUID& GetAppIdentifier() const override;
113   int GetInstanceId() const override;
114
115  private:
116   friend class LowEnergyClientFactory;
117
118   // Constructor shouldn't be called directly as instances are meant to be
119   // obtained from the factory.
120   LowEnergyClient(Adapter& adapter, const UUID& uuid, int client_id);
121
122   // BluetoothGattInterface::ClientObserver overrides:
123   void ScanResultCallback(
124       hal::BluetoothGattInterface* gatt_iface,
125       const bt_bdaddr_t& bda, int rssi, uint8_t* adv_data) override;
126   void MultiAdvEnableCallback(
127       hal::BluetoothGattInterface* gatt_iface,
128       int client_id, int status) override;
129   void MultiAdvDataCallback(
130       hal::BluetoothGattInterface* gatt_iface,
131       int client_id, int status) override;
132   void MultiAdvDisableCallback(
133       hal::BluetoothGattInterface* gatt_iface,
134       int client_id, int status) override;
135
136   // Helper method called from SetAdvertiseData/SetScanResponse.
137   bt_status_t SetAdvertiseData(
138       hal::BluetoothGattInterface* gatt_iface,
139       const AdvertiseData& data,
140       bool set_scan_rsp);
141
142   // Handles deferred advertise/scan-response data updates. We set the data if
143   // there's data to be set, otherwise we either defer it if advertisements
144   // aren't enabled or do nothing.
145   void HandleDeferredAdvertiseData(hal::BluetoothGattInterface* gatt_iface);
146
147   // Calls and clears the pending callbacks.
148   void InvokeAndClearStartCallback(BLEStatus status);
149   void InvokeAndClearStopCallback(BLEStatus status);
150
151   // Raw pointer to the Bluetooth Adapter.
152   Adapter& adapter_;
153
154   // See getters above for documentation.
155   UUID app_identifier_;
156   int client_id_;
157
158   // Protects advertising-related members below.
159   std::mutex adv_fields_lock_;
160
161   // The advertising and scan response data fields that will be sent to the
162   // controller.
163   AdvertiseData adv_data_;
164   AdvertiseData scan_response_;
165   std::atomic_bool adv_data_needs_update_;
166   std::atomic_bool scan_rsp_needs_update_;
167
168   // Latest advertising settings.
169   AdvertiseSettings advertise_settings_;
170
171   // Whether or not there is a pending call to update advertising or scan
172   // response data.
173   std::atomic_bool is_setting_adv_data_;
174
175   std::atomic_bool adv_started_;
176   std::unique_ptr<StatusCallback> adv_start_callback_;
177   std::unique_ptr<StatusCallback> adv_stop_callback_;
178
179   // Protects device scan related members below.
180   std::mutex scan_fields_lock_;
181
182   // Current scan settings.
183   ScanSettings scan_settings_;
184
185   // If true, then this client have a BLE device scan in progress.
186   std::atomic_bool scan_started_;
187
188   // Raw handle to the Delegate, which must outlive this LowEnergyClient
189   // instance.
190   std::mutex delegate_mutex_;
191   Delegate* delegate_;
192
193   DISALLOW_COPY_AND_ASSIGN(LowEnergyClient);
194 };
195
196 // LowEnergyClientFactory is used to register and obtain a per-application
197 // LowEnergyClient instance. Users should call RegisterInstance to obtain their
198 // own unique LowEnergyClient instance that has been registered with the
199 // Bluetooth stack.
200 class LowEnergyClientFactory
201     : private hal::BluetoothGattInterface::ClientObserver,
202       public BluetoothInstanceFactory {
203  public:
204   // Don't construct/destruct directly except in tests. Instead, obtain a handle
205   // from an Adapter instance.
206   LowEnergyClientFactory(Adapter& adapter);
207   ~LowEnergyClientFactory() override;
208
209   // BluetoothInstanceFactory override:
210   bool RegisterInstance(const UUID& uuid,
211                         const RegisterCallback& callback) override;
212
213  private:
214   friend class LowEnergyClient;
215
216   // BluetoothGattInterface::ClientObserver overrides:
217   void RegisterClientCallback(
218       hal::BluetoothGattInterface* gatt_iface,
219       int status, int client_id,
220       const bt_uuid_t& app_uuid) override;
221
222   // Map of pending calls to register.
223   std::mutex pending_calls_lock_;
224   std::map<UUID, RegisterCallback> pending_calls_;
225
226   // Raw pointer to the Adapter that owns this factory.
227   Adapter& adapter_;
228
229   DISALLOW_COPY_AND_ASSIGN(LowEnergyClientFactory);
230 };
231
232 }  // namespace bluetooth