Merge commit '5a3397d17ec917c7be5d5109e01a3a84a355cb1b'
[jackhill/qmk/firmware.git] / tmk_core / protocol / lufa / adafruit_ble.cpp
1 #include "adafruit_ble.h"
2 #include <stdio.h>
3 #include <stdlib.h>
4 #include <alloca.h>
5 #include <util/delay.h>
6 #include <util/atomic.h>
7 #include "debug.h"
8 #include "pincontrol.h"
9 #include "timer.h"
10 #include "action_util.h"
11 #include "ringbuffer.hpp"
12 #include <string.h>
13
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
19 #endif
20
21 #ifndef AdafruitBleCSPin
22 #define AdafruitBleCSPin B4
23 #endif
24
25 #ifndef AdafruitBleIRQPin
26 #define AdafruitBleIRQPin E6
27 #endif
28
29
30 #define SAMPLE_BATTERY
31 #define ConnectionUpdateInterval 1000 /* milliseconds */
32
33 static struct {
34 bool is_connected;
35 bool initialized;
36 bool configured;
37
38 #define ProbedEvents 1
39 #define UsingEvents 2
40 bool event_flags;
41
42 #ifdef SAMPLE_BATTERY
43 uint16_t last_battery_update;
44 uint32_t vbat;
45 #endif
46 uint16_t last_connection_update;
47 } state;
48
49 // Commands are encoded using SDEP and sent via SPI
50 // https://github.com/adafruit/Adafruit_BluefruitLE_nRF51/blob/master/SDEP.md
51
52 #define SdepMaxPayload 16
53 struct sdep_msg {
54 uint8_t type;
55 uint8_t cmd_low;
56 uint8_t cmd_high;
57 struct __attribute__((packed)) {
58 uint8_t len:7;
59 uint8_t more:1;
60 };
61 uint8_t payload[SdepMaxPayload];
62 } __attribute__((packed));
63
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
68 // information here.
69
70 enum queue_type {
71 QTKeyReport, // 1-byte modifier + 6-byte key report
72 QTConsumer, // 16-bit key code
73 #ifdef MOUSE_ENABLE
74 QTMouseMove, // 4-byte mouse report
75 #endif
76 };
77
78 struct queue_item {
79 enum queue_type queue_type;
80 uint16_t added;
81 union __attribute__((packed)) {
82 struct __attribute__((packed)) {
83 uint8_t modifier;
84 uint8_t keys[6];
85 } key;
86
87 uint16_t consumer;
88 struct __attribute__((packed)) {
89 int8_t x, y, scroll, pan;
90 uint8_t buttons;
91 } mousemove;
92 };
93 };
94
95 // Items that we wish to send
96 static RingBuffer<queue_item, 40> send_buf;
97 // Pending response; while pending, we can't send any more requests.
98 // This records the time at which we sent the command for which we
99 // are expecting a response.
100 static RingBuffer<uint16_t, 2> resp_buf;
101
102 static bool process_queue_item(struct queue_item *item, uint16_t timeout);
103
104 enum sdep_type {
105 SdepCommand = 0x10,
106 SdepResponse = 0x20,
107 SdepAlert = 0x40,
108 SdepError = 0x80,
109 SdepSlaveNotReady = 0xfe, // Try again later
110 SdepSlaveOverflow = 0xff, // You read more data than is available
111 };
112
113 enum ble_cmd {
114 BleInitialize = 0xbeef,
115 BleAtWrapper = 0x0a00,
116 BleUartTx = 0x0a01,
117 BleUartRx = 0x0a02,
118 };
119
120 enum ble_system_event_bits {
121 BleSystemConnected = 0,
122 BleSystemDisconnected = 1,
123 BleSystemUartRx = 8,
124 BleSystemMidiRx = 10,
125 };
126
127 // The SDEP.md file says 2MHz but the web page and the sample driver
128 // both use 4MHz
129 #define SpiBusSpeed 4000000
130
131 #define SdepTimeout 150 /* milliseconds */
132 #define SdepShortTimeout 10 /* milliseconds */
133 #define SdepBackOff 25 /* microseconds */
134 #define BatteryUpdateInterval 10000 /* milliseconds */
135
136 static bool at_command(const char *cmd, char *resp, uint16_t resplen,
137 bool verbose, uint16_t timeout = SdepTimeout);
138 static bool at_command_P(const char *cmd, char *resp, uint16_t resplen,
139 bool verbose = false);
140
141 struct SPI_Settings {
142 uint8_t spcr, spsr;
143 };
144
145 static struct SPI_Settings spi;
146
147 // Initialize 4Mhz MSBFIRST MODE0
148 void SPI_init(struct SPI_Settings *spi) {
149 spi->spcr = _BV(SPE) | _BV(MSTR);
150 spi->spsr = _BV(SPI2X);
151
152 static_assert(SpiBusSpeed == F_CPU / 2, "hard coded at 4Mhz");
153
154 ATOMIC_BLOCK(ATOMIC_RESTORESTATE) {
155 // Ensure that SS is OUTPUT High
156 digitalWrite(B0, PinLevelHigh);
157 pinMode(B0, PinDirectionOutput);
158
159 SPCR |= _BV(MSTR);
160 SPCR |= _BV(SPE);
161 pinMode(B1 /* SCK */, PinDirectionOutput);
162 pinMode(B2 /* MOSI */, PinDirectionOutput);
163 }
164 }
165
166 static inline void SPI_begin(struct SPI_Settings*spi) {
167 SPCR = spi->spcr;
168 SPSR = spi->spsr;
169 }
170
171 static inline uint8_t SPI_TransferByte(uint8_t data) {
172 SPDR = data;
173 asm volatile("nop");
174 while (!(SPSR & _BV(SPIF))) {
175 ; // wait
176 }
177 return SPDR;
178 }
179
180 static inline void spi_send_bytes(const uint8_t *buf, uint8_t len) {
181 if (len == 0) return;
182 const uint8_t *end = buf + len;
183 while (buf < end) {
184 SPDR = *buf;
185 while (!(SPSR & _BV(SPIF))) {
186 ; // wait
187 }
188 ++buf;
189 }
190 }
191
192 static inline uint16_t spi_read_byte(void) {
193 return SPI_TransferByte(0x00 /* dummy */);
194 }
195
196 static inline void spi_recv_bytes(uint8_t *buf, uint8_t len) {
197 const uint8_t *end = buf + len;
198 if (len == 0) return;
199 while (buf < end) {
200 SPDR = 0; // write a dummy to initiate read
201 while (!(SPSR & _BV(SPIF))) {
202 ; // wait
203 }
204 *buf = SPDR;
205 ++buf;
206 }
207 }
208
209 #if 0
210 static void dump_pkt(const struct sdep_msg *msg) {
211 print("pkt: type=");
212 print_hex8(msg->type);
213 print(" cmd=");
214 print_hex8(msg->cmd_high);
215 print_hex8(msg->cmd_low);
216 print(" len=");
217 print_hex8(msg->len);
218 print(" more=");
219 print_hex8(msg->more);
220 print("\n");
221 }
222 #endif
223
224 // Send a single SDEP packet
225 static bool sdep_send_pkt(const struct sdep_msg *msg, uint16_t timeout) {
226 SPI_begin(&spi);
227
228 digitalWrite(AdafruitBleCSPin, PinLevelLow);
229 uint16_t timerStart = timer_read();
230 bool success = false;
231 bool ready = false;
232
233 do {
234 ready = SPI_TransferByte(msg->type) != SdepSlaveNotReady;
235 if (ready) {
236 break;
237 }
238
239 // Release it and let it initialize
240 digitalWrite(AdafruitBleCSPin, PinLevelHigh);
241 _delay_us(SdepBackOff);
242 digitalWrite(AdafruitBleCSPin, PinLevelLow);
243 } while (timer_elapsed(timerStart) < timeout);
244
245 if (ready) {
246 // Slave is ready; send the rest of the packet
247 spi_send_bytes(&msg->cmd_low,
248 sizeof(*msg) - (1 + sizeof(msg->payload)) + msg->len);
249 success = true;
250 }
251
252 digitalWrite(AdafruitBleCSPin, PinLevelHigh);
253
254 return success;
255 }
256
257 static inline void sdep_build_pkt(struct sdep_msg *msg, uint16_t command,
258 const uint8_t *payload, uint8_t len,
259 bool moredata) {
260 msg->type = SdepCommand;
261 msg->cmd_low = command & 0xff;
262 msg->cmd_high = command >> 8;
263 msg->len = len;
264 msg->more = (moredata && len == SdepMaxPayload) ? 1 : 0;
265
266 static_assert(sizeof(*msg) == 20, "msg is correctly packed");
267
268 memcpy(msg->payload, payload, len);
269 }
270
271 // Read a single SDEP packet
272 static bool sdep_recv_pkt(struct sdep_msg *msg, uint16_t timeout) {
273 bool success = false;
274 uint16_t timerStart = timer_read();
275 bool ready = false;
276
277 do {
278 ready = digitalRead(AdafruitBleIRQPin);
279 if (ready) {
280 break;
281 }
282 _delay_us(1);
283 } while (timer_elapsed(timerStart) < timeout);
284
285 if (ready) {
286 SPI_begin(&spi);
287
288 digitalWrite(AdafruitBleCSPin, PinLevelLow);
289
290 do {
291 // Read the command type, waiting for the data to be ready
292 msg->type = spi_read_byte();
293 if (msg->type == SdepSlaveNotReady || msg->type == SdepSlaveOverflow) {
294 // Release it and let it initialize
295 digitalWrite(AdafruitBleCSPin, PinLevelHigh);
296 _delay_us(SdepBackOff);
297 digitalWrite(AdafruitBleCSPin, PinLevelLow);
298 continue;
299 }
300
301 // Read the rest of the header
302 spi_recv_bytes(&msg->cmd_low, sizeof(*msg) - (1 + sizeof(msg->payload)));
303
304 // and get the payload if there is any
305 if (msg->len <= SdepMaxPayload) {
306 spi_recv_bytes(msg->payload, msg->len);
307 }
308 success = true;
309 break;
310 } while (timer_elapsed(timerStart) < timeout);
311
312 digitalWrite(AdafruitBleCSPin, PinLevelHigh);
313 }
314 return success;
315 }
316
317 static void resp_buf_read_one(bool greedy) {
318 uint16_t last_send;
319 if (!resp_buf.peek(last_send)) {
320 return;
321 }
322
323 if (digitalRead(AdafruitBleIRQPin)) {
324 struct sdep_msg msg;
325
326 again:
327 if (sdep_recv_pkt(&msg, SdepTimeout)) {
328 if (!msg.more) {
329 // We got it; consume this entry
330 resp_buf.get(last_send);
331 dprintf("recv latency %dms\n", TIMER_DIFF_16(timer_read(), last_send));
332 }
333
334 if (greedy && resp_buf.peek(last_send) && digitalRead(AdafruitBleIRQPin)) {
335 goto again;
336 }
337 }
338
339 } else if (timer_elapsed(last_send) > SdepTimeout * 2) {
340 dprintf("waiting_for_result: timeout, resp_buf size %d\n",
341 (int)resp_buf.size());
342
343 // Timed out: consume this entry
344 resp_buf.get(last_send);
345 }
346 }
347
348 static void send_buf_send_one(uint16_t timeout = SdepTimeout) {
349 struct queue_item item;
350
351 // Don't send anything more until we get an ACK
352 if (!resp_buf.empty()) {
353 return;
354 }
355
356 if (!send_buf.peek(item)) {
357 return;
358 }
359 if (process_queue_item(&item, timeout)) {
360 // commit that peek
361 send_buf.get(item);
362 dprintf("send_buf_send_one: have %d remaining\n", (int)send_buf.size());
363 } else {
364 dprint("failed to send, will retry\n");
365 _delay_ms(SdepTimeout);
366 resp_buf_read_one(true);
367 }
368 }
369
370 static void resp_buf_wait(const char *cmd) {
371 bool didPrint = false;
372 while (!resp_buf.empty()) {
373 if (!didPrint) {
374 dprintf("wait on buf for %s\n", cmd);
375 didPrint = true;
376 }
377 resp_buf_read_one(true);
378 }
379 }
380
381 static bool ble_init(void) {
382 state.initialized = false;
383 state.configured = false;
384 state.is_connected = false;
385
386 pinMode(AdafruitBleIRQPin, PinDirectionInput);
387 pinMode(AdafruitBleCSPin, PinDirectionOutput);
388 digitalWrite(AdafruitBleCSPin, PinLevelHigh);
389
390 SPI_init(&spi);
391
392 // Perform a hardware reset
393 pinMode(AdafruitBleResetPin, PinDirectionOutput);
394 digitalWrite(AdafruitBleResetPin, PinLevelHigh);
395 digitalWrite(AdafruitBleResetPin, PinLevelLow);
396 _delay_ms(10);
397 digitalWrite(AdafruitBleResetPin, PinLevelHigh);
398
399 _delay_ms(1000); // Give it a second to initialize
400
401 state.initialized = true;
402 return state.initialized;
403 }
404
405 static inline uint8_t min(uint8_t a, uint8_t b) {
406 return a < b ? a : b;
407 }
408
409 static bool read_response(char *resp, uint16_t resplen, bool verbose) {
410 char *dest = resp;
411 char *end = dest + resplen;
412
413 while (true) {
414 struct sdep_msg msg;
415
416 if (!sdep_recv_pkt(&msg, 2 * SdepTimeout)) {
417 dprint("sdep_recv_pkt failed\n");
418 return false;
419 }
420
421 if (msg.type != SdepResponse) {
422 *resp = 0;
423 return false;
424 }
425
426 uint8_t len = min(msg.len, end - dest);
427 if (len > 0) {
428 memcpy(dest, msg.payload, len);
429 dest += len;
430 }
431
432 if (!msg.more) {
433 // No more data is expected!
434 break;
435 }
436 }
437
438 // Ensure the response is NUL terminated
439 *dest = 0;
440
441 // "Parse" the result text; we want to snip off the trailing OK or ERROR line
442 // Rewind past the possible trailing CRLF so that we can strip it
443 --dest;
444 while (dest > resp && (dest[0] == '\n' || dest[0] == '\r')) {
445 *dest = 0;
446 --dest;
447 }
448
449 // Look back for start of preceeding line
450 char *last_line = strrchr(resp, '\n');
451 if (last_line) {
452 ++last_line;
453 } else {
454 last_line = resp;
455 }
456
457 bool success = false;
458 static const char kOK[] PROGMEM = "OK";
459
460 success = !strcmp_P(last_line, kOK );
461
462 if (verbose || !success) {
463 dprintf("result: %s\n", resp);
464 }
465 return success;
466 }
467
468 static bool at_command(const char *cmd, char *resp, uint16_t resplen,
469 bool verbose, uint16_t timeout) {
470 const char *end = cmd + strlen(cmd);
471 struct sdep_msg msg;
472
473 if (verbose) {
474 dprintf("ble send: %s\n", cmd);
475 }
476
477 if (resp) {
478 // They want to decode the response, so we need to flush and wait
479 // for all pending I/O to finish before we start this one, so
480 // that we don't confuse the results
481 resp_buf_wait(cmd);
482 *resp = 0;
483 }
484
485 // Fragment the command into a series of SDEP packets
486 while (end - cmd > SdepMaxPayload) {
487 sdep_build_pkt(&msg, BleAtWrapper, (uint8_t *)cmd, SdepMaxPayload, true);
488 if (!sdep_send_pkt(&msg, timeout)) {
489 return false;
490 }
491 cmd += SdepMaxPayload;
492 }
493
494 sdep_build_pkt(&msg, BleAtWrapper, (uint8_t *)cmd, end - cmd, false);
495 if (!sdep_send_pkt(&msg, timeout)) {
496 return false;
497 }
498
499 if (resp == NULL) {
500 auto now = timer_read();
501 while (!resp_buf.enqueue(now)) {
502 resp_buf_read_one(false);
503 }
504 auto later = timer_read();
505 if (TIMER_DIFF_16(later, now) > 0) {
506 dprintf("waited %dms for resp_buf\n", TIMER_DIFF_16(later, now));
507 }
508 return true;
509 }
510
511 return read_response(resp, resplen, verbose);
512 }
513
514 bool at_command_P(const char *cmd, char *resp, uint16_t resplen, bool verbose) {
515 auto cmdbuf = (char *)alloca(strlen_P(cmd) + 1);
516 strcpy_P(cmdbuf, cmd);
517 return at_command(cmdbuf, resp, resplen, verbose);
518 }
519
520 bool adafruit_ble_is_connected(void) {
521 return state.is_connected;
522 }
523
524 bool adafruit_ble_enable_keyboard(void) {
525 char resbuf[128];
526
527 if (!state.initialized && !ble_init()) {
528 return false;
529 }
530
531 state.configured = false;
532
533 // Disable command echo
534 static const char kEcho[] PROGMEM = "ATE=0";
535 // Make the advertised name match the keyboard
536 static const char kGapDevName[] PROGMEM =
537 "AT+GAPDEVNAME=" STR(PRODUCT) " " STR(DESCRIPTION);
538 // Turn on keyboard support
539 static const char kHidEnOn[] PROGMEM = "AT+BLEHIDEN=1";
540
541 // Adjust intervals to improve latency. This causes the "central"
542 // system (computer/tablet) to poll us every 10-30 ms. We can't
543 // set a smaller value than 10ms, and 30ms seems to be the natural
544 // processing time on my macbook. Keeping it constrained to that
545 // feels reasonable to type to.
546 static const char kGapIntervals[] PROGMEM = "AT+GAPINTERVALS=10,30,,";
547
548 // Reset the device so that it picks up the above changes
549 static const char kATZ[] PROGMEM = "ATZ";
550
551 // Turn down the power level a bit
552 static const char kPower[] PROGMEM = "AT+BLEPOWERLEVEL=-12";
553 static PGM_P const configure_commands[] PROGMEM = {
554 kEcho,
555 kGapIntervals,
556 kGapDevName,
557 kHidEnOn,
558 kPower,
559 kATZ,
560 };
561
562 uint8_t i;
563 for (i = 0; i < sizeof(configure_commands) / sizeof(configure_commands[0]);
564 ++i) {
565 PGM_P cmd;
566 memcpy_P(&cmd, configure_commands + i, sizeof(cmd));
567
568 if (!at_command_P(cmd, resbuf, sizeof(resbuf))) {
569 dprintf("failed BLE command: %S: %s\n", cmd, resbuf);
570 goto fail;
571 }
572 }
573
574 state.configured = true;
575
576 // Check connection status in a little while; allow the ATZ time
577 // to kick in.
578 state.last_connection_update = timer_read();
579 fail:
580 return state.configured;
581 }
582
583 static void set_connected(bool connected) {
584 if (connected != state.is_connected) {
585 if (connected) {
586 print("****** BLE CONNECT!!!!\n");
587 } else {
588 print("****** BLE DISCONNECT!!!!\n");
589 }
590 state.is_connected = connected;
591
592 // TODO: if modifiers are down on the USB interface and
593 // we cut over to BLE or vice versa, they will remain stuck.
594 // This feels like a good point to do something like clearing
595 // the keyboard and/or generating a fake all keys up message.
596 // However, I've noticed that it takes a couple of seconds
597 // for macOS to to start recognizing key presses after BLE
598 // is in the connected state, so I worry that doing that
599 // here may not be good enough.
600 }
601 }
602
603 void adafruit_ble_task(void) {
604 char resbuf[48];
605
606 if (!state.configured && !adafruit_ble_enable_keyboard()) {
607 return;
608 }
609 resp_buf_read_one(true);
610 send_buf_send_one(SdepShortTimeout);
611
612 if (resp_buf.empty() && (state.event_flags & UsingEvents) &&
613 digitalRead(AdafruitBleIRQPin)) {
614 // Must be an event update
615 if (at_command_P(PSTR("AT+EVENTSTATUS"), resbuf, sizeof(resbuf))) {
616 uint32_t mask = strtoul(resbuf, NULL, 16);
617
618 if (mask & BleSystemConnected) {
619 set_connected(true);
620 } else if (mask & BleSystemDisconnected) {
621 set_connected(false);
622 }
623 }
624 }
625
626 if (timer_elapsed(state.last_connection_update) > ConnectionUpdateInterval) {
627 bool shouldPoll = true;
628 if (!(state.event_flags & ProbedEvents)) {
629 // Request notifications about connection status changes.
630 // This only works in SPIFRIEND firmware > 0.6.7, which is why
631 // we check for this conditionally here.
632 // Note that at the time of writing, HID reports only work correctly
633 // with Apple products on firmware version 0.6.7!
634 // https://forums.adafruit.com/viewtopic.php?f=8&t=104052
635 if (at_command_P(PSTR("AT+EVENTENABLE=0x1"), resbuf, sizeof(resbuf))) {
636 at_command_P(PSTR("AT+EVENTENABLE=0x2"), resbuf, sizeof(resbuf));
637 state.event_flags |= UsingEvents;
638 }
639 state.event_flags |= ProbedEvents;
640
641 // leave shouldPoll == true so that we check at least once
642 // before relying solely on events
643 } else {
644 shouldPoll = false;
645 }
646
647 static const char kGetConn[] PROGMEM = "AT+GAPGETCONN";
648 state.last_connection_update = timer_read();
649
650 if (at_command_P(kGetConn, resbuf, sizeof(resbuf))) {
651 set_connected(atoi(resbuf));
652 }
653 }
654
655 #ifdef SAMPLE_BATTERY
656 // I don't know if this really does anything useful yet; the reported
657 // voltage level always seems to be around 3200mV. We may want to just rip
658 // this code out.
659 if (timer_elapsed(state.last_battery_update) > BatteryUpdateInterval &&
660 resp_buf.empty()) {
661 state.last_battery_update = timer_read();
662
663 if (at_command_P(PSTR("AT+HWVBAT"), resbuf, sizeof(resbuf))) {
664 state.vbat = atoi(resbuf);
665 }
666 }
667 #endif
668 }
669
670 static bool process_queue_item(struct queue_item *item, uint16_t timeout) {
671 char cmdbuf[48];
672 char fmtbuf[64];
673
674 // Arrange to re-check connection after keys have settled
675 state.last_connection_update = timer_read();
676
677 #if 1
678 if (TIMER_DIFF_16(state.last_connection_update, item->added) > 0) {
679 dprintf("send latency %dms\n",
680 TIMER_DIFF_16(state.last_connection_update, item->added));
681 }
682 #endif
683
684 switch (item->queue_type) {
685 case QTKeyReport:
686 strcpy_P(fmtbuf,
687 PSTR("AT+BLEKEYBOARDCODE=%02x-00-%02x-%02x-%02x-%02x-%02x-%02x"));
688 snprintf(cmdbuf, sizeof(cmdbuf), fmtbuf, item->key.modifier,
689 item->key.keys[0], item->key.keys[1], item->key.keys[2],
690 item->key.keys[3], item->key.keys[4], item->key.keys[5]);
691 return at_command(cmdbuf, NULL, 0, true, timeout);
692
693 case QTConsumer:
694 strcpy_P(fmtbuf, PSTR("AT+BLEHIDCONTROLKEY=0x%04x"));
695 snprintf(cmdbuf, sizeof(cmdbuf), fmtbuf, item->consumer);
696 return at_command(cmdbuf, NULL, 0, true, timeout);
697
698 #ifdef MOUSE_ENABLE
699 case QTMouseMove:
700 strcpy_P(fmtbuf, PSTR("AT+BLEHIDMOUSEMOVE=%d,%d,%d,%d"));
701 snprintf(cmdbuf, sizeof(cmdbuf), fmtbuf, item->mousemove.x,
702 item->mousemove.y, item->mousemove.scroll, item->mousemove.pan);
703 if (!at_command(cmdbuf, NULL, 0, true, timeout)) {
704 return false;
705 }
706 strcpy_P(cmdbuf, PSTR("AT+BLEHIDMOUSEBUTTON="));
707 if (item->mousemove.buttons & MOUSE_BTN1) {
708 strcat(cmdbuf, "L");
709 }
710 if (item->mousemove.buttons & MOUSE_BTN2) {
711 strcat(cmdbuf, "R");
712 }
713 if (item->mousemove.buttons & MOUSE_BTN3) {
714 strcat(cmdbuf, "M");
715 }
716 if (item->mousemove.buttons == 0) {
717 strcat(cmdbuf, "0");
718 }
719 return at_command(cmdbuf, NULL, 0, true, timeout);
720 #endif
721 default:
722 return true;
723 }
724 }
725
726 bool adafruit_ble_send_keys(uint8_t hid_modifier_mask, uint8_t *keys,
727 uint8_t nkeys) {
728 struct queue_item item;
729 bool didWait = false;
730
731 item.queue_type = QTKeyReport;
732 item.key.modifier = hid_modifier_mask;
733 item.added = timer_read();
734
735 while (nkeys >= 0) {
736 item.key.keys[0] = keys[0];
737 item.key.keys[1] = nkeys >= 1 ? keys[1] : 0;
738 item.key.keys[2] = nkeys >= 2 ? keys[2] : 0;
739 item.key.keys[3] = nkeys >= 3 ? keys[3] : 0;
740 item.key.keys[4] = nkeys >= 4 ? keys[4] : 0;
741 item.key.keys[5] = nkeys >= 5 ? keys[5] : 0;
742
743 if (!send_buf.enqueue(item)) {
744 if (!didWait) {
745 dprint("wait for buf space\n");
746 didWait = true;
747 }
748 send_buf_send_one();
749 continue;
750 }
751
752 if (nkeys <= 6) {
753 return true;
754 }
755
756 nkeys -= 6;
757 keys += 6;
758 }
759
760 return true;
761 }
762
763 bool adafruit_ble_send_consumer_key(uint16_t keycode, int hold_duration) {
764 struct queue_item item;
765
766 item.queue_type = QTConsumer;
767 item.consumer = keycode;
768
769 while (!send_buf.enqueue(item)) {
770 send_buf_send_one();
771 }
772 return true;
773 }
774
775 #ifdef MOUSE_ENABLE
776 bool adafruit_ble_send_mouse_move(int8_t x, int8_t y, int8_t scroll,
777 int8_t pan, uint8_t buttons) {
778 struct queue_item item;
779
780 item.queue_type = QTMouseMove;
781 item.mousemove.x = x;
782 item.mousemove.y = y;
783 item.mousemove.scroll = scroll;
784 item.mousemove.pan = pan;
785 item.mousemove.buttons = buttons;
786
787 while (!send_buf.enqueue(item)) {
788 send_buf_send_one();
789 }
790 return true;
791 }
792 #endif
793
794 uint32_t adafruit_ble_read_battery_voltage(void) {
795 return state.vbat;
796 }
797
798 bool adafruit_ble_set_mode_leds(bool on) {
799 if (!state.configured) {
800 return false;
801 }
802
803 // The "mode" led is the red blinky one
804 at_command_P(on ? PSTR("AT+HWMODELED=1") : PSTR("AT+HWMODELED=0"), NULL, 0);
805
806 // Pin 19 is the blue "connected" LED; turn that off too.
807 // When turning LEDs back on, don't turn that LED on if we're
808 // not connected, as that would be confusing.
809 at_command_P(on && state.is_connected ? PSTR("AT+HWGPIO=19,1")
810 : PSTR("AT+HWGPIO=19,0"),
811 NULL, 0);
812 return true;
813 }
814
815 // https://learn.adafruit.com/adafruit-feather-32u4-bluefruit-le/ble-generic#at-plus-blepowerlevel
816 bool adafruit_ble_set_power_level(int8_t level) {
817 char cmd[46];
818 if (!state.configured) {
819 return false;
820 }
821 snprintf(cmd, sizeof(cmd), "AT+BLEPOWERLEVEL=%d", level);
822 return at_command(cmd, NULL, 0, false);
823 }