2 // Copyright (C) 2015 Google, Inc.
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:
8 // http://www.apache.org/licenses/LICENSE-2.0
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.
24 #include <base/macros.h>
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"
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;
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 {
52 // The Delegate interface is used to notify asynchronous events related to BLE
57 virtual ~Delegate() = default;
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;
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;
69 DISALLOW_COPY_AND_ASSIGN(Delegate);
72 // The destructor automatically unregisters this client instance from the
74 ~LowEnergyClient() override;
76 // Assigns a delegate to this instance. |delegate| must out-live this
77 // LowEnergyClient instance.
78 void SetDelegate(Delegate* delegate);
80 // Callback type used to return the result of asynchronous operations below.
81 using StatusCallback = std::function<void(BLEStatus)>;
83 // Initiates a BLE connection do device with address |address|. If
84 // |is_direct| is set, use direct connect procedure. Return true on success
86 bool Connect(std::string address, bool is_direct);
88 // Disconnect from previously connected BLE device with address |address|.
89 // Return true on success, false otherwise.
90 bool Disconnect(std::string address);
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);
99 // Stops an ongoing BLE device scan for this client.
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);
111 // Stops advertising if it was already started. Reports the result of the
112 // operation in |callback|.
113 bool StopAdvertising(const StatusCallback& callback);
115 // Returns true if advertising has been started.
116 bool IsAdvertisingStarted() const;
118 // Returns the state of pending advertising operations.
119 bool IsStartingAdvertising() const;
120 bool IsStoppingAdvertising() const;
122 // Returns the current advertising settings.
123 const AdvertiseSettings& advertise_settings() const {
124 return advertise_settings_;
127 // Returns the current scan settings.
128 const ScanSettings& scan_settings() const { return scan_settings_; }
130 // BluetoothClientInstace overrides:
131 const UUID& GetAppIdentifier() const override;
132 int GetInstanceId() const override;
135 friend class LowEnergyClientFactory;
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);
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;
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;
162 // Helper method called from SetAdvertiseData/SetScanResponse.
163 bt_status_t SetAdvertiseData(
164 hal::BluetoothGattInterface* gatt_iface,
165 const AdvertiseData& data,
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);
173 // Calls and clears the pending callbacks.
174 void InvokeAndClearStartCallback(BLEStatus status);
175 void InvokeAndClearStopCallback(BLEStatus status);
177 // Raw pointer to the Bluetooth Adapter.
180 // See getters above for documentation.
181 UUID app_identifier_;
184 // Protects advertising-related members below.
185 std::mutex adv_fields_lock_;
187 // The advertising and scan response data fields that will be sent to the
189 AdvertiseData adv_data_;
190 AdvertiseData scan_response_;
191 std::atomic_bool adv_data_needs_update_;
192 std::atomic_bool scan_rsp_needs_update_;
194 // Latest advertising settings.
195 AdvertiseSettings advertise_settings_;
197 // Whether or not there is a pending call to update advertising or scan
199 std::atomic_bool is_setting_adv_data_;
201 std::atomic_bool adv_started_;
202 std::unique_ptr<StatusCallback> adv_start_callback_;
203 std::unique_ptr<StatusCallback> adv_stop_callback_;
205 // Protects device scan related members below.
206 std::mutex scan_fields_lock_;
208 // Current scan settings.
209 ScanSettings scan_settings_;
211 // If true, then this client have a BLE device scan in progress.
212 std::atomic_bool scan_started_;
214 // Raw handle to the Delegate, which must outlive this LowEnergyClient
216 std::mutex delegate_mutex_;
219 // Protects device connection related members below.
220 std::mutex connection_fields_lock_;
222 // Maps bluetooth address to connection id
223 std::map<const bt_bdaddr_t, int, ConnComparator> connection_ids_;
225 DISALLOW_COPY_AND_ASSIGN(LowEnergyClient);
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
232 class LowEnergyClientFactory
233 : private hal::BluetoothGattInterface::ClientObserver,
234 public BluetoothInstanceFactory {
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;
241 // BluetoothInstanceFactory override:
242 bool RegisterInstance(const UUID& uuid,
243 const RegisterCallback& callback) override;
246 friend class LowEnergyClient;
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;
254 // Map of pending calls to register.
255 std::mutex pending_calls_lock_;
256 std::map<UUID, RegisterCallback> pending_calls_;
258 // Raw pointer to the Adapter that owns this factory.
261 DISALLOW_COPY_AND_ASSIGN(LowEnergyClientFactory);
264 } // namespace bluetooth