Fix battery level code in adafruit_ble.cpp (#6648)
[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 #include "analog.h"
14
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
20 #endif
21
22 #ifndef AdafruitBleCSPin
23 # define AdafruitBleCSPin B4
24 #endif
25
26 #ifndef AdafruitBleIRQPin
27 # define AdafruitBleIRQPin E6
28 #endif
29
30 #define SAMPLE_BATTERY
31 #define ConnectionUpdateInterval 1000 /* milliseconds */
32
33 #ifdef SAMPLE_BATTERY
34 #ifndef BATTERY_LEVEL_PIN
35 # define BATTERY_LEVEL_PIN 7
36 #endif
37 #endif
38
39 static struct {
40 bool is_connected;
41 bool initialized;
42 bool configured;
43
44 #define ProbedEvents 1
45 #define UsingEvents 2
46 bool event_flags;
47
48 #ifdef SAMPLE_BATTERY
49 uint16_t last_battery_update;
50 uint32_t vbat;
51 #endif
52 uint16_t last_connection_update;
53 } state;
54
55 // Commands are encoded using SDEP and sent via SPI
56 // https://github.com/adafruit/Adafruit_BluefruitLE_nRF51/blob/master/SDEP.md
57
58 #define SdepMaxPayload 16
59 struct sdep_msg {
60 uint8_t type;
61 uint8_t cmd_low;
62 uint8_t cmd_high;
63 struct __attribute__((packed)) {
64 uint8_t len : 7;
65 uint8_t more : 1;
66 };
67 uint8_t payload[SdepMaxPayload];
68 } __attribute__((packed));
69
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
74 // information here.
75
76 enum queue_type {
77 QTKeyReport, // 1-byte modifier + 6-byte key report
78 QTConsumer, // 16-bit key code
79 #ifdef MOUSE_ENABLE
80 QTMouseMove, // 4-byte mouse report
81 #endif
82 };
83
84 struct queue_item {
85 enum queue_type queue_type;
86 uint16_t added;
87 union __attribute__((packed)) {
88 struct __attribute__((packed)) {
89 uint8_t modifier;
90 uint8_t keys[6];
91 } key;
92
93 uint16_t consumer;
94 struct __attribute__((packed)) {
95 int8_t x, y, scroll, pan;
96 uint8_t buttons;
97 } mousemove;
98 };
99 };
100
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;
107
108 static bool process_queue_item(struct queue_item *item, uint16_t timeout);
109
110 enum sdep_type {
111 SdepCommand = 0x10,
112 SdepResponse = 0x20,
113 SdepAlert = 0x40,
114 SdepError = 0x80,
115 SdepSlaveNotReady = 0xfe, // Try again later
116 SdepSlaveOverflow = 0xff, // You read more data than is available
117 };
118
119 enum ble_cmd {
120 BleInitialize = 0xbeef,
121 BleAtWrapper = 0x0a00,
122 BleUartTx = 0x0a01,
123 BleUartRx = 0x0a02,
124 };
125
126 enum ble_system_event_bits {
127 BleSystemConnected = 0,
128 BleSystemDisconnected = 1,
129 BleSystemUartRx = 8,
130 BleSystemMidiRx = 10,
131 };
132
133 // The SDEP.md file says 2MHz but the web page and the sample driver
134 // both use 4MHz
135 #define SpiBusSpeed 4000000
136
137 #define SdepTimeout 150 /* milliseconds */
138 #define SdepShortTimeout 10 /* milliseconds */
139 #define SdepBackOff 25 /* microseconds */
140 #define BatteryUpdateInterval 10000 /* milliseconds */
141
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);
144
145 struct SPI_Settings {
146 uint8_t spcr, spsr;
147 };
148
149 static struct SPI_Settings spi;
150
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);
155
156 static_assert(SpiBusSpeed == F_CPU / 2, "hard coded at 4Mhz");
157
158 ATOMIC_BLOCK(ATOMIC_RESTORESTATE) {
159 // Ensure that SS is OUTPUT High
160 digitalWrite(B0, PinLevelHigh);
161 pinMode(B0, PinDirectionOutput);
162
163 SPCR |= _BV(MSTR);
164 SPCR |= _BV(SPE);
165 pinMode(B1 /* SCK */, PinDirectionOutput);
166 pinMode(B2 /* MOSI */, PinDirectionOutput);
167 }
168 }
169
170 static inline void SPI_begin(struct SPI_Settings *spi) {
171 SPCR = spi->spcr;
172 SPSR = spi->spsr;
173 }
174
175 static inline uint8_t SPI_TransferByte(uint8_t data) {
176 SPDR = data;
177 asm volatile("nop");
178 while (!(SPSR & _BV(SPIF))) {
179 ; // wait
180 }
181 return SPDR;
182 }
183
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;
187 while (buf < end) {
188 SPDR = *buf;
189 while (!(SPSR & _BV(SPIF))) {
190 ; // wait
191 }
192 ++buf;
193 }
194 }
195
196 static inline uint16_t spi_read_byte(void) { return SPI_TransferByte(0x00 /* dummy */); }
197
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;
201 while (buf < end) {
202 SPDR = 0; // write a dummy to initiate read
203 while (!(SPSR & _BV(SPIF))) {
204 ; // wait
205 }
206 *buf = SPDR;
207 ++buf;
208 }
209 }
210
211 #if 0
212 static void dump_pkt(const struct sdep_msg *msg) {
213 print("pkt: type=");
214 print_hex8(msg->type);
215 print(" cmd=");
216 print_hex8(msg->cmd_high);
217 print_hex8(msg->cmd_low);
218 print(" len=");
219 print_hex8(msg->len);
220 print(" more=");
221 print_hex8(msg->more);
222 print("\n");
223 }
224 #endif
225
226 // Send a single SDEP packet
227 static bool sdep_send_pkt(const struct sdep_msg *msg, uint16_t timeout) {
228 SPI_begin(&spi);
229
230 digitalWrite(AdafruitBleCSPin, PinLevelLow);
231 uint16_t timerStart = timer_read();
232 bool success = false;
233 bool ready = false;
234
235 do {
236 ready = SPI_TransferByte(msg->type) != SdepSlaveNotReady;
237 if (ready) {
238 break;
239 }
240
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);
246
247 if (ready) {
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);
250 success = true;
251 }
252
253 digitalWrite(AdafruitBleCSPin, PinLevelHigh);
254
255 return success;
256 }
257
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;
262 msg->len = len;
263 msg->more = (moredata && len == SdepMaxPayload) ? 1 : 0;
264
265 static_assert(sizeof(*msg) == 20, "msg is correctly packed");
266
267 memcpy(msg->payload, payload, len);
268 }
269
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();
274 bool ready = false;
275
276 do {
277 ready = digitalRead(AdafruitBleIRQPin);
278 if (ready) {
279 break;
280 }
281 _delay_us(1);
282 } while (timer_elapsed(timerStart) < timeout);
283
284 if (ready) {
285 SPI_begin(&spi);
286
287 digitalWrite(AdafruitBleCSPin, PinLevelLow);
288
289 do {
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);
297 continue;
298 }
299
300 // Read the rest of the header
301 spi_recv_bytes(&msg->cmd_low, sizeof(*msg) - (1 + sizeof(msg->payload)));
302
303 // and get the payload if there is any
304 if (msg->len <= SdepMaxPayload) {
305 spi_recv_bytes(msg->payload, msg->len);
306 }
307 success = true;
308 break;
309 } while (timer_elapsed(timerStart) < timeout);
310
311 digitalWrite(AdafruitBleCSPin, PinLevelHigh);
312 }
313 return success;
314 }
315
316 static void resp_buf_read_one(bool greedy) {
317 uint16_t last_send;
318 if (!resp_buf.peek(last_send)) {
319 return;
320 }
321
322 if (digitalRead(AdafruitBleIRQPin)) {
323 struct sdep_msg msg;
324
325 again:
326 if (sdep_recv_pkt(&msg, SdepTimeout)) {
327 if (!msg.more) {
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));
331 }
332
333 if (greedy && resp_buf.peek(last_send) && digitalRead(AdafruitBleIRQPin)) {
334 goto again;
335 }
336 }
337
338 } else if (timer_elapsed(last_send) > SdepTimeout * 2) {
339 dprintf("waiting_for_result: timeout, resp_buf size %d\n", (int)resp_buf.size());
340
341 // Timed out: consume this entry
342 resp_buf.get(last_send);
343 }
344 }
345
346 static void send_buf_send_one(uint16_t timeout = SdepTimeout) {
347 struct queue_item item;
348
349 // Don't send anything more until we get an ACK
350 if (!resp_buf.empty()) {
351 return;
352 }
353
354 if (!send_buf.peek(item)) {
355 return;
356 }
357 if (process_queue_item(&item, timeout)) {
358 // commit that peek
359 send_buf.get(item);
360 dprintf("send_buf_send_one: have %d remaining\n", (int)send_buf.size());
361 } else {
362 dprint("failed to send, will retry\n");
363 _delay_ms(SdepTimeout);
364 resp_buf_read_one(true);
365 }
366 }
367
368 static void resp_buf_wait(const char *cmd) {
369 bool didPrint = false;
370 while (!resp_buf.empty()) {
371 if (!didPrint) {
372 dprintf("wait on buf for %s\n", cmd);
373 didPrint = true;
374 }
375 resp_buf_read_one(true);
376 }
377 }
378
379 static bool ble_init(void) {
380 state.initialized = false;
381 state.configured = false;
382 state.is_connected = false;
383
384 pinMode(AdafruitBleIRQPin, PinDirectionInput);
385 pinMode(AdafruitBleCSPin, PinDirectionOutput);
386 digitalWrite(AdafruitBleCSPin, PinLevelHigh);
387
388 SPI_init(&spi);
389
390 // Perform a hardware reset
391 pinMode(AdafruitBleResetPin, PinDirectionOutput);
392 digitalWrite(AdafruitBleResetPin, PinLevelHigh);
393 digitalWrite(AdafruitBleResetPin, PinLevelLow);
394 _delay_ms(10);
395 digitalWrite(AdafruitBleResetPin, PinLevelHigh);
396
397 _delay_ms(1000); // Give it a second to initialize
398
399 state.initialized = true;
400 return state.initialized;
401 }
402
403 static inline uint8_t min(uint8_t a, uint8_t b) { return a < b ? a : b; }
404
405 static bool read_response(char *resp, uint16_t resplen, bool verbose) {
406 char *dest = resp;
407 char *end = dest + resplen;
408
409 while (true) {
410 struct sdep_msg msg;
411
412 if (!sdep_recv_pkt(&msg, 2 * SdepTimeout)) {
413 dprint("sdep_recv_pkt failed\n");
414 return false;
415 }
416
417 if (msg.type != SdepResponse) {
418 *resp = 0;
419 return false;
420 }
421
422 uint8_t len = min(msg.len, end - dest);
423 if (len > 0) {
424 memcpy(dest, msg.payload, len);
425 dest += len;
426 }
427
428 if (!msg.more) {
429 // No more data is expected!
430 break;
431 }
432 }
433
434 // Ensure the response is NUL terminated
435 *dest = 0;
436
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
439 --dest;
440 while (dest > resp && (dest[0] == '\n' || dest[0] == '\r')) {
441 *dest = 0;
442 --dest;
443 }
444
445 // Look back for start of preceeding line
446 char *last_line = strrchr(resp, '\n');
447 if (last_line) {
448 ++last_line;
449 } else {
450 last_line = resp;
451 }
452
453 bool success = false;
454 static const char kOK[] PROGMEM = "OK";
455
456 success = !strcmp_P(last_line, kOK);
457
458 if (verbose || !success) {
459 dprintf("result: %s\n", resp);
460 }
461 return success;
462 }
463
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);
466 struct sdep_msg msg;
467
468 if (verbose) {
469 dprintf("ble send: %s\n", cmd);
470 }
471
472 if (resp) {
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
476 resp_buf_wait(cmd);
477 *resp = 0;
478 }
479
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)) {
484 return false;
485 }
486 cmd += SdepMaxPayload;
487 }
488
489 sdep_build_pkt(&msg, BleAtWrapper, (uint8_t *)cmd, end - cmd, false);
490 if (!sdep_send_pkt(&msg, timeout)) {
491 return false;
492 }
493
494 if (resp == NULL) {
495 auto now = timer_read();
496 while (!resp_buf.enqueue(now)) {
497 resp_buf_read_one(false);
498 }
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));
502 }
503 return true;
504 }
505
506 return read_response(resp, resplen, verbose);
507 }
508
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);
513 }
514
515 bool adafruit_ble_is_connected(void) { return state.is_connected; }
516
517 bool adafruit_ble_enable_keyboard(void) {
518 char resbuf[128];
519
520 if (!state.initialized && !ble_init()) {
521 return false;
522 }
523
524 state.configured = false;
525
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";
532
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,,";
539
540 // Reset the device so that it picks up the above changes
541 static const char kATZ[] PROGMEM = "ATZ";
542
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,
547 };
548
549 uint8_t i;
550 for (i = 0; i < sizeof(configure_commands) / sizeof(configure_commands[0]); ++i) {
551 PGM_P cmd;
552 memcpy_P(&cmd, configure_commands + i, sizeof(cmd));
553
554 if (!at_command_P(cmd, resbuf, sizeof(resbuf))) {
555 dprintf("failed BLE command: %S: %s\n", cmd, resbuf);
556 goto fail;
557 }
558 }
559
560 state.configured = true;
561
562 // Check connection status in a little while; allow the ATZ time
563 // to kick in.
564 state.last_connection_update = timer_read();
565 fail:
566 return state.configured;
567 }
568
569 static void set_connected(bool connected) {
570 if (connected != state.is_connected) {
571 if (connected) {
572 print("****** BLE CONNECT!!!!\n");
573 } else {
574 print("****** BLE DISCONNECT!!!!\n");
575 }
576 state.is_connected = connected;
577
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.
586 }
587 }
588
589 void adafruit_ble_task(void) {
590 char resbuf[48];
591
592 if (!state.configured && !adafruit_ble_enable_keyboard()) {
593 return;
594 }
595 resp_buf_read_one(true);
596 send_buf_send_one(SdepShortTimeout);
597
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);
602
603 if (mask & BleSystemConnected) {
604 set_connected(true);
605 } else if (mask & BleSystemDisconnected) {
606 set_connected(false);
607 }
608 }
609 }
610
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;
623 }
624 state.event_flags |= ProbedEvents;
625
626 // leave shouldPoll == true so that we check at least once
627 // before relying solely on events
628 } else {
629 shouldPoll = false;
630 }
631
632 static const char kGetConn[] PROGMEM = "AT+GAPGETCONN";
633 state.last_connection_update = timer_read();
634
635 if (at_command_P(kGetConn, resbuf, sizeof(resbuf))) {
636 set_connected(atoi(resbuf));
637 }
638 }
639
640 #ifdef SAMPLE_BATTERY
641 if (timer_elapsed(state.last_battery_update) > BatteryUpdateInterval && resp_buf.empty()) {
642 state.last_battery_update = timer_read();
643
644 state.vbat = analogRead(BATTERY_LEVEL_PIN);
645 }
646 #endif
647 }
648
649 static bool process_queue_item(struct queue_item *item, uint16_t timeout) {
650 char cmdbuf[48];
651 char fmtbuf[64];
652
653 // Arrange to re-check connection after keys have settled
654 state.last_connection_update = timer_read();
655
656 #if 1
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));
659 }
660 #endif
661
662 switch (item->queue_type) {
663 case QTKeyReport:
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);
667
668 case QTConsumer:
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);
672
673 #ifdef MOUSE_ENABLE
674 case QTMouseMove:
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)) {
678 return false;
679 }
680 strcpy_P(cmdbuf, PSTR("AT+BLEHIDMOUSEBUTTON="));
681 if (item->mousemove.buttons & MOUSE_BTN1) {
682 strcat(cmdbuf, "L");
683 }
684 if (item->mousemove.buttons & MOUSE_BTN2) {
685 strcat(cmdbuf, "R");
686 }
687 if (item->mousemove.buttons & MOUSE_BTN3) {
688 strcat(cmdbuf, "M");
689 }
690 if (item->mousemove.buttons == 0) {
691 strcat(cmdbuf, "0");
692 }
693 return at_command(cmdbuf, NULL, 0, true, timeout);
694 #endif
695 default:
696 return true;
697 }
698 }
699
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;
703
704 item.queue_type = QTKeyReport;
705 item.key.modifier = hid_modifier_mask;
706 item.added = timer_read();
707
708 while (nkeys >= 0) {
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;
715
716 if (!send_buf.enqueue(item)) {
717 if (!didWait) {
718 dprint("wait for buf space\n");
719 didWait = true;
720 }
721 send_buf_send_one();
722 continue;
723 }
724
725 if (nkeys <= 6) {
726 return true;
727 }
728
729 nkeys -= 6;
730 keys += 6;
731 }
732
733 return true;
734 }
735
736 bool adafruit_ble_send_consumer_key(uint16_t keycode, int hold_duration) {
737 struct queue_item item;
738
739 item.queue_type = QTConsumer;
740 item.consumer = keycode;
741
742 while (!send_buf.enqueue(item)) {
743 send_buf_send_one();
744 }
745 return true;
746 }
747
748 #ifdef MOUSE_ENABLE
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;
751
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;
758
759 while (!send_buf.enqueue(item)) {
760 send_buf_send_one();
761 }
762 return true;
763 }
764 #endif
765
766 uint32_t adafruit_ble_read_battery_voltage(void) { return state.vbat; }
767
768 bool adafruit_ble_set_mode_leds(bool on) {
769 if (!state.configured) {
770 return false;
771 }
772
773 // The "mode" led is the red blinky one
774 at_command_P(on ? PSTR("AT+HWMODELED=1") : PSTR("AT+HWMODELED=0"), NULL, 0);
775
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);
780 return true;
781 }
782
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) {
785 char cmd[46];
786 if (!state.configured) {
787 return false;
788 }
789 snprintf(cmd, sizeof(cmd), "AT+BLEPOWERLEVEL=%d", level);
790 return at_command(cmd, NULL, 0, false);
791 }