OSDN Git Service

[automerger skipped] Merge "Reset the IRK after all devices are unpaired" into pi...
[android-x86/system-bt.git] / service / low_energy_advertiser.cc
1 //
2 //  Copyright 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 #include "service/low_energy_advertiser.h"
18
19 #include "service/adapter.h"
20 #include "service/logging_helpers.h"
21 #include "stack/include/bt_types.h"
22 #include "stack/include/hcidefs.h"
23
24 #include <base/bind.h>
25 #include <base/bind_helpers.h>
26 #include <base/callback.h>
27 #include <base/logging.h>
28
29 using std::lock_guard;
30 using std::mutex;
31
32 namespace bluetooth {
33
34 namespace {
35
36 BLEStatus GetBLEStatus(int status) {
37   if (status == BT_STATUS_FAIL) return BLE_STATUS_FAILURE;
38
39   return static_cast<BLEStatus>(status);
40 }
41
42 // The Bluetooth Core Specification defines time interval (e.g. Page Scan
43 // Interval, Advertising Interval, etc) units as 0.625 milliseconds (or 1
44 // Baseband slot). The HAL advertising functions expect the interval in this
45 // unit. This function maps an AdvertiseSettings::Mode value to the
46 // corresponding time unit.
47 int GetAdvertisingIntervalUnit(AdvertiseSettings::Mode mode) {
48   int ms;
49
50   switch (mode) {
51     case AdvertiseSettings::MODE_BALANCED:
52       ms = kAdvertisingIntervalMediumMs;
53       break;
54     case AdvertiseSettings::MODE_LOW_LATENCY:
55       ms = kAdvertisingIntervalLowMs;
56       break;
57     case AdvertiseSettings::MODE_LOW_POWER:
58       FALLTHROUGH_INTENDED; /* FALLTHROUGH */
59     default:
60       ms = kAdvertisingIntervalHighMs;
61       break;
62   }
63
64   // Convert milliseconds to Bluetooth units.
65   return (ms * 1000) / 625;
66 }
67
68 int8_t GetAdvertisingTxPower(AdvertiseSettings::TxPowerLevel tx_power) {
69   int8_t power;
70
71   switch (tx_power) {
72     case AdvertiseSettings::TX_POWER_LEVEL_ULTRA_LOW:
73       power = -21;
74       break;
75     case AdvertiseSettings::TX_POWER_LEVEL_LOW:
76       power = -15;
77       break;
78     case AdvertiseSettings::TX_POWER_LEVEL_MEDIUM:
79       power = -7;
80       break;
81     case AdvertiseSettings::TX_POWER_LEVEL_HIGH:
82       FALLTHROUGH_INTENDED; /* FALLTHROUGH */
83     default:
84       power = 1;
85       break;
86   }
87
88   return power;
89 }
90
91 void GetAdvertiseParams(const AdvertiseSettings& settings, bool has_scan_rsp,
92                         AdvertiseParameters* out_params) {
93   CHECK(out_params);
94
95   out_params->min_interval = GetAdvertisingIntervalUnit(settings.mode());
96   out_params->max_interval =
97       out_params->min_interval + kAdvertisingIntervalDeltaUnit;
98
99   if (settings.connectable())
100     out_params->advertising_event_properties =
101         kAdvertisingEventTypeLegacyConnectable;
102   else if (has_scan_rsp)
103     out_params->advertising_event_properties =
104         kAdvertisingEventTypeLegacyScannable;
105   else
106     out_params->advertising_event_properties =
107         kAdvertisingEventTypeLegacyNonConnectable;
108
109   out_params->channel_map = kAdvertisingChannelAll;
110   out_params->tx_power = GetAdvertisingTxPower(settings.tx_power_level());
111
112   // TODO: expose those new setting through AdvertiseSettings
113   out_params->primary_advertising_phy = 0x01;
114   out_params->secondary_advertising_phy = 0x01;
115   out_params->scan_request_notification_enable = 0;
116 }
117
118 }  // namespace
119
120 // LowEnergyAdvertiser implementation
121 // ========================================================
122
123 LowEnergyAdvertiser::LowEnergyAdvertiser(const Uuid& uuid, int advertiser_id)
124     : app_identifier_(uuid),
125       advertiser_id_(advertiser_id),
126       adv_started_(false),
127       adv_start_callback_(nullptr),
128       adv_stop_callback_(nullptr) {}
129
130 LowEnergyAdvertiser::~LowEnergyAdvertiser() {
131   // Automatically unregister the advertiser.
132   VLOG(1) << "LowEnergyAdvertiser unregistering advertiser: " << advertiser_id_;
133
134   // Stop advertising and ignore the result.
135   hal::BluetoothGattInterface::Get()->GetAdvertiserHALInterface()->Enable(
136       advertiser_id_, false, base::DoNothing(), 0, 0, base::DoNothing());
137   hal::BluetoothGattInterface::Get()->GetAdvertiserHALInterface()->Unregister(
138       advertiser_id_);
139 }
140
141 bool LowEnergyAdvertiser::StartAdvertising(const AdvertiseSettings& settings,
142                                            const AdvertiseData& advertise_data,
143                                            const AdvertiseData& scan_response,
144                                            const StatusCallback& callback) {
145   VLOG(2) << __func__;
146   lock_guard<mutex> lock(adv_fields_lock_);
147
148   if (IsAdvertisingStarted()) {
149     LOG(WARNING) << "Already advertising";
150     return false;
151   }
152
153   if (IsStartingAdvertising()) {
154     LOG(WARNING) << "StartAdvertising already pending";
155     return false;
156   }
157
158   if (!advertise_data.IsValid()) {
159     LOG(ERROR) << "Invalid advertising data";
160     return false;
161   }
162
163   if (!scan_response.IsValid()) {
164     LOG(ERROR) << "Invalid scan response data";
165     return false;
166   }
167
168   advertise_settings_ = settings;
169
170   AdvertiseParameters params;
171   GetAdvertiseParams(settings, !scan_response.data().empty(), &params);
172
173   hal::BluetoothGattInterface::Get()
174       ->GetAdvertiserHALInterface()
175       ->StartAdvertising(
176           advertiser_id_,
177           base::Bind(&LowEnergyAdvertiser::EnableCallback,
178                      base::Unretained(this), true, advertiser_id_),
179           params, advertise_data.data(), scan_response.data(),
180           settings.timeout().InSeconds(),
181           base::Bind(&LowEnergyAdvertiser::EnableCallback,
182                      base::Unretained(this), false, advertiser_id_));
183   ;
184
185   adv_start_callback_.reset(new StatusCallback(callback));
186   return true;
187 }
188
189 bool LowEnergyAdvertiser::StopAdvertising(const StatusCallback& callback) {
190   VLOG(2) << __func__;
191   lock_guard<mutex> lock(adv_fields_lock_);
192
193   if (!IsAdvertisingStarted()) {
194     LOG(ERROR) << "Not advertising";
195     return false;
196   }
197
198   if (IsStoppingAdvertising()) {
199     LOG(ERROR) << "StopAdvertising already pending";
200     return false;
201   }
202
203   hal::BluetoothGattInterface::Get()->GetAdvertiserHALInterface()->Enable(
204       advertiser_id_, false,
205       base::Bind(&LowEnergyAdvertiser::EnableCallback, base::Unretained(this),
206                  false, advertiser_id_),
207       0, 0, base::Bind(&LowEnergyAdvertiser::EnableCallback,
208                        base::Unretained(this), false, advertiser_id_));
209
210   // OK to set this at the end since we're still holding |adv_fields_lock_|.
211   adv_stop_callback_.reset(new StatusCallback(callback));
212
213   return true;
214 }
215
216 bool LowEnergyAdvertiser::IsAdvertisingStarted() const {
217   return adv_started_.load();
218 }
219
220 bool LowEnergyAdvertiser::IsStartingAdvertising() const {
221   return !IsAdvertisingStarted() && adv_start_callback_;
222 }
223
224 bool LowEnergyAdvertiser::IsStoppingAdvertising() const {
225   return IsAdvertisingStarted() && adv_stop_callback_;
226 }
227
228 const Uuid& LowEnergyAdvertiser::GetAppIdentifier() const {
229   return app_identifier_;
230 }
231
232 int LowEnergyAdvertiser::GetInstanceId() const { return advertiser_id_; }
233
234 void LowEnergyAdvertiser::EnableCallback(bool enable, uint8_t advertiser_id,
235                                          uint8_t status) {
236   if (advertiser_id != advertiser_id_) return;
237
238   lock_guard<mutex> lock(adv_fields_lock_);
239
240   VLOG(1) << __func__ << "advertiser_id: " << advertiser_id
241           << " status: " << status << " enable: " << enable;
242
243   if (enable) {
244     CHECK(adv_start_callback_);
245     CHECK(!adv_stop_callback_);
246
247     // Terminate operation in case of error.
248     if (status != BT_STATUS_SUCCESS) {
249       LOG(ERROR) << "Failed to enable multi-advertising";
250       InvokeAndClearStartCallback(GetBLEStatus(status));
251       return;
252     }
253
254     // All pending tasks are complete. Report success.
255     adv_started_ = true;
256     InvokeAndClearStartCallback(BLE_STATUS_SUCCESS);
257
258   } else {
259     CHECK(!adv_start_callback_);
260     CHECK(adv_stop_callback_);
261
262     if (status == BT_STATUS_SUCCESS) {
263       VLOG(1) << "Multi-advertising stopped for advertiser_id: "
264               << advertiser_id;
265       adv_started_ = false;
266     } else {
267       LOG(ERROR) << "Failed to stop multi-advertising";
268     }
269
270     InvokeAndClearStopCallback(GetBLEStatus(status));
271   }
272 }
273
274 void LowEnergyAdvertiser::InvokeAndClearStartCallback(BLEStatus status) {
275   // We allow NULL callbacks.
276   if (*adv_start_callback_) (*adv_start_callback_)(status);
277
278   adv_start_callback_ = nullptr;
279 }
280
281 void LowEnergyAdvertiser::InvokeAndClearStopCallback(BLEStatus status) {
282   // We allow NULL callbacks.
283   if (*adv_stop_callback_) (*adv_stop_callback_)(status);
284
285   adv_stop_callback_ = nullptr;
286 }
287
288 // LowEnergyAdvertiserFactory implementation
289 // ========================================================
290
291 LowEnergyAdvertiserFactory::LowEnergyAdvertiserFactory() {}
292
293 LowEnergyAdvertiserFactory::~LowEnergyAdvertiserFactory() {}
294
295 bool LowEnergyAdvertiserFactory::RegisterInstance(
296     const Uuid& app_uuid, const RegisterCallback& callback) {
297   VLOG(1) << __func__;
298   lock_guard<mutex> lock(pending_calls_lock_);
299
300   if (pending_calls_.find(app_uuid) != pending_calls_.end()) {
301     LOG(ERROR) << "Low-Energy advertiser with given Uuid already registered - "
302                << "Uuid: " << app_uuid.ToString();
303     return false;
304   }
305
306   BleAdvertiserInterface* hal_iface =
307       hal::BluetoothGattInterface::Get()->GetAdvertiserHALInterface();
308
309   VLOG(1) << __func__ << " calling register!";
310   hal_iface->RegisterAdvertiser(
311       base::Bind(&LowEnergyAdvertiserFactory::RegisterAdvertiserCallback,
312                  base::Unretained(this), callback, app_uuid));
313   VLOG(1) << __func__ << " call finished!";
314
315   pending_calls_.insert(app_uuid);
316
317   return true;
318 }
319
320 void LowEnergyAdvertiserFactory::RegisterAdvertiserCallback(
321     const RegisterCallback& callback, const Uuid& app_uuid,
322     uint8_t advertiser_id, uint8_t status) {
323   VLOG(1) << __func__;
324   lock_guard<mutex> lock(pending_calls_lock_);
325
326   auto iter = pending_calls_.find(app_uuid);
327   if (iter == pending_calls_.end()) {
328     VLOG(1) << "Ignoring callback for unknown app_id: " << app_uuid.ToString();
329     return;
330   }
331
332   // No need to construct a advertiser if the call wasn't successful.
333   std::unique_ptr<LowEnergyAdvertiser> advertiser;
334   BLEStatus result = BLE_STATUS_FAILURE;
335   if (status == BT_STATUS_SUCCESS) {
336     advertiser.reset(new LowEnergyAdvertiser(app_uuid, advertiser_id));
337
338     result = BLE_STATUS_SUCCESS;
339   }
340
341   // Notify the result via the result callback.
342   callback(result, app_uuid, std::move(advertiser));
343
344   pending_calls_.erase(iter);
345 }
346
347 }  // namespace bluetooth