1 #include "adafruit_ble.h"
5 #include <util/delay.h>
6 #include <util/atomic.h>
8 #include "pincontrol.h"
10 #include "action_util.h"
11 #include "ringbuffer.hpp"
15 // These are the pin assignments for the 32u4 boards.
16 // You may define them to something else in your config.h
17 // if yours is wired up differently.
18 #ifndef AdafruitBleResetPin
19 # define AdafruitBleResetPin D4
22 #ifndef AdafruitBleCSPin
23 # define AdafruitBleCSPin B4
26 #ifndef AdafruitBleIRQPin
27 # define AdafruitBleIRQPin E6
30 #define SAMPLE_BATTERY
31 #define ConnectionUpdateInterval 1000 /* milliseconds */
34 #ifndef BATTERY_LEVEL_PIN
35 # define BATTERY_LEVEL_PIN 7
44 #define ProbedEvents 1
49 uint16_t last_battery_update
;
52 uint16_t last_connection_update
;
55 // Commands are encoded using SDEP and sent via SPI
56 // https://github.com/adafruit/Adafruit_BluefruitLE_nRF51/blob/master/SDEP.md
58 #define SdepMaxPayload 16
63 struct __attribute__((packed
)) {
67 uint8_t payload
[SdepMaxPayload
];
68 } __attribute__((packed
));
70 // The recv latency is relatively high, so when we're hammering keys quickly,
71 // we want to avoid waiting for the responses in the matrix loop. We maintain
72 // a short queue for that. Since there is quite a lot of space overhead for
73 // the AT command representation wrapped up in SDEP, we queue the minimal
77 QTKeyReport
, // 1-byte modifier + 6-byte key report
78 QTConsumer
, // 16-bit key code
80 QTMouseMove
, // 4-byte mouse report
85 enum queue_type queue_type
;
87 union __attribute__((packed
)) {
88 struct __attribute__((packed
)) {
94 struct __attribute__((packed
)) {
95 int8_t x
, y
, scroll
, pan
;
101 // Items that we wish to send
102 static RingBuffer
<queue_item
, 40> send_buf
;
103 // Pending response; while pending, we can't send any more requests.
104 // This records the time at which we sent the command for which we
105 // are expecting a response.
106 static RingBuffer
<uint16_t, 2> resp_buf
;
108 static bool process_queue_item(struct queue_item
*item
, uint16_t timeout
);
115 SdepSlaveNotReady
= 0xfe, // Try again later
116 SdepSlaveOverflow
= 0xff, // You read more data than is available
120 BleInitialize
= 0xbeef,
121 BleAtWrapper
= 0x0a00,
126 enum ble_system_event_bits
{
127 BleSystemConnected
= 0,
128 BleSystemDisconnected
= 1,
130 BleSystemMidiRx
= 10,
133 // The SDEP.md file says 2MHz but the web page and the sample driver
135 #define SpiBusSpeed 4000000
137 #define SdepTimeout 150 /* milliseconds */
138 #define SdepShortTimeout 10 /* milliseconds */
139 #define SdepBackOff 25 /* microseconds */
140 #define BatteryUpdateInterval 10000 /* milliseconds */
142 static bool at_command(const char *cmd
, char *resp
, uint16_t resplen
, bool verbose
, uint16_t timeout
= SdepTimeout
);
143 static bool at_command_P(const char *cmd
, char *resp
, uint16_t resplen
, bool verbose
= false);
145 struct SPI_Settings
{
149 static struct SPI_Settings spi
;
151 // Initialize 4Mhz MSBFIRST MODE0
152 void SPI_init(struct SPI_Settings
*spi
) {
153 spi
->spcr
= _BV(SPE
) | _BV(MSTR
);
154 spi
->spsr
= _BV(SPI2X
);
156 static_assert(SpiBusSpeed
== F_CPU
/ 2, "hard coded at 4Mhz");
158 ATOMIC_BLOCK(ATOMIC_RESTORESTATE
) {
159 // Ensure that SS is OUTPUT High
160 digitalWrite(B0
, PinLevelHigh
);
161 pinMode(B0
, PinDirectionOutput
);
165 pinMode(B1
/* SCK */, PinDirectionOutput
);
166 pinMode(B2
/* MOSI */, PinDirectionOutput
);
170 static inline void SPI_begin(struct SPI_Settings
*spi
) {
175 static inline uint8_t SPI_TransferByte(uint8_t data
) {
178 while (!(SPSR
& _BV(SPIF
))) {
184 static inline void spi_send_bytes(const uint8_t *buf
, uint8_t len
) {
185 if (len
== 0) return;
186 const uint8_t *end
= buf
+ len
;
189 while (!(SPSR
& _BV(SPIF
))) {
196 static inline uint16_t spi_read_byte(void) { return SPI_TransferByte(0x00 /* dummy */); }
198 static inline void spi_recv_bytes(uint8_t *buf
, uint8_t len
) {
199 const uint8_t *end
= buf
+ len
;
200 if (len
== 0) return;
202 SPDR
= 0; // write a dummy to initiate read
203 while (!(SPSR
& _BV(SPIF
))) {
212 static void dump_pkt(const struct sdep_msg
*msg
) {
214 print_hex8(msg
->type
);
216 print_hex8(msg
->cmd_high
);
217 print_hex8(msg
->cmd_low
);
219 print_hex8(msg
->len
);
221 print_hex8(msg
->more
);
226 // Send a single SDEP packet
227 static bool sdep_send_pkt(const struct sdep_msg
*msg
, uint16_t timeout
) {
230 digitalWrite(AdafruitBleCSPin
, PinLevelLow
);
231 uint16_t timerStart
= timer_read();
232 bool success
= false;
236 ready
= SPI_TransferByte(msg
->type
) != SdepSlaveNotReady
;
241 // Release it and let it initialize
242 digitalWrite(AdafruitBleCSPin
, PinLevelHigh
);
243 _delay_us(SdepBackOff
);
244 digitalWrite(AdafruitBleCSPin
, PinLevelLow
);
245 } while (timer_elapsed(timerStart
) < timeout
);
248 // Slave is ready; send the rest of the packet
249 spi_send_bytes(&msg
->cmd_low
, sizeof(*msg
) - (1 + sizeof(msg
->payload
)) + msg
->len
);
253 digitalWrite(AdafruitBleCSPin
, PinLevelHigh
);
258 static inline void sdep_build_pkt(struct sdep_msg
*msg
, uint16_t command
, const uint8_t *payload
, uint8_t len
, bool moredata
) {
259 msg
->type
= SdepCommand
;
260 msg
->cmd_low
= command
& 0xff;
261 msg
->cmd_high
= command
>> 8;
263 msg
->more
= (moredata
&& len
== SdepMaxPayload
) ? 1 : 0;
265 static_assert(sizeof(*msg
) == 20, "msg is correctly packed");
267 memcpy(msg
->payload
, payload
, len
);
270 // Read a single SDEP packet
271 static bool sdep_recv_pkt(struct sdep_msg
*msg
, uint16_t timeout
) {
272 bool success
= false;
273 uint16_t timerStart
= timer_read();
277 ready
= digitalRead(AdafruitBleIRQPin
);
282 } while (timer_elapsed(timerStart
) < timeout
);
287 digitalWrite(AdafruitBleCSPin
, PinLevelLow
);
290 // Read the command type, waiting for the data to be ready
291 msg
->type
= spi_read_byte();
292 if (msg
->type
== SdepSlaveNotReady
|| msg
->type
== SdepSlaveOverflow
) {
293 // Release it and let it initialize
294 digitalWrite(AdafruitBleCSPin
, PinLevelHigh
);
295 _delay_us(SdepBackOff
);
296 digitalWrite(AdafruitBleCSPin
, PinLevelLow
);
300 // Read the rest of the header
301 spi_recv_bytes(&msg
->cmd_low
, sizeof(*msg
) - (1 + sizeof(msg
->payload
)));
303 // and get the payload if there is any
304 if (msg
->len
<= SdepMaxPayload
) {
305 spi_recv_bytes(msg
->payload
, msg
->len
);
309 } while (timer_elapsed(timerStart
) < timeout
);
311 digitalWrite(AdafruitBleCSPin
, PinLevelHigh
);
316 static void resp_buf_read_one(bool greedy
) {
318 if (!resp_buf
.peek(last_send
)) {
322 if (digitalRead(AdafruitBleIRQPin
)) {
326 if (sdep_recv_pkt(&msg
, SdepTimeout
)) {
328 // We got it; consume this entry
329 resp_buf
.get(last_send
);
330 dprintf("recv latency %dms\n", TIMER_DIFF_16(timer_read(), last_send
));
333 if (greedy
&& resp_buf
.peek(last_send
) && digitalRead(AdafruitBleIRQPin
)) {
338 } else if (timer_elapsed(last_send
) > SdepTimeout
* 2) {
339 dprintf("waiting_for_result: timeout, resp_buf size %d\n", (int)resp_buf
.size());
341 // Timed out: consume this entry
342 resp_buf
.get(last_send
);
346 static void send_buf_send_one(uint16_t timeout
= SdepTimeout
) {
347 struct queue_item item
;
349 // Don't send anything more until we get an ACK
350 if (!resp_buf
.empty()) {
354 if (!send_buf
.peek(item
)) {
357 if (process_queue_item(&item
, timeout
)) {
360 dprintf("send_buf_send_one: have %d remaining\n", (int)send_buf
.size());
362 dprint("failed to send, will retry\n");
363 _delay_ms(SdepTimeout
);
364 resp_buf_read_one(true);
368 static void resp_buf_wait(const char *cmd
) {
369 bool didPrint
= false;
370 while (!resp_buf
.empty()) {
372 dprintf("wait on buf for %s\n", cmd
);
375 resp_buf_read_one(true);
379 static bool ble_init(void) {
380 state
.initialized
= false;
381 state
.configured
= false;
382 state
.is_connected
= false;
384 pinMode(AdafruitBleIRQPin
, PinDirectionInput
);
385 pinMode(AdafruitBleCSPin
, PinDirectionOutput
);
386 digitalWrite(AdafruitBleCSPin
, PinLevelHigh
);
390 // Perform a hardware reset
391 pinMode(AdafruitBleResetPin
, PinDirectionOutput
);
392 digitalWrite(AdafruitBleResetPin
, PinLevelHigh
);
393 digitalWrite(AdafruitBleResetPin
, PinLevelLow
);
395 digitalWrite(AdafruitBleResetPin
, PinLevelHigh
);
397 _delay_ms(1000); // Give it a second to initialize
399 state
.initialized
= true;
400 return state
.initialized
;
403 static inline uint8_t min(uint8_t a
, uint8_t b
) { return a
< b
? a
: b
; }
405 static bool read_response(char *resp
, uint16_t resplen
, bool verbose
) {
407 char *end
= dest
+ resplen
;
412 if (!sdep_recv_pkt(&msg
, 2 * SdepTimeout
)) {
413 dprint("sdep_recv_pkt failed\n");
417 if (msg
.type
!= SdepResponse
) {
422 uint8_t len
= min(msg
.len
, end
- dest
);
424 memcpy(dest
, msg
.payload
, len
);
429 // No more data is expected!
434 // Ensure the response is NUL terminated
437 // "Parse" the result text; we want to snip off the trailing OK or ERROR line
438 // Rewind past the possible trailing CRLF so that we can strip it
440 while (dest
> resp
&& (dest
[0] == '\n' || dest
[0] == '\r')) {
445 // Look back for start of preceeding line
446 char *last_line
= strrchr(resp
, '\n');
453 bool success
= false;
454 static const char kOK
[] PROGMEM
= "OK";
456 success
= !strcmp_P(last_line
, kOK
);
458 if (verbose
|| !success
) {
459 dprintf("result: %s\n", resp
);
464 static bool at_command(const char *cmd
, char *resp
, uint16_t resplen
, bool verbose
, uint16_t timeout
) {
465 const char * end
= cmd
+ strlen(cmd
);
469 dprintf("ble send: %s\n", cmd
);
473 // They want to decode the response, so we need to flush and wait
474 // for all pending I/O to finish before we start this one, so
475 // that we don't confuse the results
480 // Fragment the command into a series of SDEP packets
481 while (end
- cmd
> SdepMaxPayload
) {
482 sdep_build_pkt(&msg
, BleAtWrapper
, (uint8_t *)cmd
, SdepMaxPayload
, true);
483 if (!sdep_send_pkt(&msg
, timeout
)) {
486 cmd
+= SdepMaxPayload
;
489 sdep_build_pkt(&msg
, BleAtWrapper
, (uint8_t *)cmd
, end
- cmd
, false);
490 if (!sdep_send_pkt(&msg
, timeout
)) {
495 auto now
= timer_read();
496 while (!resp_buf
.enqueue(now
)) {
497 resp_buf_read_one(false);
499 auto later
= timer_read();
500 if (TIMER_DIFF_16(later
, now
) > 0) {
501 dprintf("waited %dms for resp_buf\n", TIMER_DIFF_16(later
, now
));
506 return read_response(resp
, resplen
, verbose
);
509 bool at_command_P(const char *cmd
, char *resp
, uint16_t resplen
, bool verbose
) {
510 auto cmdbuf
= (char *)alloca(strlen_P(cmd
) + 1);
511 strcpy_P(cmdbuf
, cmd
);
512 return at_command(cmdbuf
, resp
, resplen
, verbose
);
515 bool adafruit_ble_is_connected(void) { return state
.is_connected
; }
517 bool adafruit_ble_enable_keyboard(void) {
520 if (!state
.initialized
&& !ble_init()) {
524 state
.configured
= false;
526 // Disable command echo
527 static const char kEcho
[] PROGMEM
= "ATE=0";
528 // Make the advertised name match the keyboard
529 static const char kGapDevName
[] PROGMEM
= "AT+GAPDEVNAME=" STR(PRODUCT
);
530 // Turn on keyboard support
531 static const char kHidEnOn
[] PROGMEM
= "AT+BLEHIDEN=1";
533 // Adjust intervals to improve latency. This causes the "central"
534 // system (computer/tablet) to poll us every 10-30 ms. We can't
535 // set a smaller value than 10ms, and 30ms seems to be the natural
536 // processing time on my macbook. Keeping it constrained to that
537 // feels reasonable to type to.
538 static const char kGapIntervals
[] PROGMEM
= "AT+GAPINTERVALS=10,30,,";
540 // Reset the device so that it picks up the above changes
541 static const char kATZ
[] PROGMEM
= "ATZ";
543 // Turn down the power level a bit
544 static const char kPower
[] PROGMEM
= "AT+BLEPOWERLEVEL=-12";
545 static PGM_P
const configure_commands
[] PROGMEM
= {
546 kEcho
, kGapIntervals
, kGapDevName
, kHidEnOn
, kPower
, kATZ
,
550 for (i
= 0; i
< sizeof(configure_commands
) / sizeof(configure_commands
[0]); ++i
) {
552 memcpy_P(&cmd
, configure_commands
+ i
, sizeof(cmd
));
554 if (!at_command_P(cmd
, resbuf
, sizeof(resbuf
))) {
555 dprintf("failed BLE command: %S: %s\n", cmd
, resbuf
);
560 state
.configured
= true;
562 // Check connection status in a little while; allow the ATZ time
564 state
.last_connection_update
= timer_read();
566 return state
.configured
;
569 static void set_connected(bool connected
) {
570 if (connected
!= state
.is_connected
) {
572 print("****** BLE CONNECT!!!!\n");
574 print("****** BLE DISCONNECT!!!!\n");
576 state
.is_connected
= connected
;
578 // TODO: if modifiers are down on the USB interface and
579 // we cut over to BLE or vice versa, they will remain stuck.
580 // This feels like a good point to do something like clearing
581 // the keyboard and/or generating a fake all keys up message.
582 // However, I've noticed that it takes a couple of seconds
583 // for macOS to to start recognizing key presses after BLE
584 // is in the connected state, so I worry that doing that
585 // here may not be good enough.
589 void adafruit_ble_task(void) {
592 if (!state
.configured
&& !adafruit_ble_enable_keyboard()) {
595 resp_buf_read_one(true);
596 send_buf_send_one(SdepShortTimeout
);
598 if (resp_buf
.empty() && (state
.event_flags
& UsingEvents
) && digitalRead(AdafruitBleIRQPin
)) {
599 // Must be an event update
600 if (at_command_P(PSTR("AT+EVENTSTATUS"), resbuf
, sizeof(resbuf
))) {
601 uint32_t mask
= strtoul(resbuf
, NULL
, 16);
603 if (mask
& BleSystemConnected
) {
605 } else if (mask
& BleSystemDisconnected
) {
606 set_connected(false);
611 if (timer_elapsed(state
.last_connection_update
) > ConnectionUpdateInterval
) {
612 bool shouldPoll
= true;
613 if (!(state
.event_flags
& ProbedEvents
)) {
614 // Request notifications about connection status changes.
615 // This only works in SPIFRIEND firmware > 0.6.7, which is why
616 // we check for this conditionally here.
617 // Note that at the time of writing, HID reports only work correctly
618 // with Apple products on firmware version 0.6.7!
619 // https://forums.adafruit.com/viewtopic.php?f=8&t=104052
620 if (at_command_P(PSTR("AT+EVENTENABLE=0x1"), resbuf
, sizeof(resbuf
))) {
621 at_command_P(PSTR("AT+EVENTENABLE=0x2"), resbuf
, sizeof(resbuf
));
622 state
.event_flags
|= UsingEvents
;
624 state
.event_flags
|= ProbedEvents
;
626 // leave shouldPoll == true so that we check at least once
627 // before relying solely on events
632 static const char kGetConn
[] PROGMEM
= "AT+GAPGETCONN";
633 state
.last_connection_update
= timer_read();
635 if (at_command_P(kGetConn
, resbuf
, sizeof(resbuf
))) {
636 set_connected(atoi(resbuf
));
640 #ifdef SAMPLE_BATTERY
641 if (timer_elapsed(state
.last_battery_update
) > BatteryUpdateInterval
&& resp_buf
.empty()) {
642 state
.last_battery_update
= timer_read();
644 state
.vbat
= analogRead(BATTERY_LEVEL_PIN
);
649 static bool process_queue_item(struct queue_item
*item
, uint16_t timeout
) {
653 // Arrange to re-check connection after keys have settled
654 state
.last_connection_update
= timer_read();
657 if (TIMER_DIFF_16(state
.last_connection_update
, item
->added
) > 0) {
658 dprintf("send latency %dms\n", TIMER_DIFF_16(state
.last_connection_update
, item
->added
));
662 switch (item
->queue_type
) {
664 strcpy_P(fmtbuf
, PSTR("AT+BLEKEYBOARDCODE=%02x-00-%02x-%02x-%02x-%02x-%02x-%02x"));
665 snprintf(cmdbuf
, sizeof(cmdbuf
), fmtbuf
, item
->key
.modifier
, item
->key
.keys
[0], item
->key
.keys
[1], item
->key
.keys
[2], item
->key
.keys
[3], item
->key
.keys
[4], item
->key
.keys
[5]);
666 return at_command(cmdbuf
, NULL
, 0, true, timeout
);
669 strcpy_P(fmtbuf
, PSTR("AT+BLEHIDCONTROLKEY=0x%04x"));
670 snprintf(cmdbuf
, sizeof(cmdbuf
), fmtbuf
, item
->consumer
);
671 return at_command(cmdbuf
, NULL
, 0, true, timeout
);
675 strcpy_P(fmtbuf
, PSTR("AT+BLEHIDMOUSEMOVE=%d,%d,%d,%d"));
676 snprintf(cmdbuf
, sizeof(cmdbuf
), fmtbuf
, item
->mousemove
.x
, item
->mousemove
.y
, item
->mousemove
.scroll
, item
->mousemove
.pan
);
677 if (!at_command(cmdbuf
, NULL
, 0, true, timeout
)) {
680 strcpy_P(cmdbuf
, PSTR("AT+BLEHIDMOUSEBUTTON="));
681 if (item
->mousemove
.buttons
& MOUSE_BTN1
) {
684 if (item
->mousemove
.buttons
& MOUSE_BTN2
) {
687 if (item
->mousemove
.buttons
& MOUSE_BTN3
) {
690 if (item
->mousemove
.buttons
== 0) {
693 return at_command(cmdbuf
, NULL
, 0, true, timeout
);
700 bool adafruit_ble_send_keys(uint8_t hid_modifier_mask
, uint8_t *keys
, uint8_t nkeys
) {
701 struct queue_item item
;
702 bool didWait
= false;
704 item
.queue_type
= QTKeyReport
;
705 item
.key
.modifier
= hid_modifier_mask
;
706 item
.added
= timer_read();
709 item
.key
.keys
[0] = keys
[0];
710 item
.key
.keys
[1] = nkeys
>= 1 ? keys
[1] : 0;
711 item
.key
.keys
[2] = nkeys
>= 2 ? keys
[2] : 0;
712 item
.key
.keys
[3] = nkeys
>= 3 ? keys
[3] : 0;
713 item
.key
.keys
[4] = nkeys
>= 4 ? keys
[4] : 0;
714 item
.key
.keys
[5] = nkeys
>= 5 ? keys
[5] : 0;
716 if (!send_buf
.enqueue(item
)) {
718 dprint("wait for buf space\n");
736 bool adafruit_ble_send_consumer_key(uint16_t keycode
, int hold_duration
) {
737 struct queue_item item
;
739 item
.queue_type
= QTConsumer
;
740 item
.consumer
= keycode
;
742 while (!send_buf
.enqueue(item
)) {
749 bool adafruit_ble_send_mouse_move(int8_t x
, int8_t y
, int8_t scroll
, int8_t pan
, uint8_t buttons
) {
750 struct queue_item item
;
752 item
.queue_type
= QTMouseMove
;
753 item
.mousemove
.x
= x
;
754 item
.mousemove
.y
= y
;
755 item
.mousemove
.scroll
= scroll
;
756 item
.mousemove
.pan
= pan
;
757 item
.mousemove
.buttons
= buttons
;
759 while (!send_buf
.enqueue(item
)) {
766 uint32_t adafruit_ble_read_battery_voltage(void) { return state
.vbat
; }
768 bool adafruit_ble_set_mode_leds(bool on
) {
769 if (!state
.configured
) {
773 // The "mode" led is the red blinky one
774 at_command_P(on
? PSTR("AT+HWMODELED=1") : PSTR("AT+HWMODELED=0"), NULL
, 0);
776 // Pin 19 is the blue "connected" LED; turn that off too.
777 // When turning LEDs back on, don't turn that LED on if we're
778 // not connected, as that would be confusing.
779 at_command_P(on
&& state
.is_connected
? PSTR("AT+HWGPIO=19,1") : PSTR("AT+HWGPIO=19,0"), NULL
, 0);
783 // https://learn.adafruit.com/adafruit-feather-32u4-bluefruit-le/ble-generic#at-plus-blepowerlevel
784 bool adafruit_ble_set_power_level(int8_t level
) {
786 if (!state
.configured
) {
789 snprintf(cmd
, sizeof(cmd
), "AT+BLEPOWERLEVEL=%d", level
);
790 return at_command(cmd
, NULL
, 0, false);