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