-
Notifications
You must be signed in to change notification settings - Fork 120
/
Copy pathAdafruit_BLE.cpp
620 lines (495 loc) · 18.2 KB
/
Adafruit_BLE.cpp
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
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
/**************************************************************************/
/*!
@file Adafruit_BLE.c
@author hathach
@section LICENSE
Software License Agreement (BSD License)
Copyright (c) 2014, Adafruit Industries (adafruit.com)
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holders nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**************************************************************************/
#include "Adafruit_BLE.h"
#include "Adafruit_BLEMIDI.h"
#ifndef min
#define min(a,b) ((a) < (b) ? (a) : (b))
#endif
enum {
EVENT_SYSTEM_CONNECT = 0,
EVENT_SYSTEM_DISCONNECT = 1,
EVENT_SYSTEM_BLE_UART_RX = 8,
// 9 reserved
EVENT_SYSTEM_BLE_MIDI_RX = 10,
// 11 reserved
};
enum {
NVM_USERDATA_SIZE = 256
};
/******************************************************************************/
/*!
@brief Constructor
*/
/******************************************************************************/
Adafruit_BLE::Adafruit_BLE(void)
{
_timeout = BLE_DEFAULT_TIMEOUT;
_reset_started_timestamp = 0;
_disconnect_callback = NULL;
_connect_callback = NULL;
_ble_uart_rx_callback = NULL;
_ble_midi_rx_callback = NULL;
_ble_gatt_rx_callback = NULL;
}
/******************************************************************************/
/*!
@brief Helper to install callback
@param
*/
/******************************************************************************/
void Adafruit_BLE::install_callback(bool enable, int8_t system_id, int8_t gatts_id)
{
uint8_t current_mode = _mode;
// switch mode if necessary to execute command
if ( current_mode == BLUEFRUIT_MODE_DATA ) setMode(BLUEFRUIT_MODE_COMMAND);
print( enable ? F("AT+EVENTENABLE=0x") : F("AT+EVENTDISABLE=0x") );
print( (system_id < 0) ? 0 : bit(system_id), HEX );
if ( gatts_id >= 0 )
{
print( F(",0x") );
println( bit(gatts_id), HEX );
}
println();
waitForOK();
// switch back if necessary
if ( current_mode == BLUEFRUIT_MODE_DATA ) setMode(BLUEFRUIT_MODE_DATA);
}
/******************************************************************************/
/*!
@brief Performs a system reset using AT command
@param blocking blocking until bluefruit is ready, will take 1 second mostly
*/
/******************************************************************************/
bool Adafruit_BLE::reset(boolean blocking)
{
bool isOK;
// println();
for (uint8_t t=0; t < 5; t++) {
isOK = atcommand(F("ATZ"));
if (isOK) break;
}
if (! isOK) {
// ok we're going to get desperate
delay(50);
setMode(BLUEFRUIT_MODE_COMMAND);
delay(50);
for (uint8_t t=0; t < 5; t++) {
isOK = atcommand(F("ATZ"));
if (isOK) break;
}
if (!isOK) return false;
}
_reset_started_timestamp = millis();
// Bluefruit need 1 second to reboot
if (blocking)
{
delay(1000);
}
// flush all left over
flush();
return isOK;
}
/******************************************************************************/
/*!
@brief Performs a factory reset
*/
/******************************************************************************/
bool Adafruit_BLE::factoryReset(boolean blocking)
{
println( F("AT+FACTORYRESET") );
bool isOK = waitForOK();
_reset_started_timestamp = millis();
// Bluefruit need 1 second to reboot
if (blocking)
{
delay(1000);
}
// flush all left over
flush();
return isOK;
}
/******************************************************************************/
/*!
@brief Check if the reset process is completed, should be used if user
reset Bluefruit with non-blocking aka reset(false)
*/
/******************************************************************************/
bool Adafruit_BLE::resetCompleted(void)
{
return millis() > (_reset_started_timestamp + 1000);
}
/******************************************************************************/
/*!
@brief Enable or disable AT Command echo from Bluefruit
@parma[in] enable
true to enable (default), false to disable
*/
/******************************************************************************/
bool Adafruit_BLE::echo(bool enable)
{
return atcommand(F("ATE"), (int32_t) enable);
}
/******************************************************************************/
/*!
@brief Check connection state, returns true is connected!
*/
/******************************************************************************/
bool Adafruit_BLE::isConnected(void)
{
int32_t connected = 0;
atcommandIntReply(F("AT+GAPGETCONN"), &connected);
return connected;
}
/******************************************************************************/
/*!
@brief Disconnect if currently connected
*/
/******************************************************************************/
void Adafruit_BLE::disconnect(void)
{
atcommand( F("AT+GAPDISCONNECT") );
}
/******************************************************************************/
/*!
@brief Print Bluefruit's information retrieved by ATI command
*/
/******************************************************************************/
void Adafruit_BLE::info(void)
{
uint8_t current_mode = _mode;
bool v = _verbose;
_verbose = false;
SerialDebug.println(F("----------------"));
// switch mode if necessary to execute command
if ( current_mode == BLUEFRUIT_MODE_DATA ) setMode(BLUEFRUIT_MODE_COMMAND);
println(F("ATI"));
while ( readline() ) {
if ( !strcmp(buffer, "OK") || !strcmp(buffer, "ERROR") ) break;
SerialDebug.println(buffer);
}
// switch back if necessary
if ( current_mode == BLUEFRUIT_MODE_DATA ) setMode(BLUEFRUIT_MODE_DATA);
SerialDebug.println(F("----------------"));
_verbose = v;
}
/**************************************************************************/
/*!
@brief Checks if firmware is equal or later than specified version
*/
/**************************************************************************/
bool Adafruit_BLE::isVersionAtLeast(const char * versionString)
{
uint8_t current_mode = _mode;
// switch mode if necessary to execute command
if ( current_mode == BLUEFRUIT_MODE_DATA ) setMode(BLUEFRUIT_MODE_COMMAND);
// requesting version number
println(F("ATI=4"));
readline();
bool result = ( strcmp(buffer, versionString) >= 0 );
waitForOK();
// switch back if necessary
if ( current_mode == BLUEFRUIT_MODE_DATA ) setMode(BLUEFRUIT_MODE_DATA);
return result;
}
/******************************************************************************/
/*!
@brief Get (multiple) lines of response data into internal buffer.
@param[in] period_ms
period in milliseconds between each event scanning
@return None
*/
/******************************************************************************/
void Adafruit_BLE::update(uint32_t period_ms)
{
static TimeoutTimer tt;
if ( tt.expired() )
{
tt.set(period_ms);
bool v = _verbose;
_verbose = false;
uint8_t current_mode = _mode;
// switch mode if necessary to execute command
if ( current_mode == BLUEFRUIT_MODE_DATA ) setMode(BLUEFRUIT_MODE_COMMAND);
println( F("AT+EVENTSTATUS") );
readline();
waitForOK();
// parse event status system_event, gatts_event
uint8_t tempbuf[BLE_BUFSIZE+1];
uint32_t system_event, gatts_event;
char * p_comma = NULL;
system_event = strtoul(this->buffer, &p_comma, 16);
gatts_event = strtoul(p_comma+1, NULL, 16);
//--------------------------------------------------------------------+
// System Event
//--------------------------------------------------------------------+
if ( this->_connect_callback && bitRead(system_event, EVENT_SYSTEM_CONNECT ) ) this->_connect_callback();
if ( this->_disconnect_callback && bitRead(system_event, EVENT_SYSTEM_DISCONNECT) ) this->_disconnect_callback();
if ( this->_ble_uart_rx_callback && bitRead(system_event, EVENT_SYSTEM_BLE_UART_RX) )
{
// _verbose = true;
println( F("AT+BLEUARTRX") );
uint16_t len = readline(tempbuf, BLE_BUFSIZE);
waitForOK();
this->_ble_uart_rx_callback( (char*) tempbuf, len);
}
if ( this->_ble_midi_rx_callback && bitRead(system_event, EVENT_SYSTEM_BLE_MIDI_RX) )
{
// _verbose = true;
while(1)
{
// use RAW command version
println( F("AT+BLEMIDIRXRAW") );
// readraw swallow OK/ERROR already
uint16_t len = readraw();
// break if there is no more MIDI event
if ( len == 0 ) break;
// copy to internal buffer for other usage !
memcpy(tempbuf, this->buffer, len);
Adafruit_BLEMIDI::processRxCallback(tempbuf, len, this->_ble_midi_rx_callback);
}
}
//--------------------------------------------------------------------+
// Gatt Event
//--------------------------------------------------------------------+
if ( this->_ble_gatt_rx_callback && gatts_event )
{
// _verbose = true;
for(uint8_t charid=1; charid < 30; charid++)
{
if ( bitRead(gatts_event, charid-1) )
{
print( F("AT+GATTCHARRAW=") ); // use RAW command version
println(charid);
uint16_t len = readraw(); // readraw swallow OK/ERROR already
memcpy(tempbuf, this->buffer, len);
this->_ble_gatt_rx_callback(charid, tempbuf, len);
}
}
}
// switch back if necessary
if ( current_mode == BLUEFRUIT_MODE_DATA ) setMode(BLUEFRUIT_MODE_DATA);
_verbose = v;
}
}
/******************************************************************************/
/*!
@brief Set custom ADV data packet
@param
*/
/******************************************************************************/
bool Adafruit_BLE::setAdvData(uint8_t advdata[], uint8_t size)
{
return this->atcommand(F("AT+GAPSETADVDATA"), advdata, size);
}
/******************************************************************************/
/*!
@brief Save user information to NVM section, current size limit is 256 bytes
@param data buffer holding data
@param size number of bytes
@param offset relative offset in the NVM section
*/
/******************************************************************************/
bool Adafruit_BLE::writeNVM(uint16_t offset, uint8_t const data[], uint16_t size)
{
VERIFY_(offset + size <= NVM_USERDATA_SIZE );
uint16_t type[] = { AT_ARGTYPE_UINT16, AT_ARGTYPE_UINT8, (uint16_t) (AT_ARGTYPE_BYTEARRAY + size) };
uint32_t args[] = { offset, BLE_DATATYPE_BYTEARRAY, (uint32_t) data };
return this->atcommand_full(F("AT+NVMWRITE"), NULL, 3, type, args);
}
/******************************************************************************/
/*!
@brief Save String to NVM section, current size limit is 256 bytes
@param data buffer holding data
@param size number of bytes
@param offset relative offset in the NVM section
*/
/******************************************************************************/
bool Adafruit_BLE::writeNVM(uint16_t offset, char const* str)
{
VERIFY_(offset + strlen(str) <= NVM_USERDATA_SIZE );
uint16_t type[] = { AT_ARGTYPE_UINT16, AT_ARGTYPE_UINT8, AT_ARGTYPE_STRING };
uint32_t args[] = { offset, BLE_DATATYPE_STRING, (uint32_t) str };
return this->atcommand_full(F("AT+NVMWRITE"), NULL, 3, type, args);
}
/******************************************************************************/
/*!
@brief Save an 32-bit number to NVM
@param number Number to be saved
@param offset relative offset in the NVM section
*/
/******************************************************************************/
bool Adafruit_BLE::writeNVM(uint16_t offset, int32_t number)
{
VERIFY_(offset + 4 <= NVM_USERDATA_SIZE );
uint16_t type[] = { AT_ARGTYPE_UINT16, AT_ARGTYPE_UINT8, AT_ARGTYPE_INT32 };
uint32_t args[] = { offset, BLE_DATATYPE_INTEGER, (uint32_t) number };
return this->atcommand_full(F("AT+NVMWRITE"), NULL, 3, type, args);
}
/******************************************************************************/
/*!
@brief Read an number of bytes from NVM at offset to buffer
@param
*/
/******************************************************************************/
bool Adafruit_BLE::readNVM(uint16_t offset, uint8_t data[], uint16_t size)
{
VERIFY_(offset < NVM_USERDATA_SIZE);
uint8_t current_mode = _mode;
// switch mode if necessary to execute command
if ( current_mode == BLUEFRUIT_MODE_DATA ) setMode(BLUEFRUIT_MODE_COMMAND);
// use RAW command version
print( F("AT+NVMREADRAW=") );
print(offset);
print(',');
println(size);
uint16_t len = readraw(); // readraw swallow OK/ERROR already
// Check for an error reading
if ( len != size ) return false;
// skip if NULL is entered
if (data) memcpy(data, this->buffer, min(size, BLE_BUFSIZE));
// switch back if necessary
if ( current_mode == BLUEFRUIT_MODE_DATA ) setMode(BLUEFRUIT_MODE_DATA);
return true;
}
/******************************************************************************/
/*!
@brief Read a string from NVM at offset to buffer
@param
*/
/******************************************************************************/
bool Adafruit_BLE::readNVM(uint16_t offset, char* str, uint16_t size)
{
VERIFY_(offset < NVM_USERDATA_SIZE);
uint16_t type[] = { AT_ARGTYPE_UINT16, AT_ARGTYPE_UINT16, AT_ARGTYPE_UINT8 };
uint32_t args[] = { offset, size, BLE_DATATYPE_STRING};
bool isOK = this->atcommand_full(F("AT+NVMREAD"), NULL, 3, type, args);
// skip if NULL is entered
if ( isOK && str ) strncpy(str, this->buffer, min(size, BLE_BUFSIZE));
return isOK;
}
/******************************************************************************/
/*!
@brief Read an 32-bit number from NVM
@param
*/
/******************************************************************************/
bool Adafruit_BLE::readNVM(uint16_t offset, int32_t* number)
{
return this->readNVM(offset, (uint8_t*)number, 4);
}
/**
*
* @param buffer
* @param size
* @return
*/
int Adafruit_BLE::writeBLEUart(uint8_t const * buffer, int size)
{
uint8_t current_mode = _mode;
// switch mode if necessary to execute command
if ( current_mode == BLUEFRUIT_MODE_COMMAND ) setMode(BLUEFRUIT_MODE_DATA);
size_t n = write(buffer, size);
// switch back if necessary
if ( current_mode == BLUEFRUIT_MODE_COMMAND ) setMode(BLUEFRUIT_MODE_COMMAND);
return n;
}
/**
*
* @param buffer
* @param size
* @return
*/
int Adafruit_BLE::readBLEUart(uint8_t* buffer, int size)
{
uint8_t current_mode = _mode;
// switch mode if necessary to execute command
if ( current_mode == BLUEFRUIT_MODE_COMMAND ) setMode(BLUEFRUIT_MODE_DATA);
size_t n = readBytes(buffer, size);
// switch back if necessary
if ( current_mode == BLUEFRUIT_MODE_COMMAND ) setMode(BLUEFRUIT_MODE_COMMAND);
return n;
}
/******************************************************************************/
/*!
@brief Set handle for connect callback
@param[in] fp function pointer, NULL will discard callback
*/
/******************************************************************************/
void Adafruit_BLE::setConnectCallback( void (*fp) (void) )
{
this->_connect_callback = fp;
install_callback(fp != NULL, EVENT_SYSTEM_CONNECT, -1);
}
/******************************************************************************/
/*!
@brief Set handle for disconnection callback
@param[in] fp function pointer, NULL will discard callback
*/
/******************************************************************************/
void Adafruit_BLE::setDisconnectCallback( void (*fp) (void) )
{
this->_disconnect_callback = fp;
install_callback(fp != NULL, EVENT_SYSTEM_DISCONNECT, -1);
}
/******************************************************************************/
/*!
@brief Set handle for BLE Uart Rx callback
@param[in] fp function pointer, NULL will discard callback
*/
/******************************************************************************/
void Adafruit_BLE::setBleUartRxCallback( void (*fp) (char data[], uint16_t len) )
{
this->_ble_uart_rx_callback = fp;
install_callback(fp != NULL, EVENT_SYSTEM_BLE_UART_RX, -1);
}
/******************************************************************************/
/*!
@brief Set handle for BLE MIDI Rx callback
@param[in] fp function pointer, NULL will discard callback
*/
/******************************************************************************/
void Adafruit_BLE::setBleMidiRxCallback( midiRxCallback_t fp )
{
this->_ble_midi_rx_callback = fp;
install_callback(fp != NULL, EVENT_SYSTEM_BLE_MIDI_RX, -1);
}
/******************************************************************************/
/*!
@brief Set handle for BLE Gatt Rx callback
@param[in] fp function pointer, NULL will discard callback
*/
/******************************************************************************/
void Adafruit_BLE::setBleGattRxCallback(int32_t chars_idx, void (*fp) (int32_t, uint8_t[], uint16_t) )
{
if ( chars_idx == 0) return;
this->_ble_gatt_rx_callback = fp;
install_callback(fp != NULL, -1, chars_idx-1);
}