logo

qmk_firmware

custom branch of QMK firmware git clone https://anongit.hacktivis.me/git/qmk_firmware.git

bluefruit_le.cpp (20165B)


  1. #include "bluefruit_le.h"
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <alloca.h>
  5. #include "debug.h"
  6. #include "timer.h"
  7. #include "gpio.h"
  8. #include "ringbuffer.hpp"
  9. #include <string.h>
  10. #include "spi_master.h"
  11. #include "wait.h"
  12. #include "analog.h"
  13. #include "progmem.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 BLUEFRUIT_LE_RST_PIN
  18. # define BLUEFRUIT_LE_RST_PIN D4
  19. #endif
  20. #ifndef BLUEFRUIT_LE_CS_PIN
  21. # define BLUEFRUIT_LE_CS_PIN B4
  22. #endif
  23. #ifndef BLUEFRUIT_LE_IRQ_PIN
  24. # define BLUEFRUIT_LE_IRQ_PIN E6
  25. #endif
  26. #ifndef BLUEFRUIT_LE_SCK_DIVISOR
  27. # define BLUEFRUIT_LE_SCK_DIVISOR 2 // 4MHz SCK/8MHz CPU, calculated for Feather 32U4 BLE
  28. #endif
  29. #define ConnectionUpdateInterval 1000 /* milliseconds */
  30. static struct {
  31. bool is_connected;
  32. bool initialized;
  33. bool configured;
  34. #define ProbedEvents 1
  35. #define UsingEvents 2
  36. bool event_flags;
  37. uint16_t last_connection_update;
  38. } state;
  39. // Commands are encoded using SDEP and sent via SPI
  40. // https://github.com/adafruit/Adafruit_BluefruitLE_nRF51/blob/master/SDEP.md
  41. #define SdepMaxPayload 16
  42. struct sdep_msg {
  43. uint8_t type;
  44. uint8_t cmd_low;
  45. uint8_t cmd_high;
  46. struct __attribute__((packed)) {
  47. uint8_t len : 7;
  48. uint8_t more : 1;
  49. };
  50. uint8_t payload[SdepMaxPayload];
  51. } __attribute__((packed));
  52. // The recv latency is relatively high, so when we're hammering keys quickly,
  53. // we want to avoid waiting for the responses in the matrix loop. We maintain
  54. // a short queue for that. Since there is quite a lot of space overhead for
  55. // the AT command representation wrapped up in SDEP, we queue the minimal
  56. // information here.
  57. enum queue_type {
  58. QTKeyReport, // 1-byte modifier + 6-byte key report
  59. QTConsumer, // 16-bit key code
  60. QTMouseMove, // 4-byte mouse report
  61. };
  62. struct queue_item {
  63. enum queue_type queue_type;
  64. uint16_t added;
  65. union __attribute__((packed)) {
  66. struct __attribute__((packed)) {
  67. uint8_t modifier;
  68. uint8_t keys[6];
  69. } key;
  70. uint16_t consumer;
  71. struct __attribute__((packed)) {
  72. int8_t x, y, scroll, pan;
  73. uint8_t buttons;
  74. } mousemove;
  75. };
  76. };
  77. // Items that we wish to send
  78. static RingBuffer<queue_item, 40> send_buf;
  79. // Pending response; while pending, we can't send any more requests.
  80. // This records the time at which we sent the command for which we
  81. // are expecting a response.
  82. static RingBuffer<uint16_t, 2> resp_buf;
  83. static bool process_queue_item(struct queue_item *item, uint16_t timeout);
  84. enum sdep_type {
  85. SdepCommand = 0x10,
  86. SdepResponse = 0x20,
  87. SdepAlert = 0x40,
  88. SdepError = 0x80,
  89. SdepSlaveNotReady = 0xFE, // Try again later
  90. SdepSlaveOverflow = 0xFF, // You read more data than is available
  91. };
  92. enum ble_cmd {
  93. BleInitialize = 0xBEEF,
  94. BleAtWrapper = 0x0A00,
  95. BleUartTx = 0x0A01,
  96. BleUartRx = 0x0A02,
  97. };
  98. enum ble_system_event_bits {
  99. BleSystemConnected = 0,
  100. BleSystemDisconnected = 1,
  101. BleSystemUartRx = 8,
  102. BleSystemMidiRx = 10,
  103. };
  104. #define SdepTimeout 150 /* milliseconds */
  105. #define SdepShortTimeout 10 /* milliseconds */
  106. #define SdepBackOff 25 /* microseconds */
  107. #define BatteryUpdateInterval 10000 /* milliseconds */
  108. static bool at_command(const char *cmd, char *resp, uint16_t resplen, bool verbose, uint16_t timeout = SdepTimeout);
  109. static bool at_command_P(const char *cmd, char *resp, uint16_t resplen, bool verbose = false);
  110. // Send a single SDEP packet
  111. static bool sdep_send_pkt(const struct sdep_msg *msg, uint16_t timeout) {
  112. spi_start(BLUEFRUIT_LE_CS_PIN, false, 0, BLUEFRUIT_LE_SCK_DIVISOR);
  113. uint16_t timerStart = timer_read();
  114. bool success = false;
  115. bool ready = false;
  116. do {
  117. ready = spi_write(msg->type) != SdepSlaveNotReady;
  118. if (ready) {
  119. break;
  120. }
  121. // Release it and let it initialize
  122. spi_stop();
  123. wait_us(SdepBackOff);
  124. spi_start(BLUEFRUIT_LE_CS_PIN, false, 0, BLUEFRUIT_LE_SCK_DIVISOR);
  125. } while (timer_elapsed(timerStart) < timeout);
  126. if (ready) {
  127. // Slave is ready; send the rest of the packet
  128. spi_transmit(&msg->cmd_low, sizeof(*msg) - (1 + sizeof(msg->payload)) + msg->len);
  129. success = true;
  130. }
  131. spi_stop();
  132. return success;
  133. }
  134. static inline void sdep_build_pkt(struct sdep_msg *msg, uint16_t command, const uint8_t *payload, uint8_t len, bool moredata) {
  135. msg->type = SdepCommand;
  136. msg->cmd_low = command & 0xFF;
  137. msg->cmd_high = command >> 8;
  138. msg->len = len;
  139. msg->more = (moredata && len == SdepMaxPayload) ? 1 : 0;
  140. static_assert(sizeof(*msg) == 20, "msg is correctly packed");
  141. memcpy(msg->payload, payload, len);
  142. }
  143. // Read a single SDEP packet
  144. static bool sdep_recv_pkt(struct sdep_msg *msg, uint16_t timeout) {
  145. bool success = false;
  146. uint16_t timerStart = timer_read();
  147. bool ready = false;
  148. do {
  149. ready = gpio_read_pin(BLUEFRUIT_LE_IRQ_PIN);
  150. if (ready) {
  151. break;
  152. }
  153. wait_us(1);
  154. } while (timer_elapsed(timerStart) < timeout);
  155. if (ready) {
  156. spi_start(BLUEFRUIT_LE_CS_PIN, false, 0, BLUEFRUIT_LE_SCK_DIVISOR);
  157. do {
  158. // Read the command type, waiting for the data to be ready
  159. msg->type = spi_read();
  160. if (msg->type == SdepSlaveNotReady || msg->type == SdepSlaveOverflow) {
  161. // Release it and let it initialize
  162. spi_stop();
  163. wait_us(SdepBackOff);
  164. spi_start(BLUEFRUIT_LE_CS_PIN, false, 0, BLUEFRUIT_LE_SCK_DIVISOR);
  165. continue;
  166. }
  167. // Read the rest of the header
  168. spi_receive(&msg->cmd_low, sizeof(*msg) - (1 + sizeof(msg->payload)));
  169. // and get the payload if there is any
  170. if (msg->len <= SdepMaxPayload) {
  171. spi_receive(msg->payload, msg->len);
  172. }
  173. success = true;
  174. break;
  175. } while (timer_elapsed(timerStart) < timeout);
  176. spi_stop();
  177. }
  178. return success;
  179. }
  180. static void resp_buf_read_one(bool greedy) {
  181. uint16_t last_send;
  182. if (!resp_buf.peek(last_send)) {
  183. return;
  184. }
  185. if (gpio_read_pin(BLUEFRUIT_LE_IRQ_PIN)) {
  186. struct sdep_msg msg;
  187. again:
  188. if (sdep_recv_pkt(&msg, SdepTimeout)) {
  189. if (!msg.more) {
  190. // We got it; consume this entry
  191. resp_buf.get(last_send);
  192. dprintf("recv latency %dms\n", TIMER_DIFF_16(timer_read(), last_send));
  193. }
  194. if (greedy && resp_buf.peek(last_send) && gpio_read_pin(BLUEFRUIT_LE_IRQ_PIN)) {
  195. goto again;
  196. }
  197. }
  198. } else if (timer_elapsed(last_send) > SdepTimeout * 2) {
  199. dprintf("waiting_for_result: timeout, resp_buf size %d\n", (int)resp_buf.size());
  200. // Timed out: consume this entry
  201. resp_buf.get(last_send);
  202. }
  203. }
  204. static void send_buf_send_one(uint16_t timeout = SdepTimeout) {
  205. struct queue_item item;
  206. // Don't send anything more until we get an ACK
  207. if (!resp_buf.empty()) {
  208. return;
  209. }
  210. if (!send_buf.peek(item)) {
  211. return;
  212. }
  213. if (process_queue_item(&item, timeout)) {
  214. // commit that peek
  215. send_buf.get(item);
  216. dprintf("send_buf_send_one: have %d remaining\n", (int)send_buf.size());
  217. } else {
  218. dprint("failed to send, will retry\n");
  219. wait_ms(SdepTimeout);
  220. resp_buf_read_one(true);
  221. }
  222. }
  223. static void resp_buf_wait(const char *cmd) {
  224. bool didPrint = false;
  225. while (!resp_buf.empty()) {
  226. if (!didPrint) {
  227. dprintf("wait on buf for %s\n", cmd);
  228. didPrint = true;
  229. }
  230. resp_buf_read_one(true);
  231. }
  232. }
  233. void bluefruit_le_init(void) {
  234. state.initialized = false;
  235. state.configured = false;
  236. state.is_connected = false;
  237. gpio_set_pin_input(BLUEFRUIT_LE_IRQ_PIN);
  238. spi_init();
  239. // Perform a hardware reset
  240. gpio_set_pin_output(BLUEFRUIT_LE_RST_PIN);
  241. gpio_write_pin_high(BLUEFRUIT_LE_RST_PIN);
  242. gpio_write_pin_low(BLUEFRUIT_LE_RST_PIN);
  243. wait_ms(10);
  244. gpio_write_pin_high(BLUEFRUIT_LE_RST_PIN);
  245. wait_ms(1000); // Give it a second to initialize
  246. state.initialized = true;
  247. }
  248. static inline uint8_t min(uint8_t a, uint8_t b) {
  249. return a < b ? a : b;
  250. }
  251. static bool read_response(char *resp, uint16_t resplen, bool verbose) {
  252. char *dest = resp;
  253. char *end = dest + resplen;
  254. while (true) {
  255. struct sdep_msg msg;
  256. if (!sdep_recv_pkt(&msg, 2 * SdepTimeout)) {
  257. dprint("sdep_recv_pkt failed\n");
  258. return false;
  259. }
  260. if (msg.type != SdepResponse) {
  261. *resp = 0;
  262. return false;
  263. }
  264. uint8_t len = min(msg.len, end - dest);
  265. if (len > 0) {
  266. memcpy(dest, msg.payload, len);
  267. dest += len;
  268. }
  269. if (!msg.more) {
  270. // No more data is expected!
  271. break;
  272. }
  273. }
  274. // Ensure the response is NUL terminated
  275. *dest = 0;
  276. // "Parse" the result text; we want to snip off the trailing OK or ERROR line
  277. // Rewind past the possible trailing CRLF so that we can strip it
  278. --dest;
  279. while (dest > resp && (dest[0] == '\n' || dest[0] == '\r')) {
  280. *dest = 0;
  281. --dest;
  282. }
  283. // Look back for start of preceeding line
  284. char *last_line = strrchr(resp, '\n');
  285. if (last_line) {
  286. ++last_line;
  287. } else {
  288. last_line = resp;
  289. }
  290. bool success = false;
  291. static const char kOK[] PROGMEM = "OK";
  292. success = !strcmp_P(last_line, kOK);
  293. if (verbose || !success) {
  294. dprintf("result: %s\n", resp);
  295. }
  296. return success;
  297. }
  298. static bool at_command(const char *cmd, char *resp, uint16_t resplen, bool verbose, uint16_t timeout) {
  299. const char * end = cmd + strlen(cmd);
  300. struct sdep_msg msg;
  301. if (verbose) {
  302. dprintf("ble send: %s\n", cmd);
  303. }
  304. if (resp) {
  305. // They want to decode the response, so we need to flush and wait
  306. // for all pending I/O to finish before we start this one, so
  307. // that we don't confuse the results
  308. resp_buf_wait(cmd);
  309. *resp = 0;
  310. }
  311. // Fragment the command into a series of SDEP packets
  312. while (end - cmd > SdepMaxPayload) {
  313. sdep_build_pkt(&msg, BleAtWrapper, (uint8_t *)cmd, SdepMaxPayload, true);
  314. if (!sdep_send_pkt(&msg, timeout)) {
  315. return false;
  316. }
  317. cmd += SdepMaxPayload;
  318. }
  319. sdep_build_pkt(&msg, BleAtWrapper, (uint8_t *)cmd, end - cmd, false);
  320. if (!sdep_send_pkt(&msg, timeout)) {
  321. return false;
  322. }
  323. if (resp == NULL) {
  324. uint16_t now = timer_read();
  325. while (!resp_buf.enqueue(now)) {
  326. resp_buf_read_one(false);
  327. }
  328. uint16_t later = timer_read();
  329. if (TIMER_DIFF_16(later, now) > 0) {
  330. dprintf("waited %dms for resp_buf\n", TIMER_DIFF_16(later, now));
  331. }
  332. return true;
  333. }
  334. return read_response(resp, resplen, verbose);
  335. }
  336. bool at_command_P(const char *cmd, char *resp, uint16_t resplen, bool verbose) {
  337. char *cmdbuf = (char *)alloca(strlen_P(cmd) + 1);
  338. strcpy_P(cmdbuf, cmd);
  339. return at_command(cmdbuf, resp, resplen, verbose);
  340. }
  341. bool bluefruit_le_is_connected(void) {
  342. return state.is_connected;
  343. }
  344. bool bluefruit_le_enable_keyboard(void) {
  345. char resbuf[128];
  346. if (!state.initialized) {
  347. return false;
  348. }
  349. state.configured = false;
  350. // Disable command echo
  351. static const char kEcho[] PROGMEM = "ATE=0";
  352. // Make the advertised name match the keyboard
  353. static const char kGapDevName[] PROGMEM = "AT+GAPDEVNAME=" PRODUCT;
  354. // Turn on keyboard support
  355. static const char kHidEnOn[] PROGMEM = "AT+BLEHIDEN=1";
  356. // Adjust intervals to improve latency. This causes the "central"
  357. // system (computer/tablet) to poll us every 10-30 ms. We can't
  358. // set a smaller value than 10ms, and 30ms seems to be the natural
  359. // processing time on my macbook. Keeping it constrained to that
  360. // feels reasonable to type to.
  361. static const char kGapIntervals[] PROGMEM = "AT+GAPINTERVALS=10,30,,";
  362. // Reset the device so that it picks up the above changes
  363. static const char kATZ[] PROGMEM = "ATZ";
  364. // Turn down the power level a bit
  365. static const char kPower[] PROGMEM = "AT+BLEPOWERLEVEL=-12";
  366. static PGM_P const configure_commands[] PROGMEM = {
  367. kEcho, kGapIntervals, kGapDevName, kHidEnOn, kPower, kATZ,
  368. };
  369. uint8_t i;
  370. for (i = 0; i < sizeof(configure_commands) / sizeof(configure_commands[0]); ++i) {
  371. PGM_P cmd;
  372. memcpy_P(&cmd, configure_commands + i, sizeof(cmd));
  373. if (!at_command_P(cmd, resbuf, sizeof(resbuf))) {
  374. dprintf("failed BLE command: %S: %s\n", cmd, resbuf);
  375. goto fail;
  376. }
  377. }
  378. state.configured = true;
  379. // Check connection status in a little while; allow the ATZ time
  380. // to kick in.
  381. state.last_connection_update = timer_read();
  382. fail:
  383. return state.configured;
  384. }
  385. static void set_connected(bool connected) {
  386. if (connected != state.is_connected) {
  387. if (connected) {
  388. dprint("BLE connected\n");
  389. } else {
  390. dprint("BLE disconnected\n");
  391. }
  392. state.is_connected = connected;
  393. // TODO: if modifiers are down on the USB interface and
  394. // we cut over to BLE or vice versa, they will remain stuck.
  395. // This feels like a good point to do something like clearing
  396. // the keyboard and/or generating a fake all keys up message.
  397. // However, I've noticed that it takes a couple of seconds
  398. // for macOS to to start recognizing key presses after BLE
  399. // is in the connected state, so I worry that doing that
  400. // here may not be good enough.
  401. }
  402. }
  403. void bluefruit_le_task(void) {
  404. char resbuf[48];
  405. if (!state.configured && !bluefruit_le_enable_keyboard()) {
  406. return;
  407. }
  408. resp_buf_read_one(true);
  409. send_buf_send_one(SdepShortTimeout);
  410. if (resp_buf.empty() && (state.event_flags & UsingEvents) && gpio_read_pin(BLUEFRUIT_LE_IRQ_PIN)) {
  411. // Must be an event update
  412. if (at_command_P(PSTR("AT+EVENTSTATUS"), resbuf, sizeof(resbuf))) {
  413. uint32_t mask = strtoul(resbuf, NULL, 16);
  414. if (mask & BleSystemConnected) {
  415. set_connected(true);
  416. } else if (mask & BleSystemDisconnected) {
  417. set_connected(false);
  418. }
  419. }
  420. }
  421. if (timer_elapsed(state.last_connection_update) > ConnectionUpdateInterval) {
  422. bool shouldPoll = true;
  423. if (!(state.event_flags & ProbedEvents)) {
  424. // Request notifications about connection status changes.
  425. // This only works in SPIFRIEND firmware > 0.6.7, which is why
  426. // we check for this conditionally here.
  427. // Note that at the time of writing, HID reports only work correctly
  428. // with Apple products on firmware version 0.6.7!
  429. // https://forums.adafruit.com/viewtopic.php?f=8&t=104052
  430. if (at_command_P(PSTR("AT+EVENTENABLE=0x1"), resbuf, sizeof(resbuf))) {
  431. at_command_P(PSTR("AT+EVENTENABLE=0x2"), resbuf, sizeof(resbuf));
  432. state.event_flags |= UsingEvents;
  433. }
  434. state.event_flags |= ProbedEvents;
  435. // leave shouldPoll == true so that we check at least once
  436. // before relying solely on events
  437. } else {
  438. shouldPoll = false;
  439. }
  440. static const char kGetConn[] PROGMEM = "AT+GAPGETCONN";
  441. state.last_connection_update = timer_read();
  442. if (at_command_P(kGetConn, resbuf, sizeof(resbuf))) {
  443. set_connected(atoi(resbuf));
  444. }
  445. }
  446. }
  447. static bool process_queue_item(struct queue_item *item, uint16_t timeout) {
  448. char cmdbuf[48];
  449. char fmtbuf[64];
  450. // Arrange to re-check connection after keys have settled
  451. state.last_connection_update = timer_read();
  452. #if 1
  453. if (TIMER_DIFF_16(state.last_connection_update, item->added) > 0) {
  454. dprintf("send latency %dms\n", TIMER_DIFF_16(state.last_connection_update, item->added));
  455. }
  456. #endif
  457. switch (item->queue_type) {
  458. case QTKeyReport:
  459. strcpy_P(fmtbuf, PSTR("AT+BLEKEYBOARDCODE=%02x-00-%02x-%02x-%02x-%02x-%02x-%02x"));
  460. 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]);
  461. return at_command(cmdbuf, NULL, 0, true, timeout);
  462. #ifdef EXTRAKEY_ENABLE
  463. case QTConsumer:
  464. strcpy_P(fmtbuf, PSTR("AT+BLEHIDCONTROLKEY=0x%04x"));
  465. snprintf(cmdbuf, sizeof(cmdbuf), fmtbuf, item->consumer);
  466. return at_command(cmdbuf, NULL, 0, true, timeout);
  467. #endif
  468. #ifdef MOUSE_ENABLE
  469. case QTMouseMove:
  470. strcpy_P(fmtbuf, PSTR("AT+BLEHIDMOUSEMOVE=%d,%d,%d,%d"));
  471. snprintf(cmdbuf, sizeof(cmdbuf), fmtbuf, item->mousemove.x, item->mousemove.y, item->mousemove.scroll, item->mousemove.pan);
  472. if (!at_command(cmdbuf, NULL, 0, true, timeout)) {
  473. return false;
  474. }
  475. strcpy_P(cmdbuf, PSTR("AT+BLEHIDMOUSEBUTTON="));
  476. if (item->mousemove.buttons & MOUSE_BTN1) {
  477. strcat(cmdbuf, "L");
  478. }
  479. if (item->mousemove.buttons & MOUSE_BTN2) {
  480. strcat(cmdbuf, "R");
  481. }
  482. if (item->mousemove.buttons & MOUSE_BTN3) {
  483. strcat(cmdbuf, "M");
  484. }
  485. if (item->mousemove.buttons == 0) {
  486. strcat(cmdbuf, "0");
  487. }
  488. return at_command(cmdbuf, NULL, 0, true, timeout);
  489. #endif
  490. default:
  491. return true;
  492. }
  493. }
  494. void bluefruit_le_send_keyboard(report_keyboard_t *report) {
  495. struct queue_item item;
  496. item.queue_type = QTKeyReport;
  497. item.key.modifier = report->mods;
  498. item.key.keys[0] = report->keys[0];
  499. item.key.keys[1] = report->keys[1];
  500. item.key.keys[2] = report->keys[2];
  501. item.key.keys[3] = report->keys[3];
  502. item.key.keys[4] = report->keys[4];
  503. item.key.keys[5] = report->keys[5];
  504. while (!send_buf.enqueue(item)) {
  505. send_buf_send_one();
  506. }
  507. }
  508. void bluefruit_le_send_consumer(uint16_t usage) {
  509. struct queue_item item;
  510. item.queue_type = QTConsumer;
  511. item.consumer = usage;
  512. while (!send_buf.enqueue(item)) {
  513. send_buf_send_one();
  514. }
  515. }
  516. void bluefruit_le_send_mouse(report_mouse_t *report) {
  517. struct queue_item item;
  518. item.queue_type = QTMouseMove;
  519. item.mousemove.x = report->x;
  520. item.mousemove.y = report->y;
  521. item.mousemove.scroll = report->v;
  522. item.mousemove.pan = report->h;
  523. item.mousemove.buttons = report->buttons;
  524. while (!send_buf.enqueue(item)) {
  525. send_buf_send_one();
  526. }
  527. }
  528. bool bluefruit_le_set_mode_leds(bool on) {
  529. if (!state.configured) {
  530. return false;
  531. }
  532. // The "mode" led is the red blinky one
  533. at_command_P(on ? PSTR("AT+HWMODELED=1") : PSTR("AT+HWMODELED=0"), NULL, 0);
  534. // Pin 19 is the blue "connected" LED; turn that off too.
  535. // When turning LEDs back on, don't turn that LED on if we're
  536. // not connected, as that would be confusing.
  537. at_command_P(on && state.is_connected ? PSTR("AT+HWGPIO=19,1") : PSTR("AT+HWGPIO=19,0"), NULL, 0);
  538. return true;
  539. }
  540. // https://learn.adafruit.com/adafruit-feather-32u4-bluefruit-le/ble-generic#at-plus-blepowerlevel
  541. bool bluefruit_le_set_power_level(int8_t level) {
  542. char cmd[46];
  543. if (!state.configured) {
  544. return false;
  545. }
  546. snprintf(cmd, sizeof(cmd), "AT+BLEPOWERLEVEL=%d", level);
  547. return at_command(cmd, NULL, 0, false);
  548. }