low_energy_client.h revision 480174f874a664affda33831c904eb3574ae9389
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_settings.h"
32#include "service/common/bluetooth/uuid.h"
33#include "service/hal/bluetooth_gatt_interface.h"
34
35namespace bluetooth {
36
37class Adapter;
38
39// A LowEnergyClient represents an application's handle to perform various
40// Bluetooth Low Energy GAP operations. Instances cannot be created directly and
41// should be obtained through the factory.
42class LowEnergyClient : private hal::BluetoothGattInterface::ClientObserver,
43                        public BluetoothInstance {
44 public:
45  // The destructor automatically unregisters this client instance from the
46  // stack.
47  ~LowEnergyClient() override;
48
49  // Callback type used to return the result of asynchronous operations below.
50  using StatusCallback = std::function<void(BLEStatus)>;
51
52  // Initiates a BLE device scan for this client using the given |settings| and
53  // |filters|. See the documentation for ScanSettings and ScanFilter for how
54  // these parameters can be configured. Return true on success, false
55  // otherwise. Please see logs for details in case of error.
56  bool StartScan(const ScanSettings& settings,
57                 const std::vector<ScanFilter>& filters);
58
59  // Stops an ongoing BLE device scan for this client.
60  bool StopScan();
61
62  // Starts advertising based on the given advertising and scan response
63  // data and the provided |settings|. Reports the result of the operation in
64  // |callback|. Return true on success, false otherwise. Please see logs for
65  // details in case of error.
66  bool StartAdvertising(const AdvertiseSettings& settings,
67                        const AdvertiseData& advertise_data,
68                        const AdvertiseData& scan_response,
69                        const StatusCallback& callback);
70
71  // Stops advertising if it was already started. Reports the result of the
72  // operation in |callback|.
73  bool StopAdvertising(const StatusCallback& callback);
74
75  // Returns true if advertising has been started.
76  bool IsAdvertisingStarted() const;
77
78  // Returns the state of pending advertising operations.
79  bool IsStartingAdvertising() const;
80  bool IsStoppingAdvertising() const;
81
82  // Returns the current advertising settings.
83  const AdvertiseSettings& advertise_settings() const {
84   return advertise_settings_;
85  }
86
87  // Returns the current scan settings.
88  const ScanSettings& scan_settings() const { return scan_settings_; }
89
90  // BluetoothClientInstace overrides:
91  const UUID& GetAppIdentifier() const override;
92  int GetInstanceId() const override;
93
94 private:
95  friend class LowEnergyClientFactory;
96
97  // Constructor shouldn't be called directly as instances are meant to be
98  // obtained from the factory.
99  LowEnergyClient(Adapter& adapter, const UUID& uuid, int client_id);
100
101  // BluetoothGattInterface::ClientObserver overrides:
102  void MultiAdvEnableCallback(
103      hal::BluetoothGattInterface* gatt_iface,
104      int client_id, int status) override;
105  void MultiAdvDataCallback(
106      hal::BluetoothGattInterface* gatt_iface,
107      int client_id, int status) override;
108  void MultiAdvDisableCallback(
109      hal::BluetoothGattInterface* gatt_iface,
110      int client_id, int status) override;
111
112  // Helper method called from SetAdvertiseData/SetScanResponse.
113  bt_status_t SetAdvertiseData(
114      hal::BluetoothGattInterface* gatt_iface,
115      const AdvertiseData& data,
116      bool set_scan_rsp);
117
118  // Handles deferred advertise/scan-response data updates. We set the data if
119  // there's data to be set, otherwise we either defer it if advertisements
120  // aren't enabled or do nothing.
121  void HandleDeferredAdvertiseData(hal::BluetoothGattInterface* gatt_iface);
122
123  // Calls and clears the pending callbacks.
124  void InvokeAndClearStartCallback(BLEStatus status);
125  void InvokeAndClearStopCallback(BLEStatus status);
126
127  // Raw pointer to the Bluetooth Adapter.
128  Adapter& adapter_;
129
130  // See getters above for documentation.
131  UUID app_identifier_;
132  int client_id_;
133
134  // Protects advertising-related members below.
135  std::mutex adv_fields_lock_;
136
137  // The advertising and scan response data fields that will be sent to the
138  // controller.
139  AdvertiseData adv_data_;
140  AdvertiseData scan_response_;
141  std::atomic_bool adv_data_needs_update_;
142  std::atomic_bool scan_rsp_needs_update_;
143
144  // Latest advertising settings.
145  AdvertiseSettings advertise_settings_;
146
147  // Whether or not there is a pending call to update advertising or scan
148  // response data.
149  std::atomic_bool is_setting_adv_data_;
150
151  std::atomic_bool adv_started_;
152  std::unique_ptr<StatusCallback> adv_start_callback_;
153  std::unique_ptr<StatusCallback> adv_stop_callback_;
154
155  // Protects device scan related members below.
156  std::mutex scan_fields_lock_;
157
158  // Current scan settings.
159  ScanSettings scan_settings_;
160
161  // If true, then this client have a BLE device scan in progress.
162  std::atomic_bool scan_started_;
163
164  DISALLOW_COPY_AND_ASSIGN(LowEnergyClient);
165};
166
167// LowEnergyClientFactory is used to register and obtain a per-application
168// LowEnergyClient instance. Users should call RegisterInstance to obtain their
169// own unique LowEnergyClient instance that has been registered with the
170// Bluetooth stack.
171class LowEnergyClientFactory
172    : private hal::BluetoothGattInterface::ClientObserver,
173      public BluetoothInstanceFactory {
174 public:
175  // Don't construct/destruct directly except in tests. Instead, obtain a handle
176  // from an Adapter instance.
177  LowEnergyClientFactory(Adapter& adapter);
178  ~LowEnergyClientFactory() override;
179
180  // BluetoothInstanceFactory override:
181  bool RegisterInstance(const UUID& uuid,
182                        const RegisterCallback& callback) override;
183
184 private:
185  friend class LowEnergyClient;
186
187  // BluetoothGattInterface::ClientObserver overrides:
188  void RegisterClientCallback(
189      hal::BluetoothGattInterface* gatt_iface,
190      int status, int client_id,
191      const bt_uuid_t& app_uuid) override;
192
193  // Map of pending calls to register.
194  std::mutex pending_calls_lock_;
195  std::map<UUID, RegisterCallback> pending_calls_;
196
197  // Raw pointer to the Adapter that owns this factory.
198  Adapter& adapter_;
199
200  DISALLOW_COPY_AND_ASSIGN(LowEnergyClientFactory);
201};
202
203}  // namespace bluetooth
204