adafruit_ble.cpp 21 KB

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