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