adafruit_ble.cpp 21 KB

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