adafruit_ble.cpp 21 KB

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