-
-
Notifications
You must be signed in to change notification settings - Fork 157
/
NimBLE_Client.ino
307 lines (261 loc) · 11.7 KB
/
NimBLE_Client.ino
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
/** NimBLE_Client Demo:
*
* Demonstrates many of the available features of the NimBLE client library.
*
* Created: on March 24 2020
* Author: H2zero
*/
#include <Arduino.h>
#include <NimBLEDevice.h>
static const NimBLEAdvertisedDevice* advDevice;
static bool doConnect = false;
static uint32_t scanTime = 5000; /** scan time in milliseconds, 0 = scan forever */
/** None of these are required as they will be handled by the library with defaults. **
** Remove as you see fit for your needs */
class ClientCallbacks : public NimBLEClientCallbacks {
void onConnect(NimBLEClient* pClient) override { Serial.printf("Connected\n"); }
void onDisconnect(NimBLEClient* pClient, int reason) override {
Serial.printf("%s Disconnected, reason = %d - Starting scan\n", pClient->getPeerAddress().toString().c_str(), reason);
NimBLEDevice::getScan()->start(scanTime, false, true);
}
/********************* Security handled here *********************/
void onPassKeyEntry(NimBLEConnInfo& connInfo) override {
Serial.printf("Server Passkey Entry\n");
/**
* This should prompt the user to enter the passkey displayed
* on the peer device.
*/
NimBLEDevice::injectPassKey(connInfo, 123456);
}
void onConfirmPasskey(NimBLEConnInfo& connInfo, uint32_t pass_key) override {
Serial.printf("The passkey YES/NO number: %" PRIu32 "\n", pass_key);
/** Inject false if passkeys don't match. */
NimBLEDevice::injectConfirmPasskey(connInfo, true);
}
/** Pairing process complete, we can check the results in connInfo */
void onAuthenticationComplete(NimBLEConnInfo& connInfo) override {
if (!connInfo.isEncrypted()) {
Serial.printf("Encrypt connection failed - disconnecting\n");
/** Find the client with the connection handle provided in connInfo */
NimBLEDevice::getClientByHandle(connInfo.getConnHandle())->disconnect();
return;
}
}
} clientCB;
/** Define a class to handle the callbacks when scan events are received */
class scanCallbacks : public NimBLEScanCallbacks {
void onResult(const NimBLEAdvertisedDevice* advertisedDevice) override {
Serial.printf("Advertised Device found: %s\n", advertisedDevice->toString().c_str());
if (advertisedDevice->isAdvertisingService(NimBLEUUID("DEAD"))) {
Serial.printf("Found Our Service\n");
/** stop scan before connecting */
NimBLEDevice::getScan()->stop();
/** Save the device reference in a global for the client to use*/
advDevice = advertisedDevice;
/** Ready to connect now */
doConnect = true;
}
}
/** Callback to process the results of the completed scan or restart it */
void onScanEnd(const NimBLEScanResults& results, int reason) override {
Serial.printf("Scan Ended, reason: %d, device count: %d; Restarting scan\n", reason, results.getCount());
NimBLEDevice::getScan()->start(scanTime, false, true);
}
} scanCB;
/** Notification / Indication receiving handler callback */
void notifyCB(NimBLERemoteCharacteristic* pRemoteCharacteristic, uint8_t* pData, size_t length, bool isNotify) {
std::string str = (isNotify == true) ? "Notification" : "Indication";
str += " from ";
str += pRemoteCharacteristic->getClient()->getPeerAddress().toString();
str += ": Service = " + pRemoteCharacteristic->getRemoteService()->getUUID().toString();
str += ", Characteristic = " + pRemoteCharacteristic->getUUID().toString();
str += ", Value = " + std::string((char*)pData, length);
Serial.printf("%s\n", str.c_str());
}
/** Handles the provisioning of clients and connects / interfaces with the server */
bool connectToServer() {
NimBLEClient* pClient = nullptr;
/** Check if we have a client we should reuse first **/
if (NimBLEDevice::getCreatedClientCount()) {
/**
* Special case when we already know this device, we send false as the
* second argument in connect() to prevent refreshing the service database.
* This saves considerable time and power.
*/
pClient = NimBLEDevice::getClientByPeerAddress(advDevice->getAddress());
if (pClient) {
if (!pClient->connect(advDevice, false)) {
Serial.printf("Reconnect failed\n");
return false;
}
Serial.printf("Reconnected client\n");
} else {
/**
* We don't already have a client that knows this device,
* check for a client that is disconnected that we can use.
*/
pClient = NimBLEDevice::getDisconnectedClient();
}
}
/** No client to reuse? Create a new one. */
if (!pClient) {
if (NimBLEDevice::getCreatedClientCount() >= NIMBLE_MAX_CONNECTIONS) {
Serial.printf("Max clients reached - no more connections available\n");
return false;
}
pClient = NimBLEDevice::createClient();
Serial.printf("New client created\n");
pClient->setClientCallbacks(&clientCB, false);
/**
* Set initial connection parameters:
* These settings are safe for 3 clients to connect reliably, can go faster if you have less
* connections. Timeout should be a multiple of the interval, minimum is 100ms.
* Min interval: 12 * 1.25ms = 15, Max interval: 12 * 1.25ms = 15, 0 latency, 150 * 10ms = 1500ms timeout
*/
pClient->setConnectionParams(12, 12, 0, 150);
/** Set how long we are willing to wait for the connection to complete (milliseconds), default is 30000. */
pClient->setConnectTimeout(5 * 1000);
if (!pClient->connect(advDevice)) {
/** Created a client but failed to connect, don't need to keep it as it has no data */
NimBLEDevice::deleteClient(pClient);
Serial.printf("Failed to connect, deleted client\n");
return false;
}
}
if (!pClient->isConnected()) {
if (!pClient->connect(advDevice)) {
Serial.printf("Failed to connect\n");
return false;
}
}
Serial.printf("Connected to: %s RSSI: %d\n", pClient->getPeerAddress().toString().c_str(), pClient->getRssi());
/** Now we can read/write/subscribe the characteristics of the services we are interested in */
NimBLERemoteService* pSvc = nullptr;
NimBLERemoteCharacteristic* pChr = nullptr;
NimBLERemoteDescriptor* pDsc = nullptr;
pSvc = pClient->getService("DEAD");
if (pSvc) {
pChr = pSvc->getCharacteristic("BEEF");
}
if (pChr) {
if (pChr->canRead()) {
Serial.printf("%s Value: %s\n", pChr->getUUID().toString().c_str(), pChr->readValue().c_str());
}
if (pChr->canWrite()) {
if (pChr->writeValue("Tasty")) {
Serial.printf("Wrote new value to: %s\n", pChr->getUUID().toString().c_str());
} else {
pClient->disconnect();
return false;
}
if (pChr->canRead()) {
Serial.printf("The value of: %s is now: %s\n", pChr->getUUID().toString().c_str(), pChr->readValue().c_str());
}
}
if (pChr->canNotify()) {
if (!pChr->subscribe(true, notifyCB)) {
pClient->disconnect();
return false;
}
} else if (pChr->canIndicate()) {
/** Send false as first argument to subscribe to indications instead of notifications */
if (!pChr->subscribe(false, notifyCB)) {
pClient->disconnect();
return false;
}
}
} else {
Serial.printf("DEAD service not found.\n");
}
pSvc = pClient->getService("BAAD");
if (pSvc) {
pChr = pSvc->getCharacteristic("F00D");
if (pChr) {
if (pChr->canRead()) {
Serial.printf("%s Value: %s\n", pChr->getUUID().toString().c_str(), pChr->readValue().c_str());
}
pDsc = pChr->getDescriptor(NimBLEUUID("C01D"));
if (pDsc) {
Serial.printf("Descriptor: %s Value: %s\n", pDsc->getUUID().toString().c_str(), pDsc->readValue().c_str());
}
if (pChr->canWrite()) {
if (pChr->writeValue("No tip!")) {
Serial.printf("Wrote new value to: %s\n", pChr->getUUID().toString().c_str());
} else {
pClient->disconnect();
return false;
}
if (pChr->canRead()) {
Serial.printf("The value of: %s is now: %s\n", pChr->getUUID().toString().c_str(), pChr->readValue().c_str());
}
}
if (pChr->canNotify()) {
if (!pChr->subscribe(true, notifyCB)) {
pClient->disconnect();
return false;
}
} else if (pChr->canIndicate()) {
/** Send false as first argument to subscribe to indications instead of notifications */
if (!pChr->subscribe(false, notifyCB)) {
pClient->disconnect();
return false;
}
}
}
} else {
Serial.printf("BAAD service not found.\n");
}
Serial.printf("Done with this device!\n");
return true;
}
void setup() {
Serial.begin(115200);
Serial.printf("Starting NimBLE Client\n");
/** Initialize NimBLE and set the device name */
NimBLEDevice::init("NimBLE-Client");
/**
* Set the IO capabilities of the device, each option will trigger a different pairing method.
* BLE_HS_IO_KEYBOARD_ONLY - Passkey pairing
* BLE_HS_IO_DISPLAY_YESNO - Numeric comparison pairing
* BLE_HS_IO_NO_INPUT_OUTPUT - DEFAULT setting - just works pairing
*/
// NimBLEDevice::setSecurityIOCap(BLE_HS_IO_KEYBOARD_ONLY); // use passkey
// NimBLEDevice::setSecurityIOCap(BLE_HS_IO_DISPLAY_YESNO); //use numeric comparison
/**
* 2 different ways to set security - both calls achieve the same result.
* no bonding, no man in the middle protection, BLE secure connections.
* These are the default values, only shown here for demonstration.
*/
// NimBLEDevice::setSecurityAuth(false, false, true);
NimBLEDevice::setSecurityAuth(/*BLE_SM_PAIR_AUTHREQ_BOND | BLE_SM_PAIR_AUTHREQ_MITM |*/ BLE_SM_PAIR_AUTHREQ_SC);
/** Optional: set the transmit power */
NimBLEDevice::setPower(3); // 9dbm
NimBLEScan* pScan = NimBLEDevice::getScan();
/** Set the callbacks to call when scan events occur, no duplicates */
pScan->setScanCallbacks(&scanCB, false);
/** Set scan interval (how often) and window (how long) in milliseconds */
pScan->setInterval(100);
pScan->setWindow(100);
/**
* Active scan will gather scan response data from advertisers
* but will use more energy from both devices
*/
pScan->setActiveScan(true);
/** Start scanning for advertisers */
pScan->start(scanTime);
Serial.printf("Scanning for peripherals\n");
}
void loop() {
/** Loop here until we find a device we want to connect to */
delay(10);
if (doConnect) {
doConnect = false;
/** Found a device we want to connect to, do it now */
if (connectToServer()) {
Serial.printf("Success! we should now be getting notifications, scanning for more!\n");
} else {
Serial.printf("Failed to connect, starting scan\n");
}
NimBLEDevice::getScan()->start(scanTime, false, true);
}
}