adafruit_ble.cpp 23 KB

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