1 /*
2 * Copyright 2020 The Android Open Source Project
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 #pragma once
18
19 #include <base/strings/stringprintf.h>
20
21 #include <atomic>
22 #include <cstddef>
23 #include <cstdint>
24 #include <memory>
25 #include <string>
26 #include <unordered_set>
27
28 #include "common/bind.h"
29 #include "common/init_flags.h"
30 #include "crypto_toolbox/crypto_toolbox.h"
31 #include "hci/acl_manager/assembler.h"
32 #include "hci/acl_manager/le_connection_management_callbacks.h"
33 #include "hci/acl_manager/round_robin_scheduler.h"
34 #include "hci/controller.h"
35 #include "hci/hci_layer.h"
36 #include "hci/hci_packets.h"
37 #include "hci/le_address_manager.h"
38 #include "os/alarm.h"
39 #include "os/handler.h"
40 #include "os/metrics.h"
41 #include "os/system_properties.h"
42 #include "packet/packet_view.h"
43
44 using bluetooth::crypto_toolbox::Octet16;
45
46 #define PRIVATE_ADDRESS_WITH_TYPE(addr) addr.ToString().substr(12U).c_str()
47
48 namespace bluetooth {
49 namespace hci {
50 namespace acl_manager {
51
52 using common::BindOnce;
53
54 constexpr uint16_t kScanIntervalFast = 0x0060; /* 30 ~ 60 ms (use 60) = 96 *0.625 */
55 constexpr uint16_t kScanWindowFast = 0x0030; /* 30 ms = 48 *0.625 */
56 constexpr uint16_t kScanWindow2mFast = 0x0018; /* 15 ms = 24 *0.625 */
57 constexpr uint16_t kScanWindowCodedFast = 0x0018; /* 15 ms = 24 *0.625 */
58 constexpr uint16_t kScanIntervalSlow = 0x0800; /* 1.28 s = 2048 *0.625 */
59 constexpr uint16_t kScanWindowSlow = 0x0030; /* 30 ms = 48 *0.625 */
60 constexpr std::chrono::milliseconds kCreateConnectionTimeoutMs = std::chrono::milliseconds(30 * 1000);
61 constexpr uint8_t PHY_LE_NO_PACKET = 0x00;
62 constexpr uint8_t PHY_LE_1M = 0x01;
63 constexpr uint8_t PHY_LE_2M = 0x02;
64 constexpr uint8_t PHY_LE_CODED = 0x04;
65
66 enum class ConnectabilityState {
67 DISARMED = 0,
68 ARMING = 1,
69 ARMED = 2,
70 DISARMING = 3,
71 };
72
73 #define CASE_RETURN_TEXT(code) \
74 case code: \
75 return #code
76
connectability_state_machine_text(const ConnectabilityState & state)77 inline std::string connectability_state_machine_text(const ConnectabilityState& state) {
78 switch (state) {
79 CASE_RETURN_TEXT(ConnectabilityState::DISARMED);
80 CASE_RETURN_TEXT(ConnectabilityState::ARMING);
81 CASE_RETURN_TEXT(ConnectabilityState::ARMED);
82 CASE_RETURN_TEXT(ConnectabilityState::DISARMING);
83 default:
84 return base::StringPrintf("UNKNOWN[%d]", state);
85 }
86 }
87 #undef CASE_RETURN_TEXT
88
89 struct le_acl_connection {
le_acl_connectionle_acl_connection90 le_acl_connection(AddressWithType remote_address, AclConnection::QueueDownEnd* queue_down_end, os::Handler* handler)
91 : remote_address_(remote_address),
92 assembler_(new acl_manager::assembler(remote_address, queue_down_end, handler)) {}
~le_acl_connectionle_acl_connection93 ~le_acl_connection() {
94 delete assembler_;
95 }
96 AddressWithType remote_address_;
97 acl_manager::assembler* assembler_;
98 LeConnectionManagementCallbacks* le_connection_management_callbacks_ = nullptr;
99 };
100
101 struct le_impl : public bluetooth::hci::LeAddressManagerCallback {
le_implle_impl102 le_impl(
103 HciLayer* hci_layer,
104 Controller* controller,
105 os::Handler* handler,
106 RoundRobinScheduler* round_robin_scheduler,
107 bool crash_on_unknown_handle)
108 : hci_layer_(hci_layer), controller_(controller), round_robin_scheduler_(round_robin_scheduler) {
109 hci_layer_ = hci_layer;
110 controller_ = controller;
111 handler_ = handler;
112 connections.crash_on_unknown_handle_ = crash_on_unknown_handle;
113 le_acl_connection_interface_ = hci_layer_->GetLeAclConnectionInterface(
114 handler_->BindOn(this, &le_impl::on_le_event),
115 handler_->BindOn(this, &le_impl::on_le_disconnect),
116 handler_->BindOn(this, &le_impl::on_le_read_remote_version_information));
117 le_address_manager_ = new LeAddressManager(
118 common::Bind(&le_impl::enqueue_command, common::Unretained(this)),
119 handler_,
120 controller->GetMacAddress(),
121 controller->GetLeFilterAcceptListSize(),
122 controller->GetLeResolvingListSize());
123 }
124
~le_implle_impl125 ~le_impl() {
126 if (address_manager_registered) {
127 le_address_manager_->UnregisterSync(this);
128 }
129 delete le_address_manager_;
130 hci_layer_->PutLeAclConnectionInterface();
131 connections.reset();
132 }
133
on_le_eventle_impl134 void on_le_event(LeMetaEventView event_packet) {
135 SubeventCode code = event_packet.GetSubeventCode();
136 switch (code) {
137 case SubeventCode::CONNECTION_COMPLETE:
138 on_le_connection_complete(event_packet);
139 break;
140 case SubeventCode::ENHANCED_CONNECTION_COMPLETE:
141 on_le_enhanced_connection_complete(event_packet);
142 break;
143 case SubeventCode::CONNECTION_UPDATE_COMPLETE:
144 on_le_connection_update_complete(event_packet);
145 break;
146 case SubeventCode::PHY_UPDATE_COMPLETE:
147 on_le_phy_update_complete(event_packet);
148 break;
149 case SubeventCode::DATA_LENGTH_CHANGE:
150 on_data_length_change(event_packet);
151 break;
152 case SubeventCode::REMOTE_CONNECTION_PARAMETER_REQUEST:
153 on_remote_connection_parameter_request(event_packet);
154 break;
155 default:
156 LOG_ALWAYS_FATAL("Unhandled event code %s", SubeventCodeText(code).c_str());
157 }
158 }
159
160 private:
161 static constexpr uint16_t kIllegalConnectionHandle = 0xffff;
162 struct {
163 private:
164 std::map<uint16_t, le_acl_connection> le_acl_connections_;
165 mutable std::mutex le_acl_connections_guard_;
find_callbacksle_impl::__anonbf57f2480108166 LeConnectionManagementCallbacks* find_callbacks(uint16_t handle) {
167 auto connection = le_acl_connections_.find(handle);
168 if (connection == le_acl_connections_.end()) return nullptr;
169 return connection->second.le_connection_management_callbacks_;
170 }
removele_impl::__anonbf57f2480108171 void remove(uint16_t handle) {
172 auto connection = le_acl_connections_.find(handle);
173 if (connection != le_acl_connections_.end()) {
174 connection->second.le_connection_management_callbacks_ = nullptr;
175 le_acl_connections_.erase(handle);
176 }
177 }
178
179 public:
180 bool crash_on_unknown_handle_ = false;
is_emptyle_impl::__anonbf57f2480108181 bool is_empty() const {
182 std::unique_lock<std::mutex> lock(le_acl_connections_guard_);
183 return le_acl_connections_.empty();
184 }
resetle_impl::__anonbf57f2480108185 void reset() {
186 std::unique_lock<std::mutex> lock(le_acl_connections_guard_);
187 le_acl_connections_.clear();
188 }
invalidatele_impl::__anonbf57f2480108189 void invalidate(uint16_t handle) {
190 std::unique_lock<std::mutex> lock(le_acl_connections_guard_);
191 remove(handle);
192 }
193 void execute(
194 uint16_t handle,
195 std::function<void(LeConnectionManagementCallbacks* callbacks)> execute,
196 bool remove_afterwards = false) {
197 std::unique_lock<std::mutex> lock(le_acl_connections_guard_);
198 auto callbacks = find_callbacks(handle);
199 if (callbacks != nullptr)
200 execute(callbacks);
201 else
202 ASSERT_LOG(!crash_on_unknown_handle_, "Received command for unknown handle:0x%x", handle);
203 if (remove_afterwards) remove(handle);
204 }
send_packet_upwardle_impl::__anonbf57f2480108205 bool send_packet_upward(uint16_t handle, std::function<void(struct acl_manager::assembler* assembler)> cb) {
206 std::unique_lock<std::mutex> lock(le_acl_connections_guard_);
207 auto connection = le_acl_connections_.find(handle);
208 if (connection != le_acl_connections_.end()) cb(connection->second.assembler_);
209 return connection != le_acl_connections_.end();
210 }
addle_impl::__anonbf57f2480108211 void add(
212 uint16_t handle,
213 const AddressWithType& remote_address,
214 AclConnection::QueueDownEnd* queue_end,
215 os::Handler* handler,
216 LeConnectionManagementCallbacks* le_connection_management_callbacks) {
217 std::unique_lock<std::mutex> lock(le_acl_connections_guard_);
218 auto emplace_pair = le_acl_connections_.emplace(
219 std::piecewise_construct,
220 std::forward_as_tuple(handle),
221 std::forward_as_tuple(remote_address, queue_end, handler));
222 ASSERT(emplace_pair.second); // Make sure the connection is unique
223 emplace_pair.first->second.le_connection_management_callbacks_ = le_connection_management_callbacks;
224 }
HACK_get_handlele_impl::__anonbf57f2480108225 uint16_t HACK_get_handle(Address address) const {
226 std::unique_lock<std::mutex> lock(le_acl_connections_guard_);
227 for (auto it = le_acl_connections_.begin(); it != le_acl_connections_.end(); it++) {
228 if (it->second.remote_address_.GetAddress() == address) {
229 return it->first;
230 }
231 }
232 return kIllegalConnectionHandle;
233 }
234
getAddressWithTypele_impl::__anonbf57f2480108235 AddressWithType getAddressWithType(uint16_t handle) {
236 std::unique_lock<std::mutex> lock(le_acl_connections_guard_);
237 auto it = le_acl_connections_.find(handle);
238 if (it != le_acl_connections_.end()) {
239 return it->second.remote_address_;
240 }
241 AddressWithType empty(Address::kEmpty, AddressType::RANDOM_DEVICE_ADDRESS);
242 return empty;
243 }
244
alreadyConnectedle_impl::__anonbf57f2480108245 bool alreadyConnected(AddressWithType address_with_type) {
246 for (auto it = le_acl_connections_.begin(); it != le_acl_connections_.end(); it++) {
247 if (it->second.remote_address_ == address_with_type) {
248 return true;
249 }
250 }
251 return false;
252 }
253
254 } connections;
255
256 public:
enqueue_commandle_impl257 void enqueue_command(std::unique_ptr<CommandBuilder> command_packet) {
258 hci_layer_->EnqueueCommand(
259 std::move(command_packet),
260 handler_->BindOnce(&LeAddressManager::OnCommandComplete, common::Unretained(le_address_manager_)));
261 }
262
send_packet_upwardle_impl263 bool send_packet_upward(uint16_t handle, std::function<void(struct acl_manager::assembler* assembler)> cb) {
264 return connections.send_packet_upward(handle, cb);
265 }
266
267 // connection canceled by LeAddressManager.OnPause(), will auto reconnect by LeAddressManager.OnResume()
on_le_connection_canceled_on_pausele_impl268 void on_le_connection_canceled_on_pause() {
269 ASSERT_LOG(pause_connection, "Connection must be paused to ack the le address manager");
270 arm_on_resume_ = true;
271 connectability_state_ = ConnectabilityState::DISARMED;
272 le_address_manager_->AckPause(this);
273 }
274
on_common_le_connection_completele_impl275 void on_common_le_connection_complete(AddressWithType address_with_type) {
276 auto connecting_addr_with_type = connecting_le_.find(address_with_type);
277 if (connecting_addr_with_type == connecting_le_.end()) {
278 LOG_WARN("No prior connection request for %s", address_with_type.ToString().c_str());
279 }
280 connecting_le_.clear();
281
282 if (create_connection_timeout_alarms_.find(address_with_type) != create_connection_timeout_alarms_.end()) {
283 create_connection_timeout_alarms_.at(address_with_type).Cancel();
284 create_connection_timeout_alarms_.erase(address_with_type);
285 }
286 }
287
on_le_connection_completele_impl288 void on_le_connection_complete(LeMetaEventView packet) {
289 LeConnectionCompleteView connection_complete = LeConnectionCompleteView::Create(packet);
290 ASSERT(connection_complete.IsValid());
291 auto status = connection_complete.GetStatus();
292 auto address = connection_complete.GetPeerAddress();
293 auto peer_address_type = connection_complete.GetPeerAddressType();
294 auto role = connection_complete.GetRole();
295 AddressWithType remote_address(address, peer_address_type);
296 AddressWithType local_address = le_address_manager_->GetCurrentAddress();
297 const bool in_filter_accept_list = is_device_in_connect_list(remote_address);
298 auto argument_list = std::vector<std::pair<bluetooth::os::ArgumentType, int>>();
299 argument_list.push_back(
300 std::make_pair(os::ArgumentType::ACL_STATUS_CODE, static_cast<int>(status)));
301
302 bluetooth::os::LogMetricBluetoothLEConnectionMetricEvent(
303 address,
304 android::bluetooth::le::LeConnectionOriginType::ORIGIN_NATIVE,
305 android::bluetooth::le::LeConnectionType::CONNECTION_TYPE_LE_ACL,
306 android::bluetooth::le::LeConnectionState::STATE_LE_ACL_END,
307 argument_list);
308
309 if (role == hci::Role::CENTRAL) {
310 connectability_state_ = ConnectabilityState::DISARMED;
311 if (status == ErrorCode::UNKNOWN_CONNECTION && pause_connection) {
312 on_le_connection_canceled_on_pause();
313 return;
314 }
315 on_common_le_connection_complete(remote_address);
316 if (status == ErrorCode::UNKNOWN_CONNECTION) {
317 if (remote_address.GetAddress() != Address::kEmpty) {
318 LOG_INFO("Controller send non-empty address field:%s", remote_address.GetAddress().ToString().c_str());
319 }
320 // direct connect canceled due to connection timeout, start background connect
321 create_le_connection(remote_address, false, false);
322 return;
323 }
324
325 arm_on_resume_ = false;
326 ready_to_unregister = true;
327 remove_device_from_connect_list(remote_address);
328
329 if (!connect_list.empty()) {
330 AddressWithType empty(Address::kEmpty, AddressType::RANDOM_DEVICE_ADDRESS);
331 handler_->Post(common::BindOnce(&le_impl::create_le_connection, common::Unretained(this), empty, false, false));
332 }
333
334 if (le_client_handler_ == nullptr) {
335 LOG_ERROR("No callbacks to call");
336 return;
337 }
338
339 if (status != ErrorCode::SUCCESS) {
340 le_client_handler_->Post(common::BindOnce(
341 &LeConnectionCallbacks::OnLeConnectFail, common::Unretained(le_client_callbacks_), remote_address, status));
342 return;
343 }
344 } else {
345 LOG_INFO("Received connection complete with Peripheral role");
346 if (le_client_handler_ == nullptr) {
347 LOG_ERROR("No callbacks to call");
348 return;
349 }
350
351 if (status != ErrorCode::SUCCESS) {
352 std::string error_code = ErrorCodeText(status);
353 LOG_WARN("Received on_le_connection_complete with error code %s", error_code.c_str());
354 return;
355 }
356
357 if (in_filter_accept_list) {
358 LOG_INFO(
359 "Received incoming connection of device in filter accept_list, %s",
360 PRIVATE_ADDRESS_WITH_TYPE(remote_address));
361 remove_device_from_connect_list(remote_address);
362 if (create_connection_timeout_alarms_.find(remote_address) != create_connection_timeout_alarms_.end()) {
363 create_connection_timeout_alarms_.at(remote_address).Cancel();
364 create_connection_timeout_alarms_.erase(remote_address);
365 }
366 }
367 }
368
369 uint16_t conn_interval = connection_complete.GetConnInterval();
370 uint16_t conn_latency = connection_complete.GetConnLatency();
371 uint16_t supervision_timeout = connection_complete.GetSupervisionTimeout();
372 if (!check_connection_parameters(conn_interval, conn_interval, conn_latency, supervision_timeout)) {
373 LOG_ERROR("Receive connection complete with invalid connection parameters");
374 return;
375 }
376
377 uint16_t handle = connection_complete.GetConnectionHandle();
378 auto queue = std::make_shared<AclConnection::Queue>(10);
379 auto queue_down_end = queue->GetDownEnd();
380 round_robin_scheduler_->Register(RoundRobinScheduler::ConnectionType::LE, handle, queue);
381 std::unique_ptr<LeAclConnection> connection(new LeAclConnection(
382 std::move(queue), le_acl_connection_interface_, handle, local_address, remote_address, role));
383 connection->peer_address_with_type_ = AddressWithType(address, peer_address_type);
384 connection->interval_ = conn_interval;
385 connection->latency_ = conn_latency;
386 connection->supervision_timeout_ = supervision_timeout;
387 connection->in_filter_accept_list_ = in_filter_accept_list;
388 connections.add(
389 handle, remote_address, queue_down_end, handler_, connection->GetEventCallbacks([this](uint16_t handle) {
390 this->connections.invalidate(handle);
391 }));
392 le_client_handler_->Post(common::BindOnce(&LeConnectionCallbacks::OnLeConnectSuccess,
393 common::Unretained(le_client_callbacks_), remote_address,
394 std::move(connection)));
395 }
396
on_le_enhanced_connection_completele_impl397 void on_le_enhanced_connection_complete(LeMetaEventView packet) {
398 LeEnhancedConnectionCompleteView connection_complete = LeEnhancedConnectionCompleteView::Create(packet);
399 ASSERT(connection_complete.IsValid());
400 auto status = connection_complete.GetStatus();
401 auto address = connection_complete.GetPeerAddress();
402 auto peer_address_type = connection_complete.GetPeerAddressType();
403 auto peer_resolvable_address = connection_complete.GetPeerResolvablePrivateAddress();
404 auto role = connection_complete.GetRole();
405
406 AddressType remote_address_type;
407 switch (peer_address_type) {
408 case AddressType::PUBLIC_DEVICE_ADDRESS:
409 case AddressType::PUBLIC_IDENTITY_ADDRESS:
410 remote_address_type = AddressType::PUBLIC_DEVICE_ADDRESS;
411 break;
412 case AddressType::RANDOM_DEVICE_ADDRESS:
413 case AddressType::RANDOM_IDENTITY_ADDRESS:
414 remote_address_type = AddressType::RANDOM_DEVICE_ADDRESS;
415 break;
416 }
417 AddressWithType remote_address(address, remote_address_type);
418 const bool in_filter_accept_list = is_device_in_connect_list(remote_address);
419 auto argument_list = std::vector<std::pair<bluetooth::os::ArgumentType, int>>();
420 argument_list.push_back(
421 std::make_pair(os::ArgumentType::ACL_STATUS_CODE, static_cast<int>(status)));
422
423 bluetooth::os::LogMetricBluetoothLEConnectionMetricEvent(
424 address,
425 android::bluetooth::le::LeConnectionOriginType::ORIGIN_NATIVE,
426 android::bluetooth::le::LeConnectionType::CONNECTION_TYPE_LE_ACL,
427 android::bluetooth::le::LeConnectionState::STATE_LE_ACL_END,
428 argument_list);
429
430 if (role == hci::Role::CENTRAL) {
431 connectability_state_ = ConnectabilityState::DISARMED;
432
433 if (status == ErrorCode::UNKNOWN_CONNECTION && pause_connection) {
434 on_le_connection_canceled_on_pause();
435 return;
436 }
437
438 on_common_le_connection_complete(remote_address);
439 if (status == ErrorCode::UNKNOWN_CONNECTION) {
440 if (remote_address.GetAddress() != Address::kEmpty) {
441 LOG_INFO("Controller send non-empty address field:%s", remote_address.GetAddress().ToString().c_str());
442 }
443 // direct connect canceled due to connection timeout, start background connect
444 create_le_connection(remote_address, false, false);
445 return;
446 }
447
448 arm_on_resume_ = false;
449 ready_to_unregister = true;
450 remove_device_from_connect_list(remote_address);
451
452 if (!connect_list.empty()) {
453 AddressWithType empty(Address::kEmpty, AddressType::RANDOM_DEVICE_ADDRESS);
454 handler_->Post(common::BindOnce(&le_impl::create_le_connection, common::Unretained(this), empty, false, false));
455 }
456
457 if (le_client_handler_ == nullptr) {
458 LOG_ERROR("No callbacks to call");
459 return;
460 }
461
462 if (status != ErrorCode::SUCCESS) {
463 le_client_handler_->Post(common::BindOnce(
464 &LeConnectionCallbacks::OnLeConnectFail, common::Unretained(le_client_callbacks_), remote_address, status));
465 return;
466 }
467
468 } else {
469 LOG_INFO("Received connection complete with Peripheral role");
470 if (le_client_handler_ == nullptr) {
471 LOG_ERROR("No callbacks to call");
472 return;
473 }
474
475 if (status != ErrorCode::SUCCESS) {
476 std::string error_code = ErrorCodeText(status);
477 LOG_WARN("Received on_le_enhanced_connection_complete with error code %s", error_code.c_str());
478 return;
479 }
480
481 if (in_filter_accept_list) {
482 LOG_INFO(
483 "Received incoming connection of device in filter accept_list, %s",
484 PRIVATE_ADDRESS_WITH_TYPE(remote_address));
485 remove_device_from_connect_list(remote_address);
486 if (create_connection_timeout_alarms_.find(remote_address) != create_connection_timeout_alarms_.end()) {
487 create_connection_timeout_alarms_.at(remote_address).Cancel();
488 create_connection_timeout_alarms_.erase(remote_address);
489 }
490 }
491 }
492
493 AddressWithType local_address;
494 if (role == hci::Role::CENTRAL) {
495 local_address = le_address_manager_->GetCurrentAddress();
496 } else {
497 // when accepting connection, we must obtain the address from the advertiser.
498 // When we receive "set terminated event", we associate connection handle with advertiser address
499 local_address = AddressWithType{};
500 }
501
502 uint16_t conn_interval = connection_complete.GetConnInterval();
503 uint16_t conn_latency = connection_complete.GetConnLatency();
504 uint16_t supervision_timeout = connection_complete.GetSupervisionTimeout();
505 if (!check_connection_parameters(conn_interval, conn_interval, conn_latency, supervision_timeout)) {
506 LOG_ERROR("Receive enhenced connection complete with invalid connection parameters");
507 return;
508 }
509 uint16_t handle = connection_complete.GetConnectionHandle();
510 auto queue = std::make_shared<AclConnection::Queue>(10);
511 auto queue_down_end = queue->GetDownEnd();
512 round_robin_scheduler_->Register(RoundRobinScheduler::ConnectionType::LE, handle, queue);
513 std::unique_ptr<LeAclConnection> connection(new LeAclConnection(
514 std::move(queue), le_acl_connection_interface_, handle, local_address, remote_address, role));
515 connection->peer_address_with_type_ = AddressWithType(address, peer_address_type);
516 connection->interval_ = conn_interval;
517 connection->latency_ = conn_latency;
518 connection->supervision_timeout_ = supervision_timeout;
519 connection->local_resolvable_private_address_ = connection_complete.GetLocalResolvablePrivateAddress();
520 connection->peer_resolvable_private_address_ = connection_complete.GetPeerResolvablePrivateAddress();
521 connection->in_filter_accept_list_ = in_filter_accept_list;
522 connections.add(
523 handle, remote_address, queue_down_end, handler_, connection->GetEventCallbacks([this](uint16_t handle) {
524 this->connections.invalidate(handle);
525 }));
526 le_client_handler_->Post(common::BindOnce(&LeConnectionCallbacks::OnLeConnectSuccess,
527 common::Unretained(le_client_callbacks_), remote_address,
528 std::move(connection)));
529 }
530
531 static constexpr bool kRemoveConnectionAfterwards = true;
on_le_disconnectle_impl532 void on_le_disconnect(uint16_t handle, ErrorCode reason) {
533 AddressWithType remote_address = connections.getAddressWithType(handle);
534 bool event_also_routes_to_other_receivers = connections.crash_on_unknown_handle_;
535 connections.crash_on_unknown_handle_ = false;
536 connections.execute(
537 handle,
538 [=](LeConnectionManagementCallbacks* callbacks) {
539 round_robin_scheduler_->Unregister(handle);
540 callbacks->OnDisconnection(reason);
541 },
542 kRemoveConnectionAfterwards);
543 connections.crash_on_unknown_handle_ = event_also_routes_to_other_receivers;
544
545 if (background_connections_.count(remote_address) == 1) {
546 LOG_INFO("re-add device to connect list");
547 arm_on_resume_ = true;
548 add_device_to_connect_list(remote_address);
549 }
550 }
551
on_le_connection_update_completele_impl552 void on_le_connection_update_complete(LeMetaEventView view) {
553 auto complete_view = LeConnectionUpdateCompleteView::Create(view);
554 if (!complete_view.IsValid()) {
555 LOG_ERROR("Received on_le_connection_update_complete with invalid packet");
556 return;
557 }
558 auto handle = complete_view.GetConnectionHandle();
559 connections.execute(handle, [=](LeConnectionManagementCallbacks* callbacks) {
560 callbacks->OnConnectionUpdate(
561 complete_view.GetStatus(),
562 complete_view.GetConnInterval(),
563 complete_view.GetConnLatency(),
564 complete_view.GetSupervisionTimeout());
565 });
566 }
567
on_le_phy_update_completele_impl568 void on_le_phy_update_complete(LeMetaEventView view) {
569 auto complete_view = LePhyUpdateCompleteView::Create(view);
570 if (!complete_view.IsValid()) {
571 LOG_ERROR("Received on_le_phy_update_complete with invalid packet");
572 return;
573 }
574 auto handle = complete_view.GetConnectionHandle();
575 connections.execute(handle, [=](LeConnectionManagementCallbacks* callbacks) {
576 callbacks->OnPhyUpdate(complete_view.GetStatus(), complete_view.GetTxPhy(), complete_view.GetRxPhy());
577 });
578 }
579
on_le_read_remote_version_informationle_impl580 void on_le_read_remote_version_information(
581 hci::ErrorCode hci_status, uint16_t handle, uint8_t version, uint16_t manufacturer_name, uint16_t sub_version) {
582 connections.execute(handle, [=](LeConnectionManagementCallbacks* callbacks) {
583 callbacks->OnReadRemoteVersionInformationComplete(hci_status, version, manufacturer_name, sub_version);
584 });
585 }
586
on_data_length_changele_impl587 void on_data_length_change(LeMetaEventView view) {
588 auto data_length_view = LeDataLengthChangeView::Create(view);
589 if (!data_length_view.IsValid()) {
590 LOG_ERROR("Invalid packet");
591 return;
592 }
593 auto handle = data_length_view.GetConnectionHandle();
594 connections.execute(handle, [=](LeConnectionManagementCallbacks* callbacks) {
595 callbacks->OnDataLengthChange(
596 data_length_view.GetMaxTxOctets(),
597 data_length_view.GetMaxTxTime(),
598 data_length_view.GetMaxRxOctets(),
599 data_length_view.GetMaxRxTime());
600 });
601 }
602
on_remote_connection_parameter_requestle_impl603 void on_remote_connection_parameter_request(LeMetaEventView view) {
604 auto request_view = LeRemoteConnectionParameterRequestView::Create(view);
605 if (!request_view.IsValid()) {
606 LOG_ERROR("Invalid packet");
607 return;
608 }
609
610 auto handle = request_view.GetConnectionHandle();
611 connections.execute(handle, [=](LeConnectionManagementCallbacks* callbacks) {
612 // TODO: this is blindly accepting any parameters, just so we don't hang connection
613 // have proper parameter negotiation
614 le_acl_connection_interface_->EnqueueCommand(
615 LeRemoteConnectionParameterRequestReplyBuilder::Create(
616 handle,
617 request_view.GetIntervalMin(),
618 request_view.GetIntervalMax(),
619 request_view.GetLatency(),
620 request_view.GetTimeout(),
621 0,
622 0),
623 handler_->BindOnce([](CommandCompleteView status) {}));
624 });
625 }
626
HACK_get_handlele_impl627 uint16_t HACK_get_handle(Address address) {
628 return connections.HACK_get_handle(address);
629 }
630
UpdateLocalAddressle_impl631 void UpdateLocalAddress(uint16_t handle, hci::AddressWithType address_with_type) {
632 connections.execute(handle, [=](LeConnectionManagementCallbacks* callbacks) {
633 callbacks->OnLocalAddressUpdate(address_with_type);
634 });
635 }
636
add_device_to_connect_listle_impl637 void add_device_to_connect_list(AddressWithType address_with_type) {
638 if (connections.alreadyConnected(address_with_type)) {
639 LOG_INFO("Device already connected, return");
640 return;
641 }
642
643 if (connect_list.find(address_with_type) != connect_list.end()) {
644 LOG_WARN(
645 "Device already exists in acceptlist and cannot be added:%s", PRIVATE_ADDRESS_WITH_TYPE(address_with_type));
646 return;
647 }
648
649 connect_list.insert(address_with_type);
650 register_with_address_manager();
651 le_address_manager_->AddDeviceToFilterAcceptList(
652 address_with_type.ToFilterAcceptListAddressType(), address_with_type.GetAddress());
653 }
654
is_device_in_connect_listle_impl655 bool is_device_in_connect_list(AddressWithType address_with_type) {
656 return (connect_list.find(address_with_type) != connect_list.end());
657 }
658
remove_device_from_connect_listle_impl659 void remove_device_from_connect_list(AddressWithType address_with_type) {
660 if (connect_list.find(address_with_type) == connect_list.end()) {
661 LOG_WARN("Device not in acceptlist and cannot be removed:%s", PRIVATE_ADDRESS_WITH_TYPE(address_with_type));
662 return;
663 }
664 connect_list.erase(address_with_type);
665 connecting_le_.erase(address_with_type);
666 direct_connections_.erase(address_with_type);
667 register_with_address_manager();
668 le_address_manager_->RemoveDeviceFromFilterAcceptList(
669 address_with_type.ToFilterAcceptListAddressType(), address_with_type.GetAddress());
670 }
671
clear_connect_listle_impl672 void clear_connect_list() {
673 connect_list.clear();
674 register_with_address_manager();
675 le_address_manager_->ClearFilterAcceptList();
676 }
677
add_device_to_resolving_listle_impl678 void add_device_to_resolving_list(
679 AddressWithType address_with_type,
680 const std::array<uint8_t, 16>& peer_irk,
681 const std::array<uint8_t, 16>& local_irk) {
682 register_with_address_manager();
683 le_address_manager_->AddDeviceToResolvingList(
684 address_with_type.ToPeerAddressType(), address_with_type.GetAddress(), peer_irk, local_irk);
685 }
686
remove_device_from_resolving_listle_impl687 void remove_device_from_resolving_list(AddressWithType address_with_type) {
688 register_with_address_manager();
689 le_address_manager_->RemoveDeviceFromResolvingList(
690 address_with_type.ToPeerAddressType(), address_with_type.GetAddress());
691 }
692
update_connectability_state_after_armedle_impl693 void update_connectability_state_after_armed(const ErrorCode& status) {
694 switch (connectability_state_) {
695 case ConnectabilityState::DISARMED:
696 case ConnectabilityState::ARMED:
697 case ConnectabilityState::DISARMING:
698 LOG_ERROR(
699 "Received connectability arm notification for unexpected state:%s status:%s",
700 connectability_state_machine_text(connectability_state_).c_str(),
701 ErrorCodeText(status).c_str());
702 break;
703 case ConnectabilityState::ARMING:
704 if (status != ErrorCode::SUCCESS) {
705 LOG_ERROR("Le connection state machine armed failed status:%s", ErrorCodeText(status).c_str());
706 }
707 connectability_state_ =
708 (status == ErrorCode::SUCCESS) ? ConnectabilityState::ARMED : ConnectabilityState::DISARMED;
709 LOG_INFO(
710 "Le connection state machine armed state:%s status:%s",
711 connectability_state_machine_text(connectability_state_).c_str(),
712 ErrorCodeText(status).c_str());
713 if (disarmed_while_arming_) {
714 disarmed_while_arming_ = false;
715 disarm_connectability();
716 }
717 }
718 }
719
on_extended_create_connectionle_impl720 void on_extended_create_connection(CommandStatusView status) {
721 ASSERT(status.IsValid());
722 ASSERT(status.GetCommandOpCode() == OpCode::LE_EXTENDED_CREATE_CONNECTION);
723 update_connectability_state_after_armed(status.GetStatus());
724 }
725
on_create_connectionle_impl726 void on_create_connection(CommandStatusView status) {
727 ASSERT(status.IsValid());
728 ASSERT(status.GetCommandOpCode() == OpCode::LE_CREATE_CONNECTION);
729 update_connectability_state_after_armed(status.GetStatus());
730 }
731
arm_connectabilityle_impl732 void arm_connectability() {
733 if (connectability_state_ != ConnectabilityState::DISARMED) {
734 LOG_ERROR(
735 "Attempting to re-arm le connection state machine in unexpected state:%s",
736 connectability_state_machine_text(connectability_state_).c_str());
737 return;
738 }
739 if (connect_list.empty()) {
740 LOG_INFO("Ignored request to re-arm le connection state machine when filter accept list is empty");
741 return;
742 }
743 AddressWithType empty(Address::kEmpty, AddressType::RANDOM_DEVICE_ADDRESS);
744 connectability_state_ = ConnectabilityState::ARMING;
745 connecting_le_ = connect_list;
746
747 uint16_t le_scan_interval = kScanIntervalSlow;
748 uint16_t le_scan_window = kScanWindowSlow;
749 uint16_t le_scan_window_2m = kScanWindowSlow;
750 uint16_t le_scan_window_coded = kScanWindowSlow;
751 // If there is any direct connection in the connection list, use the fast parameter
752 if (!direct_connections_.empty()) {
753 le_scan_interval = kScanIntervalFast;
754 le_scan_window = kScanWindowFast;
755 le_scan_window_2m = kScanWindow2mFast;
756 le_scan_window_coded = kScanWindowCodedFast;
757 }
758 InitiatorFilterPolicy initiator_filter_policy = InitiatorFilterPolicy::USE_FILTER_ACCEPT_LIST;
759 OwnAddressType own_address_type =
760 static_cast<OwnAddressType>(le_address_manager_->GetCurrentAddress().GetAddressType());
761 uint16_t conn_interval_min = 0x0018;
762 uint16_t conn_interval_max = 0x0028;
763 uint16_t conn_latency = 0x0000;
764 uint16_t supervision_timeout = 0x001f4;
765 ASSERT(check_connection_parameters(conn_interval_min, conn_interval_max, conn_latency, supervision_timeout));
766
767 AddressWithType address_with_type = connection_peer_address_with_type_;
768 if (initiator_filter_policy == InitiatorFilterPolicy::USE_FILTER_ACCEPT_LIST) {
769 address_with_type = AddressWithType();
770 }
771
772 if (controller_->IsSupported(OpCode::LE_EXTENDED_CREATE_CONNECTION)) {
773 uint8_t initiating_phys = PHY_LE_1M;
774 std::vector<LeCreateConnPhyScanParameters> parameters = {};
775 LeCreateConnPhyScanParameters scan_parameters;
776 scan_parameters.scan_interval_ = le_scan_interval;
777 scan_parameters.scan_window_ = le_scan_window;
778 scan_parameters.conn_interval_min_ = conn_interval_min;
779 scan_parameters.conn_interval_max_ = conn_interval_max;
780 scan_parameters.conn_latency_ = conn_latency;
781 scan_parameters.supervision_timeout_ = supervision_timeout;
782 scan_parameters.min_ce_length_ = 0x00;
783 scan_parameters.max_ce_length_ = 0x00;
784 parameters.push_back(scan_parameters);
785
786 if (controller_->SupportsBle2mPhy()) {
787 LeCreateConnPhyScanParameters scan_parameters_2m;
788 scan_parameters_2m.scan_interval_ = le_scan_interval;
789 scan_parameters_2m.scan_window_ = le_scan_window_2m;
790 scan_parameters_2m.conn_interval_min_ = conn_interval_min;
791 scan_parameters_2m.conn_interval_max_ = conn_interval_max;
792 scan_parameters_2m.conn_latency_ = conn_latency;
793 scan_parameters_2m.supervision_timeout_ = supervision_timeout;
794 scan_parameters_2m.min_ce_length_ = 0x00;
795 scan_parameters_2m.max_ce_length_ = 0x00;
796 parameters.push_back(scan_parameters_2m);
797 initiating_phys |= PHY_LE_2M;
798 }
799 if (controller_->SupportsBleCodedPhy()) {
800 LeCreateConnPhyScanParameters scan_parameters_coded;
801 scan_parameters_coded.scan_interval_ = le_scan_interval;
802 scan_parameters_coded.scan_window_ = le_scan_window_coded;
803 scan_parameters_coded.conn_interval_min_ = conn_interval_min;
804 scan_parameters_coded.conn_interval_max_ = conn_interval_max;
805 scan_parameters_coded.conn_latency_ = conn_latency;
806 scan_parameters_coded.supervision_timeout_ = supervision_timeout;
807 scan_parameters_coded.min_ce_length_ = 0x00;
808 scan_parameters_coded.max_ce_length_ = 0x00;
809 parameters.push_back(scan_parameters_coded);
810 initiating_phys |= PHY_LE_CODED;
811 }
812
813 le_acl_connection_interface_->EnqueueCommand(
814 LeExtendedCreateConnectionBuilder::Create(
815 initiator_filter_policy,
816 own_address_type,
817 address_with_type.GetAddressType(),
818 address_with_type.GetAddress(),
819 initiating_phys,
820 parameters),
821 handler_->BindOnce(&le_impl::on_extended_create_connection, common::Unretained(this)));
822 } else {
823 le_acl_connection_interface_->EnqueueCommand(
824 LeCreateConnectionBuilder::Create(
825 le_scan_interval,
826 le_scan_window,
827 initiator_filter_policy,
828 address_with_type.GetAddressType(),
829 address_with_type.GetAddress(),
830 own_address_type,
831 conn_interval_min,
832 conn_interval_max,
833 conn_latency,
834 supervision_timeout,
835 0x00,
836 0x00),
837 handler_->BindOnce(&le_impl::on_create_connection, common::Unretained(this)));
838 }
839 }
840
disarm_connectabilityle_impl841 void disarm_connectability() {
842
843 auto argument_list = std::vector<std::pair<os::ArgumentType, int>>();
844 bluetooth::os::LogMetricBluetoothLEConnectionMetricEvent(
845 Address::kEmpty,
846 os::LeConnectionOriginType::ORIGIN_UNSPECIFIED,
847 os::LeConnectionType::CONNECTION_TYPE_LE_ACL,
848 os::LeConnectionState::STATE_LE_ACL_CANCEL,
849 argument_list);
850
851 switch (connectability_state_) {
852 case ConnectabilityState::ARMED:
853 LOG_INFO("Disarming LE connection state machine with create connection cancel");
854 connectability_state_ = ConnectabilityState::DISARMING;
855 le_acl_connection_interface_->EnqueueCommand(
856 LeCreateConnectionCancelBuilder::Create(),
857 handler_->BindOnce(&le_impl::on_create_connection_cancel_complete, common::Unretained(this)));
858 break;
859
860 case ConnectabilityState::ARMING:
861 LOG_INFO("Queueing cancel connect until after connection state machine is armed");
862 disarmed_while_arming_ = true;
863 break;
864 case ConnectabilityState::DISARMING:
865 case ConnectabilityState::DISARMED:
866 LOG_ERROR(
867 "Attempting to disarm le connection state machine in unexpected state:%s",
868 connectability_state_machine_text(connectability_state_).c_str());
869 break;
870 }
871 }
872
create_le_connectionle_impl873 void create_le_connection(AddressWithType address_with_type, bool add_to_connect_list, bool is_direct) {
874 if (le_client_callbacks_ == nullptr) {
875 LOG_ERROR("No callbacks to call");
876 return;
877 }
878
879 if (connections.alreadyConnected(address_with_type)) {
880 LOG_INFO("Device already connected, return");
881 return;
882 }
883
884 // TODO: Configure default LE connection parameters?
885 if (add_to_connect_list) {
886 add_device_to_connect_list(address_with_type);
887 if (is_direct) {
888 direct_connections_.insert(address_with_type);
889 if (create_connection_timeout_alarms_.find(address_with_type) == create_connection_timeout_alarms_.end()) {
890 create_connection_timeout_alarms_.emplace(
891 std::piecewise_construct,
892 std::forward_as_tuple(address_with_type.GetAddress(), address_with_type.GetAddressType()),
893 std::forward_as_tuple(handler_));
894 create_connection_timeout_alarms_.at(address_with_type)
895 .Schedule(
896 common::BindOnce(&le_impl::on_create_connection_timeout, common::Unretained(this), address_with_type),
897 kCreateConnectionTimeoutMs);
898 }
899 }
900 }
901
902 if (!address_manager_registered) {
903 auto policy = le_address_manager_->Register(this);
904 address_manager_registered = true;
905
906 // Pause connection, wait for set random address complete
907 if (policy == LeAddressManager::AddressPolicy::USE_RESOLVABLE_ADDRESS ||
908 policy == LeAddressManager::AddressPolicy::USE_NON_RESOLVABLE_ADDRESS) {
909 pause_connection = true;
910 }
911 }
912
913 if (pause_connection) {
914 arm_on_resume_ = true;
915 return;
916 }
917
918 switch (connectability_state_) {
919 case ConnectabilityState::ARMED:
920 case ConnectabilityState::ARMING:
921 // Ignored, if we add new device to the filter accept list, create connection command will be sent by OnResume.
922 LOG_DEBUG(
923 "Deferred until filter accept list updated create connection state %s",
924 connectability_state_machine_text(connectability_state_).c_str());
925 break;
926 default:
927 // If we added to filter accept list then the arming of the le state machine
928 // must wait until the filter accept list command as completed
929 if (add_to_connect_list) {
930 arm_on_resume_ = true;
931 LOG_DEBUG("Deferred until filter accept list has completed");
932 } else {
933 handler_->CallOn(this, &le_impl::arm_connectability);
934 }
935 break;
936 }
937 }
938
on_create_connection_timeoutle_impl939 void on_create_connection_timeout(AddressWithType address_with_type) {
940 LOG_INFO("on_create_connection_timeout, address: %s", address_with_type.ToString().c_str());
941 if (create_connection_timeout_alarms_.find(address_with_type) != create_connection_timeout_alarms_.end()) {
942 create_connection_timeout_alarms_.at(address_with_type).Cancel();
943 create_connection_timeout_alarms_.erase(address_with_type);
944 auto argument_list = std::vector<std::pair<os::ArgumentType, int>>();
945 argument_list.push_back(std::make_pair(
946 os::ArgumentType::ACL_STATUS_CODE,
947 static_cast<int>(android::bluetooth::hci::StatusEnum::STATUS_CONNECTION_TOUT)));
948 bluetooth::os::LogMetricBluetoothLEConnectionMetricEvent(
949 address_with_type.GetAddress(),
950 android::bluetooth::le::LeConnectionOriginType::ORIGIN_NATIVE,
951 android::bluetooth::le::LeConnectionType::CONNECTION_TYPE_LE_ACL,
952 android::bluetooth::le::LeConnectionState::STATE_LE_ACL_TIMEOUT,
953 argument_list);
954
955 if (background_connections_.find(address_with_type) != background_connections_.end()) {
956 direct_connections_.erase(address_with_type);
957 disarm_connectability();
958 } else {
959 cancel_connect(address_with_type);
960 }
961 le_client_handler_->Post(common::BindOnce(
962 &LeConnectionCallbacks::OnLeConnectFail,
963 common::Unretained(le_client_callbacks_),
964 address_with_type,
965 ErrorCode::CONNECTION_ACCEPT_TIMEOUT));
966 }
967 }
968
cancel_connectle_impl969 void cancel_connect(AddressWithType address_with_type) {
970 // Remove any alarms for this peer, if any
971 if (create_connection_timeout_alarms_.find(address_with_type) != create_connection_timeout_alarms_.end()) {
972 create_connection_timeout_alarms_.at(address_with_type).Cancel();
973 create_connection_timeout_alarms_.erase(address_with_type);
974 }
975 // the connection will be canceled by LeAddressManager.OnPause()
976 remove_device_from_connect_list(address_with_type);
977 }
978
set_le_suggested_default_data_parametersle_impl979 void set_le_suggested_default_data_parameters(uint16_t length, uint16_t time) {
980 auto packet = LeWriteSuggestedDefaultDataLengthBuilder::Create(length, time);
981 le_acl_connection_interface_->EnqueueCommand(
982 std::move(packet), handler_->BindOnce([](CommandCompleteView complete) {}));
983 }
984
clear_resolving_listle_impl985 void clear_resolving_list() {
986 le_address_manager_->ClearResolvingList();
987 }
988
set_privacy_policy_for_initiator_addressle_impl989 void set_privacy_policy_for_initiator_address(
990 LeAddressManager::AddressPolicy address_policy,
991 AddressWithType fixed_address,
992 crypto_toolbox::Octet16 rotation_irk,
993 std::chrono::milliseconds minimum_rotation_time,
994 std::chrono::milliseconds maximum_rotation_time) {
995 le_address_manager_->SetPrivacyPolicyForInitiatorAddress(
996 address_policy,
997 fixed_address,
998 rotation_irk,
999 controller_->SupportsBlePrivacy(),
1000 minimum_rotation_time,
1001 maximum_rotation_time);
1002 }
1003
1004 // TODO(jpawlowski): remove once we have config file abstraction in cert tests
set_privacy_policy_for_initiator_address_for_testle_impl1005 void set_privacy_policy_for_initiator_address_for_test(
1006 LeAddressManager::AddressPolicy address_policy,
1007 AddressWithType fixed_address,
1008 crypto_toolbox::Octet16 rotation_irk,
1009 std::chrono::milliseconds minimum_rotation_time,
1010 std::chrono::milliseconds maximum_rotation_time) {
1011 le_address_manager_->SetPrivacyPolicyForInitiatorAddressForTest(
1012 address_policy, fixed_address, rotation_irk, minimum_rotation_time, maximum_rotation_time);
1013 }
1014
handle_register_le_callbacksle_impl1015 void handle_register_le_callbacks(LeConnectionCallbacks* callbacks, os::Handler* handler) {
1016 ASSERT(le_client_callbacks_ == nullptr);
1017 ASSERT(le_client_handler_ == nullptr);
1018 le_client_callbacks_ = callbacks;
1019 le_client_handler_ = handler;
1020 }
1021
handle_unregister_le_callbacksle_impl1022 void handle_unregister_le_callbacks(LeConnectionCallbacks* callbacks, std::promise<void> promise) {
1023 ASSERT_LOG(le_client_callbacks_ == callbacks, "Registered le callback entity is different then unregister request");
1024 le_client_callbacks_ = nullptr;
1025 le_client_handler_ = nullptr;
1026 promise.set_value();
1027 }
1028
check_connection_parametersle_impl1029 bool check_connection_parameters(
1030 uint16_t conn_interval_min, uint16_t conn_interval_max, uint16_t conn_latency, uint16_t supervision_timeout) {
1031 if (conn_interval_min < 0x0006 || conn_interval_min > 0x0C80 || conn_interval_max < 0x0006 ||
1032 conn_interval_max > 0x0C80 || conn_latency > 0x01F3 || supervision_timeout < 0x000A ||
1033 supervision_timeout > 0x0C80) {
1034 LOG_ERROR("Invalid parameter");
1035 return false;
1036 }
1037
1038 // The Maximum interval in milliseconds will be conn_interval_max * 1.25 ms
1039 // The Timeout in milliseconds will be expected_supervision_timeout * 10 ms
1040 // The Timeout in milliseconds shall be larger than (1 + Latency) * Interval_Max * 2, where Interval_Max is given in
1041 // milliseconds.
1042 uint32_t supervision_timeout_min = (uint32_t)(1 + conn_latency) * conn_interval_max * 2 + 1;
1043 if (supervision_timeout * 8 < supervision_timeout_min || conn_interval_max < conn_interval_min) {
1044 LOG_ERROR("Invalid parameter");
1045 return false;
1046 }
1047
1048 return true;
1049 }
1050
add_device_to_background_connection_listle_impl1051 void add_device_to_background_connection_list(AddressWithType address_with_type) {
1052 background_connections_.insert(address_with_type);
1053 }
1054
remove_device_from_background_connection_listle_impl1055 void remove_device_from_background_connection_list(AddressWithType address_with_type) {
1056 background_connections_.erase(address_with_type);
1057 }
1058
is_on_background_connection_listle_impl1059 void is_on_background_connection_list(AddressWithType address_with_type, std::promise<bool> promise) {
1060 promise.set_value(background_connections_.find(address_with_type) != background_connections_.end());
1061 }
1062
cancel_connection_and_remove_device_from_background_connection_listle_impl1063 void cancel_connection_and_remove_device_from_background_connection_list(AddressWithType address_with_type) {
1064 remove_device_from_background_connection_list(address_with_type);
1065 cancel_connect(address_with_type);
1066 }
1067
OnPausele_impl1068 void OnPause() override { // bluetooth::hci::LeAddressManagerCallback
1069 if (!address_manager_registered) {
1070 LOG_WARN("Unregistered!");
1071 return;
1072 }
1073 pause_connection = true;
1074 if (connectability_state_ == ConnectabilityState::DISARMED) {
1075 le_address_manager_->AckPause(this);
1076 return;
1077 }
1078 arm_on_resume_ = !connecting_le_.empty();
1079 disarm_connectability();
1080 }
1081
OnResumele_impl1082 void OnResume() override { // bluetooth::hci::LeAddressManagerCallback
1083 if (!address_manager_registered) {
1084 LOG_WARN("Unregistered!");
1085 return;
1086 }
1087 pause_connection = false;
1088 if (arm_on_resume_) {
1089 arm_connectability();
1090 }
1091 arm_on_resume_ = false;
1092 le_address_manager_->AckResume(this);
1093 check_for_unregister();
1094 }
1095
on_create_connection_cancel_completele_impl1096 void on_create_connection_cancel_complete(CommandCompleteView view) {
1097 auto complete_view = LeCreateConnectionCancelCompleteView::Create(view);
1098 ASSERT(complete_view.IsValid());
1099 if (complete_view.GetStatus() != ErrorCode::SUCCESS) {
1100 auto status = complete_view.GetStatus();
1101 std::string error_code = ErrorCodeText(status);
1102 LOG_WARN("Received on_create_connection_cancel_complete with error code %s", error_code.c_str());
1103 if (pause_connection) {
1104 LOG_WARN("AckPause");
1105 le_address_manager_->AckPause(this);
1106 return;
1107 }
1108 }
1109 if (connectability_state_ != ConnectabilityState::DISARMING) {
1110 LOG_ERROR(
1111 "Attempting to disarm le connection state machine in unexpected state:%s",
1112 connectability_state_machine_text(connectability_state_).c_str());
1113 }
1114 }
1115
register_with_address_managerle_impl1116 void register_with_address_manager() {
1117 if (!address_manager_registered) {
1118 le_address_manager_->Register(this);
1119 address_manager_registered = true;
1120 pause_connection = true;
1121 }
1122 }
1123
check_for_unregisterle_impl1124 void check_for_unregister() {
1125 if (connections.is_empty() && connecting_le_.empty() && address_manager_registered && ready_to_unregister) {
1126 le_address_manager_->Unregister(this);
1127 address_manager_registered = false;
1128 pause_connection = false;
1129 ready_to_unregister = false;
1130 }
1131 }
1132
1133 HciLayer* hci_layer_ = nullptr;
1134 Controller* controller_ = nullptr;
1135 os::Handler* handler_ = nullptr;
1136 RoundRobinScheduler* round_robin_scheduler_ = nullptr;
1137 LeAddressManager* le_address_manager_ = nullptr;
1138 LeAclConnectionInterface* le_acl_connection_interface_ = nullptr;
1139 LeConnectionCallbacks* le_client_callbacks_ = nullptr;
1140 os::Handler* le_client_handler_ = nullptr;
1141 std::unordered_set<AddressWithType> connecting_le_;
1142 bool arm_on_resume_;
1143 std::unordered_set<AddressWithType> direct_connections_;
1144 // Set of devices that will not be removed from connect list after direct connect timeout
1145 std::unordered_set<AddressWithType> background_connections_;
1146 std::unordered_set<AddressWithType> connect_list;
1147 AddressWithType connection_peer_address_with_type_; // Direct peer address UNSUPPORTEDD
1148 bool address_manager_registered = false;
1149 bool ready_to_unregister = false;
1150 bool pause_connection = false;
1151 bool disarmed_while_arming_ = false;
1152 ConnectabilityState connectability_state_{ConnectabilityState::DISARMED};
1153 std::map<AddressWithType, os::Alarm> create_connection_timeout_alarms_;
1154 };
1155
1156 #undef PRIVATE_ADDRESS_WITH_TYPE
1157
1158 } // namespace acl_manager
1159 } // namespace hci
1160 } // namespace bluetooth
1161