adafruit_ble.cpp 21 KB

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