bluefruit_le.cpp
20652 bytes
1#include "bluefruit_le.h"
2
3#include <stdio.h>
4#include <stdlib.h>
5#include <alloca.h>
6#include "debug.h"
7#include "timer.h"
8#include "gpio.h"
9#include "ringbuffer.hpp"
10#include <string.h>
11#include "spi_master.h"
12#include "wait.h"
13#include "analog.h"
14#include "progmem.h"
15
16// These are the pin assignments for the 32u4 boards.
17// You may define them to something else in your config.h
18// if yours is wired up differently.
19#ifndef BLUEFRUIT_LE_RST_PIN
20# define BLUEFRUIT_LE_RST_PIN D4
21#endif
22
23#ifndef BLUEFRUIT_LE_CS_PIN
24# define BLUEFRUIT_LE_CS_PIN B4
25#endif
26
27#ifndef BLUEFRUIT_LE_IRQ_PIN
28# define BLUEFRUIT_LE_IRQ_PIN E6
29#endif
30
31#ifndef BLUEFRUIT_LE_SCK_DIVISOR
32# define BLUEFRUIT_LE_SCK_DIVISOR 2 // 4MHz SCK/8MHz CPU, calculated for Feather 32U4 BLE
33#endif
34
35#define SAMPLE_BATTERY
36#define ConnectionUpdateInterval 1000 /* milliseconds */
37
38#ifndef BATTERY_LEVEL_PIN
39# define BATTERY_LEVEL_PIN B5
40#endif
41
42static struct {
43 bool is_connected;
44 bool initialized;
45 bool configured;
46
47#define ProbedEvents 1
48#define UsingEvents 2
49 bool event_flags;
50
51#ifdef SAMPLE_BATTERY
52 uint16_t last_battery_update;
53 uint32_t vbat;
54#endif
55 uint16_t last_connection_update;
56} state;
57
58// Commands are encoded using SDEP and sent via SPI
59// https://github.com/adafruit/Adafruit_BluefruitLE_nRF51/blob/master/SDEP.md
60
61#define SdepMaxPayload 16
62struct sdep_msg {
63 uint8_t type;
64 uint8_t cmd_low;
65 uint8_t cmd_high;
66 struct __attribute__((packed)) {
67 uint8_t len : 7;
68 uint8_t more : 1;
69 };
70 uint8_t payload[SdepMaxPayload];
71} __attribute__((packed));
72
73// The recv latency is relatively high, so when we're hammering keys quickly,
74// we want to avoid waiting for the responses in the matrix loop. We maintain
75// a short queue for that. Since there is quite a lot of space overhead for
76// the AT command representation wrapped up in SDEP, we queue the minimal
77// information here.
78
79enum queue_type {
80 QTKeyReport, // 1-byte modifier + 6-byte key report
81 QTConsumer, // 16-bit key code
82 QTMouseMove, // 4-byte mouse report
83};
84
85struct queue_item {
86 enum queue_type queue_type;
87 uint16_t added;
88 union __attribute__((packed)) {
89 struct __attribute__((packed)) {
90 uint8_t modifier;
91 uint8_t keys[6];
92 } key;
93
94 uint16_t consumer;
95 struct __attribute__((packed)) {
96 int8_t x, y, scroll, pan;
97 uint8_t buttons;
98 } mousemove;
99 };
100};
101
102// Items that we wish to send
103static RingBuffer<queue_item, 40> send_buf;
104// Pending response; while pending, we can't send any more requests.
105// This records the time at which we sent the command for which we
106// are expecting a response.
107static RingBuffer<uint16_t, 2> resp_buf;
108
109static bool process_queue_item(struct queue_item *item, uint16_t timeout);
110
111enum sdep_type {
112 SdepCommand = 0x10,
113 SdepResponse = 0x20,
114 SdepAlert = 0x40,
115 SdepError = 0x80,
116 SdepSlaveNotReady = 0xFE, // Try again later
117 SdepSlaveOverflow = 0xFF, // You read more data than is available
118};
119
120enum ble_cmd {
121 BleInitialize = 0xBEEF,
122 BleAtWrapper = 0x0A00,
123 BleUartTx = 0x0A01,
124 BleUartRx = 0x0A02,
125};
126
127enum ble_system_event_bits {
128 BleSystemConnected = 0,
129 BleSystemDisconnected = 1,
130 BleSystemUartRx = 8,
131 BleSystemMidiRx = 10,
132};
133
134#define SdepTimeout 150 /* milliseconds */
135#define SdepShortTimeout 10 /* milliseconds */
136#define SdepBackOff 25 /* microseconds */
137#define BatteryUpdateInterval 10000 /* milliseconds */
138
139static bool at_command(const char *cmd, char *resp, uint16_t resplen, bool verbose, uint16_t timeout = SdepTimeout);
140static bool at_command_P(const char *cmd, char *resp, uint16_t resplen, bool verbose = false);
141
142// Send a single SDEP packet
143static bool sdep_send_pkt(const struct sdep_msg *msg, uint16_t timeout) {
144 spi_start(BLUEFRUIT_LE_CS_PIN, false, 0, BLUEFRUIT_LE_SCK_DIVISOR);
145 uint16_t timerStart = timer_read();
146 bool success = false;
147 bool ready = false;
148
149 do {
150 ready = spi_write(msg->type) != SdepSlaveNotReady;
151 if (ready) {
152 break;
153 }
154
155 // Release it and let it initialize
156 spi_stop();
157 wait_us(SdepBackOff);
158 spi_start(BLUEFRUIT_LE_CS_PIN, false, 0, BLUEFRUIT_LE_SCK_DIVISOR);
159 } while (timer_elapsed(timerStart) < timeout);
160
161 if (ready) {
162 // Slave is ready; send the rest of the packet
163 spi_transmit(&msg->cmd_low, sizeof(*msg) - (1 + sizeof(msg->payload)) + msg->len);
164 success = true;
165 }
166
167 spi_stop();
168
169 return success;
170}
171
172static inline void sdep_build_pkt(struct sdep_msg *msg, uint16_t command, const uint8_t *payload, uint8_t len, bool moredata) {
173 msg->type = SdepCommand;
174 msg->cmd_low = command & 0xFF;
175 msg->cmd_high = command >> 8;
176 msg->len = len;
177 msg->more = (moredata && len == SdepMaxPayload) ? 1 : 0;
178
179 static_assert(sizeof(*msg) == 20, "msg is correctly packed");
180
181 memcpy(msg->payload, payload, len);
182}
183
184// Read a single SDEP packet
185static bool sdep_recv_pkt(struct sdep_msg *msg, uint16_t timeout) {
186 bool success = false;
187 uint16_t timerStart = timer_read();
188 bool ready = false;
189
190 do {
191 ready = gpio_read_pin(BLUEFRUIT_LE_IRQ_PIN);
192 if (ready) {
193 break;
194 }
195 wait_us(1);
196 } while (timer_elapsed(timerStart) < timeout);
197
198 if (ready) {
199 spi_start(BLUEFRUIT_LE_CS_PIN, false, 0, BLUEFRUIT_LE_SCK_DIVISOR);
200
201 do {
202 // Read the command type, waiting for the data to be ready
203 msg->type = spi_read();
204 if (msg->type == SdepSlaveNotReady || msg->type == SdepSlaveOverflow) {
205 // Release it and let it initialize
206 spi_stop();
207 wait_us(SdepBackOff);
208 spi_start(BLUEFRUIT_LE_CS_PIN, false, 0, BLUEFRUIT_LE_SCK_DIVISOR);
209 continue;
210 }
211
212 // Read the rest of the header
213 spi_receive(&msg->cmd_low, sizeof(*msg) - (1 + sizeof(msg->payload)));
214
215 // and get the payload if there is any
216 if (msg->len <= SdepMaxPayload) {
217 spi_receive(msg->payload, msg->len);
218 }
219 success = true;
220 break;
221 } while (timer_elapsed(timerStart) < timeout);
222
223 spi_stop();
224 }
225 return success;
226}
227
228static void resp_buf_read_one(bool greedy) {
229 uint16_t last_send;
230 if (!resp_buf.peek(last_send)) {
231 return;
232 }
233
234 if (gpio_read_pin(BLUEFRUIT_LE_IRQ_PIN)) {
235 struct sdep_msg msg;
236
237 again:
238 if (sdep_recv_pkt(&msg, SdepTimeout)) {
239 if (!msg.more) {
240 // We got it; consume this entry
241 resp_buf.get(last_send);
242 dprintf("recv latency %dms\n", TIMER_DIFF_16(timer_read(), last_send));
243 }
244
245 if (greedy && resp_buf.peek(last_send) && gpio_read_pin(BLUEFRUIT_LE_IRQ_PIN)) {
246 goto again;
247 }
248 }
249
250 } else if (timer_elapsed(last_send) > SdepTimeout * 2) {
251 dprintf("waiting_for_result: timeout, resp_buf size %d\n", (int)resp_buf.size());
252
253 // Timed out: consume this entry
254 resp_buf.get(last_send);
255 }
256}
257
258static void send_buf_send_one(uint16_t timeout = SdepTimeout) {
259 struct queue_item item;
260
261 // Don't send anything more until we get an ACK
262 if (!resp_buf.empty()) {
263 return;
264 }
265
266 if (!send_buf.peek(item)) {
267 return;
268 }
269 if (process_queue_item(&item, timeout)) {
270 // commit that peek
271 send_buf.get(item);
272 dprintf("send_buf_send_one: have %d remaining\n", (int)send_buf.size());
273 } else {
274 dprint("failed to send, will retry\n");
275 wait_ms(SdepTimeout);
276 resp_buf_read_one(true);
277 }
278}
279
280static void resp_buf_wait(const char *cmd) {
281 bool didPrint = false;
282 while (!resp_buf.empty()) {
283 if (!didPrint) {
284 dprintf("wait on buf for %s\n", cmd);
285 didPrint = true;
286 }
287 resp_buf_read_one(true);
288 }
289}
290
291void bluefruit_le_init(void) {
292 state.initialized = false;
293 state.configured = false;
294 state.is_connected = false;
295
296 gpio_set_pin_input(BLUEFRUIT_LE_IRQ_PIN);
297
298 spi_init();
299
300 // Perform a hardware reset
301 gpio_set_pin_output(BLUEFRUIT_LE_RST_PIN);
302 gpio_write_pin_high(BLUEFRUIT_LE_RST_PIN);
303 gpio_write_pin_low(BLUEFRUIT_LE_RST_PIN);
304 wait_ms(10);
305 gpio_write_pin_high(BLUEFRUIT_LE_RST_PIN);
306
307 wait_ms(1000); // Give it a second to initialize
308
309 state.initialized = true;
310}
311
312static inline uint8_t min(uint8_t a, uint8_t b) {
313 return a < b ? a : b;
314}
315
316static bool read_response(char *resp, uint16_t resplen, bool verbose) {
317 char *dest = resp;
318 char *end = dest + resplen;
319
320 while (true) {
321 struct sdep_msg msg;
322
323 if (!sdep_recv_pkt(&msg, 2 * SdepTimeout)) {
324 dprint("sdep_recv_pkt failed\n");
325 return false;
326 }
327
328 if (msg.type != SdepResponse) {
329 *resp = 0;
330 return false;
331 }
332
333 uint8_t len = min(msg.len, end - dest);
334 if (len > 0) {
335 memcpy(dest, msg.payload, len);
336 dest += len;
337 }
338
339 if (!msg.more) {
340 // No more data is expected!
341 break;
342 }
343 }
344
345 // Ensure the response is NUL terminated
346 *dest = 0;
347
348 // "Parse" the result text; we want to snip off the trailing OK or ERROR line
349 // Rewind past the possible trailing CRLF so that we can strip it
350 --dest;
351 while (dest > resp && (dest[0] == '\n' || dest[0] == '\r')) {
352 *dest = 0;
353 --dest;
354 }
355
356 // Look back for start of preceeding line
357 char *last_line = strrchr(resp, '\n');
358 if (last_line) {
359 ++last_line;
360 } else {
361 last_line = resp;
362 }
363
364 bool success = false;
365 static const char kOK[] PROGMEM = "OK";
366
367 success = !strcmp_P(last_line, kOK);
368
369 if (verbose || !success) {
370 dprintf("result: %s\n", resp);
371 }
372 return success;
373}
374
375static bool at_command(const char *cmd, char *resp, uint16_t resplen, bool verbose, uint16_t timeout) {
376 const char * end = cmd + strlen(cmd);
377 struct sdep_msg msg;
378
379 if (verbose) {
380 dprintf("ble send: %s\n", cmd);
381 }
382
383 if (resp) {
384 // They want to decode the response, so we need to flush and wait
385 // for all pending I/O to finish before we start this one, so
386 // that we don't confuse the results
387 resp_buf_wait(cmd);
388 *resp = 0;
389 }
390
391 // Fragment the command into a series of SDEP packets
392 while (end - cmd > SdepMaxPayload) {
393 sdep_build_pkt(&msg, BleAtWrapper, (uint8_t *)cmd, SdepMaxPayload, true);
394 if (!sdep_send_pkt(&msg, timeout)) {
395 return false;
396 }
397 cmd += SdepMaxPayload;
398 }
399
400 sdep_build_pkt(&msg, BleAtWrapper, (uint8_t *)cmd, end - cmd, false);
401 if (!sdep_send_pkt(&msg, timeout)) {
402 return false;
403 }
404
405 if (resp == NULL) {
406 uint16_t now = timer_read();
407 while (!resp_buf.enqueue(now)) {
408 resp_buf_read_one(false);
409 }
410 uint16_t later = timer_read();
411 if (TIMER_DIFF_16(later, now) > 0) {
412 dprintf("waited %dms for resp_buf\n", TIMER_DIFF_16(later, now));
413 }
414 return true;
415 }
416
417 return read_response(resp, resplen, verbose);
418}
419
420bool at_command_P(const char *cmd, char *resp, uint16_t resplen, bool verbose) {
421 char *cmdbuf = (char *)alloca(strlen_P(cmd) + 1);
422 strcpy_P(cmdbuf, cmd);
423 return at_command(cmdbuf, resp, resplen, verbose);
424}
425
426bool bluefruit_le_is_connected(void) {
427 return state.is_connected;
428}
429
430bool bluefruit_le_enable_keyboard(void) {
431 char resbuf[128];
432
433 if (!state.initialized) {
434 return false;
435 }
436
437 state.configured = false;
438
439 // Disable command echo
440 static const char kEcho[] PROGMEM = "ATE=0";
441 // Make the advertised name match the keyboard
442 static const char kGapDevName[] PROGMEM = "AT+GAPDEVNAME=" PRODUCT;
443 // Turn on keyboard support
444 static const char kHidEnOn[] PROGMEM = "AT+BLEHIDEN=1";
445
446 // Adjust intervals to improve latency. This causes the "central"
447 // system (computer/tablet) to poll us every 10-30 ms. We can't
448 // set a smaller value than 10ms, and 30ms seems to be the natural
449 // processing time on my macbook. Keeping it constrained to that
450 // feels reasonable to type to.
451 static const char kGapIntervals[] PROGMEM = "AT+GAPINTERVALS=10,30,,";
452
453 // Reset the device so that it picks up the above changes
454 static const char kATZ[] PROGMEM = "ATZ";
455
456 // Turn down the power level a bit
457 static const char kPower[] PROGMEM = "AT+BLEPOWERLEVEL=-12";
458 static PGM_P const configure_commands[] PROGMEM = {
459 kEcho, kGapIntervals, kGapDevName, kHidEnOn, kPower, kATZ,
460 };
461
462 uint8_t i;
463 for (i = 0; i < sizeof(configure_commands) / sizeof(configure_commands[0]); ++i) {
464 PGM_P cmd;
465 memcpy_P(&cmd, configure_commands + i, sizeof(cmd));
466
467 if (!at_command_P(cmd, resbuf, sizeof(resbuf))) {
468 dprintf("failed BLE command: %S: %s\n", cmd, resbuf);
469 goto fail;
470 }
471 }
472
473 state.configured = true;
474
475 // Check connection status in a little while; allow the ATZ time
476 // to kick in.
477 state.last_connection_update = timer_read();
478fail:
479 return state.configured;
480}
481
482static void set_connected(bool connected) {
483 if (connected != state.is_connected) {
484 if (connected) {
485 dprint("BLE connected\n");
486 } else {
487 dprint("BLE disconnected\n");
488 }
489 state.is_connected = connected;
490
491 // TODO: if modifiers are down on the USB interface and
492 // we cut over to BLE or vice versa, they will remain stuck.
493 // This feels like a good point to do something like clearing
494 // the keyboard and/or generating a fake all keys up message.
495 // However, I've noticed that it takes a couple of seconds
496 // for macOS to to start recognizing key presses after BLE
497 // is in the connected state, so I worry that doing that
498 // here may not be good enough.
499 }
500}
501
502void bluefruit_le_task(void) {
503 char resbuf[48];
504
505 if (!state.configured && !bluefruit_le_enable_keyboard()) {
506 return;
507 }
508 resp_buf_read_one(true);
509 send_buf_send_one(SdepShortTimeout);
510
511 if (resp_buf.empty() && (state.event_flags & UsingEvents) && gpio_read_pin(BLUEFRUIT_LE_IRQ_PIN)) {
512 // Must be an event update
513 if (at_command_P(PSTR("AT+EVENTSTATUS"), resbuf, sizeof(resbuf))) {
514 uint32_t mask = strtoul(resbuf, NULL, 16);
515
516 if (mask & BleSystemConnected) {
517 set_connected(true);
518 } else if (mask & BleSystemDisconnected) {
519 set_connected(false);
520 }
521 }
522 }
523
524 if (timer_elapsed(state.last_connection_update) > ConnectionUpdateInterval) {
525 bool shouldPoll = true;
526 if (!(state.event_flags & ProbedEvents)) {
527 // Request notifications about connection status changes.
528 // This only works in SPIFRIEND firmware > 0.6.7, which is why
529 // we check for this conditionally here.
530 // Note that at the time of writing, HID reports only work correctly
531 // with Apple products on firmware version 0.6.7!
532 // https://forums.adafruit.com/viewtopic.php?f=8&t=104052
533 if (at_command_P(PSTR("AT+EVENTENABLE=0x1"), resbuf, sizeof(resbuf))) {
534 at_command_P(PSTR("AT+EVENTENABLE=0x2"), resbuf, sizeof(resbuf));
535 state.event_flags |= UsingEvents;
536 }
537 state.event_flags |= ProbedEvents;
538
539 // leave shouldPoll == true so that we check at least once
540 // before relying solely on events
541 } else {
542 shouldPoll = false;
543 }
544
545 static const char kGetConn[] PROGMEM = "AT+GAPGETCONN";
546 state.last_connection_update = timer_read();
547
548 if (at_command_P(kGetConn, resbuf, sizeof(resbuf))) {
549 set_connected(atoi(resbuf));
550 }
551 }
552
553#ifdef SAMPLE_BATTERY
554 if (timer_elapsed(state.last_battery_update) > BatteryUpdateInterval && resp_buf.empty()) {
555 state.last_battery_update = timer_read();
556
557 state.vbat = analogReadPin(BATTERY_LEVEL_PIN);
558 }
559#endif
560}
561
562static bool process_queue_item(struct queue_item *item, uint16_t timeout) {
563 char cmdbuf[48];
564 char fmtbuf[64];
565
566 // Arrange to re-check connection after keys have settled
567 state.last_connection_update = timer_read();
568
569#if 1
570 if (TIMER_DIFF_16(state.last_connection_update, item->added) > 0) {
571 dprintf("send latency %dms\n", TIMER_DIFF_16(state.last_connection_update, item->added));
572 }
573#endif
574
575 switch (item->queue_type) {
576 case QTKeyReport:
577 strcpy_P(fmtbuf, PSTR("AT+BLEKEYBOARDCODE=%02x-00-%02x-%02x-%02x-%02x-%02x-%02x"));
578 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]);
579 return at_command(cmdbuf, NULL, 0, true, timeout);
580
581#ifdef EXTRAKEY_ENABLE
582 case QTConsumer:
583 strcpy_P(fmtbuf, PSTR("AT+BLEHIDCONTROLKEY=0x%04x"));
584 snprintf(cmdbuf, sizeof(cmdbuf), fmtbuf, item->consumer);
585 return at_command(cmdbuf, NULL, 0, true, timeout);
586#endif
587
588#ifdef MOUSE_ENABLE
589 case QTMouseMove:
590 strcpy_P(fmtbuf, PSTR("AT+BLEHIDMOUSEMOVE=%d,%d,%d,%d"));
591 snprintf(cmdbuf, sizeof(cmdbuf), fmtbuf, item->mousemove.x, item->mousemove.y, item->mousemove.scroll, item->mousemove.pan);
592 if (!at_command(cmdbuf, NULL, 0, true, timeout)) {
593 return false;
594 }
595 strcpy_P(cmdbuf, PSTR("AT+BLEHIDMOUSEBUTTON="));
596 if (item->mousemove.buttons & MOUSE_BTN1) {
597 strcat(cmdbuf, "L");
598 }
599 if (item->mousemove.buttons & MOUSE_BTN2) {
600 strcat(cmdbuf, "R");
601 }
602 if (item->mousemove.buttons & MOUSE_BTN3) {
603 strcat(cmdbuf, "M");
604 }
605 if (item->mousemove.buttons == 0) {
606 strcat(cmdbuf, "0");
607 }
608 return at_command(cmdbuf, NULL, 0, true, timeout);
609#endif
610 default:
611 return true;
612 }
613}
614
615void bluefruit_le_send_keyboard(report_keyboard_t *report) {
616 struct queue_item item;
617
618 item.queue_type = QTKeyReport;
619 item.key.modifier = report->mods;
620 item.key.keys[0] = report->keys[0];
621 item.key.keys[1] = report->keys[1];
622 item.key.keys[2] = report->keys[2];
623 item.key.keys[3] = report->keys[3];
624 item.key.keys[4] = report->keys[4];
625 item.key.keys[5] = report->keys[5];
626
627 while (!send_buf.enqueue(item)) {
628 send_buf_send_one();
629 }
630}
631
632void bluefruit_le_send_consumer(uint16_t usage) {
633 struct queue_item item;
634
635 item.queue_type = QTConsumer;
636 item.consumer = usage;
637
638 while (!send_buf.enqueue(item)) {
639 send_buf_send_one();
640 }
641}
642
643void bluefruit_le_send_mouse(report_mouse_t *report) {
644 struct queue_item item;
645
646 item.queue_type = QTMouseMove;
647 item.mousemove.x = report->x;
648 item.mousemove.y = report->y;
649 item.mousemove.scroll = report->v;
650 item.mousemove.pan = report->h;
651 item.mousemove.buttons = report->buttons;
652
653 while (!send_buf.enqueue(item)) {
654 send_buf_send_one();
655 }
656}
657
658uint32_t bluefruit_le_read_battery_voltage(void) {
659 return state.vbat;
660}
661
662bool bluefruit_le_set_mode_leds(bool on) {
663 if (!state.configured) {
664 return false;
665 }
666
667 // The "mode" led is the red blinky one
668 at_command_P(on ? PSTR("AT+HWMODELED=1") : PSTR("AT+HWMODELED=0"), NULL, 0);
669
670 // Pin 19 is the blue "connected" LED; turn that off too.
671 // When turning LEDs back on, don't turn that LED on if we're
672 // not connected, as that would be confusing.
673 at_command_P(on && state.is_connected ? PSTR("AT+HWGPIO=19,1") : PSTR("AT+HWGPIO=19,0"), NULL, 0);
674 return true;
675}
676
677// https://learn.adafruit.com/adafruit-feather-32u4-bluefruit-le/ble-generic#at-plus-blepowerlevel
678bool bluefruit_le_set_power_level(int8_t level) {
679 char cmd[46];
680 if (!state.configured) {
681 return false;
682 }
683 snprintf(cmd, sizeof(cmd), "AT+BLEPOWERLEVEL=%d", level);
684 return at_command(cmd, NULL, 0, false);
685}