OSDN Git Service

700ad9cf7b86644c76e2c1ea25b0e7e98bc740dc
[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 struct ConnComparator {
39     bool operator()(const bt_bdaddr_t& a, const bt_bdaddr_t& b) const {
40         return memcmp(&a, &b, sizeof(bt_bdaddr_t)) < 0;
41     }
42 };
43
44 class Adapter;
45
46 // A LowEnergyClient represents an application's handle to perform various
47 // Bluetooth Low Energy GAP operations. Instances cannot be created directly and
48 // should be obtained through the factory.
49 class LowEnergyClient : private hal::BluetoothGattInterface::ClientObserver,
50                         public BluetoothInstance {
51  public:
52   // The Delegate interface is used to notify asynchronous events related to BLE
53   // GAP operations.
54   class Delegate {
55    public:
56     Delegate() = default;
57     virtual ~Delegate() = default;
58
59     // Called asynchronously to notify the delegate of nearby BLE advertisers
60     // found during a device scan.
61     virtual void OnScanResult(LowEnergyClient* client,
62                               const ScanResult& scan_result) = 0;
63
64     // Called asynchronously to notify the delegate of connection state change
65     virtual void OnConnectionState(LowEnergyClient* client, int status,
66                                    const char* address, bool connected) = 0;
67
68    private:
69     DISALLOW_COPY_AND_ASSIGN(Delegate);
70   };
71
72   // The destructor automatically unregisters this client instance from the
73   // stack.
74   ~LowEnergyClient() override;
75
76   // Assigns a delegate to this instance. |delegate| must out-live this
77   // LowEnergyClient instance.
78   void SetDelegate(Delegate* delegate);
79
80   // Callback type used to return the result of asynchronous operations below.
81   using StatusCallback = std::function<void(BLEStatus)>;
82
83   // Initiates a BLE connection do device with address |address|. If
84   // |is_direct| is set, use direct connect procedure. Return true on success
85   //, false otherwise.
86   bool Connect(std::string address, bool is_direct);
87
88   // Disconnect from previously connected BLE device with address |address|.
89   // Return true on success, false otherwise.
90   bool Disconnect(std::string address);
91
92   // Initiates a BLE device scan for this client using the given |settings| and
93   // |filters|. See the documentation for ScanSettings and ScanFilter for how
94   // these parameters can be configured. Return true on success, false
95   // otherwise. Please see logs for details in case of error.
96   bool StartScan(const ScanSettings& settings,
97                  const std::vector<ScanFilter>& filters);
98
99   // Stops an ongoing BLE device scan for this client.
100   bool StopScan();
101
102   // Starts advertising based on the given advertising and scan response
103   // data and the provided |settings|. Reports the result of the operation in
104   // |callback|. Return true on success, false otherwise. Please see logs for
105   // details in case of error.
106   bool StartAdvertising(const AdvertiseSettings& settings,
107                         const AdvertiseData& advertise_data,
108                         const AdvertiseData& scan_response,
109                         const StatusCallback& callback);
110
111   // Stops advertising if it was already started. Reports the result of the
112   // operation in |callback|.
113   bool StopAdvertising(const StatusCallback& callback);
114
115   // Returns true if advertising has been started.
116   bool IsAdvertisingStarted() const;
117
118   // Returns the state of pending advertising operations.
119   bool IsStartingAdvertising() const;
120   bool IsStoppingAdvertising() const;
121
122   // Returns the current advertising settings.
123   const AdvertiseSettings& advertise_settings() const {
124     return advertise_settings_;
125   }
126
127   // Returns the current scan settings.
128   const ScanSettings& scan_settings() const { return scan_settings_; }
129
130   // BluetoothClientInstace overrides:
131   const UUID& GetAppIdentifier() const override;
132   int GetInstanceId() const override;
133
134  private:
135   friend class LowEnergyClientFactory;
136
137   // Constructor shouldn't be called directly as instances are meant to be
138   // obtained from the factory.
139   LowEnergyClient(Adapter& adapter, const UUID& uuid, int client_id);
140
141   // BluetoothGattInterface::ClientObserver overrides:
142   void ScanResultCallback(
143       hal::BluetoothGattInterface* gatt_iface,
144       const bt_bdaddr_t& bda, int rssi, uint8_t* adv_data) override;
145
146   void ConnectCallback(
147       hal::BluetoothGattInterface* gatt_iface, int conn_id, int status,
148       int client_id, const bt_bdaddr_t& bda) override;
149   void DisconnectCallback(
150       hal::BluetoothGattInterface* gatt_iface, int conn_id, int status,
151       int client_id, const bt_bdaddr_t& bda) override;
152   void MultiAdvEnableCallback(
153       hal::BluetoothGattInterface* gatt_iface,
154       int client_id, int status) override;
155   void MultiAdvDataCallback(
156       hal::BluetoothGattInterface* gatt_iface,
157       int client_id, int status) override;
158   void MultiAdvDisableCallback(
159       hal::BluetoothGattInterface* gatt_iface,
160       int client_id, int status) override;
161
162   // Helper method called from SetAdvertiseData/SetScanResponse.
163   bt_status_t SetAdvertiseData(
164       hal::BluetoothGattInterface* gatt_iface,
165       const AdvertiseData& data,
166       bool set_scan_rsp);
167
168   // Handles deferred advertise/scan-response data updates. We set the data if
169   // there's data to be set, otherwise we either defer it if advertisements
170   // aren't enabled or do nothing.
171   void HandleDeferredAdvertiseData(hal::BluetoothGattInterface* gatt_iface);
172
173   // Calls and clears the pending callbacks.
174   void InvokeAndClearStartCallback(BLEStatus status);
175   void InvokeAndClearStopCallback(BLEStatus status);
176
177   // Raw pointer to the Bluetooth Adapter.
178   Adapter& adapter_;
179
180   // See getters above for documentation.
181   UUID app_identifier_;
182   int client_id_;
183
184   // Protects advertising-related members below.
185   std::mutex adv_fields_lock_;
186
187   // The advertising and scan response data fields that will be sent to the
188   // controller.
189   AdvertiseData adv_data_;
190   AdvertiseData scan_response_;
191   std::atomic_bool adv_data_needs_update_;
192   std::atomic_bool scan_rsp_needs_update_;
193
194   // Latest advertising settings.
195   AdvertiseSettings advertise_settings_;
196
197   // Whether or not there is a pending call to update advertising or scan
198   // response data.
199   std::atomic_bool is_setting_adv_data_;
200
201   std::atomic_bool adv_started_;
202   std::unique_ptr<StatusCallback> adv_start_callback_;
203   std::unique_ptr<StatusCallback> adv_stop_callback_;
204
205   // Protects device scan related members below.
206   std::mutex scan_fields_lock_;
207
208   // Current scan settings.
209   ScanSettings scan_settings_;
210
211   // If true, then this client have a BLE device scan in progress.
212   std::atomic_bool scan_started_;
213
214   // Raw handle to the Delegate, which must outlive this LowEnergyClient
215   // instance.
216   std::mutex delegate_mutex_;
217   Delegate* delegate_;
218
219   // Protects device connection related members below.
220   std::mutex connection_fields_lock_;
221
222   // Maps bluetooth address to connection id
223   std::map<const bt_bdaddr_t, int, ConnComparator> connection_ids_;
224
225   DISALLOW_COPY_AND_ASSIGN(LowEnergyClient);
226 };
227
228 // LowEnergyClientFactory is used to register and obtain a per-application
229 // LowEnergyClient instance. Users should call RegisterInstance to obtain their
230 // own unique LowEnergyClient instance that has been registered with the
231 // Bluetooth stack.
232 class LowEnergyClientFactory
233     : private hal::BluetoothGattInterface::ClientObserver,
234       public BluetoothInstanceFactory {
235  public:
236   // Don't construct/destruct directly except in tests. Instead, obtain a handle
237   // from an Adapter instance.
238   LowEnergyClientFactory(Adapter& adapter);
239   ~LowEnergyClientFactory() override;
240
241   // BluetoothInstanceFactory override:
242   bool RegisterInstance(const UUID& uuid,
243                         const RegisterCallback& callback) override;
244
245  private:
246   friend class LowEnergyClient;
247
248   // BluetoothGattInterface::ClientObserver overrides:
249   void RegisterClientCallback(
250       hal::BluetoothGattInterface* gatt_iface,
251       int status, int client_id,
252       const bt_uuid_t& app_uuid) override;
253
254   // Map of pending calls to register.
255   std::mutex pending_calls_lock_;
256   std::map<UUID, RegisterCallback> pending_calls_;
257
258   // Raw pointer to the Adapter that owns this factory.
259   Adapter& adapter_;
260
261   DISALLOW_COPY_AND_ASSIGN(LowEnergyClientFactory);
262 };
263
264 }  // namespace bluetooth