1 //
2 //  Copyright (C) 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 <atomic>
20 #include <functional>
21 #include <map>
22 #include <mutex>
23 
24 #include <base/macros.h>
25 
26 #include "service/bluetooth_instance.h"
27 #include "service/common/bluetooth/low_energy_constants.h"
28 #include "service/common/bluetooth/scan_filter.h"
29 #include "service/common/bluetooth/scan_result.h"
30 #include "service/common/bluetooth/scan_settings.h"
31 #include "service/common/bluetooth/uuid.h"
32 #include "service/hal/bluetooth_gatt_interface.h"
33 
34 namespace bluetooth {
35 
36 struct ConnComparator {
operatorConnComparator37   bool operator()(const bt_bdaddr_t& a, const bt_bdaddr_t& b) const {
38     return memcmp(&a, &b, sizeof(bt_bdaddr_t)) < 0;
39   }
40 };
41 
42 class Adapter;
43 
44 // A LowEnergyClient represents an application's handle to perform various
45 // Bluetooth Low Energy GAP operations. Instances cannot be created directly and
46 // should be obtained through the factory.
47 class LowEnergyClient : private hal::BluetoothGattInterface::ClientObserver,
48                         public BluetoothInstance {
49  public:
50   // The Delegate interface is used to notify asynchronous events related to BLE
51   // GAP operations.
52   class Delegate {
53    public:
54     Delegate() = default;
55     virtual ~Delegate() = default;
56 
57     // Called asynchronously to notify the delegate of connection state change
58     virtual void OnConnectionState(LowEnergyClient* client, int status,
59                                    const char* address, bool connected) = 0;
60 
61     // Called asynchronously to notify the delegate of mtu change
62     virtual void OnMtuChanged(LowEnergyClient* client, int status,
63                               const char* address, int mtu) = 0;
64 
65    private:
66     DISALLOW_COPY_AND_ASSIGN(Delegate);
67   };
68 
69   // The destructor automatically unregisters this client instance from the
70   // stack.
71   ~LowEnergyClient() override;
72 
73   // Assigns a delegate to this instance. |delegate| must out-live this
74   // LowEnergyClient instance.
75   void SetDelegate(Delegate* delegate);
76 
77   // Callback type used to return the result of asynchronous operations below.
78   using StatusCallback = std::function<void(BLEStatus)>;
79 
80   // Initiates a BLE connection do device with address |address|. If
81   // |is_direct| is set, use direct connect procedure. Return true on success
82   //, false otherwise.
83   bool Connect(const std::string& address, bool is_direct);
84 
85   // Disconnect from previously connected BLE device with address |address|.
86   // Return true on success, false otherwise.
87   bool Disconnect(const std::string& address);
88 
89   // Sends request to set MTU to |mtu| for device with address |address|.
90   // Return true on success, false otherwise.
91   bool SetMtu(const std::string& address, int mtu);
92 
93   // BluetoothClientInstace overrides:
94   const UUID& GetAppIdentifier() const override;
95   int GetInstanceId() const override;
96 
97  private:
98   friend class LowEnergyClientFactory;
99 
100   // Constructor shouldn't be called directly as instances are meant to be
101   // obtained from the factory.
102   LowEnergyClient(Adapter& adapter, const UUID& uuid, int client_id);
103 
104   // BluetoothGattInterface::ClientObserver overrides:
105   void ConnectCallback(hal::BluetoothGattInterface* gatt_iface, int conn_id,
106                        int status, int client_id,
107                        const bt_bdaddr_t& bda) override;
108   void DisconnectCallback(hal::BluetoothGattInterface* gatt_iface, int conn_id,
109                           int status, int client_id,
110                           const bt_bdaddr_t& bda) override;
111   void MtuChangedCallback(hal::BluetoothGattInterface* gatt_iface, int conn_id,
112                           int status, int mtu) override;
113 
114   // Calls and clears the pending callbacks.
115   void InvokeAndClearStartCallback(BLEStatus status);
116   void InvokeAndClearStopCallback(BLEStatus status);
117 
118   // Raw pointer to the Bluetooth Adapter.
119   Adapter& adapter_;
120 
121   // See getters above for documentation.
122   UUID app_identifier_;
123   int client_id_;
124 
125   // Raw handle to the Delegate, which must outlive this LowEnergyClient
126   // instance.
127   std::mutex delegate_mutex_;
128   Delegate* delegate_;
129 
130   // Protects device connection related members below.
131   std::mutex connection_fields_lock_;
132 
133   // Maps bluetooth address to connection id
134   // TODO(jpawlowski): change type to bimap
135   std::map<const bt_bdaddr_t, int, ConnComparator> connection_ids_;
136 
137   DISALLOW_COPY_AND_ASSIGN(LowEnergyClient);
138 };
139 
140 // LowEnergyClientFactory is used to register and obtain a per-application
141 // LowEnergyClient instance. Users should call RegisterInstance to obtain their
142 // own unique LowEnergyClient instance that has been registered with the
143 // Bluetooth stack.
144 class LowEnergyClientFactory
145     : private hal::BluetoothGattInterface::ClientObserver,
146       public BluetoothInstanceFactory {
147  public:
148   // Don't construct/destruct directly except in tests. Instead, obtain a handle
149   // from an Adapter instance.
150   explicit LowEnergyClientFactory(Adapter& adapter);
151   ~LowEnergyClientFactory() override;
152 
153   // BluetoothInstanceFactory override:
154   bool RegisterInstance(const UUID& uuid,
155                         const RegisterCallback& callback) override;
156 
157  private:
158   friend class LowEnergyClient;
159 
160   // BluetoothGattInterface::ClientObserver overrides:
161   void RegisterClientCallback(hal::BluetoothGattInterface* gatt_iface,
162                               int status, int client_id,
163                               const bt_uuid_t& app_uuid) override;
164 
165   // Map of pending calls to register.
166   std::mutex pending_calls_lock_;
167   std::map<UUID, RegisterCallback> pending_calls_;
168 
169   // Raw pointer to the Adapter that owns this factory.
170   Adapter& adapter_;
171 
172   DISALLOW_COPY_AND_ASSIGN(LowEnergyClientFactory);
173 };
174 
175 }  // namespace bluetooth
176