You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

792 lines
23 KiB

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