aboutsummaryrefslogtreecommitdiffstats
path: root/api/direct_bt/DBTManager.hpp
blob: 5ebcf92533189e58500b51511efad6df60fd94b2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
/*
 * Author: Sven Gothel <sgothel@jausoft.com>
 * Copyright (c) 2020 Gothel Software e.K.
 * Copyright (c) 2020 ZAFENA AB
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

#ifndef DBT_MANAGER_HPP_
#define DBT_MANAGER_HPP_

#include <cstring>
#include <string>
#include <cstdint>
#include <array>

#include <mutex>
#include <atomic>
#include <thread>

#include "BTTypes.hpp"
#include "BTIoctl.hpp"
#include "OctetTypes.hpp"
#include "HCIComm.hpp"
#include "JavaUplink.hpp"
#include "MgmtTypes.hpp"
#include "LFRingbuffer.hpp"
#include "FunctionDef.hpp"

namespace direct_bt {

    typedef FunctionDef<bool, std::shared_ptr<MgmtEvent>> MgmtEventCallback;

    class MgmtAdapterEventCallback {
        private:
            /** Unique adapter index filter or <code>-1</code> to listen for all adapter. */
            int dev_id;
            /** MgmtEventCallback instance */
            MgmtEventCallback callback;

        public:
            MgmtAdapterEventCallback(int _dev_id, const MgmtEventCallback & _callback)
            : dev_id(_dev_id), callback(_callback) {}

            MgmtAdapterEventCallback(const MgmtAdapterEventCallback &o) = default;
            MgmtAdapterEventCallback(MgmtAdapterEventCallback &&o) = default;
            MgmtAdapterEventCallback& operator=(const MgmtAdapterEventCallback &o) = default;
            MgmtAdapterEventCallback& operator=(MgmtAdapterEventCallback &&o) = default;

            /** Unique adapter index filter or <code>-1</code> to listen for all adapter. */
            int getDevID() const { return dev_id; }

            /** MgmtEventCallback reference */
            MgmtEventCallback& getCallback() { return callback; }

            bool operator==(const MgmtAdapterEventCallback& rhs) const
            { return dev_id == rhs.dev_id && callback == rhs.callback; }

            bool operator!=(const MgmtAdapterEventCallback& rhs) const
            { return !(*this == rhs); }

            std::string toString() const {
                return "MgmtAdapterEventCallback[dev_id "+std::to_string(dev_id)+", "+callback.toString()+"]";
            }
    };

    typedef std::vector<MgmtAdapterEventCallback> MgmtAdapterEventCallbackList;

    /**
     * A thread safe singleton handler of the Linux Kernel's BlueZ manager control channel.
     * <p>
     * Implementation utilizes a lock free ringbuffer receiving data within its separate thread.
     * </p>
     */
    class DBTManager : public JavaUplink {
        private:
            struct WhitelistElem {
                int dev_id;
                EUI48 address;
                BDAddressType address_type;
                HCIWhitelistConnectType ctype;
            };
            std::vector<std::shared_ptr<WhitelistElem>> whitelist;

        public:
            enum Defaults : int {
                /* BT Core Spec v5.2: Vol 3, Part F 3.2.8: Maximum length of an attribute value. */
                ClientMaxMTU = 512,

                /** 3s poll timeout for mgmt reader thread */
                MGMT_READER_THREAD_POLL_TIMEOUT = 3000,
                /** 1s timeout for mgmt command replies */
                MGMT_COMMAND_REPLY_TIMEOUT = 1000,
                MGMTEVT_RING_CAPACITY = 256
            };

            static const pid_t pidSelf;

        private:
            const BTMode btMode;
            POctets rbuffer;
            HCIComm comm;

            LFRingbuffer<std::shared_ptr<MgmtEvent>, nullptr> mgmtEventRing;
            std::thread mgmtReaderThread;
            std::atomic<bool> mgmtReaderRunning;
            std::atomic<bool> mgmtReaderShallStop;

            /** One MgmtAdapterEventCallbackList per event type, allowing multiple callbacks to be invoked for each event */
            std::array<MgmtAdapterEventCallbackList, static_cast<uint16_t>(MgmtEvent::Opcode::MGMT_EVENT_TYPE_COUNT)> mgmtAdapterEventCallbackLists;
            std::recursive_mutex mtx_callbackLists;
            inline void checkMgmtEventCallbackListsIndex(const MgmtEvent::Opcode opc) const {
                if( static_cast<uint16_t>(opc) >= mgmtAdapterEventCallbackLists.size() ) {
                    throw IndexOutOfBoundsException(static_cast<uint16_t>(opc), 1, mgmtAdapterEventCallbackLists.size(), E_FILE_LINE);
                }
            }

            std::vector<std::shared_ptr<AdapterInfo>> adapterInfos;
            void mgmtReaderThreadImpl();

            /**
             * In case response size check or devID and optional opcode validation fails,
             * function returns NULL.
             */
            std::shared_ptr<MgmtEvent> sendWithReply(MgmtCommand &req);

            DBTManager(const BTMode btMode);
            DBTManager(const DBTManager&) = delete;
            void operator=(const DBTManager&) = delete;

            std::shared_ptr<AdapterInfo> initAdapter(const uint16_t dev_id, const BTMode btMode);
            void shutdownAdapter(const uint16_t dev_id);

            bool mgmtEvClassOfDeviceChangedCB(std::shared_ptr<MgmtEvent> e);
            bool mgmtEvDeviceDiscoveringCB(std::shared_ptr<MgmtEvent> e);
            bool mgmtEvDeviceFoundCB(std::shared_ptr<MgmtEvent> e);
            bool mgmtEvDeviceDisconnectedCB(std::shared_ptr<MgmtEvent> e);
            bool mgmtEvDeviceConnectedCB(std::shared_ptr<MgmtEvent> e);
            bool mgmtEvConnectFailedCB(std::shared_ptr<MgmtEvent> e);
            bool mgmtEvDevicePinCodeRequestCB(std::shared_ptr<MgmtEvent> e);
            bool mgmtEvDeviceUnpairedCB(std::shared_ptr<MgmtEvent> e);
            bool mgmtEvNewConnectionParamCB(std::shared_ptr<MgmtEvent> e);
            bool mgmtEvDeviceWhitelistAddedCB(std::shared_ptr<MgmtEvent> e);
            bool mgmtEvDeviceWhilelistRemovedCB(std::shared_ptr<MgmtEvent> e);
            void sendMgmtEvent(std::shared_ptr<MgmtEvent> event);

        public:
            /**
             * Retrieves the singleton instance.
             * <p>
             * First call will open and initialize the bluetooth kernel.
             * </p>
             */
            static DBTManager& get(const BTMode btMode) {
                /**
                 * Thread safe starting with C++11 6.7:
                 *
                 * If control enters the declaration concurrently while the variable is being initialized,
                 * the concurrent execution shall wait for completion of the initialization.
                 *
                 * (Magic Statics)
                 *
                 * Avoiding non-working double checked locking.
                 */
                static DBTManager s(btMode);
                return s;
            }
            ~DBTManager() { close(); }

            void close();

            std::string get_java_class() const override {
                return java_class();
            }
            static std::string java_class() {
                return std::string(JAVA_DBT_PACKAGE "DBTManager");
            }

            BTMode getBTMode() { return btMode; }

            /** Returns true if this mgmt instance is open and hence valid, otherwise false */
            bool isOpen() const {
                return comm.isOpen();
            }

            std::string toString() const override { return "MgmtHandler["+std::to_string(adapterInfos.size())+" adapter, "+javaObjectToString()+"]"; }

            /** retrieve information gathered at startup */

            /**
             * Returns list of AdapterInfo with index == dev_id.
             */
            const std::vector<std::shared_ptr<AdapterInfo>> getAdapterInfos() const { return adapterInfos; }

            /**
             * Returns number of AdapterInfo with index == dev_id.
             */
            int getAdapterCount() const { return adapterInfos.size(); }

            /**
             * Returns the AdapterInfo index (== dev_id) with the given address or -1 if not found.
             */
            int findAdapterInfoIdx(const EUI48 &mac) const;
            /**
             * Returns the AdapterInfo (index == dev_id) with the given address or nullptr if not found.
             */
            std::shared_ptr<AdapterInfo> findAdapterInfo(const EUI48 &mac) const;
            /**
             * Returns the AdapterInfo (index == dev_id) with the given index.
             * <p>
             * Throws IndexOutOfBoundsException if index is > adapter count.
             * </p>
             */
            std::shared_ptr<AdapterInfo> getAdapterInfo(const int idx) const;
            /**
             * Returns the default AdapterInfo (0 == index == dev_id) or nullptr if no adapter is available.
             */
            std::shared_ptr<AdapterInfo> getDefaultAdapterInfo() const { return adapterInfos.size() > 0 ? getAdapterInfo(0) : nullptr; }

            bool setMode(const int dev_id, const MgmtOpcode opc, const uint8_t mode);

            /** Start discovery on given adapter dev_id with a ScanType matching the used BTMode. Returns set ScanType. */
            ScanType startDiscovery(const int dev_id);
            /** Start discovery on given adapter dev_id with given ScanType. Returns set ScanType. */
            ScanType startDiscovery(const int dev_id, const ScanType type);
            /** Stop discovery on given adapter dev_id. */
            bool stopDiscovery(const int dev_id, const ScanType type);

            /**
             * Uploads given connection parameter for given device to the kernel.
             */
            bool uploadConnParam(const int dev_id, const EUI48 &address, const BDAddressType address_type,
                                 const uint16_t min_interval=0x000F, const uint16_t max_interval=0x000F,
                                 const uint16_t latency=0x0000, const uint16_t timeout=HCI_LE_CONN_TIMEOUT_MS/10);

            /**
             * Returns true, if the adapter's device is already whitelisted.
             */
            bool isDeviceWhitelisted(const int dev_id, const EUI48 &address);

            /**
             * Add the given device to the adapter's autoconnect whitelist.
             * <p>
             * Make sure {@link uploadConnParam(..)} is invoked first, otherwise performance will lack.
             * </p>
             * <p>
             * Method will reject duplicate devices, in which case it should be removed first.
             * </p>
             */
            bool addDeviceToWhitelist(const int dev_id, const EUI48 &address, const BDAddressType address_type, const HCIWhitelistConnectType ctype);

            /** Remove the given device from the adapter's autoconnect whitelist. */
            bool removeDeviceFromWhitelist(const int dev_id, const EUI48 &address, const BDAddressType address_type);

            /** Remove all previously added devices from the autoconnect whitelist. Returns number of removed devices. */
            int removeAllDevicesFromWhitelist();

            uint16_t create_connection(const int dev_id,
                                       const EUI48 &peer_bdaddr,
                                       const BDAddressType peer_mac_type,
                                       const BDAddressType own_mac_type=BDADDR_LE_PUBLIC,
                                       const uint16_t interval=0x0004, const uint16_t window=0x0004,
                                       const uint16_t min_interval=0x000F, const uint16_t max_interval=0x000F,
                                       const uint16_t latency=0x0000, const uint16_t supervision_timeout=HCI_LE_CONN_TIMEOUT_MS/10);

            bool disconnect(const bool ioErrorCause,
                            const int dev_id, const EUI48 &peer_bdaddr, const BDAddressType peer_mac_type,
                            const HCIErrorCode reason=HCIErrorCode::REMOTE_USER_TERMINATED_CONNECTION );

            std::shared_ptr<ConnectionInfo> getConnectionInfo(const int dev_id, const EUI48 &address, const BDAddressType address_type);
            std::shared_ptr<NameAndShortName> setLocalName(const int dev_id, const std::string & name, const std::string & short_name);

            /** MgmtEventCallback handling  */

            /**
             * Appends the given MgmtEventCallback for the given adapter dev_id to the named MgmtEvent::Opcode list,
             * if it is not present already (dev_id + opcode + callback).
             * <p>
             * The adapter dev_id allows filtering the events only directed to the given adapter.
             * Use dev_id <code>-1</code> to receive the event for all adapter.
             * </p>
             */
            void addMgmtEventCallback(const int dev_id, const MgmtEvent::Opcode opc, const MgmtEventCallback &cb);
            /** Returns count of removed given MgmtEventCallback from the named MgmtEvent::Opcode list. */
            int removeMgmtEventCallback(const MgmtEvent::Opcode opc, const MgmtEventCallback &cb);
            /** Returns count of removed MgmtEventCallback from the named MgmtEvent::Opcode list matching the given adapter dev_id . */
            int removeMgmtEventCallback(const int dev_id);
            /** Removes all MgmtEventCallbacks from the to the named MgmtEvent::Opcode list. */
            void clearMgmtEventCallbacks(const MgmtEvent::Opcode opc);
            /** Removes all MgmtEventCallbacks from all MgmtEvent::Opcode lists. */
            void clearAllMgmtEventCallbacks();
    };

} // namespace direct_bt

#endif /* DBT_MANAGER_HPP_ */