hog_boot_host_demo.c 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622
  1. /*
  2. * Copyright (C) 2020 BlueKitchen GmbH
  3. *
  4. * Redistribution and use in source and binary forms, with or without
  5. * modification, are permitted provided that the following conditions
  6. * are met:
  7. *
  8. * 1. Redistributions of source code must retain the above copyright
  9. * notice, this list of conditions and the following disclaimer.
  10. * 2. Redistributions in binary form must reproduce the above copyright
  11. * notice, this list of conditions and the following disclaimer in the
  12. * documentation and/or other materials provided with the distribution.
  13. * 3. Neither the name of the copyright holders nor the names of
  14. * contributors may be used to endorse or promote products derived
  15. * from this software without specific prior written permission.
  16. * 4. Any redistribution, use, or modification is done solely for
  17. * personal benefit and not for any commercial purpose or for
  18. * monetary gain.
  19. *
  20. * THIS SOFTWARE IS PROVIDED BY BLUEKITCHEN GMBH AND CONTRIBUTORS
  21. * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  22. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
  23. * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL MATTHIAS
  24. * RINGWALD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
  25. * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
  26. * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
  27. * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
  28. * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  29. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
  30. * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  31. * SUCH DAMAGE.
  32. *
  33. * Please inquire about commercial licensing options at
  34. * contact@bluekitchen-gmbh.com
  35. *
  36. */
  37. #define BTSTACK_FILE__ "hog_boot_host_demo.c"
  38. /*
  39. * hog_boot_host_demo.c
  40. */
  41. /* EXAMPLE_START(hog_boot_host_demo): HID-over-GATT Boot Host Demo
  42. *
  43. * @text This example implements a minimal HID-over-GATT Boot Host. It scans for LE HID devices, connects to it,
  44. * discovers the Characteristics relevant for the HID Service and enables Notifications on them.
  45. * It then dumps all Boot Keyboard and Mouse Input Reports
  46. */
  47. #include <inttypes.h>
  48. #include <stdio.h>
  49. #include <btstack_tlv.h>
  50. #include "btstack_config.h"
  51. #include "btstack.h"
  52. // TAG to store remote device address and type in TLV
  53. #define TLV_TAG_HOGD ((((uint32_t) 'H') << 24 ) | (((uint32_t) 'O') << 16) | (((uint32_t) 'G') << 8) | 'D')
  54. typedef struct {
  55. bd_addr_t addr;
  56. bd_addr_type_t addr_type;
  57. } le_device_addr_t;
  58. static enum {
  59. W4_WORKING,
  60. W4_HID_DEVICE_FOUND,
  61. W4_CONNECTED,
  62. W4_ENCRYPTED,
  63. W4_HID_SERVICE_FOUND,
  64. W4_HID_CHARACTERISTICS_FOUND,
  65. W4_BOOT_KEYBOARD_ENABLED,
  66. W4_BOOT_MOUSE_ENABLED,
  67. READY,
  68. W4_TIMEOUT_THEN_SCAN,
  69. W4_TIMEOUT_THEN_RECONNECT,
  70. } app_state;
  71. static le_device_addr_t remote_device;
  72. static hci_con_handle_t connection_handle;
  73. // used for GATT queries
  74. static gatt_client_service_t hid_service;
  75. static gatt_client_characteristic_t protocol_mode_characteristic;
  76. static gatt_client_characteristic_t boot_keyboard_input_characteristic;
  77. static gatt_client_characteristic_t boot_mouse_input_characteristic;
  78. static gatt_client_notification_t keyboard_notifications;
  79. static gatt_client_notification_t mouse_notifications;
  80. // used to implement connection timeout and reconnect timer
  81. static btstack_timer_source_t connection_timer;
  82. // register for events from HCI/GAP and SM
  83. static btstack_packet_callback_registration_t hci_event_callback_registration;
  84. static btstack_packet_callback_registration_t sm_event_callback_registration;
  85. // used to store remote device in TLV
  86. static const btstack_tlv_t * btstack_tlv_singleton_impl;
  87. static void * btstack_tlv_singleton_context;
  88. // Simplified US Keyboard with Shift modifier
  89. #define CHAR_ILLEGAL 0xff
  90. #define CHAR_RETURN '\n'
  91. #define CHAR_ESCAPE 27
  92. #define CHAR_TAB '\t'
  93. #define CHAR_BACKSPACE 0x7f
  94. /**
  95. * English (US)
  96. */
  97. static const uint8_t keytable_us_none [] = {
  98. CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, /* 0-3 */
  99. 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', /* 4-13 */
  100. 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', /* 14-23 */
  101. 'u', 'v', 'w', 'x', 'y', 'z', /* 24-29 */
  102. '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', /* 30-39 */
  103. CHAR_RETURN, CHAR_ESCAPE, CHAR_BACKSPACE, CHAR_TAB, ' ', /* 40-44 */
  104. '-', '=', '[', ']', '\\', CHAR_ILLEGAL, ';', '\'', 0x60, ',', /* 45-54 */
  105. '.', '/', CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, /* 55-60 */
  106. CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, /* 61-64 */
  107. CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, /* 65-68 */
  108. CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, /* 69-72 */
  109. CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, /* 73-76 */
  110. CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, /* 77-80 */
  111. CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, /* 81-84 */
  112. '*', '-', '+', '\n', '1', '2', '3', '4', '5', /* 85-97 */
  113. '6', '7', '8', '9', '0', '.', 0xa7, /* 97-100 */
  114. };
  115. static const uint8_t keytable_us_shift[] = {
  116. CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, /* 0-3 */
  117. 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', /* 4-13 */
  118. 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', /* 14-23 */
  119. 'U', 'V', 'W', 'X', 'Y', 'Z', /* 24-29 */
  120. '!', '@', '#', '$', '%', '^', '&', '*', '(', ')', /* 30-39 */
  121. CHAR_RETURN, CHAR_ESCAPE, CHAR_BACKSPACE, CHAR_TAB, ' ', /* 40-44 */
  122. '_', '+', '{', '}', '|', CHAR_ILLEGAL, ':', '"', 0x7E, '<', /* 45-54 */
  123. '>', '?', CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, /* 55-60 */
  124. CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, /* 61-64 */
  125. CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, /* 65-68 */
  126. CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, /* 69-72 */
  127. CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, /* 73-76 */
  128. CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, /* 77-80 */
  129. CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, /* 81-84 */
  130. '*', '-', '+', '\n', '1', '2', '3', '4', '5', /* 85-97 */
  131. '6', '7', '8', '9', '0', '.', 0xb1, /* 97-100 */
  132. };
  133. /**
  134. * @section HOG Boot Keyboard Handler
  135. * @text Boot Keyboard Input Report contains a report of format
  136. * [ modifier, reserved, 6 x usage for key 1..6 from keyboard usage]
  137. * Track new usages, map key usage to actual character and simulate terminal
  138. */
  139. /* last_keys stores keyboard report to detect new key down events */
  140. #define NUM_KEYS 6
  141. static uint8_t last_keys[NUM_KEYS];
  142. static void handle_boot_keyboard_event(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size) {
  143. UNUSED(packet_type);
  144. UNUSED(channel);
  145. UNUSED(size);
  146. if (hci_event_packet_get_type(packet) != GATT_EVENT_NOTIFICATION) return;
  147. const uint8_t * data = gatt_event_notification_get_value(packet);
  148. uint8_t new_keys[NUM_KEYS];
  149. memset(new_keys, 0, sizeof(new_keys));
  150. int new_keys_count = 0;
  151. bool shift = (data[0] & 0x22) != 0;
  152. uint8_t key_index;
  153. for (key_index = 0; key_index < NUM_KEYS; key_index++){
  154. uint16_t usage = data[2 + key_index];
  155. if (usage == 0) continue;
  156. if (usage >= sizeof(keytable_us_none)) continue;
  157. // store new keys
  158. new_keys[new_keys_count++] = usage;
  159. // check if usage was used last time (and ignore in that case)
  160. int i;
  161. for (i=0;i<NUM_KEYS;i++){
  162. if (usage == last_keys[i]){
  163. usage = 0;
  164. }
  165. }
  166. if (usage == 0) continue;
  167. // lookup character based on usage + shift modifier
  168. uint8_t key;
  169. if (shift){
  170. key = keytable_us_shift[usage];
  171. } else {
  172. key = keytable_us_none[usage];
  173. }
  174. if (key == CHAR_ILLEGAL) continue;
  175. if (key == CHAR_BACKSPACE){
  176. printf("\b \b"); // go back one char, print space, go back one char again
  177. continue;
  178. }
  179. printf("%c", key);
  180. }
  181. // store current as last report
  182. memcpy(last_keys, new_keys, NUM_KEYS);
  183. }
  184. /**
  185. * @section HOG Boot Mouse Handler
  186. * @text Boot Mouse Input Report contains a report of format
  187. * [ buttons, dx, dy, dz = scroll wheel]
  188. * Decode packet and print on stdout
  189. *
  190. * @param packet_type
  191. * @param channel
  192. * @param packet
  193. * @param size
  194. */
  195. static void handle_boot_mouse_event(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size) {
  196. UNUSED(packet_type);
  197. UNUSED(channel);
  198. UNUSED(size);
  199. if (hci_event_packet_get_type(packet) != GATT_EVENT_NOTIFICATION) return;
  200. const uint8_t * data = gatt_event_notification_get_value(packet);
  201. uint8_t buttons = data[0];
  202. int8_t dx = (int8_t) data[1];
  203. int8_t dy = (int8_t) data[2];
  204. int8_t dwheel = (int8_t) data[3];
  205. printf("Mouse: %i, %i - wheel %i - buttons 0x%02x\n", dx, dy, dwheel, buttons);
  206. }
  207. /**
  208. * @section Test if advertisement contains HID UUID
  209. * @param packet
  210. * @param size
  211. * @returns true if it does
  212. */
  213. static bool adv_event_contains_hid_service(const uint8_t * packet){
  214. const uint8_t * ad_data = gap_event_advertising_report_get_data(packet);
  215. uint16_t ad_len = gap_event_advertising_report_get_data_length(packet);
  216. return ad_data_contains_uuid16(ad_len, ad_data, ORG_BLUETOOTH_SERVICE_HUMAN_INTERFACE_DEVICE);
  217. }
  218. /**
  219. * Start scanning
  220. */
  221. static void hog_start_scan(void){
  222. printf("Scanning for LE HID devices...\n");
  223. app_state = W4_HID_DEVICE_FOUND;
  224. // Passive scanning, 100% (scan interval = scan window)
  225. gap_set_scan_parameters(0,48,48);
  226. gap_start_scan();
  227. }
  228. /**
  229. * Handle timeout for outgoing connection
  230. * @param ts
  231. */
  232. static void hog_connection_timeout(btstack_timer_source_t * ts){
  233. UNUSED(ts);
  234. printf("Timeout - abort connection\n");
  235. gap_connect_cancel();
  236. hog_start_scan();
  237. }
  238. /**
  239. * Connect to remote device but set timer for timeout
  240. */
  241. static void hog_connect(void) {
  242. // set timer
  243. btstack_run_loop_set_timer(&connection_timer, 10000);
  244. btstack_run_loop_set_timer_handler(&connection_timer, &hog_connection_timeout);
  245. btstack_run_loop_add_timer(&connection_timer);
  246. app_state = W4_CONNECTED;
  247. gap_connect(remote_device.addr, remote_device.addr_type);
  248. }
  249. /**
  250. * Handle timer event to trigger reconnect
  251. * @param ts
  252. */
  253. static void hog_reconnect_timeout(btstack_timer_source_t * ts){
  254. UNUSED(ts);
  255. switch (app_state){
  256. case W4_TIMEOUT_THEN_RECONNECT:
  257. hog_connect();
  258. break;
  259. case W4_TIMEOUT_THEN_SCAN:
  260. hog_start_scan();
  261. break;
  262. default:
  263. break;
  264. }
  265. }
  266. /**
  267. * Start connecting after boot up: connect to last used device if possible, start scan otherwise
  268. */
  269. static void hog_start_connect(void){
  270. // check if we have a bonded device
  271. btstack_tlv_get_instance(&btstack_tlv_singleton_impl, &btstack_tlv_singleton_context);
  272. if (btstack_tlv_singleton_impl){
  273. int len = btstack_tlv_singleton_impl->get_tag(btstack_tlv_singleton_context, TLV_TAG_HOGD, (uint8_t *) &remote_device, sizeof(remote_device));
  274. if (len == sizeof(remote_device)){
  275. printf("Bonded, connect to device with %s address %s ...\n", remote_device.addr_type == 0 ? "public" : "random" , bd_addr_to_str(remote_device.addr));
  276. hog_connect();
  277. return;
  278. }
  279. }
  280. // otherwise, scan for HID devices
  281. hog_start_scan();
  282. }
  283. /**
  284. * In case of error, disconnect and start scanning again
  285. */
  286. static void handle_outgoing_connection_error(void){
  287. printf("Error occurred, disconnect and start over\n");
  288. gap_disconnect(connection_handle);
  289. hog_start_scan();
  290. }
  291. /**
  292. * Handle GATT Client Events dependent on current state
  293. *
  294. * @param packet_type
  295. * @param channel
  296. * @param packet
  297. * @param size
  298. */
  299. static void handle_gatt_client_event(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size) {
  300. UNUSED(packet_type);
  301. UNUSED(channel);
  302. UNUSED(size);
  303. gatt_client_characteristic_t characteristic;
  304. static uint8_t boot_protocol_mode = 0;
  305. switch (app_state) {
  306. case W4_HID_SERVICE_FOUND:
  307. switch (hci_event_packet_get_type(packet)) {
  308. case GATT_EVENT_SERVICE_QUERY_RESULT:
  309. // store service (we expect only one)
  310. gatt_event_service_query_result_get_service(packet, &hid_service);
  311. break;
  312. case GATT_EVENT_QUERY_COMPLETE:
  313. if (gatt_event_query_complete_get_att_status(packet) != ATT_ERROR_SUCCESS) {
  314. printf("ATT Error status %x.\n", gatt_event_query_complete_get_att_status(packet));
  315. handle_outgoing_connection_error();
  316. break;
  317. }
  318. printf("Find required HID Service Characteristics...\n");
  319. app_state = W4_HID_CHARACTERISTICS_FOUND;
  320. gatt_client_discover_characteristics_for_service(&handle_gatt_client_event, connection_handle, &hid_service);
  321. break;
  322. default:
  323. break;
  324. }
  325. break;
  326. case W4_HID_CHARACTERISTICS_FOUND:
  327. switch (hci_event_packet_get_type(packet)){
  328. case GATT_EVENT_CHARACTERISTIC_QUERY_RESULT:
  329. // get characteristic
  330. gatt_event_characteristic_query_result_get_characteristic(packet, &characteristic);
  331. switch (characteristic.uuid16){
  332. case ORG_BLUETOOTH_CHARACTERISTIC_BOOT_KEYBOARD_INPUT_REPORT:
  333. printf("Found CHARACTERISTIC_BOOT_KEYBOARD_INPUT_REPORT, value handle 0x%04x\n", characteristic.value_handle);
  334. memcpy(&boot_keyboard_input_characteristic, &characteristic, sizeof(gatt_client_characteristic_t));
  335. break;
  336. case ORG_BLUETOOTH_CHARACTERISTIC_BOOT_MOUSE_INPUT_REPORT:
  337. printf("Found CHARACTERISTIC_BOOT_MOUSE_INPUT_REPORT, value handle 0x%04x\n", characteristic.value_handle);
  338. memcpy(&boot_mouse_input_characteristic, &characteristic, sizeof(gatt_client_characteristic_t));
  339. break;
  340. case ORG_BLUETOOTH_CHARACTERISTIC_PROTOCOL_MODE:
  341. printf("Found CHARACTERISTIC_PROTOCOL_MODE\n");
  342. memcpy(&protocol_mode_characteristic, &characteristic, sizeof(gatt_client_characteristic_t));
  343. break;
  344. default:
  345. break;
  346. }
  347. break;
  348. case GATT_EVENT_QUERY_COMPLETE:
  349. if (gatt_event_query_complete_get_att_status(packet) != ATT_ERROR_SUCCESS) {
  350. printf("ATT Error status %x.\n", gatt_event_query_complete_get_att_status(packet));
  351. handle_outgoing_connection_error();
  352. break;
  353. }
  354. printf("Enable Notifications for Boot Keyboard Input Report..\n");
  355. app_state = W4_BOOT_KEYBOARD_ENABLED;
  356. gatt_client_write_client_characteristic_configuration(&handle_gatt_client_event, connection_handle, &boot_keyboard_input_characteristic, GATT_CLIENT_CHARACTERISTICS_CONFIGURATION_NOTIFICATION);
  357. break;
  358. default:
  359. break;
  360. }
  361. break;
  362. case W4_BOOT_KEYBOARD_ENABLED:
  363. switch (hci_event_packet_get_type(packet)){
  364. case GATT_EVENT_QUERY_COMPLETE:
  365. if (gatt_event_query_complete_get_att_status(packet) != ATT_ERROR_SUCCESS) {
  366. printf("ATT Error status %x.\n", gatt_event_query_complete_get_att_status(packet));
  367. handle_outgoing_connection_error();
  368. break;
  369. }
  370. // setup listener
  371. gatt_client_listen_for_characteristic_value_updates(&keyboard_notifications, &handle_boot_keyboard_event, connection_handle, &boot_keyboard_input_characteristic);
  372. //
  373. printf("Enable Notifications for Boot Mouse Input Report..\n");
  374. app_state = W4_BOOT_MOUSE_ENABLED;
  375. gatt_client_write_client_characteristic_configuration(&handle_gatt_client_event, connection_handle, &boot_mouse_input_characteristic, GATT_CLIENT_CHARACTERISTICS_CONFIGURATION_NOTIFICATION);
  376. break;
  377. default:
  378. break;
  379. }
  380. break;
  381. case W4_BOOT_MOUSE_ENABLED:
  382. switch (hci_event_packet_get_type(packet)) {
  383. case GATT_EVENT_QUERY_COMPLETE:
  384. if (gatt_event_query_complete_get_att_status(packet) != ATT_ERROR_SUCCESS) {
  385. printf("ATT Error status %x.\n", gatt_event_query_complete_get_att_status(packet));
  386. handle_outgoing_connection_error();
  387. break;
  388. }
  389. // setup listener
  390. gatt_client_listen_for_characteristic_value_updates(&mouse_notifications, &handle_boot_mouse_event, connection_handle, &boot_mouse_input_characteristic);
  391. // switch to boot mode
  392. printf("Set Protocol Mode to Boot Mode..\n");
  393. gatt_client_write_value_of_characteristic_without_response(connection_handle, protocol_mode_characteristic.value_handle, 1, &boot_protocol_mode);
  394. // store device as bonded
  395. if (btstack_tlv_singleton_impl){
  396. btstack_tlv_singleton_impl->store_tag(btstack_tlv_singleton_context, TLV_TAG_HOGD, (const uint8_t *) &remote_device, sizeof(remote_device));
  397. }
  398. // done
  399. printf("Ready - please start typing or mousing..\n");
  400. app_state = READY;
  401. break;
  402. default:
  403. break;
  404. }
  405. break;
  406. default:
  407. break;
  408. }
  409. }
  410. /* LISTING_START(packetHandler): Packet Handler */
  411. static void packet_handler (uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
  412. /* LISTING_PAUSE */
  413. UNUSED(channel);
  414. UNUSED(size);
  415. uint8_t event;
  416. /* LISTING_RESUME */
  417. switch (packet_type) {
  418. case HCI_EVENT_PACKET:
  419. event = hci_event_packet_get_type(packet);
  420. switch (event) {
  421. case BTSTACK_EVENT_STATE:
  422. if (btstack_event_state_get_state(packet) != HCI_STATE_WORKING) break;
  423. btstack_assert(app_state == W4_WORKING);
  424. hog_start_connect();
  425. break;
  426. case GAP_EVENT_ADVERTISING_REPORT:
  427. if (app_state != W4_HID_DEVICE_FOUND) break;
  428. if (adv_event_contains_hid_service(packet) == false) break;
  429. // stop scan
  430. gap_stop_scan();
  431. // store remote device address and type
  432. gap_event_advertising_report_get_address(packet, remote_device.addr);
  433. remote_device.addr_type = gap_event_advertising_report_get_address_type(packet);
  434. // connect
  435. printf("Found, connect to device with %s address %s ...\n", remote_device.addr_type == 0 ? "public" : "random" , bd_addr_to_str(remote_device.addr));
  436. hog_connect();
  437. break;
  438. case HCI_EVENT_DISCONNECTION_COMPLETE:
  439. connection_handle = HCI_CON_HANDLE_INVALID;
  440. switch (app_state){
  441. case READY:
  442. printf("\nDisconnected, try to reconnect...\n");
  443. app_state = W4_TIMEOUT_THEN_RECONNECT;
  444. break;
  445. default:
  446. printf("\nDisconnected, start over...\n");
  447. app_state = W4_TIMEOUT_THEN_SCAN;
  448. break;
  449. }
  450. // set timer
  451. btstack_run_loop_set_timer(&connection_timer, 100);
  452. btstack_run_loop_set_timer_handler(&connection_timer, &hog_reconnect_timeout);
  453. btstack_run_loop_add_timer(&connection_timer);
  454. break;
  455. case HCI_EVENT_LE_META:
  456. // wait for connection complete
  457. if (hci_event_le_meta_get_subevent_code(packet) != HCI_SUBEVENT_LE_CONNECTION_COMPLETE) break;
  458. if (app_state != W4_CONNECTED) return;
  459. btstack_run_loop_remove_timer(&connection_timer);
  460. connection_handle = hci_subevent_le_connection_complete_get_connection_handle(packet);
  461. // request security
  462. app_state = W4_ENCRYPTED;
  463. sm_request_pairing(connection_handle);
  464. break;
  465. case HCI_EVENT_ENCRYPTION_CHANGE:
  466. if (connection_handle != hci_event_encryption_change_get_connection_handle(packet)) break;
  467. printf("Connection encrypted: %u\n", hci_event_encryption_change_get_encryption_enabled(packet));
  468. if (hci_event_encryption_change_get_encryption_enabled(packet) == 0){
  469. printf("Encryption failed -> abort\n");
  470. handle_outgoing_connection_error();
  471. break;
  472. }
  473. // continue - query primary services
  474. printf("Search for HID service.\n");
  475. app_state = W4_HID_SERVICE_FOUND;
  476. gatt_client_discover_primary_services_by_uuid16(handle_gatt_client_event, connection_handle, ORG_BLUETOOTH_SERVICE_HUMAN_INTERFACE_DEVICE);
  477. break;
  478. default:
  479. break;
  480. }
  481. break;
  482. default:
  483. break;
  484. }
  485. }
  486. /* LISTING_END */
  487. /* @section HCI packet handler
  488. *
  489. * @text The SM packet handler receives Security Manager Events required for pairing.
  490. * It also receives events generated during Identity Resolving
  491. * see Listing SMPacketHandler.
  492. */
  493. /* LISTING_START(SMPacketHandler): Scanning and receiving advertisements */
  494. static void sm_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
  495. UNUSED(channel);
  496. UNUSED(size);
  497. if (packet_type != HCI_EVENT_PACKET) return;
  498. switch (hci_event_packet_get_type(packet)) {
  499. case SM_EVENT_JUST_WORKS_REQUEST:
  500. printf("Just works requested\n");
  501. sm_just_works_confirm(sm_event_just_works_request_get_handle(packet));
  502. break;
  503. case SM_EVENT_NUMERIC_COMPARISON_REQUEST:
  504. printf("Confirming numeric comparison: %"PRIu32"\n", sm_event_numeric_comparison_request_get_passkey(packet));
  505. sm_numeric_comparison_confirm(sm_event_passkey_display_number_get_handle(packet));
  506. break;
  507. case SM_EVENT_PASSKEY_DISPLAY_NUMBER:
  508. printf("Display Passkey: %"PRIu32"\n", sm_event_passkey_display_number_get_passkey(packet));
  509. break;
  510. case SM_EVENT_PAIRING_COMPLETE:
  511. switch (sm_event_pairing_complete_get_status(packet)){
  512. case ERROR_CODE_SUCCESS:
  513. printf("Pairing complete, success\n");
  514. break;
  515. case ERROR_CODE_CONNECTION_TIMEOUT:
  516. printf("Pairing failed, timeout\n");
  517. break;
  518. case ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION:
  519. printf("Pairing faileed, disconnected\n");
  520. break;
  521. case ERROR_CODE_AUTHENTICATION_FAILURE:
  522. printf("Pairing failed, reason = %u\n", sm_event_pairing_complete_get_reason(packet));
  523. break;
  524. default:
  525. break;
  526. }
  527. break;
  528. default:
  529. break;
  530. }
  531. }
  532. /* LISTING_END */
  533. int btstack_main(int argc, const char * argv[]);
  534. int btstack_main(int argc, const char * argv[]){
  535. (void)argc;
  536. (void)argv;
  537. /* LISTING_START(HogBootHostSetup): HID-over-GATT Boot Host Setup */
  538. // register for events from HCI
  539. hci_event_callback_registration.callback = &packet_handler;
  540. hci_add_event_handler(&hci_event_callback_registration);
  541. // register for events from Security Manager
  542. sm_event_callback_registration.callback = &sm_packet_handler;
  543. sm_add_event_handler(&sm_event_callback_registration);
  544. // setup le device db
  545. le_device_db_init();
  546. // allow for role switch in general and sniff mode
  547. gap_set_default_link_policy_settings( LM_LINK_POLICY_ENABLE_ROLE_SWITCH | LM_LINK_POLICY_ENABLE_SNIFF_MODE );
  548. //
  549. l2cap_init();
  550. sm_init();
  551. gatt_client_init();
  552. /* LISTING_END */
  553. // Disable stdout buffering
  554. setbuf(stdout, NULL);
  555. app_state = W4_WORKING;
  556. // Turn on the device
  557. hci_power_control(HCI_POWER_ON);
  558. return 0;
  559. }
  560. /* EXAMPLE_END */