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