• 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 #pragma once
18 
19 #include <memory>
20 
21 #include "common/bidi_queue.h"
22 #include "common/callback.h"
23 #include "hci/address.h"
24 #include "hci/address_with_type.h"
25 #include "hci/hci_layer.h"
26 #include "hci/hci_packets.h"
27 #include "module.h"
28 #include "os/handler.h"
29 
30 namespace bluetooth {
31 namespace hci {
32 
33 class AclManager;
34 
35 class ConnectionManagementCallbacks {
36  public:
37   virtual ~ConnectionManagementCallbacks() = default;
38   // Invoked when controller sends Connection Packet Type Changed event with Success error code
39   virtual void OnConnectionPacketTypeChanged(uint16_t packet_type) = 0;
40   // Invoked when controller sends Authentication Complete event with Success error code
41   virtual void OnAuthenticationComplete() = 0;
42   // Invoked when controller sends Encryption Change event with Success error code
43   virtual void OnEncryptionChange(EncryptionEnabled enabled) = 0;
44   // Invoked when controller sends Change Connection Link Key Complete event with Success error code
45   virtual void OnChangeConnectionLinkKeyComplete() = 0;
46   // Invoked when controller sends Read Clock Offset Complete event with Success error code
47   virtual void OnReadClockOffsetComplete(uint16_t clock_offset) = 0;
48   // Invoked when controller sends Mode Change event with Success error code
49   virtual void OnModeChange(Mode current_mode, uint16_t interval) = 0;
50   // Invoked when controller sends QoS Setup Complete event with Success error code
51   virtual void OnQosSetupComplete(ServiceType service_type, uint32_t token_rate, uint32_t peak_bandwidth,
52                                   uint32_t latency, uint32_t delay_variation) = 0;
53   // Invoked when controller sends Flow Specification Complete event with Success error code
54   virtual void OnFlowSpecificationComplete(FlowDirection flow_direction, ServiceType service_type, uint32_t token_rate,
55                                            uint32_t token_bucket_size, uint32_t peak_bandwidth,
56                                            uint32_t access_latency) = 0;
57   // Invoked when controller sends Flush Occurred event
58   virtual void OnFlushOccurred() = 0;
59   // Invoked when controller sends Command Complete event for Role Discovery command with Success error code
60   virtual void OnRoleDiscoveryComplete(Role current_role) = 0;
61   // Invoked when controller sends Command Complete event for Read Link Policy Settings command with Success error code
62   virtual void OnReadLinkPolicySettingsComplete(uint16_t link_policy_settings) = 0;
63   // Invoked when controller sends Command Complete event for Read Automatic Flush Timeout command with Success error
64   // code
65   virtual void OnReadAutomaticFlushTimeoutComplete(uint16_t flush_timeout) = 0;
66   // Invoked when controller sends Command Complete event for Read Transmit Power Level command with Success error code
67   virtual void OnReadTransmitPowerLevelComplete(uint8_t transmit_power_level) = 0;
68   // Invoked when controller sends Command Complete event for Read Link Supervision Time out command with Success error
69   // code
70   virtual void OnReadLinkSupervisionTimeoutComplete(uint16_t link_supervision_timeout) = 0;
71   // Invoked when controller sends Command Complete event for Read Failed Contact Counter command with Success error
72   // code
73   virtual void OnReadFailedContactCounterComplete(uint16_t failed_contact_counter) = 0;
74   // Invoked when controller sends Command Complete event for Read Link Quality command with Success error code
75   virtual void OnReadLinkQualityComplete(uint8_t link_quality) = 0;
76   // Invoked when controller sends Command Complete event for Read AFH Channel Map command with Success error code
77   virtual void OnReadAfhChannelMapComplete(AfhMode afh_mode, std::array<uint8_t, 10> afh_channel_map) = 0;
78   // Invoked when controller sends Command Complete event for Read RSSI command with Success error code
79   virtual void OnReadRssiComplete(uint8_t rssi) = 0;
80   // Invoked when controller sends Command Complete event for Read Clock command with Success error code
81   virtual void OnReadClockComplete(uint32_t clock, uint16_t accuracy) = 0;
82 };
83 
84 class AclConnection {
85  public:
AclConnection()86   AclConnection()
87       : manager_(nullptr), handle_(0), address_(Address::kEmpty), address_type_(AddressType::PUBLIC_DEVICE_ADDRESS){};
88   virtual ~AclConnection() = default;
89 
GetAddress()90   virtual Address GetAddress() const {
91     return address_;
92   }
93 
GetAddressType()94   virtual AddressType GetAddressType() const {
95     return address_type_;
96   }
97 
GetHandle()98   uint16_t GetHandle() const {
99     return handle_;
100   }
101 
102   /* This return role for LE devices only, for Classic, please see |RoleDiscovery| method.
103    * TODO: split AclConnection for LE and Classic
104    */
GetRole()105   Role GetRole() const {
106     return role_;
107   }
108 
109   using Queue = common::BidiQueue<PacketView<kLittleEndian>, BasePacketBuilder>;
110   using QueueUpEnd = common::BidiQueueEnd<BasePacketBuilder, PacketView<kLittleEndian>>;
111   using QueueDownEnd = common::BidiQueueEnd<PacketView<kLittleEndian>, BasePacketBuilder>;
112   virtual QueueUpEnd* GetAclQueueEnd() const;
113   virtual void RegisterCallbacks(ConnectionManagementCallbacks* callbacks, os::Handler* handler);
114   virtual void UnregisterCallbacks(ConnectionManagementCallbacks* callbacks);
115   virtual void RegisterDisconnectCallback(common::OnceCallback<void(ErrorCode)> on_disconnect, os::Handler* handler);
116   virtual bool Disconnect(DisconnectReason reason);
117   virtual bool ChangeConnectionPacketType(uint16_t packet_type);
118   virtual bool AuthenticationRequested();
119   virtual bool SetConnectionEncryption(Enable enable);
120   virtual bool ChangeConnectionLinkKey();
121   virtual bool ReadClockOffset();
122   virtual bool HoldMode(uint16_t max_interval, uint16_t min_interval);
123   virtual bool SniffMode(uint16_t max_interval, uint16_t min_interval, uint16_t attempt, uint16_t timeout);
124   virtual bool ExitSniffMode();
125   virtual bool QosSetup(ServiceType service_type, uint32_t token_rate, uint32_t peak_bandwidth, uint32_t latency,
126                         uint32_t delay_variation);
127   virtual bool RoleDiscovery();
128   virtual bool ReadLinkPolicySettings();
129   virtual bool WriteLinkPolicySettings(uint16_t link_policy_settings);
130   virtual bool FlowSpecification(FlowDirection flow_direction, ServiceType service_type, uint32_t token_rate,
131                                  uint32_t token_bucket_size, uint32_t peak_bandwidth, uint32_t access_latency);
132   virtual bool SniffSubrating(uint16_t maximum_latency, uint16_t minimum_remote_timeout,
133                               uint16_t minimum_local_timeout);
134   virtual bool Flush();
135   virtual bool ReadAutomaticFlushTimeout();
136   virtual bool WriteAutomaticFlushTimeout(uint16_t flush_timeout);
137   virtual bool ReadTransmitPowerLevel(TransmitPowerLevelType type);
138   virtual bool ReadLinkSupervisionTimeout();
139   virtual bool WriteLinkSupervisionTimeout(uint16_t link_supervision_timeout);
140   virtual bool ReadFailedContactCounter();
141   virtual bool ResetFailedContactCounter();
142   virtual bool ReadLinkQuality();
143   virtual bool ReadAfhChannelMap();
144   virtual bool ReadRssi();
145   virtual bool ReadClock(WhichClock which_clock);
146   virtual bool ReadRemoteVersionInformation();
147   virtual bool ReadRemoteSupportedFeatures();
148   virtual bool ReadRemoteExtendedFeatures();
149 
150   // LE ACL Method
151   virtual bool LeConnectionUpdate(uint16_t conn_interval_min, uint16_t conn_interval_max, uint16_t conn_latency,
152                                   uint16_t supervision_timeout, common::OnceCallback<void(ErrorCode)> done_callback,
153                                   os::Handler* handler);
154 
155   // Ask AclManager to clean me up. Must invoke after on_disconnect is called
156   virtual void Finish();
157 
158   // TODO: API to change link settings ... ?
159 
160  private:
161   friend AclManager;
AclConnection(const AclManager * manager,uint16_t handle,Address address)162   AclConnection(const AclManager* manager, uint16_t handle, Address address)
163       : manager_(manager), handle_(handle), address_(address), address_type_(AddressType::PUBLIC_DEVICE_ADDRESS) {}
AclConnection(const AclManager * manager,uint16_t handle,Address address,AddressType address_type,Role role)164   AclConnection(const AclManager* manager, uint16_t handle, Address address, AddressType address_type, Role role)
165       : manager_(manager), handle_(handle), address_(address), address_type_(address_type), role_(role) {}
166   const AclManager* manager_;
167   uint16_t handle_;
168   Address address_;
169   AddressType address_type_;
170   Role role_;
171   DISALLOW_COPY_AND_ASSIGN(AclConnection);
172 };
173 
174 class ConnectionCallbacks {
175  public:
176   virtual ~ConnectionCallbacks() = default;
177   // Invoked when controller sends Connection Complete event with Success error code
178   virtual void OnConnectSuccess(std::unique_ptr<AclConnection> /* , initiated_by_local ? */) = 0;
179   // Invoked when controller sends Connection Complete event with non-Success error code
180   virtual void OnConnectFail(Address, ErrorCode reason) = 0;
181 };
182 
183 class LeConnectionCallbacks {
184  public:
185   virtual ~LeConnectionCallbacks() = default;
186   // Invoked when controller sends Connection Complete event with Success error code
187   // AddressWithType is always equal to the object used in AclManager#CreateLeConnection
188   virtual void OnLeConnectSuccess(AddressWithType, std::unique_ptr<AclConnection> /* , initiated_by_local ? */) = 0;
189   // Invoked when controller sends Connection Complete event with non-Success error code
190   virtual void OnLeConnectFail(AddressWithType, ErrorCode reason) = 0;
191 };
192 
193 class AclManagerCallbacks {
194  public:
195   virtual ~AclManagerCallbacks() = default;
196   // Invoked when controller sends Master Link Key Complete event with Success error code
197   virtual void OnMasterLinkKeyComplete(uint16_t connection_handle, KeyFlag key_flag) = 0;
198   // Invoked when controller sends Role Change event with Success error code
199   virtual void OnRoleChange(Address bd_addr, Role new_role) = 0;
200   // Invoked when controller sends Command Complete event for Read Default Link Policy Settings command with Success
201   // error code
202   virtual void OnReadDefaultLinkPolicySettingsComplete(uint16_t default_link_policy_settings) = 0;
203 };
204 
205 class AclManager : public Module {
206  public:
207   AclManager();
208   // NOTE: It is necessary to forward declare a default destructor that overrides the base class one, because
209   // "struct impl" is forwarded declared in .cc and compiler needs a concrete definition of "struct impl" when
210   // compiling AclManager's destructor. Hence we need to forward declare the destructor for AclManager to delay
211   // compiling AclManager's destructor until it starts linking the .cc file.
212   ~AclManager() override;
213 
214   // Should register only once when user module starts.
215   // Generates OnConnectSuccess when an incoming connection is established.
216   virtual void RegisterCallbacks(ConnectionCallbacks* callbacks, os::Handler* handler);
217 
218   // Should register only once when user module starts.
219   virtual void RegisterLeCallbacks(LeConnectionCallbacks* callbacks, os::Handler* handler);
220 
221   // Should register only once when user module starts.
222   virtual void RegisterAclManagerCallbacks(AclManagerCallbacks* callbacks, os::Handler* handler);
223 
224   // Should register only once when user module starts.
225   virtual void RegisterLeAclManagerCallbacks(AclManagerCallbacks* callbacks, os::Handler* handler);
226 
227   // Generates OnConnectSuccess if connected, or OnConnectFail otherwise
228   virtual void CreateConnection(Address address);
229 
230   // Generates OnLeConnectSuccess if connected, or OnLeConnectFail otherwise
231   virtual void CreateLeConnection(AddressWithType address_with_type);
232 
233   // Generates OnConnectFail with error code "terminated by local host 0x16" if cancelled, or OnConnectSuccess if not
234   // successfully cancelled and already connected
235   virtual void CancelConnect(Address address);
236 
237   virtual void MasterLinkKey(KeyFlag key_flag);
238   virtual void SwitchRole(Address address, Role role);
239   virtual void ReadDefaultLinkPolicySettings();
240   virtual void WriteDefaultLinkPolicySettings(uint16_t default_link_policy_settings);
241 
242   static const ModuleFactory Factory;
243 
244  protected:
245   void ListDependencies(ModuleList* list) override;
246 
247   void Start() override;
248 
249   void Stop() override;
250 
251   std::string ToString() const override;
252 
253  private:
254   friend AclConnection;
255 
256   struct impl;
257   std::unique_ptr<impl> pimpl_;
258 
259   struct acl_connection;
260   DISALLOW_COPY_AND_ASSIGN(AclManager);
261 };
262 
263 }  // namespace hci
264 }  // namespace bluetooth
265