1 /*
2  * Copyright 2019 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 #include "hci/acl_manager.h"
18 
19 #include <future>
20 #include <queue>
21 #include <set>
22 #include <utility>
23 
24 #include "acl_fragmenter.h"
25 #include "acl_manager.h"
26 #include "common/bidi_queue.h"
27 #include "hci/controller.h"
28 #include "hci/hci_layer.h"
29 
30 namespace bluetooth {
31 namespace hci {
32 
33 constexpr uint16_t kQualcommDebugHandle = 0xedc;
34 constexpr size_t kMaxQueuedPacketsPerConnection = 10;
35 
36 using common::Bind;
37 using common::BindOnce;
38 
39 namespace {
40 class PacketViewForRecombination : public packet::PacketView<kLittleEndian> {
41  public:
42   PacketViewForRecombination(const PacketView& packetView) : PacketView(packetView) {}
43   void AppendPacketView(packet::PacketView<kLittleEndian> to_append) {
44     Append(to_append);
45   }
46 };
47 
48 constexpr int kL2capBasicFrameHeaderSize = 4;
49 
50 // Per spec 5.1 Vol 2 Part B 5.3, ACL link shall carry L2CAP data. Therefore, an ACL packet shall contain L2CAP PDU.
51 // This function returns the PDU size of the L2CAP data if it's a starting packet. Returns 0 if it's invalid.
52 uint16_t GetL2capPduSize(AclPacketView packet) {
53   auto l2cap_payload = packet.GetPayload();
54   if (l2cap_payload.size() < kL2capBasicFrameHeaderSize) {
55     LOG_ERROR("Controller sent an invalid L2CAP starting packet!");
56     return 0;
57   }
58   return (l2cap_payload.at(1) << 8) + l2cap_payload.at(0);
59 }
60 
61 }  // namespace
62 
63 struct AclManager::acl_connection {
64   acl_connection(AddressWithType address_with_type, os::Handler* handler)
65       : address_with_type_(address_with_type), handler_(handler) {}
66   friend AclConnection;
67   AddressWithType address_with_type_;
68   os::Handler* handler_;
69   std::unique_ptr<AclConnection::Queue> queue_ = std::make_unique<AclConnection::Queue>(10);
70   bool is_disconnected_ = false;
71   ErrorCode disconnect_reason_;
72   os::Handler* command_complete_handler_ = nullptr;
73   os::Handler* disconnect_handler_ = nullptr;
74   ConnectionManagementCallbacks* command_complete_callbacks_ = nullptr;
75   common::OnceCallback<void(ErrorCode)> on_disconnect_callback_;
76   // For LE Connection parameter update from L2CAP
77   common::OnceCallback<void(ErrorCode)> on_connection_update_complete_callback_;
78   os::Handler* on_connection_update_complete_callback_handler_ = nullptr;
79   // Round-robin: Track if dequeue is registered for this connection
80   bool is_registered_ = false;
81   // Credits: Track the number of packets which have been sent to the controller
82   uint16_t number_of_sent_packets_ = 0;
83   PacketViewForRecombination recombination_stage_{std::make_shared<std::vector<uint8_t>>()};
84   int remaining_sdu_continuation_packet_size_ = 0;
85   bool enqueue_registered_ = false;
86   std::queue<packet::PacketView<kLittleEndian>> incoming_queue_;
87 
88   std::unique_ptr<packet::PacketView<kLittleEndian>> on_incoming_data_ready() {
89     auto packet = incoming_queue_.front();
90     incoming_queue_.pop();
91     if (incoming_queue_.empty()) {
92       auto queue_end = queue_->GetDownEnd();
93       queue_end->UnregisterEnqueue();
94       enqueue_registered_ = false;
95     }
96     return std::make_unique<PacketView<kLittleEndian>>(packet);
97   }
98 
99   void on_incoming_packet(AclPacketView packet) {
100     // TODO: What happens if the connection is stalled and fills up?
101     PacketView<kLittleEndian> payload = packet.GetPayload();
102     auto payload_size = payload.size();
103     auto packet_boundary_flag = packet.GetPacketBoundaryFlag();
104     if (packet_boundary_flag == PacketBoundaryFlag::FIRST_NON_AUTOMATICALLY_FLUSHABLE) {
105       LOG_ERROR("Controller is not allowed to send FIRST_NON_AUTOMATICALLY_FLUSHABLE to host except loopback mode");
106       return;
107     }
108     if (packet_boundary_flag == PacketBoundaryFlag::CONTINUING_FRAGMENT) {
109       if (remaining_sdu_continuation_packet_size_ < payload_size) {
110         LOG_WARN("Remote sent unexpected L2CAP PDU. Drop the entire L2CAP PDU");
111         recombination_stage_ = PacketViewForRecombination(std::make_shared<std::vector<uint8_t>>());
112         remaining_sdu_continuation_packet_size_ = 0;
113         return;
114       }
115       remaining_sdu_continuation_packet_size_ -= payload_size;
116       recombination_stage_.AppendPacketView(payload);
117       if (remaining_sdu_continuation_packet_size_ != 0) {
118         return;
119       } else {
120         payload = recombination_stage_;
121         recombination_stage_ = PacketViewForRecombination(std::make_shared<std::vector<uint8_t>>());
122       }
123     } else if (packet_boundary_flag == PacketBoundaryFlag::FIRST_AUTOMATICALLY_FLUSHABLE) {
124       if (recombination_stage_.size() > 0) {
125         LOG_ERROR("Controller sent a starting packet without finishing previous packet. Drop previous one.");
126       }
127       auto l2cap_pdu_size = GetL2capPduSize(packet);
128       remaining_sdu_continuation_packet_size_ = l2cap_pdu_size - (payload_size - kL2capBasicFrameHeaderSize);
129       if (remaining_sdu_continuation_packet_size_ > 0) {
130         recombination_stage_ = payload;
131         return;
132       }
133     }
134     if (incoming_queue_.size() > kMaxQueuedPacketsPerConnection) {
135       LOG_ERROR("Dropping packet due to congestion from remote:%s", address_with_type_.ToString().c_str());
136       return;
137     }
138 
139     incoming_queue_.push(payload);
140     if (!enqueue_registered_) {
141       enqueue_registered_ = true;
142       auto queue_end = queue_->GetDownEnd();
143       queue_end->RegisterEnqueue(
144           handler_, common::Bind(&AclManager::acl_connection::on_incoming_data_ready, common::Unretained(this)));
145     }
146   }
147 
148   void call_disconnect_callback() {
149     disconnect_handler_->Post(BindOnce(std::move(on_disconnect_callback_), disconnect_reason_));
150   }
151 };
152 
153 struct AclManager::impl {
154   impl(const AclManager& acl_manager) : acl_manager_(acl_manager) {}
155 
156   void Start() {
157     hci_layer_ = acl_manager_.GetDependency<HciLayer>();
158     handler_ = acl_manager_.GetHandler();
159     controller_ = acl_manager_.GetDependency<Controller>();
160     max_acl_packet_credits_ = controller_->GetControllerNumAclPacketBuffers();
161     acl_packet_credits_ = max_acl_packet_credits_;
162     acl_buffer_length_ = controller_->GetControllerAclPacketLength();
163     controller_->RegisterCompletedAclPacketsCallback(
164         common::Bind(&impl::incoming_acl_credits, common::Unretained(this)), handler_);
165 
166     // TODO: determine when we should reject connection
167     should_accept_connection_ = common::Bind([](Address, ClassOfDevice) { return true; });
168     hci_queue_end_ = hci_layer_->GetAclQueueEnd();
169     hci_queue_end_->RegisterDequeue(
170         handler_, common::Bind(&impl::dequeue_and_route_acl_packet_to_connection, common::Unretained(this)));
171     hci_layer_->RegisterEventHandler(EventCode::CONNECTION_COMPLETE,
172                                      Bind(&impl::on_connection_complete, common::Unretained(this)), handler_);
173     hci_layer_->RegisterEventHandler(EventCode::DISCONNECTION_COMPLETE,
174                                      Bind(&impl::on_disconnection_complete, common::Unretained(this)), handler_);
175     hci_layer_->RegisterEventHandler(EventCode::CONNECTION_REQUEST,
176                                      Bind(&impl::on_incoming_connection, common::Unretained(this)), handler_);
177     hci_layer_->RegisterLeEventHandler(SubeventCode::CONNECTION_COMPLETE,
178                                        Bind(&impl::on_le_connection_complete, common::Unretained(this)), handler_);
179     hci_layer_->RegisterLeEventHandler(SubeventCode::ENHANCED_CONNECTION_COMPLETE,
180                                        Bind(&impl::on_le_enhanced_connection_complete, common::Unretained(this)),
181                                        handler_);
182     hci_layer_->RegisterLeEventHandler(SubeventCode::CONNECTION_UPDATE_COMPLETE,
183                                        Bind(&impl::on_le_connection_update_complete, common::Unretained(this)),
184                                        handler_);
185     hci_layer_->RegisterEventHandler(EventCode::CONNECTION_PACKET_TYPE_CHANGED,
186                                      Bind(&impl::on_connection_packet_type_changed, common::Unretained(this)),
187                                      handler_);
188     hci_layer_->RegisterEventHandler(EventCode::AUTHENTICATION_COMPLETE,
189                                      Bind(&impl::on_authentication_complete, common::Unretained(this)), handler_);
190     hci_layer_->RegisterEventHandler(EventCode::READ_CLOCK_OFFSET_COMPLETE,
191                                      Bind(&impl::on_read_clock_offset_complete, common::Unretained(this)), handler_);
192     hci_layer_->RegisterEventHandler(EventCode::MODE_CHANGE, Bind(&impl::on_mode_change, common::Unretained(this)),
193                                      handler_);
194     hci_layer_->RegisterEventHandler(EventCode::QOS_SETUP_COMPLETE,
195                                      Bind(&impl::on_qos_setup_complete, common::Unretained(this)), handler_);
196     hci_layer_->RegisterEventHandler(EventCode::ROLE_CHANGE, Bind(&impl::on_role_change, common::Unretained(this)),
197                                      handler_);
198     hci_layer_->RegisterEventHandler(EventCode::FLOW_SPECIFICATION_COMPLETE,
199                                      Bind(&impl::on_flow_specification_complete, common::Unretained(this)), handler_);
200     hci_layer_->RegisterEventHandler(EventCode::FLUSH_OCCURRED,
201                                      Bind(&impl::on_flush_occurred, common::Unretained(this)), handler_);
202     hci_layer_->RegisterEventHandler(EventCode::READ_REMOTE_SUPPORTED_FEATURES_COMPLETE,
203                                      Bind(&impl::on_read_remote_supported_features_complete, common::Unretained(this)),
204                                      handler_);
205     hci_layer_->RegisterEventHandler(EventCode::READ_REMOTE_EXTENDED_FEATURES_COMPLETE,
206                                      Bind(&impl::on_read_remote_extended_features_complete, common::Unretained(this)),
207                                      handler_);
208     hci_layer_->RegisterEventHandler(EventCode::READ_REMOTE_VERSION_INFORMATION_COMPLETE,
209                                      Bind(&impl::on_read_remote_version_information_complete, common::Unretained(this)),
210                                      handler_);
211     hci_layer_->RegisterEventHandler(EventCode::ENCRYPTION_CHANGE,
212                                      Bind(&impl::on_encryption_change, common::Unretained(this)), handler_);
213     hci_layer_->RegisterEventHandler(EventCode::LINK_SUPERVISION_TIMEOUT_CHANGED,
214                                      Bind(&impl::on_link_supervision_timeout_changed, common::Unretained(this)),
215                                      handler_);
216     hci_mtu_ = controller_->GetControllerAclPacketLength();
217   }
218 
219   void Stop() {
220     hci_layer_->UnregisterEventHandler(EventCode::DISCONNECTION_COMPLETE);
221     hci_layer_->UnregisterEventHandler(EventCode::CONNECTION_COMPLETE);
222     hci_layer_->UnregisterEventHandler(EventCode::CONNECTION_REQUEST);
223     hci_layer_->UnregisterEventHandler(EventCode::AUTHENTICATION_COMPLETE);
224     hci_layer_->UnregisterEventHandler(EventCode::READ_REMOTE_SUPPORTED_FEATURES_COMPLETE);
225     hci_layer_->UnregisterEventHandler(EventCode::READ_REMOTE_EXTENDED_FEATURES_COMPLETE);
226     hci_queue_end_->UnregisterDequeue();
227     unregister_all_connections();
228     acl_connections_.clear();
229     hci_queue_end_ = nullptr;
230     handler_ = nullptr;
231     hci_layer_ = nullptr;
232   }
233 
234   void incoming_acl_credits(uint16_t handle, uint16_t credits) {
235     auto connection_pair = acl_connections_.find(handle);
236     if (connection_pair == acl_connections_.end()) {
237       LOG_INFO("Dropping %hx received credits to unknown connection 0x%0hx", credits, handle);
238       return;
239     }
240     if (connection_pair->second.is_disconnected_) {
241       LOG_INFO("Dropping %hx received credits to disconnected connection 0x%0hx", credits, handle);
242       return;
243     }
244     connection_pair->second.number_of_sent_packets_ -= credits;
245     acl_packet_credits_ += credits;
246     ASSERT(acl_packet_credits_ <= max_acl_packet_credits_);
247     start_round_robin();
248   }
249 
250   // Round-robin scheduler
251   void start_round_robin() {
252     if (acl_packet_credits_ == 0) {
253       return;
254     }
255     if (!fragments_to_send_.empty()) {
256       send_next_fragment();
257       return;
258     }
259     for (auto connection_pair = acl_connections_.begin(); connection_pair != acl_connections_.end();
260          connection_pair = std::next(connection_pair)) {
261       if (connection_pair->second.is_registered_) {
262         continue;
263       }
264       connection_pair->second.is_registered_ = true;
265       connection_pair->second.queue_->GetDownEnd()->RegisterDequeue(
266           handler_, common::Bind(&impl::handle_dequeue_from_upper, common::Unretained(this), connection_pair));
267     }
268   }
269 
270   void handle_dequeue_from_upper(std::map<uint16_t, acl_connection>::iterator connection_pair) {
271     current_connection_pair_ = connection_pair;
272     buffer_packet();
273   }
274 
275   void unregister_all_connections() {
276     for (auto connection_pair = acl_connections_.begin(); connection_pair != acl_connections_.end();
277          connection_pair = std::next(connection_pair)) {
278       if (connection_pair->second.is_registered_) {
279         connection_pair->second.is_registered_ = false;
280         connection_pair->second.queue_->GetDownEnd()->UnregisterDequeue();
281       }
282     }
283   }
284 
285   void buffer_packet() {
286     unregister_all_connections();
287     BroadcastFlag broadcast_flag = BroadcastFlag::POINT_TO_POINT;
288     //   Wrap packet and enqueue it
289     uint16_t handle = current_connection_pair_->first;
290 
291     auto packet = current_connection_pair_->second.queue_->GetDownEnd()->TryDequeue();
292     ASSERT(packet != nullptr);
293 
294     if (packet->size() <= hci_mtu_) {
295       fragments_to_send_.push_front(AclPacketBuilder::Create(handle, PacketBoundaryFlag::FIRST_AUTOMATICALLY_FLUSHABLE,
296                                                              broadcast_flag, std::move(packet)));
297     } else {
298       auto fragments = AclFragmenter(hci_mtu_, std::move(packet)).GetFragments();
299       PacketBoundaryFlag packet_boundary_flag = PacketBoundaryFlag::FIRST_AUTOMATICALLY_FLUSHABLE;
300       for (size_t i = 0; i < fragments.size(); i++) {
301         fragments_to_send_.push_back(
302             AclPacketBuilder::Create(handle, packet_boundary_flag, broadcast_flag, std::move(fragments[i])));
303         packet_boundary_flag = PacketBoundaryFlag::CONTINUING_FRAGMENT;
304       }
305     }
306     ASSERT(fragments_to_send_.size() > 0);
307 
308     current_connection_pair_->second.number_of_sent_packets_ += fragments_to_send_.size();
309     send_next_fragment();
310   }
311 
312   void send_next_fragment() {
313     hci_queue_end_->RegisterEnqueue(handler_,
314                                     common::Bind(&impl::handle_enqueue_next_fragment, common::Unretained(this)));
315   }
316 
317   std::unique_ptr<AclPacketBuilder> handle_enqueue_next_fragment() {
318     ASSERT(acl_packet_credits_ > 0);
319     if (acl_packet_credits_ == 1 || fragments_to_send_.size() == 1) {
320       hci_queue_end_->UnregisterEnqueue();
321       if (fragments_to_send_.size() == 1) {
322         handler_->Post(common::BindOnce(&impl::start_round_robin, common::Unretained(this)));
323       }
324     }
325     ASSERT(fragments_to_send_.size() > 0);
326     auto raw_pointer = fragments_to_send_.front().release();
327     acl_packet_credits_ -= 1;
328     fragments_to_send_.pop_front();
329     return std::unique_ptr<AclPacketBuilder>(raw_pointer);
330   }
331 
332   void dequeue_and_route_acl_packet_to_connection() {
333     auto packet = hci_queue_end_->TryDequeue();
334     ASSERT(packet != nullptr);
335     if (!packet->IsValid()) {
336       LOG_INFO("Dropping invalid packet of size %zu", packet->size());
337       return;
338     }
339     uint16_t handle = packet->GetHandle();
340     if (handle == kQualcommDebugHandle) {
341       return;
342     }
343     auto connection_pair = acl_connections_.find(handle);
344     if (connection_pair == acl_connections_.end()) {
345       LOG_INFO("Dropping packet of size %zu to unknown connection 0x%0hx", packet->size(), handle);
346       return;
347     }
348 
349     connection_pair->second.on_incoming_packet(*packet);
350   }
351 
352   void on_incoming_connection(EventPacketView packet) {
353     ConnectionRequestView request = ConnectionRequestView::Create(packet);
354     ASSERT(request.IsValid());
355     Address address = request.GetBdAddr();
356     if (client_callbacks_ == nullptr) {
357       LOG_ERROR("No callbacks to call");
358       auto reason = RejectConnectionReason::LIMITED_RESOURCES;
359       this->reject_connection(RejectConnectionRequestBuilder::Create(address, reason));
360       return;
361     }
362     connecting_.insert(address);
363     if (is_classic_link_already_connected(address)) {
364       auto reason = RejectConnectionReason::UNACCEPTABLE_BD_ADDR;
365       this->reject_connection(RejectConnectionRequestBuilder::Create(address, reason));
366     } else if (should_accept_connection_.Run(address, request.GetClassOfDevice())) {
367       this->accept_connection(address);
368     } else {
369       auto reason = RejectConnectionReason::LIMITED_RESOURCES;  // TODO: determine reason
370       this->reject_connection(RejectConnectionRequestBuilder::Create(address, reason));
371     }
372   }
373 
374   void on_classic_connection_complete(Address address) {
375     auto connecting_addr = connecting_.find(address);
376     if (connecting_addr == connecting_.end()) {
377       LOG_WARN("No prior connection request for %s", address.ToString().c_str());
378     } else {
379       connecting_.erase(connecting_addr);
380     }
381   }
382 
383   void on_common_le_connection_complete(AddressWithType address_with_type) {
384     auto connecting_addr_with_type = connecting_le_.find(address_with_type);
385     if (connecting_addr_with_type == connecting_le_.end()) {
386       LOG_WARN("No prior connection request for %s", address_with_type.ToString().c_str());
387     } else {
388       connecting_le_.erase(connecting_addr_with_type);
389     }
390   }
391 
392   void on_le_connection_complete(LeMetaEventView packet) {
393     LeConnectionCompleteView connection_complete = LeConnectionCompleteView::Create(packet);
394     ASSERT(connection_complete.IsValid());
395     auto status = connection_complete.GetStatus();
396     auto address = connection_complete.GetPeerAddress();
397     auto peer_address_type = connection_complete.GetPeerAddressType();
398     // TODO: find out which address and type was used to initiate the connection
399     AddressWithType address_with_type(address, peer_address_type);
400     on_common_le_connection_complete(address_with_type);
401     if (status != ErrorCode::SUCCESS) {
402       le_client_handler_->Post(common::BindOnce(&LeConnectionCallbacks::OnLeConnectFail,
403                                                 common::Unretained(le_client_callbacks_), address_with_type, status));
404       return;
405     }
406     // TODO: Check and save other connection parameters
407     uint16_t handle = connection_complete.GetConnectionHandle();
408     ASSERT(acl_connections_.count(handle) == 0);
409     acl_connections_.emplace(std::piecewise_construct, std::forward_as_tuple(handle),
410                              std::forward_as_tuple(address_with_type, handler_));
411     if (acl_connections_.size() == 1 && fragments_to_send_.size() == 0) {
412       start_round_robin();
413     }
414     auto role = connection_complete.GetRole();
415     std::unique_ptr<AclConnection> connection_proxy(
416         new AclConnection(&acl_manager_, handle, address, peer_address_type, role));
417     le_client_handler_->Post(common::BindOnce(&LeConnectionCallbacks::OnLeConnectSuccess,
418                                               common::Unretained(le_client_callbacks_), address_with_type,
419                                               std::move(connection_proxy)));
420   }
421 
422   void on_le_enhanced_connection_complete(LeMetaEventView packet) {
423     LeEnhancedConnectionCompleteView connection_complete = LeEnhancedConnectionCompleteView::Create(packet);
424     ASSERT(connection_complete.IsValid());
425     auto status = connection_complete.GetStatus();
426     auto address = connection_complete.GetPeerAddress();
427     auto peer_address_type = connection_complete.GetPeerAddressType();
428     auto peer_resolvable_address = connection_complete.GetPeerResolvablePrivateAddress();
429     AddressWithType reporting_address_with_type(address, peer_address_type);
430     if (!peer_resolvable_address.IsEmpty()) {
431       reporting_address_with_type = AddressWithType(peer_resolvable_address, AddressType::RANDOM_DEVICE_ADDRESS);
432     }
433     on_common_le_connection_complete(reporting_address_with_type);
434     if (status != ErrorCode::SUCCESS) {
435       le_client_handler_->Post(common::BindOnce(&LeConnectionCallbacks::OnLeConnectFail,
436                                                 common::Unretained(le_client_callbacks_), reporting_address_with_type,
437                                                 status));
438       return;
439     }
440     // TODO: Check and save other connection parameters
441     uint16_t handle = connection_complete.GetConnectionHandle();
442     ASSERT(acl_connections_.count(handle) == 0);
443     acl_connections_.emplace(std::piecewise_construct, std::forward_as_tuple(handle),
444                              std::forward_as_tuple(reporting_address_with_type, handler_));
445     if (acl_connections_.size() == 1 && fragments_to_send_.size() == 0) {
446       start_round_robin();
447     }
448     auto role = connection_complete.GetRole();
449     std::unique_ptr<AclConnection> connection_proxy(
450         new AclConnection(&acl_manager_, handle, address, peer_address_type, role));
451     le_client_handler_->Post(common::BindOnce(&LeConnectionCallbacks::OnLeConnectSuccess,
452                                               common::Unretained(le_client_callbacks_), reporting_address_with_type,
453                                               std::move(connection_proxy)));
454   }
455 
456   void on_connection_complete(EventPacketView packet) {
457     ConnectionCompleteView connection_complete = ConnectionCompleteView::Create(packet);
458     ASSERT(connection_complete.IsValid());
459     auto status = connection_complete.GetStatus();
460     auto address = connection_complete.GetBdAddr();
461     on_classic_connection_complete(address);
462     if (status != ErrorCode::SUCCESS) {
463       client_handler_->Post(common::BindOnce(&ConnectionCallbacks::OnConnectFail, common::Unretained(client_callbacks_),
464                                              address, status));
465       return;
466     }
467     uint16_t handle = connection_complete.GetConnectionHandle();
468     ASSERT(acl_connections_.count(handle) == 0);
469     acl_connections_.emplace(
470         std::piecewise_construct, std::forward_as_tuple(handle),
471         std::forward_as_tuple(AddressWithType{address, AddressType::PUBLIC_DEVICE_ADDRESS}, handler_));
472     if (acl_connections_.size() == 1 && fragments_to_send_.size() == 0) {
473       start_round_robin();
474     }
475     std::unique_ptr<AclConnection> connection_proxy(new AclConnection(&acl_manager_, handle, address));
476     client_handler_->Post(common::BindOnce(&ConnectionCallbacks::OnConnectSuccess,
477                                            common::Unretained(client_callbacks_), std::move(connection_proxy)));
478     while (!pending_outgoing_connections_.empty()) {
479       auto create_connection_packet_and_address = std::move(pending_outgoing_connections_.front());
480       pending_outgoing_connections_.pop();
481       if (!is_classic_link_already_connected(create_connection_packet_and_address.first)) {
482         connecting_.insert(create_connection_packet_and_address.first);
483         hci_layer_->EnqueueCommand(std::move(create_connection_packet_and_address.second),
484                                    common::BindOnce([](CommandStatusView status) {
485                                      ASSERT(status.IsValid());
486                                      ASSERT(status.GetCommandOpCode() == OpCode::CREATE_CONNECTION);
487                                    }),
488                                    handler_);
489         break;
490       }
491     }
492   }
493 
494   void on_disconnection_complete(EventPacketView packet) {
495     DisconnectionCompleteView disconnection_complete = DisconnectionCompleteView::Create(packet);
496     ASSERT(disconnection_complete.IsValid());
497     uint16_t handle = disconnection_complete.GetConnectionHandle();
498     auto status = disconnection_complete.GetStatus();
499     if (status == ErrorCode::SUCCESS) {
500       ASSERT(acl_connections_.count(handle) == 1);
501       auto& acl_connection = acl_connections_.find(handle)->second;
502       acl_connection.is_disconnected_ = true;
503       acl_connection.disconnect_reason_ = disconnection_complete.GetReason();
504       acl_connection.call_disconnect_callback();
505       // Reclaim outstanding packets
506       acl_packet_credits_ += acl_connection.number_of_sent_packets_;
507       acl_connection.number_of_sent_packets_ = 0;
508     } else {
509       std::string error_code = ErrorCodeText(status);
510       LOG_ERROR("Received disconnection complete with error code %s, handle 0x%02hx", error_code.c_str(), handle);
511     }
512   }
513 
514   void on_connection_packet_type_changed(EventPacketView packet) {
515     ConnectionPacketTypeChangedView packet_type_changed = ConnectionPacketTypeChangedView::Create(packet);
516     if (!packet_type_changed.IsValid()) {
517       LOG_ERROR("Received on_connection_packet_type_changed with invalid packet");
518       return;
519     } else if (packet_type_changed.GetStatus() != ErrorCode::SUCCESS) {
520       auto status = packet_type_changed.GetStatus();
521       std::string error_code = ErrorCodeText(status);
522       LOG_ERROR("Received on_connection_packet_type_changed with error code %s", error_code.c_str());
523       return;
524     }
525     uint16_t handle = packet_type_changed.GetConnectionHandle();
526     auto& acl_connection = acl_connections_.find(handle)->second;
527     if (acl_connection.command_complete_handler_ != nullptr) {
528       uint16_t packet_type = packet_type_changed.GetPacketType();
529       acl_connection.command_complete_handler_->Post(
530           common::BindOnce(&ConnectionManagementCallbacks::OnConnectionPacketTypeChanged,
531                            common::Unretained(acl_connection.command_complete_callbacks_), packet_type));
532     }
533   }
534 
535   void on_master_link_key_complete(EventPacketView packet) {
536     MasterLinkKeyCompleteView complete_view = MasterLinkKeyCompleteView::Create(packet);
537     if (!complete_view.IsValid()) {
538       LOG_ERROR("Received on_master_link_key_complete with invalid packet");
539       return;
540     } else if (complete_view.GetStatus() != ErrorCode::SUCCESS) {
541       auto status = complete_view.GetStatus();
542       std::string error_code = ErrorCodeText(status);
543       LOG_ERROR("Received on_master_link_key_complete with error code %s", error_code.c_str());
544       return;
545     }
546     if (acl_manager_client_callbacks_ != nullptr) {
547       uint16_t connection_handle = complete_view.GetConnectionHandle();
548       KeyFlag key_flag = complete_view.GetKeyFlag();
549       acl_manager_client_handler_->Post(common::BindOnce(&AclManagerCallbacks::OnMasterLinkKeyComplete,
550                                                          common::Unretained(acl_manager_client_callbacks_),
551                                                          connection_handle, key_flag));
552     }
553   }
554 
555   void on_authentication_complete(EventPacketView packet) {
556     AuthenticationCompleteView authentication_complete = AuthenticationCompleteView::Create(packet);
557     if (!authentication_complete.IsValid()) {
558       LOG_ERROR("Received on_authentication_complete with invalid packet");
559       return;
560     } else if (authentication_complete.GetStatus() != ErrorCode::SUCCESS) {
561       auto status = authentication_complete.GetStatus();
562       std::string error_code = ErrorCodeText(status);
563       LOG_ERROR("Received on_authentication_complete with error code %s", error_code.c_str());
564       return;
565     }
566     uint16_t handle = authentication_complete.GetConnectionHandle();
567     auto& acl_connection = acl_connections_.find(handle)->second;
568     if (acl_connection.command_complete_handler_ != nullptr) {
569       acl_connection.command_complete_handler_->Post(
570           common::BindOnce(&ConnectionManagementCallbacks::OnAuthenticationComplete,
571                            common::Unretained(acl_connection.command_complete_callbacks_)));
572     }
573   }
574 
575   void on_encryption_change(EventPacketView packet) {
576     EncryptionChangeView encryption_change_view = EncryptionChangeView::Create(packet);
577     if (!encryption_change_view.IsValid()) {
578       LOG_ERROR("Received on_encryption_change with invalid packet");
579       return;
580     } else if (encryption_change_view.GetStatus() != ErrorCode::SUCCESS) {
581       auto status = encryption_change_view.GetStatus();
582       std::string error_code = ErrorCodeText(status);
583       LOG_ERROR("Received on_change_connection_link_key_complete with error code %s", error_code.c_str());
584       return;
585     }
586     uint16_t handle = encryption_change_view.GetConnectionHandle();
587     auto& acl_connection = acl_connections_.find(handle)->second;
588     if (acl_connection.command_complete_handler_ != nullptr) {
589       EncryptionEnabled enabled = encryption_change_view.GetEncryptionEnabled();
590       acl_connection.command_complete_handler_->Post(
591           common::BindOnce(&ConnectionManagementCallbacks::OnEncryptionChange,
592                            common::Unretained(acl_connection.command_complete_callbacks_), enabled));
593     }
594   }
595 
596   void on_change_connection_link_key_complete(EventPacketView packet) {
597     ChangeConnectionLinkKeyCompleteView complete_view = ChangeConnectionLinkKeyCompleteView::Create(packet);
598     if (!complete_view.IsValid()) {
599       LOG_ERROR("Received on_change_connection_link_key_complete with invalid packet");
600       return;
601     } else if (complete_view.GetStatus() != ErrorCode::SUCCESS) {
602       auto status = complete_view.GetStatus();
603       std::string error_code = ErrorCodeText(status);
604       LOG_ERROR("Received on_change_connection_link_key_complete with error code %s", error_code.c_str());
605       return;
606     }
607     uint16_t handle = complete_view.GetConnectionHandle();
608     auto& acl_connection = acl_connections_.find(handle)->second;
609     if (acl_connection.command_complete_handler_ != nullptr) {
610       acl_connection.command_complete_handler_->Post(
611           common::BindOnce(&ConnectionManagementCallbacks::OnChangeConnectionLinkKeyComplete,
612                            common::Unretained(acl_connection.command_complete_callbacks_)));
613     }
614   }
615 
616   void on_read_clock_offset_complete(EventPacketView packet) {
617     ReadClockOffsetCompleteView complete_view = ReadClockOffsetCompleteView::Create(packet);
618     if (!complete_view.IsValid()) {
619       LOG_ERROR("Received on_read_clock_offset_complete with invalid packet");
620       return;
621     } else if (complete_view.GetStatus() != ErrorCode::SUCCESS) {
622       auto status = complete_view.GetStatus();
623       std::string error_code = ErrorCodeText(status);
624       LOG_ERROR("Received on_read_clock_offset_complete with error code %s", error_code.c_str());
625       return;
626     }
627     uint16_t handle = complete_view.GetConnectionHandle();
628     auto& acl_connection = acl_connections_.find(handle)->second;
629     if (acl_connection.command_complete_handler_ != nullptr) {
630       uint16_t clock_offset = complete_view.GetClockOffset();
631       acl_connection.command_complete_handler_->Post(
632           common::BindOnce(&ConnectionManagementCallbacks::OnReadClockOffsetComplete,
633                            common::Unretained(acl_connection.command_complete_callbacks_), clock_offset));
634     }
635   }
636 
637   void on_mode_change(EventPacketView packet) {
638     ModeChangeView mode_change_view = ModeChangeView::Create(packet);
639     if (!mode_change_view.IsValid()) {
640       LOG_ERROR("Received on_mode_change with invalid packet");
641       return;
642     } else if (mode_change_view.GetStatus() != ErrorCode::SUCCESS) {
643       auto status = mode_change_view.GetStatus();
644       std::string error_code = ErrorCodeText(status);
645       LOG_ERROR("Received on_mode_change with error code %s", error_code.c_str());
646       return;
647     }
648     uint16_t handle = mode_change_view.GetConnectionHandle();
649     auto& acl_connection = acl_connections_.find(handle)->second;
650     if (acl_connection.command_complete_handler_ != nullptr) {
651       Mode current_mode = mode_change_view.GetCurrentMode();
652       uint16_t interval = mode_change_view.GetInterval();
653       acl_connection.command_complete_handler_->Post(
654           common::BindOnce(&ConnectionManagementCallbacks::OnModeChange,
655                            common::Unretained(acl_connection.command_complete_callbacks_), current_mode, interval));
656     }
657   }
658 
659   void on_qos_setup_complete(EventPacketView packet) {
660     QosSetupCompleteView complete_view = QosSetupCompleteView::Create(packet);
661     if (!complete_view.IsValid()) {
662       LOG_ERROR("Received on_qos_setup_complete with invalid packet");
663       return;
664     } else if (complete_view.GetStatus() != ErrorCode::SUCCESS) {
665       auto status = complete_view.GetStatus();
666       std::string error_code = ErrorCodeText(status);
667       LOG_ERROR("Received on_qos_setup_complete with error code %s", error_code.c_str());
668       return;
669     }
670     uint16_t handle = complete_view.GetConnectionHandle();
671     auto& acl_connection = acl_connections_.find(handle)->second;
672     if (acl_connection.command_complete_handler_ != nullptr) {
673       ServiceType service_type = complete_view.GetServiceType();
674       uint32_t token_rate = complete_view.GetTokenRate();
675       uint32_t peak_bandwidth = complete_view.GetPeakBandwidth();
676       uint32_t latency = complete_view.GetLatency();
677       uint32_t delay_variation = complete_view.GetDelayVariation();
678       acl_connection.command_complete_handler_->Post(
679           common::BindOnce(&ConnectionManagementCallbacks::OnQosSetupComplete,
680                            common::Unretained(acl_connection.command_complete_callbacks_), service_type, token_rate,
681                            peak_bandwidth, latency, delay_variation));
682     }
683   }
684 
685   void on_role_change(EventPacketView packet) {
686     RoleChangeView role_change_view = RoleChangeView::Create(packet);
687     if (!role_change_view.IsValid()) {
688       LOG_ERROR("Received on_role_change with invalid packet");
689       return;
690     } else if (role_change_view.GetStatus() != ErrorCode::SUCCESS) {
691       auto status = role_change_view.GetStatus();
692       std::string error_code = ErrorCodeText(status);
693       LOG_ERROR("Received on_role_change with error code %s", error_code.c_str());
694       return;
695     }
696     if (acl_manager_client_callbacks_ != nullptr) {
697       Address bd_addr = role_change_view.GetBdAddr();
698       Role new_role = role_change_view.GetNewRole();
699       acl_manager_client_handler_->Post(common::BindOnce(
700           &AclManagerCallbacks::OnRoleChange, common::Unretained(acl_manager_client_callbacks_), bd_addr, new_role));
701     }
702   }
703 
704   void on_flow_specification_complete(EventPacketView packet) {
705     FlowSpecificationCompleteView complete_view = FlowSpecificationCompleteView::Create(packet);
706     if (!complete_view.IsValid()) {
707       LOG_ERROR("Received on_flow_specification_complete with invalid packet");
708       return;
709     } else if (complete_view.GetStatus() != ErrorCode::SUCCESS) {
710       auto status = complete_view.GetStatus();
711       std::string error_code = ErrorCodeText(status);
712       LOG_ERROR("Received on_flow_specification_complete with error code %s", error_code.c_str());
713       return;
714     }
715     uint16_t handle = complete_view.GetConnectionHandle();
716     auto& acl_connection = acl_connections_.find(handle)->second;
717     if (acl_connection.command_complete_handler_ != nullptr) {
718       FlowDirection flow_direction = complete_view.GetFlowDirection();
719       ServiceType service_type = complete_view.GetServiceType();
720       uint32_t token_rate = complete_view.GetTokenRate();
721       uint32_t token_bucket_size = complete_view.GetTokenBucketSize();
722       uint32_t peak_bandwidth = complete_view.GetPeakBandwidth();
723       uint32_t access_latency = complete_view.GetAccessLatency();
724       acl_connection.command_complete_handler_->Post(
725           common::BindOnce(&ConnectionManagementCallbacks::OnFlowSpecificationComplete,
726                            common::Unretained(acl_connection.command_complete_callbacks_), flow_direction, service_type,
727                            token_rate, token_bucket_size, peak_bandwidth, access_latency));
728     }
729   }
730 
731   void on_flush_occurred(EventPacketView packet) {
732     FlushOccurredView flush_occurred_view = FlushOccurredView::Create(packet);
733     if (!flush_occurred_view.IsValid()) {
734       LOG_ERROR("Received on_flush_occurred with invalid packet");
735       return;
736     }
737     uint16_t handle = flush_occurred_view.GetConnectionHandle();
738     auto& acl_connection = acl_connections_.find(handle)->second;
739     if (acl_connection.command_complete_handler_ != nullptr) {
740       acl_connection.command_complete_handler_->Post(
741           common::BindOnce(&ConnectionManagementCallbacks::OnFlushOccurred,
742                            common::Unretained(acl_connection.command_complete_callbacks_)));
743     }
744   }
745 
746   void on_read_remote_version_information_complete(EventPacketView packet) {
747     auto view = ReadRemoteVersionInformationCompleteView::Create(packet);
748     ASSERT_LOG(view.IsValid(), "Read remote version information packet invalid");
749     LOG_INFO("UNIMPLEMENTED called");
750   }
751 
752   void on_read_remote_supported_features_complete(EventPacketView packet) {
753     auto view = ReadRemoteSupportedFeaturesCompleteView::Create(packet);
754     ASSERT_LOG(view.IsValid(), "Read remote supported features packet invalid");
755     LOG_INFO("UNIMPLEMENTED called");
756   }
757 
758   void on_read_remote_extended_features_complete(EventPacketView packet) {
759     auto view = ReadRemoteExtendedFeaturesCompleteView::Create(packet);
760     ASSERT_LOG(view.IsValid(), "Read remote extended features packet invalid");
761     LOG_INFO("UNIMPLEMENTED called");
762   }
763 
764   void on_link_supervision_timeout_changed(EventPacketView packet) {
765     auto view = LinkSupervisionTimeoutChangedView::Create(packet);
766     ASSERT_LOG(view.IsValid(), "Link supervision timeout changed packet invalid");
767     LOG_INFO("UNIMPLEMENTED called");
768   }
769 
770   void on_role_discovery_complete(CommandCompleteView view) {
771     auto complete_view = RoleDiscoveryCompleteView::Create(view);
772     if (!complete_view.IsValid()) {
773       LOG_ERROR("Received on_role_discovery_complete with invalid packet");
774       return;
775     } else if (complete_view.GetStatus() != ErrorCode::SUCCESS) {
776       auto status = complete_view.GetStatus();
777       std::string error_code = ErrorCodeText(status);
778       LOG_ERROR("Received on_role_discovery_complete with error code %s", error_code.c_str());
779       return;
780     }
781     uint16_t handle = complete_view.GetConnectionHandle();
782     auto& acl_connection = acl_connections_.find(handle)->second;
783     if (acl_connection.command_complete_handler_ != nullptr) {
784       Role role = complete_view.GetCurrentRole();
785       acl_connection.command_complete_handler_->Post(
786           common::BindOnce(&ConnectionManagementCallbacks::OnRoleDiscoveryComplete,
787                            common::Unretained(acl_connection.command_complete_callbacks_), role));
788     }
789   }
790 
791   void on_read_link_policy_settings_complete(CommandCompleteView view) {
792     auto complete_view = ReadLinkPolicySettingsCompleteView::Create(view);
793     if (!complete_view.IsValid()) {
794       LOG_ERROR("Received on_read_link_policy_settings_complete with invalid packet");
795       return;
796     } else if (complete_view.GetStatus() != ErrorCode::SUCCESS) {
797       auto status = complete_view.GetStatus();
798       std::string error_code = ErrorCodeText(status);
799       LOG_ERROR("Received on_read_link_policy_settings_complete with error code %s", error_code.c_str());
800       return;
801     }
802     uint16_t handle = complete_view.GetConnectionHandle();
803     auto& acl_connection = acl_connections_.find(handle)->second;
804     if (acl_connection.command_complete_handler_ != nullptr) {
805       uint16_t link_policy_settings = complete_view.GetLinkPolicySettings();
806       acl_connection.command_complete_handler_->Post(
807           common::BindOnce(&ConnectionManagementCallbacks::OnReadLinkPolicySettingsComplete,
808                            common::Unretained(acl_connection.command_complete_callbacks_), link_policy_settings));
809     }
810   }
811 
812   void on_read_default_link_policy_settings_complete(CommandCompleteView view) {
813     auto complete_view = ReadDefaultLinkPolicySettingsCompleteView::Create(view);
814     if (!complete_view.IsValid()) {
815       LOG_ERROR("Received on_read_link_policy_settings_complete with invalid packet");
816       return;
817     } else if (complete_view.GetStatus() != ErrorCode::SUCCESS) {
818       auto status = complete_view.GetStatus();
819       std::string error_code = ErrorCodeText(status);
820       LOG_ERROR("Received on_read_link_policy_settings_complete with error code %s", error_code.c_str());
821       return;
822     }
823     if (acl_manager_client_callbacks_ != nullptr) {
824       uint16_t default_link_policy_settings = complete_view.GetDefaultLinkPolicySettings();
825       acl_manager_client_handler_->Post(common::BindOnce(&AclManagerCallbacks::OnReadDefaultLinkPolicySettingsComplete,
826                                                          common::Unretained(acl_manager_client_callbacks_),
827                                                          default_link_policy_settings));
828     }
829   }
830 
831   void on_read_automatic_flush_timeout_complete(CommandCompleteView view) {
832     auto complete_view = ReadAutomaticFlushTimeoutCompleteView::Create(view);
833     if (!complete_view.IsValid()) {
834       LOG_ERROR("Received on_read_automatic_flush_timeout_complete with invalid packet");
835       return;
836     } else if (complete_view.GetStatus() != ErrorCode::SUCCESS) {
837       auto status = complete_view.GetStatus();
838       std::string error_code = ErrorCodeText(status);
839       LOG_ERROR("Received on_read_automatic_flush_timeout_complete with error code %s", error_code.c_str());
840       return;
841     }
842     uint16_t handle = complete_view.GetConnectionHandle();
843     auto& acl_connection = acl_connections_.find(handle)->second;
844     if (acl_connection.command_complete_handler_ != nullptr) {
845       uint16_t flush_timeout = complete_view.GetFlushTimeout();
846       acl_connection.command_complete_handler_->Post(
847           common::BindOnce(&ConnectionManagementCallbacks::OnReadAutomaticFlushTimeoutComplete,
848                            common::Unretained(acl_connection.command_complete_callbacks_), flush_timeout));
849     }
850   }
851 
852   void on_read_transmit_power_level_complete(CommandCompleteView view) {
853     auto complete_view = ReadTransmitPowerLevelCompleteView::Create(view);
854     if (!complete_view.IsValid()) {
855       LOG_ERROR("Received on_read_transmit_power_level_complete with invalid packet");
856       return;
857     } else if (complete_view.GetStatus() != ErrorCode::SUCCESS) {
858       auto status = complete_view.GetStatus();
859       std::string error_code = ErrorCodeText(status);
860       LOG_ERROR("Received on_read_transmit_power_level_complete with error code %s", error_code.c_str());
861       return;
862     }
863     uint16_t handle = complete_view.GetConnectionHandle();
864     auto& acl_connection = acl_connections_.find(handle)->second;
865     if (acl_connection.command_complete_handler_ != nullptr) {
866       uint8_t transmit_power_level = complete_view.GetTransmitPowerLevel();
867       acl_connection.command_complete_handler_->Post(
868           common::BindOnce(&ConnectionManagementCallbacks::OnReadTransmitPowerLevelComplete,
869                            common::Unretained(acl_connection.command_complete_callbacks_), transmit_power_level));
870     }
871   }
872 
873   void on_read_link_supervision_timeout_complete(CommandCompleteView view) {
874     auto complete_view = ReadLinkSupervisionTimeoutCompleteView::Create(view);
875     if (!complete_view.IsValid()) {
876       LOG_ERROR("Received on_read_link_supervision_timeout_complete with invalid packet");
877       return;
878     } else if (complete_view.GetStatus() != ErrorCode::SUCCESS) {
879       auto status = complete_view.GetStatus();
880       std::string error_code = ErrorCodeText(status);
881       LOG_ERROR("Received on_read_link_supervision_timeout_complete with error code %s", error_code.c_str());
882       return;
883     }
884     uint16_t handle = complete_view.GetConnectionHandle();
885     auto& acl_connection = acl_connections_.find(handle)->second;
886     if (acl_connection.command_complete_handler_ != nullptr) {
887       uint16_t link_supervision_timeout = complete_view.GetLinkSupervisionTimeout();
888       acl_connection.command_complete_handler_->Post(
889           common::BindOnce(&ConnectionManagementCallbacks::OnReadLinkSupervisionTimeoutComplete,
890                            common::Unretained(acl_connection.command_complete_callbacks_), link_supervision_timeout));
891     }
892   }
893 
894   void on_read_failed_contact_counter_complete(CommandCompleteView view) {
895     auto complete_view = ReadFailedContactCounterCompleteView::Create(view);
896     if (!complete_view.IsValid()) {
897       LOG_ERROR("Received on_read_failed_contact_counter_complete with invalid packet");
898       return;
899     } else if (complete_view.GetStatus() != ErrorCode::SUCCESS) {
900       auto status = complete_view.GetStatus();
901       std::string error_code = ErrorCodeText(status);
902       LOG_ERROR("Received on_read_failed_contact_counter_complete with error code %s", error_code.c_str());
903       return;
904     }
905     uint16_t handle = complete_view.GetConnectionHandle();
906     auto& acl_connection = acl_connections_.find(handle)->second;
907     if (acl_connection.command_complete_handler_ != nullptr) {
908       uint16_t failed_contact_counter = complete_view.GetFailedContactCounter();
909       acl_connection.command_complete_handler_->Post(
910           common::BindOnce(&ConnectionManagementCallbacks::OnReadFailedContactCounterComplete,
911                            common::Unretained(acl_connection.command_complete_callbacks_), failed_contact_counter));
912     }
913   }
914 
915   void on_read_link_quality_complete(CommandCompleteView view) {
916     auto complete_view = ReadLinkQualityCompleteView::Create(view);
917     if (!complete_view.IsValid()) {
918       LOG_ERROR("Received on_read_link_quality_complete with invalid packet");
919       return;
920     } else if (complete_view.GetStatus() != ErrorCode::SUCCESS) {
921       auto status = complete_view.GetStatus();
922       std::string error_code = ErrorCodeText(status);
923       LOG_ERROR("Received on_read_link_quality_complete with error code %s", error_code.c_str());
924       return;
925     }
926     uint16_t handle = complete_view.GetConnectionHandle();
927     auto& acl_connection = acl_connections_.find(handle)->second;
928     if (acl_connection.command_complete_handler_ != nullptr) {
929       uint8_t link_quality = complete_view.GetLinkQuality();
930       acl_connection.command_complete_handler_->Post(
931           common::BindOnce(&ConnectionManagementCallbacks::OnReadLinkQualityComplete,
932                            common::Unretained(acl_connection.command_complete_callbacks_), link_quality));
933     }
934   }
935 
936   void on_read_afh_channel_map_complete(CommandCompleteView view) {
937     auto complete_view = ReadAfhChannelMapCompleteView::Create(view);
938     if (!complete_view.IsValid()) {
939       LOG_ERROR("Received on_read_afh_channel_map_complete with invalid packet");
940       return;
941     } else if (complete_view.GetStatus() != ErrorCode::SUCCESS) {
942       auto status = complete_view.GetStatus();
943       std::string error_code = ErrorCodeText(status);
944       LOG_ERROR("Received on_read_afh_channel_map_complete with error code %s", error_code.c_str());
945       return;
946     }
947     uint16_t handle = complete_view.GetConnectionHandle();
948     auto& acl_connection = acl_connections_.find(handle)->second;
949     if (acl_connection.command_complete_handler_ != nullptr) {
950       AfhMode afh_mode = complete_view.GetAfhMode();
951       std::array<uint8_t, 10> afh_channel_map = complete_view.GetAfhChannelMap();
952       acl_connection.command_complete_handler_->Post(
953           common::BindOnce(&ConnectionManagementCallbacks::OnReadAfhChannelMapComplete,
954                            common::Unretained(acl_connection.command_complete_callbacks_), afh_mode, afh_channel_map));
955     }
956   }
957 
958   void on_read_rssi_complete(CommandCompleteView view) {
959     auto complete_view = ReadRssiCompleteView::Create(view);
960     if (!complete_view.IsValid()) {
961       LOG_ERROR("Received on_read_rssi_complete with invalid packet");
962       return;
963     } else if (complete_view.GetStatus() != ErrorCode::SUCCESS) {
964       auto status = complete_view.GetStatus();
965       std::string error_code = ErrorCodeText(status);
966       LOG_ERROR("Received on_read_rssi_complete with error code %s", error_code.c_str());
967       return;
968     }
969     uint16_t handle = complete_view.GetConnectionHandle();
970     auto& acl_connection = acl_connections_.find(handle)->second;
971     if (acl_connection.command_complete_handler_ != nullptr) {
972       uint8_t rssi = complete_view.GetRssi();
973       acl_connection.command_complete_handler_->Post(
974           common::BindOnce(&ConnectionManagementCallbacks::OnReadRssiComplete,
975                            common::Unretained(acl_connection.command_complete_callbacks_), rssi));
976     }
977   }
978 
979   void on_read_remote_version_information_status(CommandStatusView view) {
980     ASSERT_LOG(view.IsValid(), "Bad status packet!");
981     LOG_INFO("UNIMPLEMENTED called: %s", hci::ErrorCodeText(view.GetStatus()).c_str());
982   }
983 
984   void on_read_remote_supported_features_status(CommandStatusView view) {
985     ASSERT_LOG(view.IsValid(), "Bad status packet!");
986     LOG_INFO("UNIMPLEMENTED called: %s", hci::ErrorCodeText(view.GetStatus()).c_str());
987   }
988 
989   void on_read_remote_extended_features_status(CommandStatusView view) {
990     ASSERT_LOG(view.IsValid(), "Broken");
991     LOG_INFO("UNIMPLEMENTED called: %s", hci::ErrorCodeText(view.GetStatus()).c_str());
992   }
993 
994   void on_read_clock_complete(CommandCompleteView view) {
995     auto complete_view = ReadClockCompleteView::Create(view);
996     if (!complete_view.IsValid()) {
997       LOG_ERROR("Received on_read_clock_complete with invalid packet");
998       return;
999     } else if (complete_view.GetStatus() != ErrorCode::SUCCESS) {
1000       auto status = complete_view.GetStatus();
1001       std::string error_code = ErrorCodeText(status);
1002       LOG_ERROR("Received on_read_clock_complete with error code %s", error_code.c_str());
1003       return;
1004     }
1005     uint16_t handle = complete_view.GetConnectionHandle();
1006     auto& acl_connection = acl_connections_.find(handle)->second;
1007     if (acl_connection.command_complete_handler_ != nullptr) {
1008       uint32_t clock = complete_view.GetClock();
1009       uint16_t accuracy = complete_view.GetAccuracy();
1010       acl_connection.command_complete_handler_->Post(
1011           common::BindOnce(&ConnectionManagementCallbacks::OnReadClockComplete,
1012                            common::Unretained(acl_connection.command_complete_callbacks_), clock, accuracy));
1013     }
1014   }
1015 
1016   void on_le_connection_update_complete(LeMetaEventView view) {
1017     auto complete_view = LeConnectionUpdateCompleteView::Create(view);
1018     if (!complete_view.IsValid()) {
1019       LOG_ERROR("Received on_le_connection_update_complete with invalid packet");
1020       return;
1021     } else if (complete_view.GetStatus() != ErrorCode::SUCCESS) {
1022       auto status = complete_view.GetStatus();
1023       std::string error_code = ErrorCodeText(status);
1024       LOG_ERROR("Received on_le_connection_update_complete with error code %s", error_code.c_str());
1025       return;
1026     }
1027     auto handle = complete_view.GetConnectionHandle();
1028     if (acl_connections_.find(handle) == acl_connections_.end()) {
1029       LOG_WARN("Can't find connection");
1030       return;
1031     }
1032     auto& connection = acl_connections_.find(handle)->second;
1033     if (connection.is_disconnected_) {
1034       LOG_INFO("Already disconnected");
1035       return;
1036     }
1037     if (!connection.on_connection_update_complete_callback_.is_null()) {
1038       connection.on_connection_update_complete_callback_handler_->Post(
1039           common::BindOnce(std::move(connection.on_connection_update_complete_callback_), complete_view.GetStatus()));
1040       connection.on_connection_update_complete_callback_handler_ = nullptr;
1041     }
1042   }
1043 
1044   bool is_classic_link_already_connected(Address address) {
1045     for (const auto& connection : acl_connections_) {
1046       if (connection.second.address_with_type_.GetAddress() == address) {
1047         return true;
1048       }
1049     }
1050     return false;
1051   }
1052 
1053   void create_connection(Address address) {
1054     // TODO: Configure default connection parameters?
1055     uint16_t packet_type = 0x4408 /* DM 1,3,5 */ | 0x8810 /*DH 1,3,5 */;
1056     PageScanRepetitionMode page_scan_repetition_mode = PageScanRepetitionMode::R1;
1057     uint16_t clock_offset = 0;
1058     ClockOffsetValid clock_offset_valid = ClockOffsetValid::INVALID;
1059     CreateConnectionRoleSwitch allow_role_switch = CreateConnectionRoleSwitch::ALLOW_ROLE_SWITCH;
1060     ASSERT(client_callbacks_ != nullptr);
1061     std::unique_ptr<CreateConnectionBuilder> packet = CreateConnectionBuilder::Create(
1062         address, packet_type, page_scan_repetition_mode, clock_offset, clock_offset_valid, allow_role_switch);
1063 
1064     if (connecting_.empty()) {
1065       if (is_classic_link_already_connected(address)) {
1066         LOG_WARN("already connected: %s", address.ToString().c_str());
1067         return;
1068       }
1069       connecting_.insert(address);
1070       hci_layer_->EnqueueCommand(std::move(packet), common::BindOnce([](CommandStatusView status) {
1071                                    ASSERT(status.IsValid());
1072                                    ASSERT(status.GetCommandOpCode() == OpCode::CREATE_CONNECTION);
1073                                  }),
1074                                  handler_);
1075     } else {
1076       pending_outgoing_connections_.emplace(address, std::move(packet));
1077     }
1078   }
1079 
1080   void create_le_connection(AddressWithType address_with_type) {
1081     // TODO: Add white list handling.
1082     // TODO: Configure default LE connection parameters?
1083     uint16_t le_scan_interval = 0x0060;
1084     uint16_t le_scan_window = 0x0030;
1085     InitiatorFilterPolicy initiator_filter_policy = InitiatorFilterPolicy::USE_PEER_ADDRESS;
1086     OwnAddressType own_address_type = OwnAddressType::RANDOM_DEVICE_ADDRESS;
1087     uint16_t conn_interval_min = 0x0018;
1088     uint16_t conn_interval_max = 0x0028;
1089     uint16_t conn_latency = 0x0000;
1090     uint16_t supervision_timeout = 0x001f4;
1091     ASSERT(le_client_callbacks_ != nullptr);
1092 
1093     connecting_le_.insert(address_with_type);
1094 
1095     // TODO: make features check nicer, like HCI_LE_EXTENDED_ADVERTISING_SUPPORTED
1096     if (controller_->GetControllerLeLocalSupportedFeatures() & 0x0010) {
1097       LeCreateConnPhyScanParameters tmp;
1098       tmp.scan_interval_ = le_scan_interval;
1099       tmp.scan_window_ = le_scan_window;
1100       tmp.conn_interval_min_ = conn_interval_min;
1101       tmp.conn_interval_max_ = conn_interval_max;
1102       tmp.conn_latency_ = conn_latency;
1103       tmp.supervision_timeout_ = supervision_timeout;
1104       tmp.min_ce_length_ = 0x00;
1105       tmp.max_ce_length_ = 0x00;
1106 
1107       // With real controllers, we must set random address before using it to establish connection
1108       // TODO: have separate state machine generate new address when needed, consider using auto-generation in
1109       // controller
1110       hci_layer_->EnqueueCommand(hci::LeSetRandomAddressBuilder::Create(Address{{0x00, 0x11, 0xFF, 0xFF, 0x33, 0x22}}),
1111                                  common::BindOnce([](CommandCompleteView status) {}), handler_);
1112 
1113       hci_layer_->EnqueueCommand(LeExtendedCreateConnectionBuilder::Create(
1114                                      initiator_filter_policy, own_address_type, address_with_type.GetAddressType(),
1115                                      address_with_type.GetAddress(), 0x01 /* 1M PHY ONLY */, {tmp}),
1116                                  common::BindOnce([](CommandStatusView status) {
1117                                    ASSERT(status.IsValid());
1118                                    ASSERT(status.GetCommandOpCode() == OpCode::LE_EXTENDED_CREATE_CONNECTION);
1119                                  }),
1120                                  handler_);
1121     } else {
1122       hci_layer_->EnqueueCommand(
1123           LeCreateConnectionBuilder::Create(le_scan_interval, le_scan_window, initiator_filter_policy,
1124                                             address_with_type.GetAddressType(), address_with_type.GetAddress(),
1125                                             own_address_type, conn_interval_min, conn_interval_max, conn_latency,
1126                                             supervision_timeout, kMinimumCeLength, kMaximumCeLength),
1127           common::BindOnce([](CommandStatusView status) {
1128             ASSERT(status.IsValid());
1129             ASSERT(status.GetCommandOpCode() == OpCode::LE_CREATE_CONNECTION);
1130           }),
1131           handler_);
1132     }
1133   }
1134 
1135   void cancel_connect(Address address) {
1136     auto connecting_addr = connecting_.find(address);
1137     if (connecting_addr == connecting_.end()) {
1138       LOG_INFO("Cannot cancel non-existent connection to %s", address.ToString().c_str());
1139       return;
1140     }
1141     std::unique_ptr<CreateConnectionCancelBuilder> packet = CreateConnectionCancelBuilder::Create(address);
1142     hci_layer_->EnqueueCommand(std::move(packet), common::BindOnce([](CommandCompleteView complete) { /* TODO */ }),
1143                                handler_);
1144   }
1145 
1146   void master_link_key(KeyFlag key_flag) {
1147     std::unique_ptr<MasterLinkKeyBuilder> packet = MasterLinkKeyBuilder::Create(key_flag);
1148     hci_layer_->EnqueueCommand(
1149         std::move(packet),
1150         common::BindOnce(&impl::check_command_status<MasterLinkKeyStatusView>, common::Unretained(this)), handler_);
1151   }
1152 
1153   void switch_role(Address address, Role role) {
1154     std::unique_ptr<SwitchRoleBuilder> packet = SwitchRoleBuilder::Create(address, role);
1155     hci_layer_->EnqueueCommand(
1156         std::move(packet),
1157         common::BindOnce(&impl::check_command_status<SwitchRoleStatusView>, common::Unretained(this)), handler_);
1158   }
1159 
1160   void read_default_link_policy_settings() {
1161     std::unique_ptr<ReadDefaultLinkPolicySettingsBuilder> packet = ReadDefaultLinkPolicySettingsBuilder::Create();
1162     hci_layer_->EnqueueCommand(
1163         std::move(packet),
1164         common::BindOnce(&impl::on_read_default_link_policy_settings_complete, common::Unretained(this)), handler_);
1165   }
1166 
1167   void write_default_link_policy_settings(uint16_t default_link_policy_settings) {
1168     std::unique_ptr<WriteDefaultLinkPolicySettingsBuilder> packet =
1169         WriteDefaultLinkPolicySettingsBuilder::Create(default_link_policy_settings);
1170     hci_layer_->EnqueueCommand(
1171         std::move(packet),
1172         BindOnce(&AclManager::impl::check_command_complete<WriteDefaultLinkPolicySettingsCompleteView>,
1173                  common::Unretained(this)),
1174         handler_);
1175   }
1176 
1177   void accept_connection(Address address) {
1178     auto role = AcceptConnectionRequestRole::BECOME_MASTER;  // We prefer to be master
1179     hci_layer_->EnqueueCommand(AcceptConnectionRequestBuilder::Create(address, role),
1180                                common::BindOnce(&impl::on_accept_connection_status, common::Unretained(this), address),
1181                                handler_);
1182   }
1183 
1184   void handle_disconnect(uint16_t handle, DisconnectReason reason) {
1185     ASSERT(acl_connections_.count(handle) == 1);
1186     std::unique_ptr<DisconnectBuilder> packet = DisconnectBuilder::Create(handle, reason);
1187     hci_layer_->EnqueueCommand(std::move(packet), BindOnce([](CommandStatusView status) { /* TODO: check? */ }),
1188                                handler_);
1189   }
1190 
1191   void handle_change_connection_packet_type(uint16_t handle, uint16_t packet_type) {
1192     ASSERT(acl_connections_.count(handle) == 1);
1193     std::unique_ptr<ChangeConnectionPacketTypeBuilder> packet =
1194         ChangeConnectionPacketTypeBuilder::Create(handle, packet_type);
1195     hci_layer_->EnqueueCommand(std::move(packet),
1196                                BindOnce(&AclManager::impl::check_command_status<ChangeConnectionPacketTypeStatusView>,
1197                                         common::Unretained(this)),
1198                                handler_);
1199   }
1200 
1201   void handle_authentication_requested(uint16_t handle) {
1202     std::unique_ptr<AuthenticationRequestedBuilder> packet = AuthenticationRequestedBuilder::Create(handle);
1203     hci_layer_->EnqueueCommand(
1204         std::move(packet),
1205         BindOnce(&AclManager::impl::check_command_status<AuthenticationRequestedStatusView>, common::Unretained(this)),
1206         handler_);
1207   }
1208 
1209   void handle_set_connection_encryption(uint16_t handle, Enable enable) {
1210     std::unique_ptr<SetConnectionEncryptionBuilder> packet = SetConnectionEncryptionBuilder::Create(handle, enable);
1211     hci_layer_->EnqueueCommand(
1212         std::move(packet),
1213         BindOnce(&AclManager::impl::check_command_status<SetConnectionEncryptionStatusView>, common::Unretained(this)),
1214         handler_);
1215   }
1216 
1217   void handle_change_connection_link_key(uint16_t handle) {
1218     std::unique_ptr<ChangeConnectionLinkKeyBuilder> packet = ChangeConnectionLinkKeyBuilder::Create(handle);
1219     hci_layer_->EnqueueCommand(
1220         std::move(packet),
1221         BindOnce(&AclManager::impl::check_command_status<ChangeConnectionLinkKeyStatusView>, common::Unretained(this)),
1222         handler_);
1223   }
1224 
1225   void handle_read_clock_offset(uint16_t handle) {
1226     std::unique_ptr<ReadClockOffsetBuilder> packet = ReadClockOffsetBuilder::Create(handle);
1227     hci_layer_->EnqueueCommand(
1228         std::move(packet),
1229         BindOnce(&AclManager::impl::check_command_status<ReadClockOffsetStatusView>, common::Unretained(this)),
1230         handler_);
1231   }
1232 
1233   void handle_hold_mode(uint16_t handle, uint16_t max_interval, uint16_t min_interval) {
1234     std::unique_ptr<HoldModeBuilder> packet = HoldModeBuilder::Create(handle, max_interval, min_interval);
1235     hci_layer_->EnqueueCommand(
1236         std::move(packet),
1237         BindOnce(&AclManager::impl::check_command_status<HoldModeStatusView>, common::Unretained(this)), handler_);
1238   }
1239 
1240   void handle_sniff_mode(uint16_t handle, uint16_t max_interval, uint16_t min_interval, int16_t attempt,
1241                          uint16_t timeout) {
1242     std::unique_ptr<SniffModeBuilder> packet =
1243         SniffModeBuilder::Create(handle, max_interval, min_interval, attempt, timeout);
1244     hci_layer_->EnqueueCommand(
1245         std::move(packet),
1246         BindOnce(&AclManager::impl::check_command_status<SniffModeStatusView>, common::Unretained(this)), handler_);
1247   }
1248 
1249   void handle_exit_sniff_mode(uint16_t handle) {
1250     std::unique_ptr<ExitSniffModeBuilder> packet = ExitSniffModeBuilder::Create(handle);
1251     hci_layer_->EnqueueCommand(
1252         std::move(packet),
1253         BindOnce(&AclManager::impl::check_command_status<ExitSniffModeStatusView>, common::Unretained(this)), handler_);
1254   }
1255 
1256   void handle_qos_setup_mode(uint16_t handle, ServiceType service_type, uint32_t token_rate, uint32_t peak_bandwidth,
1257                              uint32_t latency, uint32_t delay_variation) {
1258     std::unique_ptr<QosSetupBuilder> packet =
1259         QosSetupBuilder::Create(handle, service_type, token_rate, peak_bandwidth, latency, delay_variation);
1260     hci_layer_->EnqueueCommand(
1261         std::move(packet),
1262         BindOnce(&AclManager::impl::check_command_status<QosSetupStatusView>, common::Unretained(this)), handler_);
1263   }
1264 
1265   void handle_role_discovery(uint16_t handle) {
1266     std::unique_ptr<RoleDiscoveryBuilder> packet = RoleDiscoveryBuilder::Create(handle);
1267     hci_layer_->EnqueueCommand(std::move(packet),
1268                                common::BindOnce(&impl::on_role_discovery_complete, common::Unretained(this)), handler_);
1269   }
1270 
1271   void handle_read_link_policy_settings(uint16_t handle) {
1272     std::unique_ptr<ReadLinkPolicySettingsBuilder> packet = ReadLinkPolicySettingsBuilder::Create(handle);
1273     hci_layer_->EnqueueCommand(std::move(packet),
1274                                common::BindOnce(&impl::on_read_link_policy_settings_complete, common::Unretained(this)),
1275                                handler_);
1276   }
1277 
1278   void handle_write_link_policy_settings(uint16_t handle, uint16_t link_policy_settings) {
1279     std::unique_ptr<WriteLinkPolicySettingsBuilder> packet =
1280         WriteLinkPolicySettingsBuilder::Create(handle, link_policy_settings);
1281     hci_layer_->EnqueueCommand(std::move(packet),
1282                                BindOnce(&AclManager::impl::check_command_complete<WriteLinkPolicySettingsCompleteView>,
1283                                         common::Unretained(this)),
1284                                handler_);
1285   }
1286 
1287   void handle_flow_specification(uint16_t handle, FlowDirection flow_direction, ServiceType service_type,
1288                                  uint32_t token_rate, uint32_t token_bucket_size, uint32_t peak_bandwidth,
1289                                  uint32_t access_latency) {
1290     std::unique_ptr<FlowSpecificationBuilder> packet = FlowSpecificationBuilder::Create(
1291         handle, flow_direction, service_type, token_rate, token_bucket_size, peak_bandwidth, access_latency);
1292     hci_layer_->EnqueueCommand(
1293         std::move(packet),
1294         BindOnce(&AclManager::impl::check_command_status<FlowSpecificationStatusView>, common::Unretained(this)),
1295         handler_);
1296   }
1297 
1298   void handle_sniff_subrating(uint16_t handle, uint16_t maximum_latency, uint16_t minimum_remote_timeout,
1299                               uint16_t minimum_local_timeout) {
1300     std::unique_ptr<SniffSubratingBuilder> packet =
1301         SniffSubratingBuilder::Create(handle, maximum_latency, minimum_remote_timeout, minimum_local_timeout);
1302     hci_layer_->EnqueueCommand(
1303         std::move(packet),
1304         BindOnce(&AclManager::impl::check_command_complete<SniffSubratingCompleteView>, common::Unretained(this)),
1305         handler_);
1306   }
1307 
1308   void handle_flush(uint16_t handle) {
1309     std::unique_ptr<FlushBuilder> packet = FlushBuilder::Create(handle);
1310     hci_layer_->EnqueueCommand(
1311         std::move(packet),
1312         BindOnce(&AclManager::impl::check_command_complete<FlushCompleteView>, common::Unretained(this)), handler_);
1313   }
1314 
1315   void handle_read_automatic_flush_timeout(uint16_t handle) {
1316     std::unique_ptr<ReadAutomaticFlushTimeoutBuilder> packet = ReadAutomaticFlushTimeoutBuilder::Create(handle);
1317     hci_layer_->EnqueueCommand(
1318         std::move(packet), common::BindOnce(&impl::on_read_automatic_flush_timeout_complete, common::Unretained(this)),
1319         handler_);
1320   }
1321 
1322   void handle_write_automatic_flush_timeout(uint16_t handle, uint16_t flush_timeout) {
1323     std::unique_ptr<WriteAutomaticFlushTimeoutBuilder> packet =
1324         WriteAutomaticFlushTimeoutBuilder::Create(handle, flush_timeout);
1325     hci_layer_->EnqueueCommand(
1326         std::move(packet),
1327         BindOnce(&AclManager::impl::check_command_complete<WriteAutomaticFlushTimeoutCompleteView>,
1328                  common::Unretained(this)),
1329         handler_);
1330   }
1331 
1332   void handle_read_transmit_power_level(uint16_t handle, TransmitPowerLevelType type) {
1333     std::unique_ptr<ReadTransmitPowerLevelBuilder> packet = ReadTransmitPowerLevelBuilder::Create(handle, type);
1334     hci_layer_->EnqueueCommand(std::move(packet),
1335                                common::BindOnce(&impl::on_read_transmit_power_level_complete, common::Unretained(this)),
1336                                handler_);
1337   }
1338 
1339   void handle_read_link_supervision_timeout(uint16_t handle) {
1340     std::unique_ptr<ReadLinkSupervisionTimeoutBuilder> packet = ReadLinkSupervisionTimeoutBuilder::Create(handle);
1341     hci_layer_->EnqueueCommand(
1342         std::move(packet), common::BindOnce(&impl::on_read_link_supervision_timeout_complete, common::Unretained(this)),
1343         handler_);
1344   }
1345 
1346   void handle_write_link_supervision_timeout(uint16_t handle, uint16_t link_supervision_timeout) {
1347     std::unique_ptr<WriteLinkSupervisionTimeoutBuilder> packet =
1348         WriteLinkSupervisionTimeoutBuilder::Create(handle, link_supervision_timeout);
1349     hci_layer_->EnqueueCommand(
1350         std::move(packet),
1351         BindOnce(&AclManager::impl::check_command_complete<WriteLinkSupervisionTimeoutCompleteView>,
1352                  common::Unretained(this)),
1353         handler_);
1354   }
1355 
1356   void handle_read_failed_contact_counter(uint16_t handle) {
1357     std::unique_ptr<ReadFailedContactCounterBuilder> packet = ReadFailedContactCounterBuilder::Create(handle);
1358     hci_layer_->EnqueueCommand(
1359         std::move(packet), common::BindOnce(&impl::on_read_failed_contact_counter_complete, common::Unretained(this)),
1360         handler_);
1361   }
1362 
1363   void handle_reset_failed_contact_counter(uint16_t handle) {
1364     std::unique_ptr<ResetFailedContactCounterBuilder> packet = ResetFailedContactCounterBuilder::Create(handle);
1365     hci_layer_->EnqueueCommand(std::move(packet), BindOnce([](CommandCompleteView view) { /* TODO: check? */ }),
1366                                handler_);
1367   }
1368 
1369   void handle_read_link_quality(uint16_t handle) {
1370     std::unique_ptr<ReadLinkQualityBuilder> packet = ReadLinkQualityBuilder::Create(handle);
1371     hci_layer_->EnqueueCommand(
1372         std::move(packet), common::BindOnce(&impl::on_read_link_quality_complete, common::Unretained(this)), handler_);
1373   }
1374 
1375   void handle_afh_channel_map(uint16_t handle) {
1376     std::unique_ptr<ReadAfhChannelMapBuilder> packet = ReadAfhChannelMapBuilder::Create(handle);
1377     hci_layer_->EnqueueCommand(std::move(packet),
1378                                common::BindOnce(&impl::on_read_afh_channel_map_complete, common::Unretained(this)),
1379                                handler_);
1380   }
1381 
1382   void handle_read_rssi(uint16_t handle) {
1383     std::unique_ptr<ReadRssiBuilder> packet = ReadRssiBuilder::Create(handle);
1384     hci_layer_->EnqueueCommand(std::move(packet),
1385                                common::BindOnce(&impl::on_read_rssi_complete, common::Unretained(this)), handler_);
1386   }
1387 
1388   void handle_read_remote_version_information(uint16_t handle) {
1389     hci_layer_->EnqueueCommand(
1390         ReadRemoteVersionInformationBuilder::Create(handle),
1391         common::BindOnce(&impl::on_read_remote_version_information_status, common::Unretained(this)), handler_);
1392   }
1393 
1394   void handle_read_remote_supported_features(uint16_t handle) {
1395     hci_layer_->EnqueueCommand(
1396         ReadRemoteSupportedFeaturesBuilder::Create(handle),
1397         common::BindOnce(&impl::on_read_remote_supported_features_status, common::Unretained(this)), handler_);
1398   }
1399 
1400   void handle_read_remote_extended_features(uint16_t handle) {
1401     // TODO(optedoblivion): Read the other pages until max pages
1402     hci_layer_->EnqueueCommand(
1403         ReadRemoteExtendedFeaturesBuilder::Create(handle, 1),
1404         common::BindOnce(&impl::on_read_remote_extended_features_status, common::Unretained(this)), handler_);
1405   }
1406 
1407   void handle_read_clock(uint16_t handle, WhichClock which_clock) {
1408     std::unique_ptr<ReadClockBuilder> packet = ReadClockBuilder::Create(handle, which_clock);
1409     hci_layer_->EnqueueCommand(std::move(packet),
1410                                common::BindOnce(&impl::on_read_clock_complete, common::Unretained(this)), handler_);
1411   }
1412 
1413   void handle_le_connection_update(uint16_t handle, uint16_t conn_interval_min, uint16_t conn_interval_max,
1414                                    uint16_t conn_latency, uint16_t supervision_timeout) {
1415     auto packet = LeConnectionUpdateBuilder::Create(handle, conn_interval_min, conn_interval_max, conn_latency,
1416                                                     supervision_timeout, kMinimumCeLength, kMaximumCeLength);
1417     hci_layer_->EnqueueCommand(std::move(packet), common::BindOnce([](CommandStatusView status) {
1418                                  ASSERT(status.IsValid());
1419                                  ASSERT(status.GetCommandOpCode() == OpCode::LE_CREATE_CONNECTION);
1420                                }),
1421                                handler_);
1422   }
1423 
1424   template <class T>
1425   void check_command_complete(CommandCompleteView view) {
1426     ASSERT(view.IsValid());
1427     auto status_view = T::Create(view);
1428     if (!status_view.IsValid()) {
1429       LOG_ERROR("Received command complete with invalid packet, opcode 0x%02hx", view.GetCommandOpCode());
1430       return;
1431     }
1432     ErrorCode status = status_view.GetStatus();
1433     OpCode op_code = status_view.GetCommandOpCode();
1434     if (status != ErrorCode::SUCCESS) {
1435       std::string error_code = ErrorCodeText(status);
1436       LOG_ERROR("Received command complete with error code %s, opcode 0x%02hx", error_code.c_str(), op_code);
1437       return;
1438     }
1439   }
1440 
1441   template <class T>
1442   void check_command_status(CommandStatusView view) {
1443     ASSERT(view.IsValid());
1444     auto status_view = T::Create(view);
1445     if (!status_view.IsValid()) {
1446       LOG_ERROR("Received command status with invalid packet, opcode 0x%02hx", view.GetCommandOpCode());
1447       return;
1448     }
1449     ErrorCode status = status_view.GetStatus();
1450     OpCode op_code = status_view.GetCommandOpCode();
1451     if (status != ErrorCode::SUCCESS) {
1452       std::string error_code = ErrorCodeText(status);
1453       LOG_ERROR("Received command status with error code %s, opcode 0x%02hx", error_code.c_str(), op_code);
1454       return;
1455     }
1456   }
1457 
1458   void cleanup(uint16_t handle) {
1459     ASSERT(acl_connections_.count(handle) == 1);
1460     auto& acl_connection = acl_connections_.find(handle)->second;
1461     if (acl_connection.is_registered_) {
1462       acl_connection.is_registered_ = false;
1463       acl_connection.queue_->GetDownEnd()->UnregisterDequeue();
1464     }
1465     acl_connections_.erase(handle);
1466   }
1467 
1468   void on_accept_connection_status(Address address, CommandStatusView status) {
1469     auto accept_status = AcceptConnectionRequestStatusView::Create(status);
1470     ASSERT(accept_status.IsValid());
1471     if (status.GetStatus() != ErrorCode::SUCCESS) {
1472       cancel_connect(address);
1473     }
1474   }
1475 
1476   void reject_connection(std::unique_ptr<RejectConnectionRequestBuilder> builder) {
1477     hci_layer_->EnqueueCommand(std::move(builder), BindOnce([](CommandStatusView status) { /* TODO: check? */ }),
1478                                handler_);
1479   }
1480 
1481   void handle_register_callbacks(ConnectionCallbacks* callbacks, os::Handler* handler) {
1482     ASSERT(client_callbacks_ == nullptr);
1483     ASSERT(client_handler_ == nullptr);
1484     client_callbacks_ = callbacks;
1485     client_handler_ = handler;
1486   }
1487 
1488   void handle_register_le_callbacks(LeConnectionCallbacks* callbacks, os::Handler* handler) {
1489     ASSERT(le_client_callbacks_ == nullptr);
1490     ASSERT(le_client_handler_ == nullptr);
1491     le_client_callbacks_ = callbacks;
1492     le_client_handler_ = handler;
1493   }
1494 
1495   void handle_register_acl_manager_callbacks(AclManagerCallbacks* callbacks, os::Handler* handler) {
1496     ASSERT(acl_manager_client_callbacks_ == nullptr);
1497     ASSERT(acl_manager_client_handler_ == nullptr);
1498     acl_manager_client_callbacks_ = callbacks;
1499     acl_manager_client_handler_ = handler;
1500   }
1501 
1502   void handle_register_le_acl_manager_callbacks(AclManagerCallbacks* callbacks, os::Handler* handler) {
1503     ASSERT(le_acl_manager_client_callbacks_ == nullptr);
1504     ASSERT(le_acl_manager_client_handler_ == nullptr);
1505     le_acl_manager_client_callbacks_ = callbacks;
1506     le_acl_manager_client_handler_ = handler;
1507   }
1508 
1509   acl_connection& check_and_get_connection(uint16_t handle) {
1510     auto connection = acl_connections_.find(handle);
1511     ASSERT(connection != acl_connections_.end());
1512     return connection->second;
1513   }
1514 
1515   AclConnection::QueueUpEnd* get_acl_queue_end(uint16_t handle) {
1516     auto& connection = check_and_get_connection(handle);
1517     return connection.queue_->GetUpEnd();
1518   }
1519 
1520   void RegisterCallbacks(uint16_t handle, ConnectionManagementCallbacks* callbacks, os::Handler* handler) {
1521     auto& connection = check_and_get_connection(handle);
1522     ASSERT(connection.command_complete_callbacks_ == nullptr);
1523     connection.command_complete_callbacks_ = callbacks;
1524     connection.command_complete_handler_ = handler;
1525   }
1526 
1527   void UnregisterCallbacks(uint16_t handle, ConnectionManagementCallbacks* callbacks) {
1528     auto& connection = check_and_get_connection(handle);
1529     ASSERT(connection.command_complete_callbacks_ == callbacks);
1530     connection.command_complete_callbacks_ = nullptr;
1531   }
1532 
1533   void RegisterDisconnectCallback(uint16_t handle, common::OnceCallback<void(ErrorCode)> on_disconnect,
1534                                   os::Handler* handler) {
1535     auto& connection = check_and_get_connection(handle);
1536     connection.on_disconnect_callback_ = std::move(on_disconnect);
1537     connection.disconnect_handler_ = handler;
1538     if (connection.is_disconnected_) {
1539       connection.call_disconnect_callback();
1540     }
1541   }
1542 
1543   bool Disconnect(uint16_t handle, DisconnectReason reason) {
1544     auto& connection = check_and_get_connection(handle);
1545     if (connection.is_disconnected_) {
1546       LOG_INFO("Already disconnected");
1547       return false;
1548     }
1549     handler_->Post(BindOnce(&impl::handle_disconnect, common::Unretained(this), handle, reason));
1550     return true;
1551   }
1552 
1553   bool ChangeConnectionPacketType(uint16_t handle, uint16_t packet_type) {
1554     auto& connection = check_and_get_connection(handle);
1555     if (connection.is_disconnected_) {
1556       LOG_INFO("Already disconnected");
1557       return false;
1558     }
1559     handler_->Post(
1560         BindOnce(&impl::handle_change_connection_packet_type, common::Unretained(this), handle, packet_type));
1561     return true;
1562   }
1563 
1564   bool AuthenticationRequested(uint16_t handle) {
1565     LOG_INFO("Auth reqiuest");
1566     auto& connection = check_and_get_connection(handle);
1567     if (connection.is_disconnected_) {
1568       LOG_INFO("Already disconnected");
1569       return false;
1570     }
1571     handler_->Post(BindOnce(&impl::handle_authentication_requested, common::Unretained(this), handle));
1572     return true;
1573   }
1574 
1575   bool SetConnectionEncryption(uint16_t handle, Enable enable) {
1576     auto& connection = check_and_get_connection(handle);
1577     if (connection.is_disconnected_) {
1578       LOG_INFO("Already disconnected");
1579       return false;
1580     }
1581     handler_->Post(BindOnce(&impl::handle_set_connection_encryption, common::Unretained(this), handle, enable));
1582     return true;
1583   }
1584 
1585   bool ChangeConnectionLinkKey(uint16_t handle) {
1586     auto& connection = check_and_get_connection(handle);
1587     if (connection.is_disconnected_) {
1588       LOG_INFO("Already disconnected");
1589       return false;
1590     }
1591     handler_->Post(BindOnce(&impl::handle_change_connection_link_key, common::Unretained(this), handle));
1592     return true;
1593   }
1594 
1595   bool ReadClockOffset(uint16_t handle) {
1596     auto& connection = check_and_get_connection(handle);
1597     if (connection.is_disconnected_) {
1598       LOG_INFO("Already disconnected");
1599       return false;
1600     }
1601     handler_->Post(BindOnce(&impl::handle_read_clock_offset, common::Unretained(this), handle));
1602     return true;
1603   }
1604 
1605   bool HoldMode(uint16_t handle, uint16_t max_interval, uint16_t min_interval) {
1606     auto& connection = check_and_get_connection(handle);
1607     if (connection.is_disconnected_) {
1608       LOG_INFO("Already disconnected");
1609       return false;
1610     }
1611     handler_->Post(BindOnce(&impl::handle_hold_mode, common::Unretained(this), handle, max_interval, min_interval));
1612     return true;
1613   }
1614 
1615   bool SniffMode(uint16_t handle, uint16_t max_interval, uint16_t min_interval, int16_t attempt, uint16_t timeout) {
1616     auto& connection = check_and_get_connection(handle);
1617     if (connection.is_disconnected_) {
1618       LOG_INFO("Already disconnected");
1619       return false;
1620     }
1621     handler_->Post(BindOnce(&impl::handle_sniff_mode, common::Unretained(this), handle, max_interval, min_interval,
1622                             attempt, timeout));
1623     return true;
1624   }
1625 
1626   bool ExitSniffMode(uint16_t handle) {
1627     auto& connection = check_and_get_connection(handle);
1628     if (connection.is_disconnected_) {
1629       LOG_INFO("Already disconnected");
1630       return false;
1631     }
1632     handler_->Post(BindOnce(&impl::handle_exit_sniff_mode, common::Unretained(this), handle));
1633     return true;
1634   }
1635 
1636   bool QosSetup(uint16_t handle, ServiceType service_type, uint32_t token_rate, uint32_t peak_bandwidth,
1637                 uint32_t latency, uint32_t delay_variation) {
1638     auto& connection = check_and_get_connection(handle);
1639     if (connection.is_disconnected_) {
1640       LOG_INFO("Already disconnected");
1641       return false;
1642     }
1643     handler_->Post(BindOnce(&impl::handle_qos_setup_mode, common::Unretained(this), handle, service_type, token_rate,
1644                             peak_bandwidth, latency, delay_variation));
1645     return true;
1646   }
1647 
1648   bool RoleDiscovery(uint16_t handle) {
1649     auto& connection = check_and_get_connection(handle);
1650     if (connection.is_disconnected_) {
1651       LOG_INFO("Already disconnected");
1652       return false;
1653     }
1654     handler_->Post(BindOnce(&impl::handle_role_discovery, common::Unretained(this), handle));
1655     return true;
1656   }
1657 
1658   bool ReadLinkPolicySettings(uint16_t handle) {
1659     auto& connection = check_and_get_connection(handle);
1660     if (connection.is_disconnected_) {
1661       LOG_INFO("Already disconnected");
1662       return false;
1663     }
1664     handler_->Post(BindOnce(&impl::handle_read_link_policy_settings, common::Unretained(this), handle));
1665     return true;
1666   }
1667 
1668   bool WriteLinkPolicySettings(uint16_t handle, uint16_t link_policy_settings) {
1669     auto& connection = check_and_get_connection(handle);
1670     if (connection.is_disconnected_) {
1671       LOG_INFO("Already disconnected");
1672       return false;
1673     }
1674     handler_->Post(
1675         BindOnce(&impl::handle_write_link_policy_settings, common::Unretained(this), handle, link_policy_settings));
1676     return true;
1677   }
1678 
1679   bool FlowSpecification(uint16_t handle, FlowDirection flow_direction, ServiceType service_type, uint32_t token_rate,
1680                          uint32_t token_bucket_size, uint32_t peak_bandwidth, uint32_t access_latency) {
1681     auto& connection = check_and_get_connection(handle);
1682     if (connection.is_disconnected_) {
1683       LOG_INFO("Already disconnected");
1684       return false;
1685     }
1686     handler_->Post(BindOnce(&impl::handle_flow_specification, common::Unretained(this), handle, flow_direction,
1687                             service_type, token_rate, token_bucket_size, peak_bandwidth, access_latency));
1688     return true;
1689   }
1690 
1691   bool SniffSubrating(uint16_t handle, uint16_t maximum_latency, uint16_t minimum_remote_timeout,
1692                       uint16_t minimum_local_timeout) {
1693     auto& connection = check_and_get_connection(handle);
1694     if (connection.is_disconnected_) {
1695       LOG_INFO("Already disconnected");
1696       return false;
1697     }
1698     handler_->Post(BindOnce(&impl::handle_sniff_subrating, common::Unretained(this), handle, maximum_latency,
1699                             minimum_remote_timeout, minimum_local_timeout));
1700     return true;
1701   }
1702 
1703   bool Flush(uint16_t handle) {
1704     auto& connection = check_and_get_connection(handle);
1705     if (connection.is_disconnected_) {
1706       LOG_INFO("Already disconnected");
1707       return false;
1708     }
1709     handler_->Post(BindOnce(&impl::handle_flush, common::Unretained(this), handle));
1710     return true;
1711   }
1712 
1713   bool ReadAutomaticFlushTimeout(uint16_t handle) {
1714     auto& connection = check_and_get_connection(handle);
1715     if (connection.is_disconnected_) {
1716       LOG_INFO("Already disconnected");
1717       return false;
1718     }
1719     handler_->Post(BindOnce(&impl::handle_read_automatic_flush_timeout, common::Unretained(this), handle));
1720     return true;
1721   }
1722 
1723   bool WriteAutomaticFlushTimeout(uint16_t handle, uint16_t flush_timeout) {
1724     auto& connection = check_and_get_connection(handle);
1725     if (connection.is_disconnected_) {
1726       LOG_INFO("Already disconnected");
1727       return false;
1728     }
1729     handler_->Post(
1730         BindOnce(&impl::handle_write_automatic_flush_timeout, common::Unretained(this), handle, flush_timeout));
1731     return true;
1732   }
1733 
1734   bool ReadTransmitPowerLevel(uint16_t handle, TransmitPowerLevelType type) {
1735     auto& connection = check_and_get_connection(handle);
1736     if (connection.is_disconnected_) {
1737       LOG_INFO("Already disconnected");
1738       return false;
1739     }
1740     handler_->Post(BindOnce(&impl::handle_read_transmit_power_level, common::Unretained(this), handle, type));
1741     return true;
1742   }
1743 
1744   bool ReadLinkSupervisionTimeout(uint16_t handle) {
1745     auto& connection = check_and_get_connection(handle);
1746     if (connection.is_disconnected_) {
1747       LOG_INFO("Already disconnected");
1748       return false;
1749     }
1750     handler_->Post(BindOnce(&impl::handle_read_link_supervision_timeout, common::Unretained(this), handle));
1751     return true;
1752   }
1753 
1754   bool WriteLinkSupervisionTimeout(uint16_t handle, uint16_t link_supervision_timeout) {
1755     auto& connection = check_and_get_connection(handle);
1756     if (connection.is_disconnected_) {
1757       LOG_INFO("Already disconnected");
1758       return false;
1759     }
1760     handler_->Post(BindOnce(&impl::handle_write_link_supervision_timeout, common::Unretained(this), handle,
1761                             link_supervision_timeout));
1762     return true;
1763   }
1764 
1765   bool ReadFailedContactCounter(uint16_t handle) {
1766     auto& connection = check_and_get_connection(handle);
1767     if (connection.is_disconnected_) {
1768       LOG_INFO("Already disconnected");
1769       return false;
1770     }
1771     handler_->Post(BindOnce(&impl::handle_read_failed_contact_counter, common::Unretained(this), handle));
1772     return true;
1773   }
1774 
1775   bool ResetFailedContactCounter(uint16_t handle) {
1776     auto& connection = check_and_get_connection(handle);
1777     if (connection.is_disconnected_) {
1778       LOG_INFO("Already disconnected");
1779       return false;
1780     }
1781     handler_->Post(BindOnce(&impl::handle_reset_failed_contact_counter, common::Unretained(this), handle));
1782     return true;
1783   }
1784 
1785   bool ReadLinkQuality(uint16_t handle) {
1786     auto& connection = check_and_get_connection(handle);
1787     if (connection.is_disconnected_) {
1788       LOG_INFO("Already disconnected");
1789       return false;
1790     }
1791     handler_->Post(BindOnce(&impl::handle_read_link_quality, common::Unretained(this), handle));
1792     return true;
1793   }
1794 
1795   bool ReadAfhChannelMap(uint16_t handle) {
1796     auto& connection = check_and_get_connection(handle);
1797     if (connection.is_disconnected_) {
1798       LOG_INFO("Already disconnected");
1799       return false;
1800     }
1801     handler_->Post(BindOnce(&impl::handle_afh_channel_map, common::Unretained(this), handle));
1802     return true;
1803   }
1804 
1805   bool ReadRssi(uint16_t handle) {
1806     auto& connection = check_and_get_connection(handle);
1807     if (connection.is_disconnected_) {
1808       LOG_INFO("Already disconnected");
1809       return false;
1810     }
1811     handler_->Post(BindOnce(&impl::handle_read_rssi, common::Unretained(this), handle));
1812     return true;
1813   }
1814 
1815   bool ReadRemoteVersionInformation(uint16_t handle) {
1816     auto& connection = check_and_get_connection(handle);
1817     if (connection.is_disconnected_) {
1818       LOG_INFO("Already disconnected");
1819       return false;
1820     }
1821     handler_->Post(BindOnce(&impl::handle_read_remote_version_information, common::Unretained(this), handle));
1822     return true;
1823   }
1824 
1825   bool ReadRemoteSupportedFeatures(uint16_t handle) {
1826     auto& connection = check_and_get_connection(handle);
1827     if (connection.is_disconnected_) {
1828       LOG_INFO("Already disconnected");
1829       return false;
1830     }
1831     handler_->Post(BindOnce(&impl::handle_read_remote_supported_features, common::Unretained(this), handle));
1832     return true;
1833   }
1834 
1835   bool ReadRemoteExtendedFeatures(uint16_t handle) {
1836     auto& connection = check_and_get_connection(handle);
1837     if (connection.is_disconnected_) {
1838       LOG_INFO("Already disconnected");
1839       return false;
1840     }
1841     handler_->Post(BindOnce(&impl::handle_read_remote_extended_features, common::Unretained(this), handle));
1842     return true;
1843   }
1844 
1845   bool ReadClock(uint16_t handle, WhichClock which_clock) {
1846     auto& connection = check_and_get_connection(handle);
1847     if (connection.is_disconnected_) {
1848       LOG_INFO("Already disconnected");
1849       return false;
1850     }
1851     handler_->Post(BindOnce(&impl::handle_read_clock, common::Unretained(this), handle, which_clock));
1852     return true;
1853   }
1854 
1855   bool LeConnectionUpdate(uint16_t handle, uint16_t conn_interval_min, uint16_t conn_interval_max,
1856                           uint16_t conn_latency, uint16_t supervision_timeout,
1857                           common::OnceCallback<void(ErrorCode)> done_callback, os::Handler* handler) {
1858     auto& connection = check_and_get_connection(handle);
1859     if (connection.is_disconnected_) {
1860       LOG_INFO("Already disconnected");
1861       return false;
1862     }
1863     if (!connection.on_connection_update_complete_callback_.is_null()) {
1864       LOG_INFO("There is another pending connection update");
1865       return false;
1866     }
1867     connection.on_connection_update_complete_callback_ = std::move(done_callback);
1868     connection.on_connection_update_complete_callback_handler_ = handler;
1869     if (conn_interval_min < 0x0006 || conn_interval_min > 0x0C80 || conn_interval_max < 0x0006 ||
1870         conn_interval_max > 0x0C80 || conn_latency > 0x01F3 || supervision_timeout < 0x000A ||
1871         supervision_timeout > 0x0C80) {
1872       LOG_ERROR("Invalid parameter");
1873       return false;
1874     }
1875     handler_->Post(BindOnce(&impl::handle_le_connection_update, common::Unretained(this), handle, conn_interval_min,
1876                             conn_interval_max, conn_latency, supervision_timeout));
1877     return true;
1878   }
1879 
1880   void Finish(uint16_t handle) {
1881     auto& connection = check_and_get_connection(handle);
1882     ASSERT_LOG(connection.is_disconnected_, "Finish must be invoked after disconnection (handle 0x%04hx)", handle);
1883     handler_->Post(BindOnce(&impl::cleanup, common::Unretained(this), handle));
1884   }
1885 
1886   const AclManager& acl_manager_;
1887 
1888   static constexpr uint16_t kMinimumCeLength = 0x0002;
1889   static constexpr uint16_t kMaximumCeLength = 0x0C00;
1890 
1891   Controller* controller_ = nullptr;
1892   uint16_t max_acl_packet_credits_ = 0;
1893   uint16_t acl_packet_credits_ = 0;
1894   uint16_t acl_buffer_length_ = 0;
1895 
1896   std::list<std::unique_ptr<AclPacketBuilder>> fragments_to_send_;
1897   std::map<uint16_t, acl_connection>::iterator current_connection_pair_;
1898 
1899   HciLayer* hci_layer_ = nullptr;
1900   os::Handler* handler_ = nullptr;
1901   ConnectionCallbacks* client_callbacks_ = nullptr;
1902   os::Handler* client_handler_ = nullptr;
1903   LeConnectionCallbacks* le_client_callbacks_ = nullptr;
1904   os::Handler* le_client_handler_ = nullptr;
1905   AclManagerCallbacks* acl_manager_client_callbacks_ = nullptr;
1906   os::Handler* acl_manager_client_handler_ = nullptr;
1907   AclManagerCallbacks* le_acl_manager_client_callbacks_ = nullptr;
1908   os::Handler* le_acl_manager_client_handler_ = nullptr;
1909   common::BidiQueueEnd<AclPacketBuilder, AclPacketView>* hci_queue_end_ = nullptr;
1910   std::map<uint16_t, AclManager::acl_connection> acl_connections_;
1911   std::set<Address> connecting_;
1912   std::set<AddressWithType> connecting_le_;
1913   common::Callback<bool(Address, ClassOfDevice)> should_accept_connection_;
1914   std::queue<std::pair<Address, std::unique_ptr<CreateConnectionBuilder>>> pending_outgoing_connections_;
1915   size_t hci_mtu_{0};
1916 };
1917 
1918 AclConnection::QueueUpEnd* AclConnection::GetAclQueueEnd() const {
1919   return manager_->pimpl_->get_acl_queue_end(handle_);
1920 }
1921 
1922 void AclConnection::RegisterCallbacks(ConnectionManagementCallbacks* callbacks, os::Handler* handler) {
1923   return manager_->pimpl_->RegisterCallbacks(handle_, callbacks, handler);
1924 }
1925 
1926 void AclConnection::UnregisterCallbacks(ConnectionManagementCallbacks* callbacks) {
1927   return manager_->pimpl_->UnregisterCallbacks(handle_, callbacks);
1928 }
1929 
1930 void AclConnection::RegisterDisconnectCallback(common::OnceCallback<void(ErrorCode)> on_disconnect,
1931                                                os::Handler* handler) {
1932   return manager_->pimpl_->RegisterDisconnectCallback(handle_, std::move(on_disconnect), handler);
1933 }
1934 
1935 bool AclConnection::Disconnect(DisconnectReason reason) {
1936   return manager_->pimpl_->Disconnect(handle_, reason);
1937 }
1938 
1939 bool AclConnection::ChangeConnectionPacketType(uint16_t packet_type) {
1940   return manager_->pimpl_->ChangeConnectionPacketType(handle_, packet_type);
1941 }
1942 
1943 bool AclConnection::AuthenticationRequested() {
1944   return manager_->pimpl_->AuthenticationRequested(handle_);
1945 }
1946 
1947 bool AclConnection::SetConnectionEncryption(Enable enable) {
1948   return manager_->pimpl_->SetConnectionEncryption(handle_, enable);
1949 }
1950 
1951 bool AclConnection::ChangeConnectionLinkKey() {
1952   return manager_->pimpl_->ChangeConnectionLinkKey(handle_);
1953 }
1954 
1955 bool AclConnection::ReadClockOffset() {
1956   return manager_->pimpl_->ReadClockOffset(handle_);
1957 }
1958 
1959 bool AclConnection::HoldMode(uint16_t max_interval, uint16_t min_interval) {
1960   return manager_->pimpl_->HoldMode(handle_, max_interval, min_interval);
1961 }
1962 
1963 bool AclConnection::SniffMode(uint16_t max_interval, uint16_t min_interval, uint16_t attempt, uint16_t timeout) {
1964   return manager_->pimpl_->SniffMode(handle_, max_interval, min_interval, attempt, timeout);
1965 }
1966 
1967 bool AclConnection::ExitSniffMode() {
1968   return manager_->pimpl_->ExitSniffMode(handle_);
1969 }
1970 
1971 bool AclConnection::QosSetup(ServiceType service_type, uint32_t token_rate, uint32_t peak_bandwidth, uint32_t latency,
1972                              uint32_t delay_variation) {
1973   return manager_->pimpl_->QosSetup(handle_, service_type, token_rate, peak_bandwidth, latency, delay_variation);
1974 }
1975 
1976 bool AclConnection::RoleDiscovery() {
1977   return manager_->pimpl_->RoleDiscovery(handle_);
1978 }
1979 
1980 bool AclConnection::ReadLinkPolicySettings() {
1981   return manager_->pimpl_->ReadLinkPolicySettings(handle_);
1982 }
1983 
1984 bool AclConnection::WriteLinkPolicySettings(uint16_t link_policy_settings) {
1985   return manager_->pimpl_->WriteLinkPolicySettings(handle_, link_policy_settings);
1986 }
1987 
1988 bool AclConnection::FlowSpecification(FlowDirection flow_direction, ServiceType service_type, uint32_t token_rate,
1989                                       uint32_t token_bucket_size, uint32_t peak_bandwidth, uint32_t access_latency) {
1990   return manager_->pimpl_->FlowSpecification(handle_, flow_direction, service_type, token_rate, token_bucket_size,
1991                                              peak_bandwidth, access_latency);
1992 }
1993 
1994 bool AclConnection::SniffSubrating(uint16_t maximum_latency, uint16_t minimum_remote_timeout,
1995                                    uint16_t minimum_local_timeout) {
1996   return manager_->pimpl_->SniffSubrating(handle_, maximum_latency, minimum_remote_timeout, minimum_local_timeout);
1997 }
1998 
1999 bool AclConnection::Flush() {
2000   return manager_->pimpl_->Flush(handle_);
2001 }
2002 
2003 bool AclConnection::ReadAutomaticFlushTimeout() {
2004   return manager_->pimpl_->ReadAutomaticFlushTimeout(handle_);
2005 }
2006 
2007 bool AclConnection::WriteAutomaticFlushTimeout(uint16_t flush_timeout) {
2008   return manager_->pimpl_->WriteAutomaticFlushTimeout(handle_, flush_timeout);
2009 }
2010 
2011 bool AclConnection::ReadTransmitPowerLevel(TransmitPowerLevelType type) {
2012   return manager_->pimpl_->ReadTransmitPowerLevel(handle_, type);
2013 }
2014 
2015 bool AclConnection::ReadLinkSupervisionTimeout() {
2016   return manager_->pimpl_->ReadLinkSupervisionTimeout(handle_);
2017 }
2018 
2019 bool AclConnection::WriteLinkSupervisionTimeout(uint16_t link_supervision_timeout) {
2020   return manager_->pimpl_->WriteLinkSupervisionTimeout(handle_, link_supervision_timeout);
2021 }
2022 
2023 bool AclConnection::ReadFailedContactCounter() {
2024   return manager_->pimpl_->ReadFailedContactCounter(handle_);
2025 }
2026 
2027 bool AclConnection::ResetFailedContactCounter() {
2028   return manager_->pimpl_->ResetFailedContactCounter(handle_);
2029 }
2030 
2031 bool AclConnection::ReadLinkQuality() {
2032   return manager_->pimpl_->ReadLinkQuality(handle_);
2033 }
2034 
2035 bool AclConnection::ReadAfhChannelMap() {
2036   return manager_->pimpl_->ReadAfhChannelMap(handle_);
2037 }
2038 
2039 bool AclConnection::ReadRssi() {
2040   return manager_->pimpl_->ReadRssi(handle_);
2041 }
2042 
2043 bool AclConnection::ReadRemoteVersionInformation() {
2044   return manager_->pimpl_->ReadRemoteVersionInformation(handle_);
2045 }
2046 
2047 bool AclConnection::ReadRemoteSupportedFeatures() {
2048   return manager_->pimpl_->ReadRemoteSupportedFeatures(handle_);
2049 }
2050 
2051 bool AclConnection::ReadRemoteExtendedFeatures() {
2052   return manager_->pimpl_->ReadRemoteExtendedFeatures(handle_);
2053 }
2054 
2055 bool AclConnection::ReadClock(WhichClock which_clock) {
2056   return manager_->pimpl_->ReadClock(handle_, which_clock);
2057 }
2058 
2059 bool AclConnection::LeConnectionUpdate(uint16_t conn_interval_min, uint16_t conn_interval_max, uint16_t conn_latency,
2060                                        uint16_t supervision_timeout,
2061                                        common::OnceCallback<void(ErrorCode)> done_callback, os::Handler* handler) {
2062   return manager_->pimpl_->LeConnectionUpdate(handle_, conn_interval_min, conn_interval_max, conn_latency,
2063                                               supervision_timeout, std::move(done_callback), handler);
2064 }
2065 
2066 void AclConnection::Finish() {
2067   return manager_->pimpl_->Finish(handle_);
2068 }
2069 
2070 AclManager::AclManager() : pimpl_(std::make_unique<impl>(*this)) {}
2071 
2072 void AclManager::RegisterCallbacks(ConnectionCallbacks* callbacks, os::Handler* handler) {
2073   ASSERT(callbacks != nullptr && handler != nullptr);
2074   GetHandler()->Post(common::BindOnce(&impl::handle_register_callbacks, common::Unretained(pimpl_.get()),
2075                                       common::Unretained(callbacks), common::Unretained(handler)));
2076 }
2077 
2078 void AclManager::RegisterLeCallbacks(LeConnectionCallbacks* callbacks, os::Handler* handler) {
2079   ASSERT(callbacks != nullptr && handler != nullptr);
2080   GetHandler()->Post(common::BindOnce(&impl::handle_register_le_callbacks, common::Unretained(pimpl_.get()),
2081                                       common::Unretained(callbacks), common::Unretained(handler)));
2082 }
2083 
2084 void AclManager::RegisterAclManagerCallbacks(AclManagerCallbacks* callbacks, os::Handler* handler) {
2085   ASSERT(callbacks != nullptr && handler != nullptr);
2086   GetHandler()->Post(common::BindOnce(&impl::handle_register_acl_manager_callbacks, common::Unretained(pimpl_.get()),
2087                                       common::Unretained(callbacks), common::Unretained(handler)));
2088 }
2089 
2090 void AclManager::RegisterLeAclManagerCallbacks(AclManagerCallbacks* callbacks, os::Handler* handler) {
2091   ASSERT(callbacks != nullptr && handler != nullptr);
2092   GetHandler()->Post(common::BindOnce(&impl::handle_register_le_acl_manager_callbacks, common::Unretained(pimpl_.get()),
2093                                       common::Unretained(callbacks), common::Unretained(handler)));
2094 }
2095 
2096 void AclManager::CreateConnection(Address address) {
2097   GetHandler()->Post(common::BindOnce(&impl::create_connection, common::Unretained(pimpl_.get()), address));
2098 }
2099 
2100 void AclManager::CreateLeConnection(AddressWithType address_with_type) {
2101   GetHandler()->Post(
2102       common::BindOnce(&impl::create_le_connection, common::Unretained(pimpl_.get()), address_with_type));
2103 }
2104 
2105 void AclManager::CancelConnect(Address address) {
2106   GetHandler()->Post(BindOnce(&impl::cancel_connect, common::Unretained(pimpl_.get()), address));
2107 }
2108 
2109 void AclManager::MasterLinkKey(KeyFlag key_flag) {
2110   GetHandler()->Post(BindOnce(&impl::master_link_key, common::Unretained(pimpl_.get()), key_flag));
2111 }
2112 
2113 void AclManager::SwitchRole(Address address, Role role) {
2114   GetHandler()->Post(BindOnce(&impl::switch_role, common::Unretained(pimpl_.get()), address, role));
2115 }
2116 
2117 void AclManager::ReadDefaultLinkPolicySettings() {
2118   GetHandler()->Post(BindOnce(&impl::read_default_link_policy_settings, common::Unretained(pimpl_.get())));
2119 }
2120 
2121 void AclManager::WriteDefaultLinkPolicySettings(uint16_t default_link_policy_settings) {
2122   GetHandler()->Post(BindOnce(&impl::write_default_link_policy_settings, common::Unretained(pimpl_.get()),
2123                               default_link_policy_settings));
2124 }
2125 
2126 void AclManager::ListDependencies(ModuleList* list) {
2127   list->add<HciLayer>();
2128   list->add<Controller>();
2129 }
2130 
2131 void AclManager::Start() {
2132   pimpl_->Start();
2133 }
2134 
2135 void AclManager::Stop() {
2136   pimpl_->Stop();
2137 }
2138 
2139 std::string AclManager::ToString() const {
2140   return "Acl Manager";
2141 }
2142 
2143 const ModuleFactory AclManager::Factory = ModuleFactory([]() { return new AclManager(); });
2144 
2145 AclManager::~AclManager() = default;
2146 
2147 }  // namespace hci
2148 }  // namespace bluetooth
2149