low_energy_advertiser.cc 10 KB

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