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"
14 // These are the pin assignments for the 32u4 boards.
15 // You may define them to something else in your config.h
16 // if yours is wired up differently.
17 #ifndef AdafruitBleResetPin
18 #define AdafruitBleResetPin D4
21 #ifndef AdafruitBleCSPin
22 #define AdafruitBleCSPin B4
25 #ifndef AdafruitBleIRQPin
26 #define AdafruitBleIRQPin E6
30 #define SAMPLE_BATTERY
31 #define ConnectionUpdateInterval 1000 /* milliseconds */
38 #define ProbedEvents 1
43 uint16_t last_battery_update
;
46 uint16_t last_connection_update
;
49 // Commands are encoded using SDEP and sent via SPI
50 // https://github.com/adafruit/Adafruit_BluefruitLE_nRF51/blob/master/SDEP.md
52 #define SdepMaxPayload 16
57 struct __attribute__((packed
)) {
61 uint8_t payload
[SdepMaxPayload
];
62 } __attribute__((packed
));
64 // The recv latency is relatively high, so when we're hammering keys quickly,
65 // we want to avoid waiting for the responses in the matrix loop. We maintain
66 // a short queue for that. Since there is quite a lot of space overhead for
67 // the AT command representation wrapped up in SDEP, we queue the minimal
71 QTKeyReport
, // 1-byte modifier + 6-byte key report
72 QTConsumer
, // 16-bit key code
74 QTMouseMove
, // 4-byte mouse report
79 enum queue_type queue_type
;
81 union __attribute__((packed
)) {
82 struct __attribute__((packed
)) {
88 struct __attribute__((packed
)) {
89 int8_t x
, y
, scroll
, pan
;
94 // Items that we wish to send
95 static RingBuffer
<queue_item
, 40> send_buf
;
96 // Pending response; while pending, we can't send any more requests.
97 // This records the time at which we sent the command for which we
98 // are expecting a response.
99 static RingBuffer
<uint16_t, 2> resp_buf
;
101 static bool process_queue_item(struct queue_item
*item
, uint16_t timeout
);
108 SdepSlaveNotReady
= 0xfe, // Try again later
109 SdepSlaveOverflow
= 0xff, // You read more data than is available
113 BleInitialize
= 0xbeef,
114 BleAtWrapper
= 0x0a00,
119 enum ble_system_event_bits
{
120 BleSystemConnected
= 0,
121 BleSystemDisconnected
= 1,
123 BleSystemMidiRx
= 10,
126 // The SDEP.md file says 2MHz but the web page and the sample driver
128 #define SpiBusSpeed 4000000
130 #define SdepTimeout 150 /* milliseconds */
131 #define SdepShortTimeout 10 /* milliseconds */
132 #define SdepBackOff 25 /* microseconds */
133 #define BatteryUpdateInterval 10000 /* milliseconds */
135 static bool at_command(const char *cmd
, char *resp
, uint16_t resplen
,
136 bool verbose
, uint16_t timeout
= SdepTimeout
);
137 static bool at_command_P(const char *cmd
, char *resp
, uint16_t resplen
,
138 bool verbose
= false);
140 struct SPI_Settings
{
144 static struct SPI_Settings spi
;
146 // Initialize 4Mhz MSBFIRST MODE0
147 void SPI_init(struct SPI_Settings
*spi
) {
148 spi
->spcr
= _BV(SPE
) | _BV(MSTR
);
149 spi
->spsr
= _BV(SPI2X
);
151 static_assert(SpiBusSpeed
== F_CPU
/ 2, "hard coded at 4Mhz");
153 ATOMIC_BLOCK(ATOMIC_RESTORESTATE
) {
154 // Ensure that SS is OUTPUT High
155 digitalWrite(B0
, PinLevelHigh
);
156 pinMode(B0
, PinDirectionOutput
);
160 pinMode(B1
/* SCK */, PinDirectionOutput
);
161 pinMode(B2
/* MOSI */, PinDirectionOutput
);
165 static inline void SPI_begin(struct SPI_Settings
*spi
) {
170 static inline uint8_t SPI_TransferByte(uint8_t data
) {
173 while (!(SPSR
& _BV(SPIF
))) {
179 static inline void spi_send_bytes(const uint8_t *buf
, uint8_t len
) {
180 if (len
== 0) return;
181 const uint8_t *end
= buf
+ len
;
184 while (!(SPSR
& _BV(SPIF
))) {
191 static inline uint16_t spi_read_byte(void) {
192 return SPI_TransferByte(0x00 /* dummy */);
195 static inline void spi_recv_bytes(uint8_t *buf
, uint8_t len
) {
196 const uint8_t *end
= buf
+ len
;
197 if (len
== 0) return;
199 SPDR
= 0; // write a dummy to initiate read
200 while (!(SPSR
& _BV(SPIF
))) {
209 static void dump_pkt(const struct sdep_msg
*msg
) {
211 print_hex8(msg
->type
);
213 print_hex8(msg
->cmd_high
);
214 print_hex8(msg
->cmd_low
);
216 print_hex8(msg
->len
);
218 print_hex8(msg
->more
);
223 // Send a single SDEP packet
224 static bool sdep_send_pkt(const struct sdep_msg
*msg
, uint16_t timeout
) {
227 digitalWrite(AdafruitBleCSPin
, PinLevelLow
);
228 uint16_t timerStart
= timer_read();
229 bool success
= false;
233 ready
= SPI_TransferByte(msg
->type
) != SdepSlaveNotReady
;
238 // Release it and let it initialize
239 digitalWrite(AdafruitBleCSPin
, PinLevelHigh
);
240 _delay_us(SdepBackOff
);
241 digitalWrite(AdafruitBleCSPin
, PinLevelLow
);
242 } while (timer_elapsed(timerStart
) < timeout
);
245 // Slave is ready; send the rest of the packet
246 spi_send_bytes(&msg
->cmd_low
,
247 sizeof(*msg
) - (1 + sizeof(msg
->payload
)) + msg
->len
);
251 digitalWrite(AdafruitBleCSPin
, PinLevelHigh
);
256 static inline void sdep_build_pkt(struct sdep_msg
*msg
, uint16_t command
,
257 const uint8_t *payload
, uint8_t len
,
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",
340 (int)resp_buf
.size());
342 // Timed out: consume this entry
343 resp_buf
.get(last_send
);
347 static void send_buf_send_one(uint16_t timeout
= SdepTimeout
) {
348 struct queue_item item
;
350 // Don't send anything more until we get an ACK
351 if (!resp_buf
.empty()) {
355 if (!send_buf
.peek(item
)) {
358 if (process_queue_item(&item
, timeout
)) {
361 dprintf("send_buf_send_one: have %d remaining\n", (int)send_buf
.size());
363 dprint("failed to send, will retry\n");
364 _delay_ms(SdepTimeout
);
365 resp_buf_read_one(true);
369 static void resp_buf_wait(const char *cmd
) {
370 bool didPrint
= false;
371 while (!resp_buf
.empty()) {
373 dprintf("wait on buf for %s\n", cmd
);
376 resp_buf_read_one(true);
380 static bool ble_init(void) {
381 state
.initialized
= false;
382 state
.configured
= false;
383 state
.is_connected
= false;
385 pinMode(AdafruitBleIRQPin
, PinDirectionInput
);
386 pinMode(AdafruitBleCSPin
, PinDirectionOutput
);
387 digitalWrite(AdafruitBleCSPin
, PinLevelHigh
);
391 // Perform a hardware reset
392 pinMode(AdafruitBleResetPin
, PinDirectionOutput
);
393 digitalWrite(AdafruitBleResetPin
, PinLevelHigh
);
394 digitalWrite(AdafruitBleResetPin
, PinLevelLow
);
396 digitalWrite(AdafruitBleResetPin
, PinLevelHigh
);
398 _delay_ms(1000); // Give it a second to initialize
400 state
.initialized
= true;
401 return state
.initialized
;
404 static inline uint8_t min(uint8_t a
, uint8_t b
) {
405 return a
< b
? a
: b
;
408 static bool read_response(char *resp
, uint16_t resplen
, bool verbose
) {
410 char *end
= dest
+ resplen
;
415 if (!sdep_recv_pkt(&msg
, 2 * SdepTimeout
)) {
416 dprint("sdep_recv_pkt failed\n");
420 if (msg
.type
!= SdepResponse
) {
425 uint8_t len
= min(msg
.len
, end
- dest
);
427 memcpy(dest
, msg
.payload
, len
);
432 // No more data is expected!
437 // Ensure the response is NUL terminated
440 // "Parse" the result text; we want to snip off the trailing OK or ERROR line
441 // Rewind past the possible trailing CRLF so that we can strip it
443 while (dest
> resp
&& (dest
[0] == '\n' || dest
[0] == '\r')) {
448 // Look back for start of preceeding line
449 char *last_line
= strrchr(resp
, '\n');
456 bool success
= false;
457 static const char kOK
[] PROGMEM
= "OK";
459 success
= !strcmp_P(last_line
, kOK
);
461 if (verbose
|| !success
) {
462 dprintf("result: %s\n", resp
);
467 static bool at_command(const char *cmd
, char *resp
, uint16_t resplen
,
468 bool verbose
, uint16_t timeout
) {
469 const char *end
= cmd
+ strlen(cmd
);
473 dprintf("ble send: %s\n", cmd
);
477 // They want to decode the response, so we need to flush and wait
478 // for all pending I/O to finish before we start this one, so
479 // that we don't confuse the results
484 // Fragment the command into a series of SDEP packets
485 while (end
- cmd
> SdepMaxPayload
) {
486 sdep_build_pkt(&msg
, BleAtWrapper
, (uint8_t *)cmd
, SdepMaxPayload
, true);
487 if (!sdep_send_pkt(&msg
, timeout
)) {
490 cmd
+= SdepMaxPayload
;
493 sdep_build_pkt(&msg
, BleAtWrapper
, (uint8_t *)cmd
, end
- cmd
, false);
494 if (!sdep_send_pkt(&msg
, timeout
)) {
499 auto now
= timer_read();
500 while (!resp_buf
.enqueue(now
)) {
501 resp_buf_read_one(false);
503 auto later
= timer_read();
504 if (TIMER_DIFF_16(later
, now
) > 0) {
505 dprintf("waited %dms for resp_buf\n", TIMER_DIFF_16(later
, now
));
510 return read_response(resp
, resplen
, verbose
);
513 bool at_command_P(const char *cmd
, char *resp
, uint16_t resplen
, bool verbose
) {
514 auto cmdbuf
= (char *)alloca(strlen_P(cmd
) + 1);
515 strcpy_P(cmdbuf
, cmd
);
516 return at_command(cmdbuf
, resp
, resplen
, verbose
);
519 bool adafruit_ble_is_connected(void) {
520 return state
.is_connected
;
523 bool adafruit_ble_enable_keyboard(void) {
526 if (!state
.initialized
&& !ble_init()) {
530 state
.configured
= false;
532 // Disable command echo
533 static const char kEcho
[] PROGMEM
= "ATE=0";
534 // Make the advertised name match the keyboard
535 static const char kGapDevName
[] PROGMEM
=
536 "AT+GAPDEVNAME=" STR(PRODUCT
) " " STR(DESCRIPTION
);
537 // Turn on keyboard support
538 static const char kHidEnOn
[] PROGMEM
= "AT+BLEHIDEN=1";
540 // Adjust intervals to improve latency. This causes the "central"
541 // system (computer/tablet) to poll us every 10-30 ms. We can't
542 // set a smaller value than 10ms, and 30ms seems to be the natural
543 // processing time on my macbook. Keeping it constrained to that
544 // feels reasonable to type to.
545 static const char kGapIntervals
[] PROGMEM
= "AT+GAPINTERVALS=10,30,,";
547 // Reset the device so that it picks up the above changes
548 static const char kATZ
[] PROGMEM
= "ATZ";
550 // Turn down the power level a bit
551 static const char kPower
[] PROGMEM
= "AT+BLEPOWERLEVEL=-12";
552 static PGM_P
const configure_commands
[] PROGMEM
= {
562 for (i
= 0; i
< sizeof(configure_commands
) / sizeof(configure_commands
[0]);
565 memcpy_P(&cmd
, configure_commands
+ i
, sizeof(cmd
));
567 if (!at_command_P(cmd
, resbuf
, sizeof(resbuf
))) {
568 dprintf("failed BLE command: %S: %s\n", cmd
, resbuf
);
573 state
.configured
= true;
575 // Check connection status in a little while; allow the ATZ time
577 state
.last_connection_update
= timer_read();
579 return state
.configured
;
582 static void set_connected(bool connected
) {
583 if (connected
!= state
.is_connected
) {
585 print("****** BLE CONNECT!!!!\n");
587 print("****** BLE DISCONNECT!!!!\n");
589 state
.is_connected
= connected
;
591 // TODO: if modifiers are down on the USB interface and
592 // we cut over to BLE or vice versa, they will remain stuck.
593 // This feels like a good point to do something like clearing
594 // the keyboard and/or generating a fake all keys up message.
595 // However, I've noticed that it takes a couple of seconds
596 // for macOS to to start recognizing key presses after BLE
597 // is in the connected state, so I worry that doing that
598 // here may not be good enough.
602 void adafruit_ble_task(void) {
605 if (!state
.configured
&& !adafruit_ble_enable_keyboard()) {
608 resp_buf_read_one(true);
609 send_buf_send_one(SdepShortTimeout
);
611 if (resp_buf
.empty() && (state
.event_flags
& UsingEvents
) &&
612 digitalRead(AdafruitBleIRQPin
)) {
613 // Must be an event update
614 if (at_command_P(PSTR("AT+EVENTSTATUS"), resbuf
, sizeof(resbuf
))) {
615 uint32_t mask
= strtoul(resbuf
, NULL
, 16);
617 if (mask
& BleSystemConnected
) {
619 } else if (mask
& BleSystemDisconnected
) {
620 set_connected(false);
625 if (timer_elapsed(state
.last_connection_update
) > ConnectionUpdateInterval
) {
626 bool shouldPoll
= true;
627 if (!(state
.event_flags
& ProbedEvents
)) {
628 // Request notifications about connection status changes.
629 // This only works in SPIFRIEND firmware > 0.6.7, which is why
630 // we check for this conditionally here.
631 // Note that at the time of writing, HID reports only work correctly
632 // with Apple products on firmware version 0.6.7!
633 // https://forums.adafruit.com/viewtopic.php?f=8&t=104052
634 if (at_command_P(PSTR("AT+EVENTENABLE=0x1"), resbuf
, sizeof(resbuf
))) {
635 at_command_P(PSTR("AT+EVENTENABLE=0x2"), resbuf
, sizeof(resbuf
));
636 state
.event_flags
|= UsingEvents
;
638 state
.event_flags
|= ProbedEvents
;
640 // leave shouldPoll == true so that we check at least once
641 // before relying solely on events
646 static const char kGetConn
[] PROGMEM
= "AT+GAPGETCONN";
647 state
.last_connection_update
= timer_read();
649 if (at_command_P(kGetConn
, resbuf
, sizeof(resbuf
))) {
650 set_connected(atoi(resbuf
));
654 #ifdef SAMPLE_BATTERY
655 // I don't know if this really does anything useful yet; the reported
656 // voltage level always seems to be around 3200mV. We may want to just rip
658 if (timer_elapsed(state
.last_battery_update
) > BatteryUpdateInterval
&&
660 state
.last_battery_update
= timer_read();
662 if (at_command_P(PSTR("AT+HWVBAT"), resbuf
, sizeof(resbuf
))) {
663 state
.vbat
= atoi(resbuf
);
669 static bool process_queue_item(struct queue_item
*item
, uint16_t timeout
) {
673 // Arrange to re-check connection after keys have settled
674 state
.last_connection_update
= timer_read();
677 if (TIMER_DIFF_16(state
.last_connection_update
, item
->added
) > 0) {
678 dprintf("send latency %dms\n",
679 TIMER_DIFF_16(state
.last_connection_update
, item
->added
));
683 switch (item
->queue_type
) {
686 PSTR("AT+BLEKEYBOARDCODE=%02x-00-%02x-%02x-%02x-%02x-%02x-%02x"));
687 snprintf(cmdbuf
, sizeof(cmdbuf
), fmtbuf
, item
->key
.modifier
,
688 item
->key
.keys
[0], item
->key
.keys
[1], item
->key
.keys
[2],
689 item
->key
.keys
[3], item
->key
.keys
[4], item
->key
.keys
[5]);
690 return at_command(cmdbuf
, NULL
, 0, true, timeout
);
693 strcpy_P(fmtbuf
, PSTR("AT+BLEHIDCONTROLKEY=0x%04x"));
694 snprintf(cmdbuf
, sizeof(cmdbuf
), fmtbuf
, item
->consumer
);
695 return at_command(cmdbuf
, NULL
, 0, true, timeout
);
699 strcpy_P(fmtbuf
, PSTR("AT+BLEHIDMOUSEMOVE=%d,%d,%d,%d"));
700 snprintf(cmdbuf
, sizeof(cmdbuf
), fmtbuf
, item
->mousemove
.x
,
701 item
->mousemove
.y
, item
->mousemove
.scroll
, item
->mousemove
.pan
);
702 return at_command(cmdbuf
, NULL
, 0, true, timeout
);
709 bool adafruit_ble_send_keys(uint8_t hid_modifier_mask
, uint8_t *keys
,
711 struct queue_item item
;
712 bool didWait
= false;
714 item
.queue_type
= QTKeyReport
;
715 item
.key
.modifier
= hid_modifier_mask
;
716 item
.added
= timer_read();
719 item
.key
.keys
[0] = keys
[0];
720 item
.key
.keys
[1] = nkeys
>= 1 ? keys
[1] : 0;
721 item
.key
.keys
[2] = nkeys
>= 2 ? keys
[2] : 0;
722 item
.key
.keys
[3] = nkeys
>= 3 ? keys
[3] : 0;
723 item
.key
.keys
[4] = nkeys
>= 4 ? keys
[4] : 0;
724 item
.key
.keys
[5] = nkeys
>= 5 ? keys
[5] : 0;
726 if (!send_buf
.enqueue(item
)) {
728 dprint("wait for buf space\n");
746 bool adafruit_ble_send_consumer_key(uint16_t keycode
, int hold_duration
) {
747 struct queue_item item
;
749 item
.queue_type
= QTConsumer
;
750 item
.consumer
= keycode
;
752 while (!send_buf
.enqueue(item
)) {
759 bool adafruit_ble_send_mouse_move(int8_t x
, int8_t y
, int8_t scroll
,
761 struct queue_item item
;
763 item
.queue_type
= QTMouseMove
;
764 item
.mousemove
.x
= x
;
765 item
.mousemove
.y
= y
;
766 item
.mousemove
.scroll
= scroll
;
767 item
.mousemove
.pan
= pan
;
769 while (!send_buf
.enqueue(item
)) {
776 uint32_t adafruit_ble_read_battery_voltage(void) {
780 bool adafruit_ble_set_mode_leds(bool on
) {
781 if (!state
.configured
) {
785 // The "mode" led is the red blinky one
786 at_command_P(on
? PSTR("AT+HWMODELED=1") : PSTR("AT+HWMODELED=0"), NULL
, 0);
788 // Pin 19 is the blue "connected" LED; turn that off too.
789 // When turning LEDs back on, don't turn that LED on if we're
790 // not connected, as that would be confusing.
791 at_command_P(on
&& state
.is_connected
? PSTR("AT+HWGPIO=19,1")
792 : PSTR("AT+HWGPIO=19,0"),
797 // https://learn.adafruit.com/adafruit-feather-32u4-bluefruit-le/ble-generic#at-plus-blepowerlevel
798 bool adafruit_ble_set_power_level(int8_t level
) {
800 if (!state
.configured
) {
803 snprintf(cmd
, sizeof(cmd
), "AT+BLEPOWERLEVEL=%d", level
);
804 return at_command(cmd
, NULL
, 0, false);