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(
66       ::grpc::ServerContext* context,
67       const ConnectionMsg* request,
68       ::grpc::ServerWriter<ConnectionEvent>* writer) override {
69     log::info("peer={}", request->address());
70     Address peer;
71     log::assert_that(
72         Address::FromString(request->address(), peer),
73         "assert failed: Address::FromString(request->address(), peer)");
74     acl_manager_->CreateConnection(peer);
75     if (per_connection_events_.size() > current_connection_request_) {
76       return ::grpc::Status(::grpc::StatusCode::RESOURCE_EXHAUSTED, "Only one outstanding request is supported");
77     }
78     per_connection_events_.emplace_back(std::make_unique<::bluetooth::grpc::GrpcEventQueue<ConnectionEvent>>(
79         std::string("connection attempt ") + 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(
84       ::grpc::ServerContext* /* context */,
85       const HandleMsg* request,
86       ::google::protobuf::Empty* /* response */) override {
87     log::info("handle={}", request->handle());
88     std::unique_lock<std::mutex> lock(acl_connections_mutex_);
89     auto connection = acl_connections_.find(request->handle());
90     if (connection == acl_connections_.end()) {
91       log::error("Invalid handle");
92       return ::grpc::Status(::grpc::StatusCode::INVALID_ARGUMENT, "Invalid handle");
93     } else {
94       connection->second.connection_->Disconnect(DisconnectReason::REMOTE_USER_TERMINATED_CONNECTION);
95       return ::grpc::Status::OK;
96     }
97   }
98 
AuthenticationRequested(::grpc::ServerContext *,const HandleMsg * request,::google::protobuf::Empty *)99   ::grpc::Status AuthenticationRequested(
100       ::grpc::ServerContext* /* context */,
101       const HandleMsg* request,
102       ::google::protobuf::Empty* /* response */) override {
103     log::info("handle={}", request->handle());
104     std::unique_lock<std::mutex> lock(acl_connections_mutex_);
105     auto connection = acl_connections_.find(request->handle());
106     if (connection == acl_connections_.end()) {
107       log::error("Invalid handle");
108       return ::grpc::Status(::grpc::StatusCode::INVALID_ARGUMENT, "Invalid handle");
109     } else {
110       connection->second.connection_->AuthenticationRequested();
111       return ::grpc::Status::OK;
112     }
113   };
114 
115 #define GET_CONNECTION(view)                                                         \
116   std::map<uint16_t, Connection>::iterator connection;                               \
117   do {                                                                               \
118     if (!view.IsValid()) {                                                           \
119       return ::grpc::Status(::grpc::StatusCode::INVALID_ARGUMENT, "Invalid handle"); \
120     }                                                                                \
121     std::unique_lock<std::mutex> lock(acl_connections_mutex_);                       \
122     connection = acl_connections_.find(view.GetConnectionHandle());                  \
123     if (connection == acl_connections_.end()) {                                      \
124       return ::grpc::Status(::grpc::StatusCode::INVALID_ARGUMENT, "Invalid handle"); \
125     }                                                                                \
126   } while (0)
127 
ConnectionCommand(::grpc::ServerContext *,const ConnectionCommandMsg * request,::google::protobuf::Empty *)128   ::grpc::Status ConnectionCommand(
129       ::grpc::ServerContext* /* context */,
130       const ConnectionCommandMsg* request,
131       ::google::protobuf::Empty* /* response */) override {
132     log::info("size={}", request->packet().size());
133     auto command_view =
134         ConnectionManagementCommandView::Create(AclCommandView::Create(CommandView::Create(PacketView<kLittleEndian>(
135             std::make_shared<std::vector<uint8_t>>(request->packet().begin(), request->packet().end())))));
136     if (!command_view.IsValid()) {
137       return ::grpc::Status(::grpc::StatusCode::INVALID_ARGUMENT, "Invalid command packet");
138     }
139     log::info("opcode={}", OpCodeText(command_view.GetOpCode()));
140     switch (command_view.GetOpCode()) {
141       case OpCode::AUTHENTICATION_REQUESTED: {
142         GET_CONNECTION(AuthenticationRequestedView::Create(command_view));
143         connection->second.connection_->AuthenticationRequested();
144         return ::grpc::Status::OK;
145       }
146       case OpCode::DISCONNECT: {
147         auto view = DisconnectView::Create(command_view);
148         GET_CONNECTION(view);
149         connection->second.connection_->Disconnect(view.GetReason());
150         return ::grpc::Status::OK;
151       }
152       case OpCode::CHANGE_CONNECTION_PACKET_TYPE: {
153         auto view = ChangeConnectionPacketTypeView::Create(command_view);
154         GET_CONNECTION(view);
155         connection->second.connection_->ChangeConnectionPacketType(view.GetPacketType());
156         return ::grpc::Status::OK;
157       }
158       case OpCode::SET_CONNECTION_ENCRYPTION: {
159         auto view = SetConnectionEncryptionView::Create(command_view);
160         GET_CONNECTION(view);
161         connection->second.connection_->SetConnectionEncryption(view.GetEncryptionEnable());
162         return ::grpc::Status::OK;
163       }
164       case OpCode::CHANGE_CONNECTION_LINK_KEY: {
165         GET_CONNECTION(ChangeConnectionLinkKeyView::Create(command_view));
166         connection->second.connection_->ChangeConnectionLinkKey();
167         return ::grpc::Status::OK;
168       }
169       case OpCode::READ_CLOCK_OFFSET: {
170         GET_CONNECTION(ReadClockOffsetView::Create(command_view));
171         connection->second.connection_->ReadClockOffset();
172         return ::grpc::Status::OK;
173       }
174       case OpCode::HOLD_MODE: {
175         auto view = HoldModeView::Create(command_view);
176         GET_CONNECTION(view);
177         connection->second.connection_->HoldMode(view.GetHoldModeMaxInterval(), view.GetHoldModeMinInterval());
178         return ::grpc::Status::OK;
179       }
180       case OpCode::SNIFF_MODE: {
181         auto view = SniffModeView::Create(command_view);
182         GET_CONNECTION(view);
183         connection->second.connection_->SniffMode(
184             view.GetSniffMaxInterval(), view.GetSniffMinInterval(), view.GetSniffAttempt(), view.GetSniffTimeout());
185         return ::grpc::Status::OK;
186       }
187       case OpCode::EXIT_SNIFF_MODE: {
188         GET_CONNECTION(ExitSniffModeView::Create(command_view));
189         connection->second.connection_->ExitSniffMode();
190         return ::grpc::Status::OK;
191       }
192       case OpCode::FLUSH: {
193         GET_CONNECTION(FlushView::Create(command_view));
194         connection->second.connection_->Flush();
195         return ::grpc::Status::OK;
196       }
197       case OpCode::READ_AUTOMATIC_FLUSH_TIMEOUT: {
198         GET_CONNECTION(ReadAutomaticFlushTimeoutView::Create(command_view));
199         connection->second.connection_->ReadAutomaticFlushTimeout();
200         return ::grpc::Status::OK;
201       }
202       case OpCode::WRITE_AUTOMATIC_FLUSH_TIMEOUT: {
203         auto view = WriteAutomaticFlushTimeoutView::Create(command_view);
204         GET_CONNECTION(view);
205         connection->second.connection_->WriteAutomaticFlushTimeout(view.GetFlushTimeout());
206         return ::grpc::Status::OK;
207       }
208       case OpCode::READ_TRANSMIT_POWER_LEVEL: {
209         auto view = ReadTransmitPowerLevelView::Create(command_view);
210         GET_CONNECTION(view);
211         connection->second.connection_->ReadTransmitPowerLevel(view.GetTransmitPowerLevelType());
212         return ::grpc::Status::OK;
213       }
214       case OpCode::READ_LINK_SUPERVISION_TIMEOUT: {
215         GET_CONNECTION(ReadLinkSupervisionTimeoutView::Create(command_view));
216         connection->second.connection_->ReadLinkSupervisionTimeout();
217         return ::grpc::Status::OK;
218       }
219       case OpCode::WRITE_LINK_SUPERVISION_TIMEOUT: {
220         auto view = WriteLinkSupervisionTimeoutView::Create(command_view);
221         GET_CONNECTION(view);
222         connection->second.connection_->WriteLinkSupervisionTimeout(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(
279       ::grpc::ServerContext* context,
280       const google::protobuf::Empty* /* request */,
281       ::grpc::ServerWriter<ConnectionEvent>* writer) override {
282     log::info("wait for one incoming connection");
283     if (per_connection_events_.size() > current_connection_request_) {
284       return ::grpc::Status(::grpc::StatusCode::RESOURCE_EXHAUSTED, "Only one outstanding connection is supported");
285     }
286     per_connection_events_.emplace_back(std::make_unique<::bluetooth::grpc::GrpcEventQueue<ConnectionEvent>>(
287         std::string("incoming connection ") + std::to_string(current_connection_request_)));
288     return per_connection_events_[current_connection_request_]->RunLoop(context, writer);
289   }
290 
SendAclData(::grpc::ServerContext *,const AclData * request,::google::protobuf::Empty *)291   ::grpc::Status SendAclData(
292       ::grpc::ServerContext* /* context */,
293       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(
308               &AclManagerFacadeService::enqueue_packet,
309               common::Unretained(this),
310               common::Unretained(request),
311               common::Passed(std::move(promise))));
312       auto status = future.wait_for(std::chrono::milliseconds(1000));
313       if (status != std::future_status::ready) {
314         return ::grpc::Status(::grpc::StatusCode::RESOURCE_EXHAUSTED, "Can't send packet");
315       }
316     }
317     return ::grpc::Status::OK;
318   }
319 
enqueue_packet(const AclData * request,std::promise<void> promise)320   std::unique_ptr<BasePacketBuilder> enqueue_packet(const AclData* request, std::promise<void> promise) {
321     auto connection = acl_connections_.find(request->handle());
322     log::assert_that(connection != acl_connections_.end(), "handle {}", request->handle());
323     connection->second.connection_->GetAclQueueEnd()->UnregisterEnqueue();
324     std::unique_ptr<RawBuilder> packet =
325         std::make_unique<RawBuilder>(std::vector<uint8_t>(request->payload().begin(), request->payload().end()));
326     promise.set_value();
327     return packet;
328   }
329 
FetchAclData(::grpc::ServerContext * context,const HandleMsg * request,::grpc::ServerWriter<AclData> * writer)330   ::grpc::Status FetchAclData(
331       ::grpc::ServerContext* context, const HandleMsg* request, ::grpc::ServerWriter<AclData>* writer) override {
332     log::info("handle={}", request->handle());
333     auto connection = acl_connections_.find(request->handle());
334     if (connection == acl_connections_.end()) {
335       return ::grpc::Status(::grpc::StatusCode::INVALID_ARGUMENT, "Invalid handle");
336     }
337     return connection->second.pending_acl_data_.RunLoop(context, writer);
338   }
339 
to_handle(uint32_t current_request)340   static inline uint16_t to_handle(uint32_t current_request) {
341     return (current_request + 0x10) % 0xe00;
342   }
343 
builder_to_string(std::unique_ptr<BasePacketBuilder> builder)344   static inline std::string builder_to_string(std::unique_ptr<BasePacketBuilder> builder) {
345     std::vector<uint8_t> bytes;
346     BitInserter bit_inserter(bytes);
347     builder->Serialize(bit_inserter);
348     return std::string(bytes.begin(), bytes.end());
349   }
350 
on_incoming_acl(std::shared_ptr<ClassicAclConnection> connection,uint16_t handle)351   void on_incoming_acl(std::shared_ptr<ClassicAclConnection> connection, uint16_t handle) {
352     log::info("handle={}, addr={}", connection->GetHandle(), connection->GetAddress());
353     auto packet = connection->GetAclQueueEnd()->TryDequeue();
354     auto connection_tracker = acl_connections_.find(handle);
355     log::assert_that(connection_tracker != acl_connections_.end(), "handle {}", handle);
356     AclData acl_data;
357     acl_data.set_handle(handle);
358     acl_data.set_payload(std::string(packet->begin(), packet->end()));
359     log::info("length={}", acl_data.payload().size());
360     connection_tracker->second.pending_acl_data_.OnIncomingEvent(acl_data);
361   }
362 
OnConnectSuccess(std::unique_ptr<ClassicAclConnection> connection)363   void OnConnectSuccess(std::unique_ptr<ClassicAclConnection> connection) override {
364     log::info("handle={}, addr={}", connection->GetHandle(), connection->GetAddress());
365     std::unique_lock<std::mutex> lock(acl_connections_mutex_);
366     std::shared_ptr<ClassicAclConnection> shared_connection = std::move(connection);
367     uint16_t handle = to_handle(current_connection_request_);
368     acl_connections_.erase(handle);
369     acl_connections_.emplace(
370         std::piecewise_construct,
371         std::forward_as_tuple(handle),
372         std::forward_as_tuple(handle, shared_connection, per_connection_events_[current_connection_request_]));
373     shared_connection->GetAclQueueEnd()->RegisterDequeue(
374         facade_handler_,
375         common::Bind(&AclManagerFacadeService::on_incoming_acl, common::Unretained(this), shared_connection, handle));
376     auto callbacks = acl_connections_.find(handle)->second.GetCallbacks();
377     shared_connection->RegisterCallbacks(callbacks, facade_handler_);
378     auto addr = shared_connection->GetAddress();
379     std::unique_ptr<BasePacketBuilder> builder =
380         ConnectionCompleteBuilder::Create(ErrorCode::SUCCESS, handle, addr, LinkType::ACL, Enable::DISABLED);
381     ConnectionEvent success;
382     success.set_payload(builder_to_string(std::move(builder)));
383     per_connection_events_[current_connection_request_]->OnIncomingEvent(success);
384     current_connection_request_++;
385   }
386 
OnConnectRequest(Address,ClassOfDevice)387   void OnConnectRequest(Address /* address */, ClassOfDevice /* cod */) override {
388     log::error("Remote connect request unimplemented");
389   }
390 
OnConnectFail(Address address,ErrorCode reason,bool)391   void OnConnectFail(Address address, ErrorCode reason, bool /* locally_initiated */) override {
392     log::info("addr={}, reason={}", address, ErrorCodeText(reason));
393     std::unique_ptr<BasePacketBuilder> builder =
394         ConnectionCompleteBuilder::Create(reason, 0, address, LinkType::ACL, Enable::DISABLED);
395     ConnectionEvent fail;
396     fail.set_payload(builder_to_string(std::move(builder)));
397     per_connection_events_[current_connection_request_]->OnIncomingEvent(fail);
398     current_connection_request_++;
399   }
400 
401   class Connection : public ConnectionManagementCallbacks {
402    public:
Connection(uint16_t handle,std::shared_ptr<ClassicAclConnection> connection,std::shared_ptr<::bluetooth::grpc::GrpcEventQueue<ConnectionEvent>> event_stream)403     Connection(
404         uint16_t handle,
405         std::shared_ptr<ClassicAclConnection> connection,
406         std::shared_ptr<::bluetooth::grpc::GrpcEventQueue<ConnectionEvent>> event_stream)
407         : handle_(handle), connection_(std::move(connection)), event_stream_(std::move(event_stream)) {}
408 
GetCallbacks()409     ConnectionManagementCallbacks* GetCallbacks() {
410       return this;
411     }
412 
OnCentralLinkKeyComplete(KeyFlag key_flag)413     void OnCentralLinkKeyComplete(KeyFlag key_flag) override {
414       log::info("key_flag:{}", KeyFlagText(key_flag));
415     }
416 
OnRoleChange(hci::ErrorCode,Role new_role)417     void OnRoleChange(hci::ErrorCode /* hci_status */, Role new_role) override {
418       log::info("new_role:{}", (uint8_t)new_role);
419     }
420 
OnReadLinkPolicySettingsComplete(uint16_t link_policy_settings)421     void OnReadLinkPolicySettingsComplete(uint16_t link_policy_settings) override {
422       log::info("link_policy_settings:{}", link_policy_settings);
423     }
424 
OnConnectionPacketTypeChanged(uint16_t packet_type)425     void OnConnectionPacketTypeChanged(uint16_t packet_type) override {
426       log::info("OnConnectionPacketTypeChanged packet_type:{}", packet_type);
427     }
428 
OnAuthenticationComplete(hci::ErrorCode)429     void OnAuthenticationComplete(hci::ErrorCode /* hci_status */) override {
430       log::info("OnAuthenticationComplete");
431     }
432 
OnEncryptionChange(EncryptionEnabled enabled)433     void OnEncryptionChange(EncryptionEnabled enabled) override {
434       log::info("OnConnectionPacketTypeChanged enabled:{}", (uint8_t)enabled);
435     }
436 
OnChangeConnectionLinkKeyComplete()437     void OnChangeConnectionLinkKeyComplete() override {
438       log::info("OnChangeConnectionLinkKeyComplete");
439     };
440 
OnReadClockOffsetComplete(uint16_t clock_offset)441     void OnReadClockOffsetComplete(uint16_t clock_offset) override {
442       log::info("OnReadClockOffsetComplete clock_offset:{}", clock_offset);
443     };
444 
OnModeChange(ErrorCode,Mode current_mode,uint16_t interval)445     void OnModeChange(ErrorCode /* status */, Mode current_mode, uint16_t interval) override {
446       log::info("OnModeChange Mode:{}, interval:{}", (uint8_t)current_mode, interval);
447     };
448 
OnSniffSubrating(hci::ErrorCode,uint16_t maximum_transmit_latency,uint16_t maximum_receive_latency,uint16_t minimum_remote_timeout,uint16_t minimum_local_timeout)449     void OnSniffSubrating(
450         hci::ErrorCode /* hci_status */,
451         uint16_t maximum_transmit_latency,
452         uint16_t maximum_receive_latency,
453         uint16_t minimum_remote_timeout,
454         uint16_t minimum_local_timeout) override {
455       log::info(
456           "OnSniffSubrating maximum_transmit_latency:{}, maximum_receive_latency:{} "
457           "minimum_remote_timeout:{} minimum_local_timeout:{}",
458           maximum_transmit_latency,
459           maximum_receive_latency,
460           minimum_remote_timeout,
461           minimum_local_timeout);
462     }
463 
OnQosSetupComplete(ServiceType service_type,uint32_t token_rate,uint32_t peak_bandwidth,uint32_t latency,uint32_t delay_variation)464     void OnQosSetupComplete(
465         ServiceType service_type,
466         uint32_t token_rate,
467         uint32_t peak_bandwidth,
468         uint32_t latency,
469         uint32_t delay_variation) override {
470       log::info(
471           "OnQosSetupComplete service_type:{}, token_rate:{}, peak_bandwidth:{}, latency:{}, "
472           "delay_variation:{}",
473           (uint8_t)service_type,
474           token_rate,
475           peak_bandwidth,
476           latency,
477           delay_variation);
478     }
479 
OnFlowSpecificationComplete(FlowDirection flow_direction,ServiceType service_type,uint32_t token_rate,uint32_t token_bucket_size,uint32_t peak_bandwidth,uint32_t access_latency)480     void OnFlowSpecificationComplete(
481         FlowDirection flow_direction,
482         ServiceType service_type,
483         uint32_t token_rate,
484         uint32_t token_bucket_size,
485         uint32_t peak_bandwidth,
486         uint32_t access_latency) override {
487       log::info(
488           "OnFlowSpecificationComplete flow_direction:{}. service_type:{}, token_rate:{}, "
489           "token_bucket_size:{}, peak_bandwidth:{}, access_latency:{}",
490           (uint8_t)flow_direction,
491           (uint8_t)service_type,
492           token_rate,
493           token_bucket_size,
494           peak_bandwidth,
495           access_latency);
496     }
497 
OnFlushOccurred()498     void OnFlushOccurred() override {
499       log::info("OnFlushOccurred");
500     }
501 
OnRoleDiscoveryComplete(Role current_role)502     void OnRoleDiscoveryComplete(Role current_role) override {
503       log::info("OnRoleDiscoveryComplete current_role:{}", (uint8_t)current_role);
504     }
505 
OnReadAutomaticFlushTimeoutComplete(uint16_t flush_timeout)506     void OnReadAutomaticFlushTimeoutComplete(uint16_t flush_timeout) override {
507       log::info("OnReadAutomaticFlushTimeoutComplete flush_timeout:{}", flush_timeout);
508     }
509 
OnReadTransmitPowerLevelComplete(uint8_t transmit_power_level)510     void OnReadTransmitPowerLevelComplete(uint8_t transmit_power_level) override {
511       log::info("OnReadTransmitPowerLevelComplete transmit_power_level:{}", transmit_power_level);
512     }
513 
OnReadLinkSupervisionTimeoutComplete(uint16_t link_supervision_timeout)514     void OnReadLinkSupervisionTimeoutComplete(uint16_t link_supervision_timeout) override {
515       log::info(
516           "OnReadLinkSupervisionTimeoutComplete link_supervision_timeout:{}",
517           link_supervision_timeout);
518     }
519 
OnReadFailedContactCounterComplete(uint16_t failed_contact_counter)520     void OnReadFailedContactCounterComplete(uint16_t failed_contact_counter) override {
521       log::info(
522           "OnReadFailedContactCounterComplete failed_contact_counter:{}", failed_contact_counter);
523     }
524 
OnReadLinkQualityComplete(uint8_t link_quality)525     void OnReadLinkQualityComplete(uint8_t link_quality) override {
526       log::info("OnReadLinkQualityComplete link_quality:{}", link_quality);
527     }
528 
OnReadAfhChannelMapComplete(AfhMode afh_mode,std::array<uint8_t,10>)529     void OnReadAfhChannelMapComplete(
530         AfhMode afh_mode, std::array<uint8_t, 10> /* afh_channel_map */) override {
531       log::info("OnReadAfhChannelMapComplete afh_mode:{}", (uint8_t)afh_mode);
532     }
533 
OnReadRssiComplete(uint8_t rssi)534     void OnReadRssiComplete(uint8_t rssi) override {
535       log::info("OnReadRssiComplete rssi:{}", rssi);
536     }
537 
OnReadClockComplete(uint32_t clock,uint16_t accuracy)538     void OnReadClockComplete(uint32_t clock, uint16_t accuracy) override {
539       log::info("OnReadClockComplete clock:{}, accuracy:{}", clock, accuracy);
540     }
541 
OnDisconnection(ErrorCode reason)542     void OnDisconnection(ErrorCode reason) override {
543       log::info("reason: {}", ErrorCodeText(reason));
544       std::unique_ptr<BasePacketBuilder> builder =
545           DisconnectionCompleteBuilder::Create(ErrorCode::SUCCESS, handle_, reason);
546       ConnectionEvent disconnection;
547       disconnection.set_payload(builder_to_string(std::move(builder)));
548       event_stream_->OnIncomingEvent(disconnection);
549     }
OnReadRemoteVersionInformationComplete(hci::ErrorCode,uint8_t lmp_version,uint16_t manufacturer_name,uint16_t sub_version)550     void OnReadRemoteVersionInformationComplete(
551         hci::ErrorCode /* error_status */,
552         uint8_t lmp_version,
553         uint16_t manufacturer_name,
554         uint16_t sub_version) override {
555       log::info(
556           "OnReadRemoteVersionInformationComplete lmp_version:{} manufacturer_name:{} "
557           "sub_version:{}",
558           lmp_version,
559           manufacturer_name,
560           sub_version);
561     }
OnReadRemoteSupportedFeaturesComplete(uint64_t features)562     void OnReadRemoteSupportedFeaturesComplete(uint64_t features) override {
563       log::info(
564           "OnReadRemoteSupportedFeaturesComplete features:0x{:x}",
565           static_cast<unsigned long>(features));
566     }
OnReadRemoteExtendedFeaturesComplete(uint8_t page_number,uint8_t max_page_number,uint64_t features)567     void OnReadRemoteExtendedFeaturesComplete(
568         uint8_t page_number, uint8_t max_page_number, uint64_t features) override {
569       log::info(
570           "OnReadRemoteExtendedFeaturesComplete page_number:{} max_page_number:{} features:0x{:x}",
571           page_number,
572           max_page_number,
573           static_cast<unsigned long>(features));
574     }
575 
576     uint16_t handle_;
577     std::shared_ptr<ClassicAclConnection> connection_;
578     std::shared_ptr<::bluetooth::grpc::GrpcEventQueue<ConnectionEvent>> event_stream_;
579     ::bluetooth::grpc::GrpcEventQueue<AclData> pending_acl_data_{std::string("PendingAclData") +
580                                                                  std::to_string(handle_)};
581   };
582 
583  private:
584   AclManager* acl_manager_;
585   ::bluetooth::os::Handler* facade_handler_;
586   mutable std::mutex acl_connections_mutex_;
587   std::map<uint16_t, Connection> acl_connections_;
588   std::vector<std::shared_ptr<::bluetooth::grpc::GrpcEventQueue<ConnectionEvent>>> per_connection_events_;
589   uint32_t current_connection_request_{0};
590 };
591 
ListDependencies(ModuleList * list) const592 void AclManagerFacadeModule::ListDependencies(ModuleList* list) const {
593   ::bluetooth::grpc::GrpcFacadeModule::ListDependencies(list);
594   list->add<AclManager>();
595 }
596 
Start()597 void AclManagerFacadeModule::Start() {
598   ::bluetooth::grpc::GrpcFacadeModule::Start();
599   service_ = new AclManagerFacadeService(GetDependency<AclManager>(), GetHandler());
600 }
601 
Stop()602 void AclManagerFacadeModule::Stop() {
603   delete service_;
604   ::bluetooth::grpc::GrpcFacadeModule::Stop();
605 }
606 
GetService() const607 ::grpc::Service* AclManagerFacadeModule::GetService() const {
608   return service_;
609 }
610 
611 const ModuleFactory AclManagerFacadeModule::Factory =
__anonfb0023bf0102() 612     ::bluetooth::ModuleFactory([]() { return new AclManagerFacadeModule(); });
613 
614 }  // namespace facade
615 }  // namespace hci
616 }  // namespace bluetooth
617