1//
2//  Copyright 2015 Google, Inc.
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 <mutex>
20#include <unordered_set>
21#include <vector>
22
23#include <base/macros.h>
24#include <hardware/bluetooth.h>
25#include <hardware/bt_gatt.h>
26
27namespace bluetooth {
28namespace hal {
29
30// This class represents the standard BT-GATT interface. This class combines
31// GATT profile server and client role operations with general GAP profile
32// operations of various roles (central, scanner, peripheral, advertiser),
33// wrapping around the underlying bt_gatt_interface_t structure. A single
34// instance of this class exists per application and it allows multiple classes
35// to interface with the global HAL interface by multiplexing callbacks among
36// registered clients.
37//
38// This is declared as an abstract interface so that a fake implementation can
39// be injected for testing the upper layer.
40class BluetoothGattInterface {
41 public:
42  // The HAL interface doesn't allow registering "user data" that carries
43  // context beyond the callback parameters, forcing implementations to deal
44  // with global variables. The *Observer interface is to redirect these events
45  // to interested parties in an object-oriented manner.
46
47  // The standard LE scanner callback interface.
48  class ScannerObserver {
49   public:
50    virtual ~ScannerObserver() = default;
51
52    // All of the events below correspond to callbacks defined in
53    // "btgatt_scanner_callbacks_t" in the HAL API definitions.
54
55    virtual void ScanResultCallback(
56        BluetoothGattInterface* gatt_iface, const RawAddress& bda, int rssi,
57        std::vector<uint8_t> adv_data);  // NOLINT(pass-by-value)
58  };
59
60  // The standard BT-GATT client callback interface.
61  class ClientObserver {
62   public:
63    virtual ~ClientObserver() = default;
64
65    // All of the events below correspond to callbacks defined in
66    // "bt_gatt_client_callbacks_t" in the HAL API definitions.
67
68    virtual void RegisterClientCallback(BluetoothGattInterface* gatt_iface,
69                                        int status, int client_if,
70                                        const bluetooth::Uuid& app_uuid);
71
72    virtual void ConnectCallback(BluetoothGattInterface* gatt_iface,
73                                 int conn_id, int status, int client_if,
74                                 const RawAddress& bda);
75
76    virtual void DisconnectCallback(BluetoothGattInterface* gatt_iface,
77                                    int conn_id, int status, int client_if,
78                                    const RawAddress& bda);
79
80    virtual void SearchCompleteCallback(BluetoothGattInterface* gatt_iface,
81                                        int conn_id, int status);
82
83    virtual void RegisterForNotificationCallback(
84        BluetoothGattInterface* gatt_iface, int conn_id, int status,
85        int registered, uint16_t handle);
86
87    virtual void NotifyCallback(BluetoothGattInterface* gatt_iface, int conn_id,
88                                const btgatt_notify_params_t& p_data);
89
90    virtual void WriteCharacteristicCallback(BluetoothGattInterface* gatt_iface,
91                                             int conn_id, int status,
92                                             uint16_t handle);
93
94    virtual void WriteDescriptorCallback(BluetoothGattInterface* gatt_iface,
95                                         int conn_id, int status,
96                                         uint16_t handle);
97
98    virtual void MtuChangedCallback(BluetoothGattInterface* gatt_iface,
99                                    int conn_id, int status, int mtu);
100
101    virtual void GetGattDbCallback(BluetoothGattInterface* gatt_iface,
102                                   int conn_id,
103                                   const btgatt_db_element_t* gatt_db,
104                                   int size);
105
106    virtual void ServicesRemovedCallback(BluetoothGattInterface* gatt_iface,
107                                         int conn_id, uint16_t start_handle,
108                                         uint16_t end_handle);
109
110    virtual void ServicesAddedCallback(BluetoothGattInterface* gatt_iface,
111                                       int conn_id,
112                                       const btgatt_db_element_t& added,
113                                       int added_count);
114  };
115
116  // The standard BT-GATT server callback interface.
117  class ServerObserver {
118   public:
119    virtual ~ServerObserver() = default;
120
121    virtual void RegisterServerCallback(BluetoothGattInterface* gatt_iface,
122                                        int status, int server_if,
123                                        const bluetooth::Uuid& app_uuid);
124
125    virtual void ConnectionCallback(BluetoothGattInterface* gatt_iface,
126                                    int conn_id, int server_if, int connected,
127                                    const RawAddress& bda);
128
129    virtual void ServiceAddedCallback(
130        BluetoothGattInterface* gatt_iface, int status, int server_if,
131        std::vector<btgatt_db_element_t> service);  // NOLINT(pass-by-value)
132
133    virtual void ServiceStoppedCallback(BluetoothGattInterface* gatt_iface,
134                                        int status, int server_if,
135                                        int srvc_handle);
136
137    virtual void ServiceDeletedCallback(BluetoothGattInterface* gatt_iface,
138                                        int status, int server_if,
139                                        int srvc_handle);
140
141    virtual void RequestReadCharacteristicCallback(
142        BluetoothGattInterface* gatt_iface, int conn_id, int trans_id,
143        const RawAddress& bda, int attr_handle, int offset, bool is_long);
144
145    virtual void RequestReadDescriptorCallback(
146        BluetoothGattInterface* gatt_iface, int conn_id, int trans_id,
147        const RawAddress& bda, int attr_handle, int offset, bool is_long);
148
149    virtual void RequestWriteCharacteristicCallback(
150        BluetoothGattInterface* gatt_iface, int conn_id, int trans_id,
151        const RawAddress& bda, int attr_handle, int offset, bool need_rsp,
152        bool is_prep,
153        std::vector<uint8_t> value);  // NOLINT(pass-by-value)
154
155    virtual void RequestWriteDescriptorCallback(
156        BluetoothGattInterface* gatt_iface, int conn_id, int trans_id,
157        const RawAddress& bda, int attr_handle, int offset, bool need_rsp,
158        bool is_prep,
159        std::vector<uint8_t> value);  // NOLINT(pass-by-alue)
160
161    virtual void RequestExecWriteCallback(BluetoothGattInterface* gatt_iface,
162                                          int conn_id, int trans_id,
163                                          const RawAddress& bda,
164                                          int exec_write);
165
166    virtual void ResponseConfirmationCallback(
167        BluetoothGattInterface* gatt_iface, int status, int handle);
168
169    virtual void IndicationSentCallback(BluetoothGattInterface* gatt_iface,
170                                        int conn_id, int status);
171
172    virtual void MtuChangedCallback(BluetoothGattInterface* gatt_iface,
173                                    int conn_id, int mtu);
174  };
175
176  // Initialize and clean up the BluetoothInterface singleton. Returns false if
177  // the underlying HAL interface failed to initialize, and true on success.
178  static bool Initialize();
179
180  // Shuts down and cleans up the interface. CleanUp must be called on the same
181  // thread that called Initialize.
182  static void CleanUp();
183
184  // Returns true if the interface was initialized and a global singleton has
185  // been created.
186  static bool IsInitialized();
187
188  // Initialize for testing. Use this to inject a test version of
189  // BluetoothGattInterface. To be used from unit tests only.
190  static void InitializeForTesting(BluetoothGattInterface* test_instance);
191
192  // Returns the BluetoothGattInterface singleton. If the interface has
193  // not been initialized, returns nullptr. This method is thread-safe, in that
194  // it will block if the internal lock is being held by another thread. Don't
195  // call this re-entrantly from an observer event as this may cause a deadlock.
196  static BluetoothGattInterface* Get();
197
198  // Add or remove an observer that is interested in LE scanner interface
199  // notifications from us. Thread-safety is guaranteed by ObserverList.
200  virtual void AddScannerObserver(ScannerObserver* observer) = 0;
201  virtual void RemoveScannerObserver(ScannerObserver* observer) = 0;
202
203  // Add or remove an observer that is interested in GATT client interface
204  // notifications from us. Thread-safety is guaranteed by ObserverList.
205  virtual void AddClientObserver(ClientObserver* observer) = 0;
206  virtual void RemoveClientObserver(ClientObserver* observer) = 0;
207
208  // Add or remove an observer that is interested in GATT server interface
209  // notifications from us. Thread-safety is guaranteed by ObserverList.
210  virtual void AddServerObserver(ServerObserver* observer) = 0;
211  virtual void RemoveServerObserver(ServerObserver* observer) = 0;
212
213  // The HAL module pointer that represents the standard BT LE advertiser
214  // interface. This is implemented in and provided by the shared Bluetooth
215  // library, so this isn't owned by us.
216  //
217  // Upper layers can make ble_advertiser_interface_t API calls through this
218  // structure.
219  virtual BleAdvertiserInterface* GetAdvertiserHALInterface() const = 0;
220
221  // The HAL module pointer that represents the standard BT LE scanner
222  // interface. This is implemented in and provided by the shared Bluetooth
223  // library, so this isn't owned by us.
224  //
225  // Upper layers can make ble_scanner_interface_t API calls through this
226  // structure.
227  virtual BleScannerInterface* GetScannerHALInterface() const = 0;
228
229  // The HAL module pointer that represents the standard BT-GATT client
230  // interface. This is implemented in and provided by the shared Bluetooth
231  // library, so this isn't owned by us.
232  //
233  // Upper layers can make btgatt_client_interface_t API calls through this
234  // structure.
235  virtual const btgatt_client_interface_t* GetClientHALInterface() const = 0;
236
237  // The HAL module pointer that represents the standard BT-GATT server
238  // interface. This is implemented in and provided by the shared Bluetooth
239  // library, so this isn't owned by us.
240  //
241  // Upper layers can make btgatt_server_interface_t API calls through this
242  // structure.
243  virtual const btgatt_server_interface_t* GetServerHALInterface() const = 0;
244
245  // Initiates a regular BLE device scan. This is called internally from each
246  // LowEnergyClient. This function synchronizes the scan requests and maintains
247  // an internal reference count for each scan client that is interested.
248  bt_status_t StartScan(int client_id);
249  bt_status_t StopScan(int client_id);
250
251 protected:
252  BluetoothGattInterface() = default;
253  virtual ~BluetoothGattInterface() = default;
254
255 private:
256  // Used to keep a reference count for the different BLE scan clients.
257  std::mutex scan_clients_lock_;
258  std::unordered_set<int> scan_client_set_;
259
260  DISALLOW_COPY_AND_ASSIGN(BluetoothGattInterface);
261};
262
263}  // namespace hal
264}  // namespace bluetooth
265