adafruit_ble.cpp 23 KB

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