2 // Copyright 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.
17 #include "service/low_energy_advertiser.h"
19 #include "service/adapter.h"
20 #include "service/logging_helpers.h"
21 #include "stack/include/bt_types.h"
22 #include "stack/include/hcidefs.h"
24 #include <base/bind.h>
25 #include <base/bind_helpers.h>
26 #include <base/callback.h>
27 #include <base/logging.h>
29 using std::lock_guard;
36 BLEStatus GetBLEStatus(int status) {
37 if (status == BT_STATUS_FAIL) return BLE_STATUS_FAILURE;
39 return static_cast<BLEStatus>(status);
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) {
51 case AdvertiseSettings::MODE_BALANCED:
52 ms = kAdvertisingIntervalMediumMs;
54 case AdvertiseSettings::MODE_LOW_LATENCY:
55 ms = kAdvertisingIntervalLowMs;
57 case AdvertiseSettings::MODE_LOW_POWER:
58 FALLTHROUGH_INTENDED; /* FALLTHROUGH */
60 ms = kAdvertisingIntervalHighMs;
64 // Convert milliseconds to Bluetooth units.
65 return (ms * 1000) / 625;
68 int8_t GetAdvertisingTxPower(AdvertiseSettings::TxPowerLevel tx_power) {
72 case AdvertiseSettings::TX_POWER_LEVEL_ULTRA_LOW:
75 case AdvertiseSettings::TX_POWER_LEVEL_LOW:
78 case AdvertiseSettings::TX_POWER_LEVEL_MEDIUM:
81 case AdvertiseSettings::TX_POWER_LEVEL_HIGH:
82 FALLTHROUGH_INTENDED; /* FALLTHROUGH */
91 void GetAdvertiseParams(const AdvertiseSettings& settings, bool has_scan_rsp,
92 AdvertiseParameters* out_params) {
95 out_params->min_interval = GetAdvertisingIntervalUnit(settings.mode());
96 out_params->max_interval =
97 out_params->min_interval + kAdvertisingIntervalDeltaUnit;
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;
106 out_params->advertising_event_properties =
107 kAdvertisingEventTypeLegacyNonConnectable;
109 out_params->channel_map = kAdvertisingChannelAll;
110 out_params->tx_power = GetAdvertisingTxPower(settings.tx_power_level());
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;
120 // LowEnergyAdvertiser implementation
121 // ========================================================
123 LowEnergyAdvertiser::LowEnergyAdvertiser(const Uuid& uuid, int advertiser_id)
124 : app_identifier_(uuid),
125 advertiser_id_(advertiser_id),
127 adv_start_callback_(nullptr),
128 adv_stop_callback_(nullptr) {}
130 LowEnergyAdvertiser::~LowEnergyAdvertiser() {
131 // Automatically unregister the advertiser.
132 VLOG(1) << "LowEnergyAdvertiser unregistering advertiser: " << advertiser_id_;
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(
141 bool LowEnergyAdvertiser::StartAdvertising(const AdvertiseSettings& settings,
142 const AdvertiseData& advertise_data,
143 const AdvertiseData& scan_response,
144 const StatusCallback& callback) {
146 lock_guard<mutex> lock(adv_fields_lock_);
148 if (IsAdvertisingStarted()) {
149 LOG(WARNING) << "Already advertising";
153 if (IsStartingAdvertising()) {
154 LOG(WARNING) << "StartAdvertising already pending";
158 if (!advertise_data.IsValid()) {
159 LOG(ERROR) << "Invalid advertising data";
163 if (!scan_response.IsValid()) {
164 LOG(ERROR) << "Invalid scan response data";
168 advertise_settings_ = settings;
170 AdvertiseParameters params;
171 GetAdvertiseParams(settings, !scan_response.data().empty(), ¶ms);
173 hal::BluetoothGattInterface::Get()
174 ->GetAdvertiserHALInterface()
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_));
185 adv_start_callback_.reset(new StatusCallback(callback));
189 bool LowEnergyAdvertiser::StopAdvertising(const StatusCallback& callback) {
191 lock_guard<mutex> lock(adv_fields_lock_);
193 if (!IsAdvertisingStarted()) {
194 LOG(ERROR) << "Not advertising";
198 if (IsStoppingAdvertising()) {
199 LOG(ERROR) << "StopAdvertising already pending";
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_));
210 // OK to set this at the end since we're still holding |adv_fields_lock_|.
211 adv_stop_callback_.reset(new StatusCallback(callback));
216 bool LowEnergyAdvertiser::IsAdvertisingStarted() const {
217 return adv_started_.load();
220 bool LowEnergyAdvertiser::IsStartingAdvertising() const {
221 return !IsAdvertisingStarted() && adv_start_callback_;
224 bool LowEnergyAdvertiser::IsStoppingAdvertising() const {
225 return IsAdvertisingStarted() && adv_stop_callback_;
228 const Uuid& LowEnergyAdvertiser::GetAppIdentifier() const {
229 return app_identifier_;
232 int LowEnergyAdvertiser::GetInstanceId() const { return advertiser_id_; }
234 void LowEnergyAdvertiser::EnableCallback(bool enable, uint8_t advertiser_id,
236 if (advertiser_id != advertiser_id_) return;
238 lock_guard<mutex> lock(adv_fields_lock_);
240 VLOG(1) << __func__ << "advertiser_id: " << advertiser_id
241 << " status: " << status << " enable: " << enable;
244 CHECK(adv_start_callback_);
245 CHECK(!adv_stop_callback_);
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));
254 // All pending tasks are complete. Report success.
256 InvokeAndClearStartCallback(BLE_STATUS_SUCCESS);
259 CHECK(!adv_start_callback_);
260 CHECK(adv_stop_callback_);
262 if (status == BT_STATUS_SUCCESS) {
263 VLOG(1) << "Multi-advertising stopped for advertiser_id: "
265 adv_started_ = false;
267 LOG(ERROR) << "Failed to stop multi-advertising";
270 InvokeAndClearStopCallback(GetBLEStatus(status));
274 void LowEnergyAdvertiser::InvokeAndClearStartCallback(BLEStatus status) {
275 // We allow NULL callbacks.
276 if (*adv_start_callback_) (*adv_start_callback_)(status);
278 adv_start_callback_ = nullptr;
281 void LowEnergyAdvertiser::InvokeAndClearStopCallback(BLEStatus status) {
282 // We allow NULL callbacks.
283 if (*adv_stop_callback_) (*adv_stop_callback_)(status);
285 adv_stop_callback_ = nullptr;
288 // LowEnergyAdvertiserFactory implementation
289 // ========================================================
291 LowEnergyAdvertiserFactory::LowEnergyAdvertiserFactory() {}
293 LowEnergyAdvertiserFactory::~LowEnergyAdvertiserFactory() {}
295 bool LowEnergyAdvertiserFactory::RegisterInstance(
296 const Uuid& app_uuid, const RegisterCallback& callback) {
298 lock_guard<mutex> lock(pending_calls_lock_);
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();
306 BleAdvertiserInterface* hal_iface =
307 hal::BluetoothGattInterface::Get()->GetAdvertiserHALInterface();
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!";
315 pending_calls_.insert(app_uuid);
320 void LowEnergyAdvertiserFactory::RegisterAdvertiserCallback(
321 const RegisterCallback& callback, const Uuid& app_uuid,
322 uint8_t advertiser_id, uint8_t status) {
324 lock_guard<mutex> lock(pending_calls_lock_);
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();
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));
338 result = BLE_STATUS_SUCCESS;
341 // Notify the result via the result callback.
342 callback(result, app_uuid, std::move(advertiser));
344 pending_calls_.erase(iter);
347 } // namespace bluetooth