bluefruit_le.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705
  1. #include "bluefruit_le.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 BLUEFRUIT_LE_RST_PIN
  18. # define BLUEFRUIT_LE_RST_PIN D4
  19. #endif
  20. #ifndef BLUEFRUIT_LE_CS_PIN
  21. # define BLUEFRUIT_LE_CS_PIN B4
  22. #endif
  23. #ifndef BLUEFRUIT_LE_IRQ_PIN
  24. # define BLUEFRUIT_LE_IRQ_PIN E6
  25. #endif
  26. #ifndef BLUEFRUIT_LE_SCK_DIVISOR
  27. # define BLUEFRUIT_LE_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(BLUEFRUIT_LE_CS_PIN, false, 0, BLUEFRUIT_LE_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(BLUEFRUIT_LE_CS_PIN, false, 0, BLUEFRUIT_LE_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(BLUEFRUIT_LE_IRQ_PIN);
  160. if (ready) {
  161. break;
  162. }
  163. wait_us(1);
  164. } while (timer_elapsed(timerStart) < timeout);
  165. if (ready) {
  166. spi_start(BLUEFRUIT_LE_CS_PIN, false, 0, BLUEFRUIT_LE_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(BLUEFRUIT_LE_CS_PIN, false, 0, BLUEFRUIT_LE_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(BLUEFRUIT_LE_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(BLUEFRUIT_LE_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(BLUEFRUIT_LE_IRQ_PIN);
  248. spi_init();
  249. // Perform a hardware reset
  250. setPinOutput(BLUEFRUIT_LE_RST_PIN);
  251. writePinHigh(BLUEFRUIT_LE_RST_PIN);
  252. writePinLow(BLUEFRUIT_LE_RST_PIN);
  253. wait_ms(10);
  254. writePinHigh(BLUEFRUIT_LE_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) {
  260. return a < b ? a : b;
  261. }
  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. uint16_t now = timer_read();
  336. while (!resp_buf.enqueue(now)) {
  337. resp_buf_read_one(false);
  338. }
  339. uint16_t 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. char *cmdbuf = (char *)alloca(strlen_P(cmd) + 1);
  349. strcpy_P(cmdbuf, cmd);
  350. return at_command(cmdbuf, resp, resplen, verbose);
  351. }
  352. bool bluefruit_le_is_connected(void) {
  353. return state.is_connected;
  354. }
  355. bool bluefruit_le_enable_keyboard(void) {
  356. char resbuf[128];
  357. if (!state.initialized && !ble_init()) {
  358. return false;
  359. }
  360. state.configured = false;
  361. // Disable command echo
  362. static const char kEcho[] PROGMEM = "ATE=0";
  363. // Make the advertised name match the keyboard
  364. static const char kGapDevName[] PROGMEM = "AT+GAPDEVNAME=" STR(PRODUCT);
  365. // Turn on keyboard support
  366. static const char kHidEnOn[] PROGMEM = "AT+BLEHIDEN=1";
  367. // Adjust intervals to improve latency. This causes the "central"
  368. // system (computer/tablet) to poll us every 10-30 ms. We can't
  369. // set a smaller value than 10ms, and 30ms seems to be the natural
  370. // processing time on my macbook. Keeping it constrained to that
  371. // feels reasonable to type to.
  372. static const char kGapIntervals[] PROGMEM = "AT+GAPINTERVALS=10,30,,";
  373. // Reset the device so that it picks up the above changes
  374. static const char kATZ[] PROGMEM = "ATZ";
  375. // Turn down the power level a bit
  376. static const char kPower[] PROGMEM = "AT+BLEPOWERLEVEL=-12";
  377. static PGM_P const configure_commands[] PROGMEM = {
  378. kEcho, kGapIntervals, kGapDevName, kHidEnOn, kPower, kATZ,
  379. };
  380. uint8_t i;
  381. for (i = 0; i < sizeof(configure_commands) / sizeof(configure_commands[0]); ++i) {
  382. PGM_P cmd;
  383. memcpy_P(&cmd, configure_commands + i, sizeof(cmd));
  384. if (!at_command_P(cmd, resbuf, sizeof(resbuf))) {
  385. dprintf("failed BLE command: %S: %s\n", cmd, resbuf);
  386. goto fail;
  387. }
  388. }
  389. state.configured = true;
  390. // Check connection status in a little while; allow the ATZ time
  391. // to kick in.
  392. state.last_connection_update = timer_read();
  393. fail:
  394. return state.configured;
  395. }
  396. static void set_connected(bool connected) {
  397. if (connected != state.is_connected) {
  398. if (connected) {
  399. dprint("BLE connected\n");
  400. } else {
  401. dprint("BLE disconnected\n");
  402. }
  403. state.is_connected = connected;
  404. // TODO: if modifiers are down on the USB interface and
  405. // we cut over to BLE or vice versa, they will remain stuck.
  406. // This feels like a good point to do something like clearing
  407. // the keyboard and/or generating a fake all keys up message.
  408. // However, I've noticed that it takes a couple of seconds
  409. // for macOS to to start recognizing key presses after BLE
  410. // is in the connected state, so I worry that doing that
  411. // here may not be good enough.
  412. }
  413. }
  414. void bluefruit_le_task(void) {
  415. char resbuf[48];
  416. if (!state.configured && !bluefruit_le_enable_keyboard()) {
  417. return;
  418. }
  419. resp_buf_read_one(true);
  420. send_buf_send_one(SdepShortTimeout);
  421. if (resp_buf.empty() && (state.event_flags & UsingEvents) && readPin(BLUEFRUIT_LE_IRQ_PIN)) {
  422. // Must be an event update
  423. if (at_command_P(PSTR("AT+EVENTSTATUS"), resbuf, sizeof(resbuf))) {
  424. uint32_t mask = strtoul(resbuf, NULL, 16);
  425. if (mask & BleSystemConnected) {
  426. set_connected(true);
  427. } else if (mask & BleSystemDisconnected) {
  428. set_connected(false);
  429. }
  430. }
  431. }
  432. if (timer_elapsed(state.last_connection_update) > ConnectionUpdateInterval) {
  433. bool shouldPoll = true;
  434. if (!(state.event_flags & ProbedEvents)) {
  435. // Request notifications about connection status changes.
  436. // This only works in SPIFRIEND firmware > 0.6.7, which is why
  437. // we check for this conditionally here.
  438. // Note that at the time of writing, HID reports only work correctly
  439. // with Apple products on firmware version 0.6.7!
  440. // https://forums.adafruit.com/viewtopic.php?f=8&t=104052
  441. if (at_command_P(PSTR("AT+EVENTENABLE=0x1"), resbuf, sizeof(resbuf))) {
  442. at_command_P(PSTR("AT+EVENTENABLE=0x2"), resbuf, sizeof(resbuf));
  443. state.event_flags |= UsingEvents;
  444. }
  445. state.event_flags |= ProbedEvents;
  446. // leave shouldPoll == true so that we check at least once
  447. // before relying solely on events
  448. } else {
  449. shouldPoll = false;
  450. }
  451. static const char kGetConn[] PROGMEM = "AT+GAPGETCONN";
  452. state.last_connection_update = timer_read();
  453. if (at_command_P(kGetConn, resbuf, sizeof(resbuf))) {
  454. set_connected(atoi(resbuf));
  455. }
  456. }
  457. #ifdef SAMPLE_BATTERY
  458. if (timer_elapsed(state.last_battery_update) > BatteryUpdateInterval && resp_buf.empty()) {
  459. state.last_battery_update = timer_read();
  460. state.vbat = analogReadPin(BATTERY_LEVEL_PIN);
  461. }
  462. #endif
  463. }
  464. static bool process_queue_item(struct queue_item *item, uint16_t timeout) {
  465. char cmdbuf[48];
  466. char fmtbuf[64];
  467. // Arrange to re-check connection after keys have settled
  468. state.last_connection_update = timer_read();
  469. #if 1
  470. if (TIMER_DIFF_16(state.last_connection_update, item->added) > 0) {
  471. dprintf("send latency %dms\n", TIMER_DIFF_16(state.last_connection_update, item->added));
  472. }
  473. #endif
  474. switch (item->queue_type) {
  475. case QTKeyReport:
  476. strcpy_P(fmtbuf, PSTR("AT+BLEKEYBOARDCODE=%02x-00-%02x-%02x-%02x-%02x-%02x-%02x"));
  477. 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]);
  478. return at_command(cmdbuf, NULL, 0, true, timeout);
  479. case QTConsumer:
  480. strcpy_P(fmtbuf, PSTR("AT+BLEHIDCONTROLKEY=0x%04x"));
  481. snprintf(cmdbuf, sizeof(cmdbuf), fmtbuf, item->consumer);
  482. return at_command(cmdbuf, NULL, 0, true, timeout);
  483. #ifdef MOUSE_ENABLE
  484. case QTMouseMove:
  485. strcpy_P(fmtbuf, PSTR("AT+BLEHIDMOUSEMOVE=%d,%d,%d,%d"));
  486. snprintf(cmdbuf, sizeof(cmdbuf), fmtbuf, item->mousemove.x, item->mousemove.y, item->mousemove.scroll, item->mousemove.pan);
  487. if (!at_command(cmdbuf, NULL, 0, true, timeout)) {
  488. return false;
  489. }
  490. strcpy_P(cmdbuf, PSTR("AT+BLEHIDMOUSEBUTTON="));
  491. if (item->mousemove.buttons & MOUSE_BTN1) {
  492. strcat(cmdbuf, "L");
  493. }
  494. if (item->mousemove.buttons & MOUSE_BTN2) {
  495. strcat(cmdbuf, "R");
  496. }
  497. if (item->mousemove.buttons & MOUSE_BTN3) {
  498. strcat(cmdbuf, "M");
  499. }
  500. if (item->mousemove.buttons == 0) {
  501. strcat(cmdbuf, "0");
  502. }
  503. return at_command(cmdbuf, NULL, 0, true, timeout);
  504. #endif
  505. default:
  506. return true;
  507. }
  508. }
  509. void bluefruit_le_send_keys(uint8_t hid_modifier_mask, uint8_t *keys, uint8_t nkeys) {
  510. struct queue_item item;
  511. bool didWait = false;
  512. item.queue_type = QTKeyReport;
  513. item.key.modifier = hid_modifier_mask;
  514. item.added = timer_read();
  515. while (nkeys >= 0) {
  516. item.key.keys[0] = keys[0];
  517. item.key.keys[1] = nkeys >= 1 ? keys[1] : 0;
  518. item.key.keys[2] = nkeys >= 2 ? keys[2] : 0;
  519. item.key.keys[3] = nkeys >= 3 ? keys[3] : 0;
  520. item.key.keys[4] = nkeys >= 4 ? keys[4] : 0;
  521. item.key.keys[5] = nkeys >= 5 ? keys[5] : 0;
  522. if (!send_buf.enqueue(item)) {
  523. if (!didWait) {
  524. dprint("wait for buf space\n");
  525. didWait = true;
  526. }
  527. send_buf_send_one();
  528. continue;
  529. }
  530. if (nkeys <= 6) {
  531. return;
  532. }
  533. nkeys -= 6;
  534. keys += 6;
  535. }
  536. }
  537. void bluefruit_le_send_consumer_key(uint16_t usage) {
  538. struct queue_item item;
  539. item.queue_type = QTConsumer;
  540. item.consumer = usage;
  541. while (!send_buf.enqueue(item)) {
  542. send_buf_send_one();
  543. }
  544. }
  545. #ifdef MOUSE_ENABLE
  546. void bluefruit_le_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. }
  558. #endif
  559. uint32_t bluefruit_le_read_battery_voltage(void) {
  560. return state.vbat;
  561. }
  562. bool bluefruit_le_set_mode_leds(bool on) {
  563. if (!state.configured) {
  564. return false;
  565. }
  566. // The "mode" led is the red blinky one
  567. at_command_P(on ? PSTR("AT+HWMODELED=1") : PSTR("AT+HWMODELED=0"), NULL, 0);
  568. // Pin 19 is the blue "connected" LED; turn that off too.
  569. // When turning LEDs back on, don't turn that LED on if we're
  570. // not connected, as that would be confusing.
  571. at_command_P(on && state.is_connected ? PSTR("AT+HWGPIO=19,1") : PSTR("AT+HWGPIO=19,0"), NULL, 0);
  572. return true;
  573. }
  574. // https://learn.adafruit.com/adafruit-feather-32u4-bluefruit-le/ble-generic#at-plus-blepowerlevel
  575. bool bluefruit_le_set_power_level(int8_t level) {
  576. char cmd[46];
  577. if (!state.configured) {
  578. return false;
  579. }
  580. snprintf(cmd, sizeof(cmd), "AT+BLEPOWERLEVEL=%d", level);
  581. return at_command(cmd, NULL, 0, false);
  582. }