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/facade/acl_manager_facade.h"
18 
19 #include <bluetooth/log.h>
20 
21 #include <condition_variable>
22 #include <memory>
23 #include <mutex>
24 
25 #include "blueberry/facade/hci/acl_manager_facade.grpc.pb.h"
26 #include "blueberry/facade/hci/acl_manager_facade.pb.h"
27 #include "common/bind.h"
28 #include "grpc/grpc_event_queue.h"
29 #include "hci/acl_manager.h"
30 #include "hci/address.h"
31 #include "hci/class_of_device.h"
32 #include "hci/hci_packets.h"
33 #include "packet/raw_builder.h"
34 
35 using ::grpc::ServerAsyncResponseWriter;
36 using ::grpc::ServerAsyncWriter;
37 using ::grpc::ServerContext;
38 
39 using ::bluetooth::packet::RawBuilder;
40 
41 namespace bluetooth {
42 namespace hci {
43 namespace facade {
44 
45 using acl_manager::ClassicAclConnection;
46 using acl_manager::ConnectionCallbacks;
47 using acl_manager::ConnectionManagementCallbacks;
48 
49 using namespace blueberry::facade::hci;
50 
51 class AclManagerFacadeService : public AclManagerFacade::Service, public ConnectionCallbacks {
52 public:
AclManagerFacadeService(AclManager * acl_manager,::bluetooth::os::Handler * facade_handler)53   AclManagerFacadeService(AclManager* acl_manager, ::bluetooth::os::Handler* facade_handler)
54       : acl_manager_(acl_manager), facade_handler_(facade_handler) {
55     acl_manager_->RegisterCallbacks(this, facade_handler_);
56   }
57 
~AclManagerFacadeService()58   ~AclManagerFacadeService() {
59     std::unique_lock<std::mutex> lock(acl_connections_mutex_);
60     for (auto& connection : acl_connections_) {
61       connection.second.connection_->GetAclQueueEnd()->UnregisterDequeue();
62     }
63   }
64 
CreateConnection(::grpc::ServerContext * context,const ConnectionMsg * request,::grpc::ServerWriter<ConnectionEvent> * writer)65   ::grpc::Status CreateConnection(::grpc::ServerContext* context, const ConnectionMsg* request,
66                                   ::grpc::ServerWriter<ConnectionEvent>* writer) override {
67     log::info("peer={}", request->address());
68     Address peer;
69     log::assert_that(Address::FromString(request->address(), peer),
70                      "assert failed: Address::FromString(request->address(), peer)");
71     acl_manager_->CreateConnection(peer);
72     if (per_connection_events_.size() > current_connection_request_) {
73       return ::grpc::Status(::grpc::StatusCode::RESOURCE_EXHAUSTED,
74                             "Only one outstanding request is supported");
75     }
76     per_connection_events_.emplace_back(
77             std::make_unique<::bluetooth::grpc::GrpcEventQueue<ConnectionEvent>>(
78                     std::string("connection attempt ") +
79                     std::to_string(current_connection_request_)));
80     return per_connection_events_[current_connection_request_]->RunLoop(context, writer);
81   }
82 
Disconnect(::grpc::ServerContext *,const HandleMsg * request,::google::protobuf::Empty *)83   ::grpc::Status Disconnect(::grpc::ServerContext* /* context */, const HandleMsg* request,
84                             ::google::protobuf::Empty* /* response */) override {
85     log::info("handle={}", request->handle());
86     std::unique_lock<std::mutex> lock(acl_connections_mutex_);
87     auto connection = acl_connections_.find(request->handle());
88     if (connection == acl_connections_.end()) {
89       log::error("Invalid handle");
90       return ::grpc::Status(::grpc::StatusCode::INVALID_ARGUMENT, "Invalid handle");
91     } else {
92       connection->second.connection_->Disconnect(
93               DisconnectReason::REMOTE_USER_TERMINATED_CONNECTION);
94       return ::grpc::Status::OK;
95     }
96   }
97 
AuthenticationRequested(::grpc::ServerContext *,const HandleMsg * request,::google::protobuf::Empty *)98   ::grpc::Status AuthenticationRequested(::grpc::ServerContext* /* context */,
99                                          const HandleMsg* request,
100                                          ::google::protobuf::Empty* /* response */) override {
101     log::info("handle={}", request->handle());
102     std::unique_lock<std::mutex> lock(acl_connections_mutex_);
103     auto connection = acl_connections_.find(request->handle());
104     if (connection == acl_connections_.end()) {
105       log::error("Invalid handle");
106       return ::grpc::Status(::grpc::StatusCode::INVALID_ARGUMENT, "Invalid handle");
107     } else {
108       connection->second.connection_->AuthenticationRequested();
109       return ::grpc::Status::OK;
110     }
111   }
112 
113 #define GET_CONNECTION(view)                                                         \
114   std::map<uint16_t, Connection>::iterator connection;                               \
115   do {                                                                               \
116     if (!view.IsValid()) {                                                           \
117       return ::grpc::Status(::grpc::StatusCode::INVALID_ARGUMENT, "Invalid handle"); \
118     }                                                                                \
119     std::unique_lock<std::mutex> lock(acl_connections_mutex_);                       \
120     connection = acl_connections_.find(view.GetConnectionHandle());                  \
121     if (connection == acl_connections_.end()) {                                      \
122       return ::grpc::Status(::grpc::StatusCode::INVALID_ARGUMENT, "Invalid handle"); \
123     }                                                                                \
124   } while (0)
125 
ConnectionCommand(::grpc::ServerContext *,const ConnectionCommandMsg * request,::google::protobuf::Empty *)126   ::grpc::Status ConnectionCommand(::grpc::ServerContext* /* context */,
127                                    const ConnectionCommandMsg* request,
128                                    ::google::protobuf::Empty* /* response */) override {
129     log::info("size={}", request->packet().size());
130     auto command_view = ConnectionManagementCommandView::Create(AclCommandView::Create(
131             CommandView::Create(PacketView<kLittleEndian>(std::make_shared<std::vector<uint8_t>>(
132                     request->packet().begin(), request->packet().end())))));
133     if (!command_view.IsValid()) {
134       return ::grpc::Status(::grpc::StatusCode::INVALID_ARGUMENT, "Invalid command packet");
135     }
136     log::info("opcode={}", OpCodeText(command_view.GetOpCode()));
137     switch (command_view.GetOpCode()) {
138       case OpCode::AUTHENTICATION_REQUESTED: {
139         GET_CONNECTION(AuthenticationRequestedView::Create(command_view));
140         connection->second.connection_->AuthenticationRequested();
141         return ::grpc::Status::OK;
142       }
143       case OpCode::DISCONNECT: {
144         auto view = DisconnectView::Create(command_view);
145         GET_CONNECTION(view);
146         connection->second.connection_->Disconnect(view.GetReason());
147         return ::grpc::Status::OK;
148       }
149       case OpCode::CHANGE_CONNECTION_PACKET_TYPE: {
150         auto view = ChangeConnectionPacketTypeView::Create(command_view);
151         GET_CONNECTION(view);
152         connection->second.connection_->ChangeConnectionPacketType(view.GetPacketType());
153         return ::grpc::Status::OK;
154       }
155       case OpCode::SET_CONNECTION_ENCRYPTION: {
156         auto view = SetConnectionEncryptionView::Create(command_view);
157         GET_CONNECTION(view);
158         connection->second.connection_->SetConnectionEncryption(view.GetEncryptionEnable());
159         return ::grpc::Status::OK;
160       }
161       case OpCode::CHANGE_CONNECTION_LINK_KEY: {
162         GET_CONNECTION(ChangeConnectionLinkKeyView::Create(command_view));
163         connection->second.connection_->ChangeConnectionLinkKey();
164         return ::grpc::Status::OK;
165       }
166       case OpCode::READ_CLOCK_OFFSET: {
167         GET_CONNECTION(ReadClockOffsetView::Create(command_view));
168         connection->second.connection_->ReadClockOffset();
169         return ::grpc::Status::OK;
170       }
171       case OpCode::HOLD_MODE: {
172         auto view = HoldModeView::Create(command_view);
173         GET_CONNECTION(view);
174         connection->second.connection_->HoldMode(view.GetHoldModeMaxInterval(),
175                                                  view.GetHoldModeMinInterval());
176         return ::grpc::Status::OK;
177       }
178       case OpCode::SNIFF_MODE: {
179         auto view = SniffModeView::Create(command_view);
180         GET_CONNECTION(view);
181         connection->second.connection_->SniffMode(view.GetSniffMaxInterval(),
182                                                   view.GetSniffMinInterval(),
183                                                   view.GetSniffAttempt(), view.GetSniffTimeout());
184         return ::grpc::Status::OK;
185       }
186       case OpCode::EXIT_SNIFF_MODE: {
187         GET_CONNECTION(ExitSniffModeView::Create(command_view));
188         connection->second.connection_->ExitSniffMode();
189         return ::grpc::Status::OK;
190       }
191       case OpCode::FLUSH: {
192         GET_CONNECTION(FlushView::Create(command_view));
193         connection->second.connection_->Flush();
194         return ::grpc::Status::OK;
195       }
196       case OpCode::READ_AUTOMATIC_FLUSH_TIMEOUT: {
197         GET_CONNECTION(ReadAutomaticFlushTimeoutView::Create(command_view));
198         connection->second.connection_->ReadAutomaticFlushTimeout();
199         return ::grpc::Status::OK;
200       }
201       case OpCode::WRITE_AUTOMATIC_FLUSH_TIMEOUT: {
202         auto view = WriteAutomaticFlushTimeoutView::Create(command_view);
203         GET_CONNECTION(view);
204         connection->second.connection_->WriteAutomaticFlushTimeout(view.GetFlushTimeout());
205         return ::grpc::Status::OK;
206       }
207       case OpCode::READ_TRANSMIT_POWER_LEVEL: {
208         auto view = ReadTransmitPowerLevelView::Create(command_view);
209         GET_CONNECTION(view);
210         connection->second.connection_->ReadTransmitPowerLevel(view.GetTransmitPowerLevelType());
211         return ::grpc::Status::OK;
212       }
213       case OpCode::READ_LINK_SUPERVISION_TIMEOUT: {
214         GET_CONNECTION(ReadLinkSupervisionTimeoutView::Create(command_view));
215         connection->second.connection_->ReadLinkSupervisionTimeout();
216         return ::grpc::Status::OK;
217       }
218       case OpCode::WRITE_LINK_SUPERVISION_TIMEOUT: {
219         auto view = WriteLinkSupervisionTimeoutView::Create(command_view);
220         GET_CONNECTION(view);
221         connection->second.connection_->WriteLinkSupervisionTimeout(
222                 view.GetLinkSupervisionTimeout());
223         return ::grpc::Status::OK;
224       }
225       case OpCode::READ_FAILED_CONTACT_COUNTER: {
226         GET_CONNECTION(ReadFailedContactCounterView::Create(command_view));
227         connection->second.connection_->ReadFailedContactCounter();
228         return ::grpc::Status::OK;
229       }
230       case OpCode::RESET_FAILED_CONTACT_COUNTER: {
231         GET_CONNECTION(ResetFailedContactCounterView::Create(command_view));
232         connection->second.connection_->ResetFailedContactCounter();
233         return ::grpc::Status::OK;
234       }
235       case OpCode::READ_LINK_QUALITY: {
236         GET_CONNECTION(ReadLinkQualityView::Create(command_view));
237         connection->second.connection_->ReadLinkQuality();
238         return ::grpc::Status::OK;
239       }
240       case OpCode::READ_AFH_CHANNEL_MAP: {
241         GET_CONNECTION(ReadAfhChannelMapView::Create(command_view));
242         connection->second.connection_->ReadAfhChannelMap();
243         return ::grpc::Status::OK;
244       }
245       case OpCode::READ_RSSI: {
246         GET_CONNECTION(ReadRssiView::Create(command_view));
247         connection->second.connection_->ReadRssi();
248         return ::grpc::Status::OK;
249       }
250       case OpCode::READ_CLOCK: {
251         auto view = ReadClockView::Create(command_view);
252         GET_CONNECTION(view);
253         connection->second.connection_->ReadClock(view.GetWhichClock());
254         return ::grpc::Status::OK;
255       }
256       case OpCode::READ_REMOTE_VERSION_INFORMATION: {
257         GET_CONNECTION(ReadRemoteVersionInformationView::Create(command_view));
258         connection->second.connection_->ReadRemoteVersionInformation();
259         return ::grpc::Status::OK;
260       }
261       case OpCode::READ_REMOTE_SUPPORTED_FEATURES: {
262         GET_CONNECTION(ReadRemoteSupportedFeaturesView::Create(command_view));
263         connection->second.connection_->ReadRemoteSupportedFeatures();
264         return ::grpc::Status::OK;
265       }
266       case OpCode::READ_REMOTE_EXTENDED_FEATURES: {
267         GET_CONNECTION(ReadRemoteExtendedFeaturesView::Create(command_view));
268         uint8_t page_number = 0;
269         connection->second.connection_->ReadRemoteExtendedFeatures(page_number);
270         return ::grpc::Status::OK;
271       }
272       default:
273         return ::grpc::Status(::grpc::StatusCode::INVALID_ARGUMENT, "Invalid command packet");
274     }
275   }
276 #undef GET_CONNECTION
277 
FetchIncomingConnection(::grpc::ServerContext * context,const google::protobuf::Empty *,::grpc::ServerWriter<ConnectionEvent> * writer)278   ::grpc::Status FetchIncomingConnection(::grpc::ServerContext* context,
279                                          const google::protobuf::Empty* /* request */,
280                                          ::grpc::ServerWriter<ConnectionEvent>* writer) override {
281     log::info("wait for one incoming connection");
282     if (per_connection_events_.size() > current_connection_request_) {
283       return ::grpc::Status(::grpc::StatusCode::RESOURCE_EXHAUSTED,
284                             "Only one outstanding connection is supported");
285     }
286     per_connection_events_.emplace_back(
287             std::make_unique<::bluetooth::grpc::GrpcEventQueue<ConnectionEvent>>(
288                     std::string("incoming connection ") +
289                     std::to_string(current_connection_request_)));
290     return per_connection_events_[current_connection_request_]->RunLoop(context, writer);
291   }
292 
SendAclData(::grpc::ServerContext *,const AclData * request,::google::protobuf::Empty *)293   ::grpc::Status SendAclData(::grpc::ServerContext* /* context */, const AclData* request,
294                              ::google::protobuf::Empty* /* response */) override {
295     log::info("handle={}, size={}", request->handle(), request->payload().size());
296     std::promise<void> promise;
297     auto future = promise.get_future();
298     {
299       std::unique_lock<std::mutex> lock(acl_connections_mutex_);
300       auto connection = acl_connections_.find(request->handle());
301       if (connection == acl_connections_.end()) {
302         return ::grpc::Status(::grpc::StatusCode::INVALID_ARGUMENT, "Invalid handle");
303       }
304       // TODO: This is unsafe because connection may have gone
305       connection->second.connection_->GetAclQueueEnd()->RegisterEnqueue(
306               facade_handler_,
307               common::Bind(&AclManagerFacadeService::enqueue_packet, common::Unretained(this),
308                            common::Unretained(request), common::Passed(std::move(promise))));
309       auto status = future.wait_for(std::chrono::milliseconds(1000));
310       if (status != std::future_status::ready) {
311         return ::grpc::Status(::grpc::StatusCode::RESOURCE_EXHAUSTED, "Can't send packet");
312       }
313     }
314     return ::grpc::Status::OK;
315   }
316 
enqueue_packet(const AclData * request,std::promise<void> promise)317   std::unique_ptr<BasePacketBuilder> enqueue_packet(const AclData* request,
318                                                     std::promise<void> promise) {
319     auto connection = acl_connections_.find(request->handle());
320     log::assert_that(connection != acl_connections_.end(), "handle {}", request->handle());
321     connection->second.connection_->GetAclQueueEnd()->UnregisterEnqueue();
322     std::unique_ptr<RawBuilder> packet = std::make_unique<RawBuilder>(
323             std::vector<uint8_t>(request->payload().begin(), request->payload().end()));
324     promise.set_value();
325     return packet;
326   }
327 
FetchAclData(::grpc::ServerContext * context,const HandleMsg * request,::grpc::ServerWriter<AclData> * writer)328   ::grpc::Status FetchAclData(::grpc::ServerContext* context, const HandleMsg* request,
329                               ::grpc::ServerWriter<AclData>* writer) override {
330     log::info("handle={}", request->handle());
331     auto connection = acl_connections_.find(request->handle());
332     if (connection == acl_connections_.end()) {
333       return ::grpc::Status(::grpc::StatusCode::INVALID_ARGUMENT, "Invalid handle");
334     }
335     return connection->second.pending_acl_data_.RunLoop(context, writer);
336   }
337 
to_handle(uint32_t current_request)338   static inline uint16_t to_handle(uint32_t current_request) {
339     return (current_request + 0x10) % 0xe00;
340   }
341 
builder_to_string(std::unique_ptr<BasePacketBuilder> builder)342   static inline std::string builder_to_string(std::unique_ptr<BasePacketBuilder> builder) {
343     std::vector<uint8_t> bytes;
344     BitInserter bit_inserter(bytes);
345     builder->Serialize(bit_inserter);
346     return std::string(bytes.begin(), bytes.end());
347   }
348 
on_incoming_acl(std::shared_ptr<ClassicAclConnection> connection,uint16_t handle)349   void on_incoming_acl(std::shared_ptr<ClassicAclConnection> connection, uint16_t handle) {
350     log::info("handle={}, addr={}", connection->GetHandle(), connection->GetAddress());
351     auto packet = connection->GetAclQueueEnd()->TryDequeue();
352     auto connection_tracker = acl_connections_.find(handle);
353     log::assert_that(connection_tracker != acl_connections_.end(), "handle {}", handle);
354     AclData acl_data;
355     acl_data.set_handle(handle);
356     acl_data.set_payload(std::string(packet->begin(), packet->end()));
357     log::info("length={}", acl_data.payload().size());
358     connection_tracker->second.pending_acl_data_.OnIncomingEvent(acl_data);
359   }
360 
OnConnectSuccess(std::unique_ptr<ClassicAclConnection> connection)361   void OnConnectSuccess(std::unique_ptr<ClassicAclConnection> connection) override {
362     log::info("handle={}, addr={}", connection->GetHandle(), connection->GetAddress());
363     std::unique_lock<std::mutex> lock(acl_connections_mutex_);
364     std::shared_ptr<ClassicAclConnection> shared_connection = std::move(connection);
365     uint16_t handle = to_handle(current_connection_request_);
366     acl_connections_.erase(handle);
367     acl_connections_.emplace(
368             std::piecewise_construct, std::forward_as_tuple(handle),
369             std::forward_as_tuple(handle, shared_connection,
370                                   per_connection_events_[current_connection_request_]));
371     shared_connection->GetAclQueueEnd()->RegisterDequeue(
372             facade_handler_, common::Bind(&AclManagerFacadeService::on_incoming_acl,
373                                           common::Unretained(this), shared_connection, handle));
374     auto callbacks = acl_connections_.find(handle)->second.GetCallbacks();
375     shared_connection->RegisterCallbacks(callbacks, facade_handler_);
376     auto addr = shared_connection->GetAddress();
377     std::unique_ptr<BasePacketBuilder> builder = ConnectionCompleteBuilder::Create(
378             ErrorCode::SUCCESS, handle, addr, LinkType::ACL, Enable::DISABLED);
379     ConnectionEvent success;
380     success.set_payload(builder_to_string(std::move(builder)));
381     per_connection_events_[current_connection_request_]->OnIncomingEvent(success);
382     current_connection_request_++;
383   }
384 
OnConnectRequest(Address,ClassOfDevice)385   void OnConnectRequest(Address /* address */, ClassOfDevice /* cod */) override {
386     log::error("Remote connect request unimplemented");
387   }
388 
OnConnectFail(Address address,ErrorCode reason,bool)389   void OnConnectFail(Address address, ErrorCode reason, bool /* locally_initiated */) override {
390     log::info("addr={}, reason={}", address, ErrorCodeText(reason));
391     std::unique_ptr<BasePacketBuilder> builder =
392             ConnectionCompleteBuilder::Create(reason, 0, address, LinkType::ACL, Enable::DISABLED);
393     ConnectionEvent fail;
394     fail.set_payload(builder_to_string(std::move(builder)));
395     per_connection_events_[current_connection_request_]->OnIncomingEvent(fail);
396     current_connection_request_++;
397   }
398 
399   class Connection : public ConnectionManagementCallbacks {
400   public:
Connection(uint16_t handle,std::shared_ptr<ClassicAclConnection> connection,std::shared_ptr<::bluetooth::grpc::GrpcEventQueue<ConnectionEvent>> event_stream)401     Connection(uint16_t handle, std::shared_ptr<ClassicAclConnection> connection,
402                std::shared_ptr<::bluetooth::grpc::GrpcEventQueue<ConnectionEvent>> event_stream)
403         : handle_(handle),
404           connection_(std::move(connection)),
405           event_stream_(std::move(event_stream)) {}
406 
GetCallbacks()407     ConnectionManagementCallbacks* GetCallbacks() { return this; }
408 
OnCentralLinkKeyComplete(KeyFlag key_flag)409     void OnCentralLinkKeyComplete(KeyFlag key_flag) override {
410       log::info("key_flag:{}", KeyFlagText(key_flag));
411     }
412 
OnRoleChange(hci::ErrorCode,Role new_role)413     void OnRoleChange(hci::ErrorCode /* hci_status */, Role new_role) override {
414       log::info("new_role:{}", (uint8_t)new_role);
415     }
416 
OnReadLinkPolicySettingsComplete(uint16_t link_policy_settings)417     void OnReadLinkPolicySettingsComplete(uint16_t link_policy_settings) override {
418       log::info("link_policy_settings:{}", link_policy_settings);
419     }
420 
OnConnectionPacketTypeChanged(uint16_t packet_type)421     void OnConnectionPacketTypeChanged(uint16_t packet_type) override {
422       log::info("OnConnectionPacketTypeChanged packet_type:{}", packet_type);
423     }
424 
OnAuthenticationComplete(hci::ErrorCode)425     void OnAuthenticationComplete(hci::ErrorCode /* hci_status */) override {
426       log::info("OnAuthenticationComplete");
427     }
428 
OnEncryptionChange(EncryptionEnabled enabled)429     void OnEncryptionChange(EncryptionEnabled enabled) override {
430       log::info("OnConnectionPacketTypeChanged enabled:{}", (uint8_t)enabled);
431     }
432 
OnChangeConnectionLinkKeyComplete()433     void OnChangeConnectionLinkKeyComplete() override {
434       log::info("OnChangeConnectionLinkKeyComplete");
435     }
436 
OnReadClockOffsetComplete(uint16_t clock_offset)437     void OnReadClockOffsetComplete(uint16_t clock_offset) override {
438       log::info("OnReadClockOffsetComplete clock_offset:{}", clock_offset);
439     }
440 
OnModeChange(ErrorCode,Mode current_mode,uint16_t interval)441     void OnModeChange(ErrorCode /* status */, Mode current_mode, uint16_t interval) override {
442       log::info("OnModeChange Mode:{}, interval:{}", (uint8_t)current_mode, interval);
443     }
444 
OnSniffSubrating(hci::ErrorCode,uint16_t maximum_transmit_latency,uint16_t maximum_receive_latency,uint16_t minimum_remote_timeout,uint16_t minimum_local_timeout)445     void OnSniffSubrating(hci::ErrorCode /* hci_status */, uint16_t maximum_transmit_latency,
446                           uint16_t maximum_receive_latency, uint16_t minimum_remote_timeout,
447                           uint16_t minimum_local_timeout) override {
448       log::info(
449               "OnSniffSubrating maximum_transmit_latency:{}, maximum_receive_latency:{} "
450               "minimum_remote_timeout:{} minimum_local_timeout:{}",
451               maximum_transmit_latency, maximum_receive_latency, minimum_remote_timeout,
452               minimum_local_timeout);
453     }
454 
OnQosSetupComplete(ServiceType service_type,uint32_t token_rate,uint32_t peak_bandwidth,uint32_t latency,uint32_t delay_variation)455     void OnQosSetupComplete(ServiceType service_type, uint32_t token_rate, uint32_t peak_bandwidth,
456                             uint32_t latency, uint32_t delay_variation) override {
457       log::info(
458               "OnQosSetupComplete service_type:{}, token_rate:{}, peak_bandwidth:{}, latency:{}, "
459               "delay_variation:{}",
460               (uint8_t)service_type, token_rate, peak_bandwidth, latency, delay_variation);
461     }
462 
OnFlowSpecificationComplete(FlowDirection flow_direction,ServiceType service_type,uint32_t token_rate,uint32_t token_bucket_size,uint32_t peak_bandwidth,uint32_t access_latency)463     void OnFlowSpecificationComplete(FlowDirection flow_direction, ServiceType service_type,
464                                      uint32_t token_rate, uint32_t token_bucket_size,
465                                      uint32_t peak_bandwidth, uint32_t access_latency) override {
466       log::info(
467               "OnFlowSpecificationComplete flow_direction:{}. service_type:{}, token_rate:{}, "
468               "token_bucket_size:{}, peak_bandwidth:{}, access_latency:{}",
469               (uint8_t)flow_direction, (uint8_t)service_type, token_rate, token_bucket_size,
470               peak_bandwidth, access_latency);
471     }
472 
OnFlushOccurred()473     void OnFlushOccurred() override { log::info("OnFlushOccurred"); }
474 
OnRoleDiscoveryComplete(Role current_role)475     void OnRoleDiscoveryComplete(Role current_role) override {
476       log::info("OnRoleDiscoveryComplete current_role:{}", (uint8_t)current_role);
477     }
478 
OnReadAutomaticFlushTimeoutComplete(uint16_t flush_timeout)479     void OnReadAutomaticFlushTimeoutComplete(uint16_t flush_timeout) override {
480       log::info("OnReadAutomaticFlushTimeoutComplete flush_timeout:{}", flush_timeout);
481     }
482 
OnReadTransmitPowerLevelComplete(uint8_t transmit_power_level)483     void OnReadTransmitPowerLevelComplete(uint8_t transmit_power_level) override {
484       log::info("OnReadTransmitPowerLevelComplete transmit_power_level:{}", transmit_power_level);
485     }
486 
OnReadLinkSupervisionTimeoutComplete(uint16_t link_supervision_timeout)487     void OnReadLinkSupervisionTimeoutComplete(uint16_t link_supervision_timeout) override {
488       log::info("OnReadLinkSupervisionTimeoutComplete link_supervision_timeout:{}",
489                 link_supervision_timeout);
490     }
491 
OnReadFailedContactCounterComplete(uint16_t failed_contact_counter)492     void OnReadFailedContactCounterComplete(uint16_t failed_contact_counter) override {
493       log::info("OnReadFailedContactCounterComplete failed_contact_counter:{}",
494                 failed_contact_counter);
495     }
496 
OnReadLinkQualityComplete(uint8_t link_quality)497     void OnReadLinkQualityComplete(uint8_t link_quality) override {
498       log::info("OnReadLinkQualityComplete link_quality:{}", link_quality);
499     }
500 
OnReadAfhChannelMapComplete(AfhMode afh_mode,std::array<uint8_t,10>)501     void OnReadAfhChannelMapComplete(AfhMode afh_mode,
502                                      std::array<uint8_t, 10> /* afh_channel_map */) override {
503       log::info("OnReadAfhChannelMapComplete afh_mode:{}", (uint8_t)afh_mode);
504     }
505 
OnReadRssiComplete(uint8_t rssi)506     void OnReadRssiComplete(uint8_t rssi) override {
507       log::info("OnReadRssiComplete rssi:{}", rssi);
508     }
509 
OnReadClockComplete(uint32_t clock,uint16_t accuracy)510     void OnReadClockComplete(uint32_t clock, uint16_t accuracy) override {
511       log::info("OnReadClockComplete clock:{}, accuracy:{}", clock, accuracy);
512     }
513 
OnDisconnection(ErrorCode reason)514     void OnDisconnection(ErrorCode reason) override {
515       log::info("reason: {}", ErrorCodeText(reason));
516       std::unique_ptr<BasePacketBuilder> builder =
517               DisconnectionCompleteBuilder::Create(ErrorCode::SUCCESS, handle_, reason);
518       ConnectionEvent disconnection;
519       disconnection.set_payload(builder_to_string(std::move(builder)));
520       event_stream_->OnIncomingEvent(disconnection);
521     }
OnReadRemoteVersionInformationComplete(hci::ErrorCode,uint8_t lmp_version,uint16_t manufacturer_name,uint16_t sub_version)522     void OnReadRemoteVersionInformationComplete(hci::ErrorCode /* error_status */,
523                                                 uint8_t lmp_version, uint16_t manufacturer_name,
524                                                 uint16_t sub_version) override {
525       log::info(
526               "OnReadRemoteVersionInformationComplete lmp_version:{} manufacturer_name:{} "
527               "sub_version:{}",
528               lmp_version, manufacturer_name, sub_version);
529     }
OnReadRemoteSupportedFeaturesComplete(uint64_t features)530     void OnReadRemoteSupportedFeaturesComplete(uint64_t features) override {
531       log::info("OnReadRemoteSupportedFeaturesComplete features:0x{:x}", features);
532     }
OnReadRemoteExtendedFeaturesComplete(uint8_t page_number,uint8_t max_page_number,uint64_t features)533     void OnReadRemoteExtendedFeaturesComplete(uint8_t page_number, uint8_t max_page_number,
534                                               uint64_t features) override {
535       log::info(
536               "OnReadRemoteExtendedFeaturesComplete page_number:{} max_page_number:{} "
537               "features:0x{:x}",
538               page_number, max_page_number, features);
539     }
540 
541     uint16_t handle_;
542     std::shared_ptr<ClassicAclConnection> connection_;
543     std::shared_ptr<::bluetooth::grpc::GrpcEventQueue<ConnectionEvent>> event_stream_;
544     ::bluetooth::grpc::GrpcEventQueue<AclData> pending_acl_data_{std::string("PendingAclData") +
545                                                                  std::to_string(handle_)};
546   };
547 
548 private:
549   AclManager* acl_manager_;
550   ::bluetooth::os::Handler* facade_handler_;
551   mutable std::mutex acl_connections_mutex_;
552   std::map<uint16_t, Connection> acl_connections_;
553   std::vector<std::shared_ptr<::bluetooth::grpc::GrpcEventQueue<ConnectionEvent>>>
554           per_connection_events_;
555   uint32_t current_connection_request_{0};
556 };
557 
ListDependencies(ModuleList * list) const558 void AclManagerFacadeModule::ListDependencies(ModuleList* list) const {
559   ::bluetooth::grpc::GrpcFacadeModule::ListDependencies(list);
560   list->add<AclManager>();
561 }
562 
Start()563 void AclManagerFacadeModule::Start() {
564   ::bluetooth::grpc::GrpcFacadeModule::Start();
565   service_ = new AclManagerFacadeService(GetDependency<AclManager>(), GetHandler());
566 }
567 
Stop()568 void AclManagerFacadeModule::Stop() {
569   delete service_;
570   ::bluetooth::grpc::GrpcFacadeModule::Stop();
571 }
572 
GetService() const573 ::grpc::Service* AclManagerFacadeModule::GetService() const { return service_; }
574 
575 const ModuleFactory AclManagerFacadeModule::Factory =
__anon743920b50102() 576         ::bluetooth::ModuleFactory([]() { return new AclManagerFacadeModule(); });
577 
578 }  // namespace facade
579 }  // namespace hci
580 }  // namespace bluetooth
581