diff options
Diffstat (limited to 'drivers/bluetooth')
-rw-r--r-- | drivers/bluetooth/adafruit_ble.cpp | 699 | ||||
-rw-r--r-- | drivers/bluetooth/adafruit_ble.h | 59 | ||||
-rw-r--r-- | drivers/bluetooth/outputselect.c | 79 | ||||
-rw-r--r-- | drivers/bluetooth/outputselect.h | 34 | ||||
-rw-r--r-- | drivers/bluetooth/ringbuffer.hpp | 66 |
5 files changed, 937 insertions, 0 deletions
diff --git a/drivers/bluetooth/adafruit_ble.cpp b/drivers/bluetooth/adafruit_ble.cpp new file mode 100644 index 000000000..34a780e9a --- /dev/null +++ b/drivers/bluetooth/adafruit_ble.cpp | |||
@@ -0,0 +1,699 @@ | |||
1 | #include "adafruit_ble.h" | ||
2 | |||
3 | #include <stdio.h> | ||
4 | #include <stdlib.h> | ||
5 | #include <alloca.h> | ||
6 | #include "debug.h" | ||
7 | #include "timer.h" | ||
8 | #include "action_util.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 ADAFRUIT_BLE_RST_PIN | ||
20 | # define ADAFRUIT_BLE_RST_PIN D4 | ||
21 | #endif | ||
22 | |||
23 | #ifndef ADAFRUIT_BLE_CS_PIN | ||
24 | # define ADAFRUIT_BLE_CS_PIN B4 | ||
25 | #endif | ||
26 | |||
27 | #ifndef ADAFRUIT_BLE_IRQ_PIN | ||
28 | # define ADAFRUIT_BLE_IRQ_PIN E6 | ||
29 | #endif | ||
30 | |||
31 | #ifndef ADAFRUIT_BLE_SCK_DIVISOR | ||
32 | # define ADAFRUIT_BLE_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 | |||
42 | static 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 | ||
62 | struct 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 | |||
79 | enum queue_type { | ||
80 | QTKeyReport, // 1-byte modifier + 6-byte key report | ||
81 | QTConsumer, // 16-bit key code | ||
82 | #ifdef MOUSE_ENABLE | ||
83 | QTMouseMove, // 4-byte mouse report | ||
84 | #endif | ||
85 | }; | ||
86 | |||
87 | struct queue_item { | ||
88 | enum queue_type queue_type; | ||
89 | uint16_t added; | ||
90 | union __attribute__((packed)) { | ||
91 | struct __attribute__((packed)) { | ||
92 | uint8_t modifier; | ||
93 | uint8_t keys[6]; | ||
94 | } key; | ||
95 | |||
96 | uint16_t consumer; | ||
97 | struct __attribute__((packed)) { | ||
98 | int8_t x, y, scroll, pan; | ||
99 | uint8_t buttons; | ||
100 | } mousemove; | ||
101 | }; | ||
102 | }; | ||
103 | |||
104 | // Items that we wish to send | ||
105 | static RingBuffer<queue_item, 40> send_buf; | ||
106 | // Pending response; while pending, we can't send any more requests. | ||
107 | // This records the time at which we sent the command for which we | ||
108 | // are expecting a response. | ||
109 | static RingBuffer<uint16_t, 2> resp_buf; | ||
110 | |||
111 | static bool process_queue_item(struct queue_item *item, uint16_t timeout); | ||
112 | |||
113 | enum sdep_type { | ||
114 | SdepCommand = 0x10, | ||
115 | SdepResponse = 0x20, | ||
116 | SdepAlert = 0x40, | ||
117 | SdepError = 0x80, | ||
118 | SdepSlaveNotReady = 0xFE, // Try again later | ||
119 | SdepSlaveOverflow = 0xFF, // You read more data than is available | ||
120 | }; | ||
121 | |||
122 | enum ble_cmd { | ||
123 | BleInitialize = 0xBEEF, | ||
124 | BleAtWrapper = 0x0A00, | ||
125 | BleUartTx = 0x0A01, | ||
126 | BleUartRx = 0x0A02, | ||
127 | }; | ||
128 | |||
129 | enum ble_system_event_bits { | ||
130 | BleSystemConnected = 0, | ||
131 | BleSystemDisconnected = 1, | ||
132 | BleSystemUartRx = 8, | ||
133 | BleSystemMidiRx = 10, | ||
134 | }; | ||
135 | |||
136 | #define SdepTimeout 150 /* milliseconds */ | ||
137 | #define SdepShortTimeout 10 /* milliseconds */ | ||
138 | #define SdepBackOff 25 /* microseconds */ | ||
139 | #define BatteryUpdateInterval 10000 /* milliseconds */ | ||
140 | |||
141 | static bool at_command(const char *cmd, char *resp, uint16_t resplen, bool verbose, uint16_t timeout = SdepTimeout); | ||
142 | static bool at_command_P(const char *cmd, char *resp, uint16_t resplen, bool verbose = false); | ||
143 | |||
144 | // Send a single SDEP packet | ||
145 | static bool sdep_send_pkt(const struct sdep_msg *msg, uint16_t timeout) { | ||
146 | spi_start(ADAFRUIT_BLE_CS_PIN, false, 0, ADAFRUIT_BLE_SCK_DIVISOR); | ||
147 | uint16_t timerStart = timer_read(); | ||
148 | bool success = false; | ||
149 | bool ready = false; | ||
150 | |||
151 | do { | ||
152 | ready = spi_write(msg->type) != SdepSlaveNotReady; | ||
153 | if (ready) { | ||
154 | break; | ||
155 | } | ||
156 | |||
157 | // Release it and let it initialize | ||
158 | spi_stop(); | ||
159 | wait_us(SdepBackOff); | ||
160 | spi_start(ADAFRUIT_BLE_CS_PIN, false, 0, ADAFRUIT_BLE_SCK_DIVISOR); | ||
161 | } while (timer_elapsed(timerStart) < timeout); | ||
162 | |||
163 | if (ready) { | ||
164 | // Slave is ready; send the rest of the packet | ||
165 | spi_transmit(&msg->cmd_low, sizeof(*msg) - (1 + sizeof(msg->payload)) + msg->len); | ||
166 | success = true; | ||
167 | } | ||
168 | |||
169 | spi_stop(); | ||
170 | |||
171 | return success; | ||
172 | } | ||
173 | |||
174 | static inline void sdep_build_pkt(struct sdep_msg *msg, uint16_t command, const uint8_t *payload, uint8_t len, bool moredata) { | ||
175 | msg->type = SdepCommand; | ||
176 | msg->cmd_low = command & 0xFF; | ||
177 | msg->cmd_high = command >> 8; | ||
178 | msg->len = len; | ||
179 | msg->more = (moredata && len == SdepMaxPayload) ? 1 : 0; | ||
180 | |||
181 | static_assert(sizeof(*msg) == 20, "msg is correctly packed"); | ||
182 | |||
183 | memcpy(msg->payload, payload, len); | ||
184 | } | ||
185 | |||
186 | // Read a single SDEP packet | ||
187 | static bool sdep_recv_pkt(struct sdep_msg *msg, uint16_t timeout) { | ||
188 | bool success = false; | ||
189 | uint16_t timerStart = timer_read(); | ||
190 | bool ready = false; | ||
191 | |||
192 | do { | ||
193 | ready = readPin(ADAFRUIT_BLE_IRQ_PIN); | ||
194 | if (ready) { | ||
195 | break; | ||
196 | } | ||
197 | wait_us(1); | ||
198 | } while (timer_elapsed(timerStart) < timeout); | ||
199 | |||
200 | if (ready) { | ||
201 | spi_start(ADAFRUIT_BLE_CS_PIN, false, 0, ADAFRUIT_BLE_SCK_DIVISOR); | ||
202 | |||
203 | do { | ||
204 | // Read the command type, waiting for the data to be ready | ||
205 | msg->type = spi_read(); | ||
206 | if (msg->type == SdepSlaveNotReady || msg->type == SdepSlaveOverflow) { | ||
207 | // Release it and let it initialize | ||
208 | spi_stop(); | ||
209 | wait_us(SdepBackOff); | ||
210 | spi_start(ADAFRUIT_BLE_CS_PIN, false, 0, ADAFRUIT_BLE_SCK_DIVISOR); | ||
211 | continue; | ||
212 | } | ||
213 | |||
214 | // Read the rest of the header | ||
215 | spi_receive(&msg->cmd_low, sizeof(*msg) - (1 + sizeof(msg->payload))); | ||
216 | |||
217 | // and get the payload if there is any | ||
218 | if (msg->len <= SdepMaxPayload) { | ||
219 | spi_receive(msg->payload, msg->len); | ||
220 | } | ||
221 | success = true; | ||
222 | break; | ||
223 | } while (timer_elapsed(timerStart) < timeout); | ||
224 | |||
225 | spi_stop(); | ||
226 | } | ||
227 | return success; | ||
228 | } | ||
229 | |||
230 | static void resp_buf_read_one(bool greedy) { | ||
231 | uint16_t last_send; | ||
232 | if (!resp_buf.peek(last_send)) { | ||
233 | return; | ||
234 | } | ||
235 | |||
236 | if (readPin(ADAFRUIT_BLE_IRQ_PIN)) { | ||
237 | struct sdep_msg msg; | ||
238 | |||
239 | again: | ||
240 | if (sdep_recv_pkt(&msg, SdepTimeout)) { | ||
241 | if (!msg.more) { | ||
242 | // We got it; consume this entry | ||
243 | resp_buf.get(last_send); | ||
244 | dprintf("recv latency %dms\n", TIMER_DIFF_16(timer_read(), last_send)); | ||
245 | } | ||
246 | |||
247 | if (greedy && resp_buf.peek(last_send) && readPin(ADAFRUIT_BLE_IRQ_PIN)) { | ||
248 | goto again; | ||
249 | } | ||
250 | } | ||
251 | |||
252 | } else if (timer_elapsed(last_send) > SdepTimeout * 2) { | ||
253 | dprintf("waiting_for_result: timeout, resp_buf size %d\n", (int)resp_buf.size()); | ||
254 | |||
255 | // Timed out: consume this entry | ||
256 | resp_buf.get(last_send); | ||
257 | } | ||
258 | } | ||
259 | |||
260 | static void send_buf_send_one(uint16_t timeout = SdepTimeout) { | ||
261 | struct queue_item item; | ||
262 | |||
263 | // Don't send anything more until we get an ACK | ||
264 | if (!resp_buf.empty()) { | ||
265 | return; | ||
266 | } | ||
267 | |||
268 | if (!send_buf.peek(item)) { | ||
269 | return; | ||
270 | } | ||
271 | if (process_queue_item(&item, timeout)) { | ||
272 | // commit that peek | ||
273 | send_buf.get(item); | ||
274 | dprintf("send_buf_send_one: have %d remaining\n", (int)send_buf.size()); | ||
275 | } else { | ||
276 | dprint("failed to send, will retry\n"); | ||
277 | wait_ms(SdepTimeout); | ||
278 | resp_buf_read_one(true); | ||
279 | } | ||
280 | } | ||
281 | |||
282 | static void resp_buf_wait(const char *cmd) { | ||
283 | bool didPrint = false; | ||
284 | while (!resp_buf.empty()) { | ||
285 | if (!didPrint) { | ||
286 | dprintf("wait on buf for %s\n", cmd); | ||
287 | didPrint = true; | ||
288 | } | ||
289 | resp_buf_read_one(true); | ||
290 | } | ||
291 | } | ||
292 | |||
293 | static bool ble_init(void) { | ||
294 | state.initialized = false; | ||
295 | state.configured = false; | ||
296 | state.is_connected = false; | ||
297 | |||
298 | setPinInput(ADAFRUIT_BLE_IRQ_PIN); | ||
299 | |||
300 | spi_init(); | ||
301 | |||
302 | // Perform a hardware reset | ||
303 | setPinOutput(ADAFRUIT_BLE_RST_PIN); | ||
304 | writePinHigh(ADAFRUIT_BLE_RST_PIN); | ||
305 | writePinLow(ADAFRUIT_BLE_RST_PIN); | ||
306 | wait_ms(10); | ||
307 | writePinHigh(ADAFRUIT_BLE_RST_PIN); | ||
308 | |||
309 | wait_ms(1000); // Give it a second to initialize | ||
310 | |||
311 | state.initialized = true; | ||
312 | return state.initialized; | ||
313 | } | ||
314 | |||
315 | static inline uint8_t min(uint8_t a, uint8_t b) { return a < b ? a : b; } | ||
316 | |||
317 | static bool read_response(char *resp, uint16_t resplen, bool verbose) { | ||
318 | char *dest = resp; | ||
319 | char *end = dest + resplen; | ||
320 | |||
321 | while (true) { | ||
322 | struct sdep_msg msg; | ||
323 | |||
324 | if (!sdep_recv_pkt(&msg, 2 * SdepTimeout)) { | ||
325 | dprint("sdep_recv_pkt failed\n"); | ||
326 | return false; | ||
327 | } | ||
328 | |||
329 | if (msg.type != SdepResponse) { | ||
330 | *resp = 0; | ||
331 | return false; | ||
332 | } | ||
333 | |||
334 | uint8_t len = min(msg.len, end - dest); | ||
335 | if (len > 0) { | ||
336 | memcpy(dest, msg.payload, len); | ||
337 | dest += len; | ||
338 | } | ||
339 | |||
340 | if (!msg.more) { | ||
341 | // No more data is expected! | ||
342 | break; | ||
343 | } | ||
344 | } | ||
345 | |||
346 | // Ensure the response is NUL terminated | ||
347 | *dest = 0; | ||
348 | |||
349 | // "Parse" the result text; we want to snip off the trailing OK or ERROR line | ||
350 | // Rewind past the possible trailing CRLF so that we can strip it | ||
351 | --dest; | ||
352 | while (dest > resp && (dest[0] == '\n' || dest[0] == '\r')) { | ||
353 | *dest = 0; | ||
354 | --dest; | ||
355 | } | ||
356 | |||
357 | // Look back for start of preceeding line | ||
358 | char *last_line = strrchr(resp, '\n'); | ||
359 | if (last_line) { | ||
360 | ++last_line; | ||
361 | } else { | ||
362 | last_line = resp; | ||
363 | } | ||
364 | |||
365 | bool success = false; | ||
366 | static const char kOK[] PROGMEM = "OK"; | ||
367 | |||
368 | success = !strcmp_P(last_line, kOK); | ||
369 | |||
370 | if (verbose || !success) { | ||
371 | dprintf("result: %s\n", resp); | ||
372 | } | ||
373 | return success; | ||
374 | } | ||
375 | |||
376 | static bool at_command(const char *cmd, char *resp, uint16_t resplen, bool verbose, uint16_t timeout) { | ||
377 | const char * end = cmd + strlen(cmd); | ||
378 | struct sdep_msg msg; | ||
379 | |||
380 | if (verbose) { | ||
381 | dprintf("ble send: %s\n", cmd); | ||
382 | } | ||
383 | |||
384 | if (resp) { | ||
385 | // They want to decode the response, so we need to flush and wait | ||
386 | // for all pending I/O to finish before we start this one, so | ||
387 | // that we don't confuse the results | ||
388 | resp_buf_wait(cmd); | ||
389 | *resp = 0; | ||
390 | } | ||
391 | |||
392 | // Fragment the command into a series of SDEP packets | ||
393 | while (end - cmd > SdepMaxPayload) { | ||
394 | sdep_build_pkt(&msg, BleAtWrapper, (uint8_t *)cmd, SdepMaxPayload, true); | ||
395 | if (!sdep_send_pkt(&msg, timeout)) { | ||
396 | return false; | ||
397 | } | ||
398 | cmd += SdepMaxPayload; | ||
399 | } | ||
400 | |||
401 | sdep_build_pkt(&msg, BleAtWrapper, (uint8_t *)cmd, end - cmd, false); | ||
402 | if (!sdep_send_pkt(&msg, timeout)) { | ||
403 | return false; | ||
404 | } | ||
405 | |||
406 | if (resp == NULL) { | ||
407 | uint16_t now = timer_read(); | ||
408 | while (!resp_buf.enqueue(now)) { | ||
409 | resp_buf_read_one(false); | ||
410 | } | ||
411 | uint16_t later = timer_read(); | ||
412 | if (TIMER_DIFF_16(later, now) > 0) { | ||
413 | dprintf("waited %dms for resp_buf\n", TIMER_DIFF_16(later, now)); | ||
414 | } | ||
415 | return true; | ||
416 | } | ||
417 | |||
418 | return read_response(resp, resplen, verbose); | ||
419 | } | ||
420 | |||
421 | bool at_command_P(const char *cmd, char *resp, uint16_t resplen, bool verbose) { | ||
422 | char *cmdbuf = (char *)alloca(strlen_P(cmd) + 1); | ||
423 | strcpy_P(cmdbuf, cmd); | ||
424 | return at_command(cmdbuf, resp, resplen, verbose); | ||
425 | } | ||
426 | |||
427 | bool adafruit_ble_is_connected(void) { return state.is_connected; } | ||
428 | |||
429 | bool adafruit_ble_enable_keyboard(void) { | ||
430 | char resbuf[128]; | ||
431 | |||
432 | if (!state.initialized && !ble_init()) { | ||
433 | return false; | ||
434 | } | ||
435 | |||
436 | state.configured = false; | ||
437 | |||
438 | // Disable command echo | ||
439 | static const char kEcho[] PROGMEM = "ATE=0"; | ||
440 | // Make the advertised name match the keyboard | ||
441 | static const char kGapDevName[] PROGMEM = "AT+GAPDEVNAME=" STR(PRODUCT); | ||
442 | // Turn on keyboard support | ||
443 | static const char kHidEnOn[] PROGMEM = "AT+BLEHIDEN=1"; | ||
444 | |||
445 | // Adjust intervals to improve latency. This causes the "central" | ||
446 | // system (computer/tablet) to poll us every 10-30 ms. We can't | ||
447 | // set a smaller value than 10ms, and 30ms seems to be the natural | ||
448 | // processing time on my macbook. Keeping it constrained to that | ||
449 | // feels reasonable to type to. | ||
450 | static const char kGapIntervals[] PROGMEM = "AT+GAPINTERVALS=10,30,,"; | ||
451 | |||
452 | // Reset the device so that it picks up the above changes | ||
453 | static const char kATZ[] PROGMEM = "ATZ"; | ||
454 | |||
455 | // Turn down the power level a bit | ||
456 | static const char kPower[] PROGMEM = "AT+BLEPOWERLEVEL=-12"; | ||
457 | static PGM_P const configure_commands[] PROGMEM = { | ||
458 | kEcho, kGapIntervals, kGapDevName, kHidEnOn, kPower, kATZ, | ||
459 | }; | ||
460 | |||
461 | uint8_t i; | ||
462 | for (i = 0; i < sizeof(configure_commands) / sizeof(configure_commands[0]); ++i) { | ||
463 | PGM_P cmd; | ||
464 | memcpy_P(&cmd, configure_commands + i, sizeof(cmd)); | ||
465 | |||
466 | if (!at_command_P(cmd, resbuf, sizeof(resbuf))) { | ||
467 | dprintf("failed BLE command: %S: %s\n", cmd, resbuf); | ||
468 | goto fail; | ||
469 | } | ||
470 | } | ||
471 | |||
472 | state.configured = true; | ||
473 | |||
474 | // Check connection status in a little while; allow the ATZ time | ||
475 | // to kick in. | ||
476 | state.last_connection_update = timer_read(); | ||
477 | fail: | ||
478 | return state.configured; | ||
479 | } | ||
480 | |||
481 | static void set_connected(bool connected) { | ||
482 | if (connected != state.is_connected) { | ||
483 | if (connected) { | ||
484 | dprint("BLE connected\n"); | ||
485 | } else { | ||
486 | dprint("BLE disconnected\n"); | ||
487 | } | ||
488 | state.is_connected = connected; | ||
489 | |||
490 | // TODO: if modifiers are down on the USB interface and | ||
491 | // we cut over to BLE or vice versa, they will remain stuck. | ||
492 | // This feels like a good point to do something like clearing | ||
493 | // the keyboard and/or generating a fake all keys up message. | ||
494 | // However, I've noticed that it takes a couple of seconds | ||
495 | // for macOS to to start recognizing key presses after BLE | ||
496 | // is in the connected state, so I worry that doing that | ||
497 | // here may not be good enough. | ||
498 | } | ||
499 | } | ||
500 | |||
501 | void adafruit_ble_task(void) { | ||
502 | char resbuf[48]; | ||
503 | |||
504 | if (!state.configured && !adafruit_ble_enable_keyboard()) { | ||
505 | return; | ||
506 | } | ||
507 | resp_buf_read_one(true); | ||
508 | send_buf_send_one(SdepShortTimeout); | ||
509 | |||
510 | if (resp_buf.empty() && (state.event_flags & UsingEvents) && readPin(ADAFRUIT_BLE_IRQ_PIN)) { | ||
511 | // Must be an event update | ||
512 | if (at_command_P(PSTR("AT+EVENTSTATUS"), resbuf, sizeof(resbuf))) { | ||
513 | uint32_t mask = strtoul(resbuf, NULL, 16); | ||
514 | |||
515 | if (mask & BleSystemConnected) { | ||
516 | set_connected(true); | ||
517 | } else if (mask & BleSystemDisconnected) { | ||
518 | set_connected(false); | ||
519 | } | ||
520 | } | ||
521 | } | ||
522 | |||
523 | if (timer_elapsed(state.last_connection_update) > ConnectionUpdateInterval) { | ||
524 | bool shouldPoll = true; | ||
525 | if (!(state.event_flags & ProbedEvents)) { | ||
526 | // Request notifications about connection status changes. | ||
527 | // This only works in SPIFRIEND firmware > 0.6.7, which is why | ||
528 | // we check for this conditionally here. | ||
529 | // Note that at the time of writing, HID reports only work correctly | ||
530 | // with Apple products on firmware version 0.6.7! | ||
531 | // https://forums.adafruit.com/viewtopic.php?f=8&t=104052 | ||
532 | if (at_command_P(PSTR("AT+EVENTENABLE=0x1"), resbuf, sizeof(resbuf))) { | ||
533 | at_command_P(PSTR("AT+EVENTENABLE=0x2"), resbuf, sizeof(resbuf)); | ||
534 | state.event_flags |= UsingEvents; | ||
535 | } | ||
536 | state.event_flags |= ProbedEvents; | ||
537 | |||
538 | // leave shouldPoll == true so that we check at least once | ||
539 | // before relying solely on events | ||
540 | } else { | ||
541 | shouldPoll = false; | ||
542 | } | ||
543 | |||
544 | static const char kGetConn[] PROGMEM = "AT+GAPGETCONN"; | ||
545 | state.last_connection_update = timer_read(); | ||
546 | |||
547 | if (at_command_P(kGetConn, resbuf, sizeof(resbuf))) { | ||
548 | set_connected(atoi(resbuf)); | ||
549 | } | ||
550 | } | ||
551 | |||
552 | #ifdef SAMPLE_BATTERY | ||
553 | if (timer_elapsed(state.last_battery_update) > BatteryUpdateInterval && resp_buf.empty()) { | ||
554 | state.last_battery_update = timer_read(); | ||
555 | |||
556 | state.vbat = analogReadPin(BATTERY_LEVEL_PIN); | ||
557 | } | ||
558 | #endif | ||
559 | } | ||
560 | |||
561 | static bool process_queue_item(struct queue_item *item, uint16_t timeout) { | ||
562 | char cmdbuf[48]; | ||
563 | char fmtbuf[64]; | ||
564 | |||
565 | // Arrange to re-check connection after keys have settled | ||
566 | state.last_connection_update = timer_read(); | ||
567 | |||
568 | #if 1 | ||
569 | if (TIMER_DIFF_16(state.last_connection_update, item->added) > 0) { | ||
570 | dprintf("send latency %dms\n", TIMER_DIFF_16(state.last_connection_update, item->added)); | ||
571 | } | ||
572 | #endif | ||
573 | |||
574 | switch (item->queue_type) { | ||
575 | case QTKeyReport: | ||
576 | strcpy_P(fmtbuf, PSTR("AT+BLEKEYBOARDCODE=%02x-00-%02x-%02x-%02x-%02x-%02x-%02x")); | ||
577 | 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]); | ||
578 | return at_command(cmdbuf, NULL, 0, true, timeout); | ||
579 | |||
580 | case QTConsumer: | ||
581 | strcpy_P(fmtbuf, PSTR("AT+BLEHIDCONTROLKEY=0x%04x")); | ||
582 | snprintf(cmdbuf, sizeof(cmdbuf), fmtbuf, item->consumer); | ||
583 | return at_command(cmdbuf, NULL, 0, true, timeout); | ||
584 | |||
585 | #ifdef MOUSE_ENABLE | ||
586 | case QTMouseMove: | ||
587 | strcpy_P(fmtbuf, PSTR("AT+BLEHIDMOUSEMOVE=%d,%d,%d,%d")); | ||
588 | snprintf(cmdbuf, sizeof(cmdbuf), fmtbuf, item->mousemove.x, item->mousemove.y, item->mousemove.scroll, item->mousemove.pan); | ||
589 | if (!at_command(cmdbuf, NULL, 0, true, timeout)) { | ||
590 | return false; | ||
591 | } | ||
592 | strcpy_P(cmdbuf, PSTR("AT+BLEHIDMOUSEBUTTON=")); | ||
593 | if (item->mousemove.buttons & MOUSE_BTN1) { | ||
594 | strcat(cmdbuf, "L"); | ||
595 | } | ||
596 | if (item->mousemove.buttons & MOUSE_BTN2) { | ||
597 | strcat(cmdbuf, "R"); | ||
598 | } | ||
599 | if (item->mousemove.buttons & MOUSE_BTN3) { | ||
600 | strcat(cmdbuf, "M"); | ||
601 | } | ||
602 | if (item->mousemove.buttons == 0) { | ||
603 | strcat(cmdbuf, "0"); | ||
604 | } | ||
605 | return at_command(cmdbuf, NULL, 0, true, timeout); | ||
606 | #endif | ||
607 | default: | ||
608 | return true; | ||
609 | } | ||
610 | } | ||
611 | |||
612 | void adafruit_ble_send_keys(uint8_t hid_modifier_mask, uint8_t *keys, uint8_t nkeys) { | ||
613 | struct queue_item item; | ||
614 | bool didWait = false; | ||
615 | |||
616 | item.queue_type = QTKeyReport; | ||
617 | item.key.modifier = hid_modifier_mask; | ||
618 | item.added = timer_read(); | ||
619 | |||
620 | while (nkeys >= 0) { | ||
621 | item.key.keys[0] = keys[0]; | ||
622 | item.key.keys[1] = nkeys >= 1 ? keys[1] : 0; | ||
623 | item.key.keys[2] = nkeys >= 2 ? keys[2] : 0; | ||
624 | item.key.keys[3] = nkeys >= 3 ? keys[3] : 0; | ||
625 | item.key.keys[4] = nkeys >= 4 ? keys[4] : 0; | ||
626 | item.key.keys[5] = nkeys >= 5 ? keys[5] : 0; | ||
627 | |||
628 | if (!send_buf.enqueue(item)) { | ||
629 | if (!didWait) { | ||
630 | dprint("wait for buf space\n"); | ||
631 | didWait = true; | ||
632 | } | ||
633 | send_buf_send_one(); | ||
634 | continue; | ||
635 | } | ||
636 | |||
637 | if (nkeys <= 6) { | ||
638 | return; | ||
639 | } | ||
640 | |||
641 | nkeys -= 6; | ||
642 | keys += 6; | ||
643 | } | ||
644 | } | ||
645 | |||
646 | void adafruit_ble_send_consumer_key(uint16_t usage) { | ||
647 | struct queue_item item; | ||
648 | |||
649 | item.queue_type = QTConsumer; | ||
650 | item.consumer = usage; | ||
651 | |||
652 | while (!send_buf.enqueue(item)) { | ||
653 | send_buf_send_one(); | ||
654 | } | ||
655 | } | ||
656 | |||
657 | #ifdef MOUSE_ENABLE | ||
658 | void adafruit_ble_send_mouse_move(int8_t x, int8_t y, int8_t scroll, int8_t pan, uint8_t buttons) { | ||
659 | struct queue_item item; | ||
660 | |||
661 | item.queue_type = QTMouseMove; | ||
662 | item.mousemove.x = x; | ||
663 | item.mousemove.y = y; | ||
664 | item.mousemove.scroll = scroll; | ||
665 | item.mousemove.pan = pan; | ||
666 | item.mousemove.buttons = buttons; | ||
667 | |||
668 | while (!send_buf.enqueue(item)) { | ||
669 | send_buf_send_one(); | ||
670 | } | ||
671 | } | ||
672 | #endif | ||
673 | |||
674 | uint32_t adafruit_ble_read_battery_voltage(void) { return state.vbat; } | ||
675 | |||
676 | bool adafruit_ble_set_mode_leds(bool on) { | ||
677 | if (!state.configured) { | ||
678 | return false; | ||
679 | } | ||
680 | |||
681 | // The "mode" led is the red blinky one | ||
682 | at_command_P(on ? PSTR("AT+HWMODELED=1") : PSTR("AT+HWMODELED=0"), NULL, 0); | ||
683 | |||
684 | // Pin 19 is the blue "connected" LED; turn that off too. | ||
685 | // When turning LEDs back on, don't turn that LED on if we're | ||
686 | // not connected, as that would be confusing. | ||
687 | at_command_P(on && state.is_connected ? PSTR("AT+HWGPIO=19,1") : PSTR("AT+HWGPIO=19,0"), NULL, 0); | ||
688 | return true; | ||
689 | } | ||
690 | |||
691 | // https://learn.adafruit.com/adafruit-feather-32u4-bluefruit-le/ble-generic#at-plus-blepowerlevel | ||
692 | bool adafruit_ble_set_power_level(int8_t level) { | ||
693 | char cmd[46]; | ||
694 | if (!state.configured) { | ||
695 | return false; | ||
696 | } | ||
697 | snprintf(cmd, sizeof(cmd), "AT+BLEPOWERLEVEL=%d", level); | ||
698 | return at_command(cmd, NULL, 0, false); | ||
699 | } | ||
diff --git a/drivers/bluetooth/adafruit_ble.h b/drivers/bluetooth/adafruit_ble.h new file mode 100644 index 000000000..b43e0771d --- /dev/null +++ b/drivers/bluetooth/adafruit_ble.h | |||
@@ -0,0 +1,59 @@ | |||
1 | /* Bluetooth Low Energy Protocol for QMK. | ||
2 | * Author: Wez Furlong, 2016 | ||
3 | * Supports the Adafruit BLE board built around the nRF51822 chip. | ||
4 | */ | ||
5 | |||
6 | #pragma once | ||
7 | |||
8 | #include <stdbool.h> | ||
9 | #include <stdint.h> | ||
10 | #include <string.h> | ||
11 | |||
12 | #include "config_common.h" | ||
13 | |||
14 | #ifdef __cplusplus | ||
15 | extern "C" { | ||
16 | #endif | ||
17 | |||
18 | /* Instruct the module to enable HID keyboard support and reset */ | ||
19 | extern bool adafruit_ble_enable_keyboard(void); | ||
20 | |||
21 | /* Query to see if the BLE module is connected */ | ||
22 | extern bool adafruit_ble_query_is_connected(void); | ||
23 | |||
24 | /* Returns true if we believe that the BLE module is connected. | ||
25 | * This uses our cached understanding that is maintained by | ||
26 | * calling ble_task() periodically. */ | ||
27 | extern bool adafruit_ble_is_connected(void); | ||
28 | |||
29 | /* Call this periodically to process BLE-originated things */ | ||
30 | extern void adafruit_ble_task(void); | ||
31 | |||
32 | /* Generates keypress events for a set of keys. | ||
33 | * The hid modifier mask specifies the state of the modifier keys for | ||
34 | * this set of keys. | ||
35 | * Also sends a key release indicator, so that the keys do not remain | ||
36 | * held down. */ | ||
37 | extern void adafruit_ble_send_keys(uint8_t hid_modifier_mask, uint8_t *keys, uint8_t nkeys); | ||
38 | |||
39 | /* Send a consumer usage. | ||
40 | * (milliseconds) */ | ||
41 | extern void adafruit_ble_send_consumer_key(uint16_t usage); | ||
42 | |||
43 | #ifdef MOUSE_ENABLE | ||
44 | /* Send a mouse/wheel movement report. | ||
45 | * The parameters are signed and indicate positive or negative direction | ||
46 | * change. */ | ||
47 | extern void adafruit_ble_send_mouse_move(int8_t x, int8_t y, int8_t scroll, int8_t pan, uint8_t buttons); | ||
48 | #endif | ||
49 | |||
50 | /* Compute battery voltage by reading an analog pin. | ||
51 | * Returns the integer number of millivolts */ | ||
52 | extern uint32_t adafruit_ble_read_battery_voltage(void); | ||
53 | |||
54 | extern bool adafruit_ble_set_mode_leds(bool on); | ||
55 | extern bool adafruit_ble_set_power_level(int8_t level); | ||
56 | |||
57 | #ifdef __cplusplus | ||
58 | } | ||
59 | #endif | ||
diff --git a/drivers/bluetooth/outputselect.c b/drivers/bluetooth/outputselect.c new file mode 100644 index 000000000..f758c6528 --- /dev/null +++ b/drivers/bluetooth/outputselect.c | |||
@@ -0,0 +1,79 @@ | |||
1 | /* | ||
2 | Copyright 2017 Priyadi Iman Nurcahyo | ||
3 | This program is free software: you can redistribute it and/or modify | ||
4 | it under the terms of the GNU General Public License as published by | ||
5 | the Free Software Foundation, either version 2 of the License, or | ||
6 | (at your option) any later version. | ||
7 | This program is distributed in the hope that it will be useful, | ||
8 | but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
9 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
10 | GNU General Public License for more details. | ||
11 | You should have received a copy of the GNU General Public License | ||
12 | along with this program. If not, see <http://www.gnu.org/licenses/>. | ||
13 | */ | ||
14 | |||
15 | #include "outputselect.h" | ||
16 | |||
17 | #if defined(PROTOCOL_LUFA) | ||
18 | # include "lufa.h" | ||
19 | #endif | ||
20 | |||
21 | #ifdef MODULE_ADAFRUIT_BLE | ||
22 | # include "adafruit_ble.h" | ||
23 | #endif | ||
24 | |||
25 | uint8_t desired_output = OUTPUT_DEFAULT; | ||
26 | |||
27 | /** \brief Set Output | ||
28 | * | ||
29 | * FIXME: Needs doc | ||
30 | */ | ||
31 | void set_output(uint8_t output) { | ||
32 | set_output_user(output); | ||
33 | desired_output = output; | ||
34 | } | ||
35 | |||
36 | /** \brief Set Output User | ||
37 | * | ||
38 | * FIXME: Needs doc | ||
39 | */ | ||
40 | __attribute__((weak)) void set_output_user(uint8_t output) {} | ||
41 | |||
42 | static bool is_usb_configured(void) { | ||
43 | #if defined(PROTOCOL_LUFA) | ||
44 | return USB_DeviceState == DEVICE_STATE_Configured; | ||
45 | #endif | ||
46 | } | ||
47 | |||
48 | /** \brief Auto Detect Output | ||
49 | * | ||
50 | * FIXME: Needs doc | ||
51 | */ | ||
52 | uint8_t auto_detect_output(void) { | ||
53 | if (is_usb_configured()) { | ||
54 | return OUTPUT_USB; | ||
55 | } | ||
56 | |||
57 | #ifdef MODULE_ADAFRUIT_BLE | ||
58 | if (adafruit_ble_is_connected()) { | ||
59 | return OUTPUT_BLUETOOTH; | ||
60 | } | ||
61 | #endif | ||
62 | |||
63 | #ifdef BLUETOOTH_ENABLE | ||
64 | return OUTPUT_BLUETOOTH; // should check if BT is connected here | ||
65 | #endif | ||
66 | |||
67 | return OUTPUT_NONE; | ||
68 | } | ||
69 | |||
70 | /** \brief Where To Send | ||
71 | * | ||
72 | * FIXME: Needs doc | ||
73 | */ | ||
74 | uint8_t where_to_send(void) { | ||
75 | if (desired_output == OUTPUT_AUTO) { | ||
76 | return auto_detect_output(); | ||
77 | } | ||
78 | return desired_output; | ||
79 | } | ||
diff --git a/drivers/bluetooth/outputselect.h b/drivers/bluetooth/outputselect.h new file mode 100644 index 000000000..c4548e112 --- /dev/null +++ b/drivers/bluetooth/outputselect.h | |||
@@ -0,0 +1,34 @@ | |||
1 | /* | ||
2 | Copyright 2017 Priyadi Iman Nurcahyo | ||
3 | This program is free software: you can redistribute it and/or modify | ||
4 | it under the terms of the GNU General Public License as published by | ||
5 | the Free Software Foundation, either version 2 of the License, or | ||
6 | (at your option) any later version. | ||
7 | This program is distributed in the hope that it will be useful, | ||
8 | but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
9 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
10 | GNU General Public License for more details. | ||
11 | You should have received a copy of the GNU General Public License | ||
12 | along with this program. If not, see <http://www.gnu.org/licenses/>. | ||
13 | */ | ||
14 | |||
15 | #pragma once | ||
16 | |||
17 | #include <stdint.h> | ||
18 | |||
19 | enum outputs { | ||
20 | OUTPUT_AUTO, | ||
21 | |||
22 | OUTPUT_NONE, | ||
23 | OUTPUT_USB, | ||
24 | OUTPUT_BLUETOOTH | ||
25 | }; | ||
26 | |||
27 | #ifndef OUTPUT_DEFAULT | ||
28 | # define OUTPUT_DEFAULT OUTPUT_AUTO | ||
29 | #endif | ||
30 | |||
31 | void set_output(uint8_t output); | ||
32 | void set_output_user(uint8_t output); | ||
33 | uint8_t auto_detect_output(void); | ||
34 | uint8_t where_to_send(void); | ||
diff --git a/drivers/bluetooth/ringbuffer.hpp b/drivers/bluetooth/ringbuffer.hpp new file mode 100644 index 000000000..70a3c4881 --- /dev/null +++ b/drivers/bluetooth/ringbuffer.hpp | |||
@@ -0,0 +1,66 @@ | |||
1 | #pragma once | ||
2 | // A simple ringbuffer holding Size elements of type T | ||
3 | template <typename T, uint8_t Size> | ||
4 | class RingBuffer { | ||
5 | protected: | ||
6 | T buf_[Size]; | ||
7 | uint8_t head_{0}, tail_{0}; | ||
8 | public: | ||
9 | inline uint8_t nextPosition(uint8_t position) { | ||
10 | return (position + 1) % Size; | ||
11 | } | ||
12 | |||
13 | inline uint8_t prevPosition(uint8_t position) { | ||
14 | if (position == 0) { | ||
15 | return Size - 1; | ||
16 | } | ||
17 | return position - 1; | ||
18 | } | ||
19 | |||
20 | inline bool enqueue(const T &item) { | ||
21 | static_assert(Size > 1, "RingBuffer size must be > 1"); | ||
22 | uint8_t next = nextPosition(head_); | ||
23 | if (next == tail_) { | ||
24 | // Full | ||
25 | return false; | ||
26 | } | ||
27 | |||
28 | buf_[head_] = item; | ||
29 | head_ = next; | ||
30 | return true; | ||
31 | } | ||
32 | |||
33 | inline bool get(T &dest, bool commit = true) { | ||
34 | auto tail = tail_; | ||
35 | if (tail == head_) { | ||
36 | // No more data | ||
37 | return false; | ||
38 | } | ||
39 | |||
40 | dest = buf_[tail]; | ||
41 | tail = nextPosition(tail); | ||
42 | |||
43 | if (commit) { | ||
44 | tail_ = tail; | ||
45 | } | ||
46 | return true; | ||
47 | } | ||
48 | |||
49 | inline bool empty() const { return head_ == tail_; } | ||
50 | |||
51 | inline uint8_t size() const { | ||
52 | int diff = head_ - tail_; | ||
53 | if (diff >= 0) { | ||
54 | return diff; | ||
55 | } | ||
56 | return Size + diff; | ||
57 | } | ||
58 | |||
59 | inline T& front() { | ||
60 | return buf_[tail_]; | ||
61 | } | ||
62 | |||
63 | inline bool peek(T &item) { | ||
64 | return get(item, false); | ||
65 | } | ||
66 | }; | ||