adafruit_ble.cpp 21 KB

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