xref: /btstack/example/hid_host_demo.c (revision 6973c35a87cc7f398c429d8942b18d0a401e28a3)
1 /*
2  * Copyright (C) 2017 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  * [email protected]
35  *
36  */
37 
38 #define __BTSTACK_FILE__ "hid_host_demo.c"
39 
40 /*
41  * hid_host_demo.c
42  */
43 
44 /* EXAMPLE_START(hid_host_demo): HID Host Demo
45  *
46  * @text This example implements an HID Host. For now, it connnects to a fixed device, queries the HID SDP
47  * record and opens the HID Control + Interrupt channels
48  */
49 
50 #include <inttypes.h>
51 #include <stdio.h>
52 
53 #include "btstack_config.h"
54 #include "btstack.h"
55 
56 #define MAX_ATTRIBUTE_VALUE_SIZE 300
57 
58 // SDP
59 static uint8_t            hid_descriptor[MAX_ATTRIBUTE_VALUE_SIZE];
60 static uint16_t           hid_descriptor_len;
61 
62 static uint16_t           hid_control_psm;
63 static uint16_t           hid_interrupt_psm;
64 
65 static uint8_t            attribute_value[MAX_ATTRIBUTE_VALUE_SIZE];
66 static const unsigned int attribute_value_buffer_size = MAX_ATTRIBUTE_VALUE_SIZE;
67 
68 // L2CAP
69 static uint16_t           l2cap_hid_control_cid;
70 static uint16_t           l2cap_hid_interrupt_cid;
71 
72 // MBP 2016
73 static const char * remote_addr_string = "F4-0F-24-3B-1B-E1";
74 // iMpulse static const char * remote_addr_string = "64:6E:6C:C1:AA:B5";
75 
76 static bd_addr_t remote_addr;
77 
78 static btstack_packet_callback_registration_t hci_event_callback_registration;
79 
80 // Simplified US Keyboard with Shift modifier
81 
82 #define CHAR_ILLEGAL     0xff
83 #define CHAR_RETURN     '\n'
84 #define CHAR_ESCAPE      27
85 #define CHAR_TAB         '\t'
86 #define CHAR_BACKSPACE   0x7f
87 
88 /**
89  * English (US)
90  */
91 static const uint8_t keytable_us_none [] = {
92     CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL,             /*   0-3 */
93     'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',                   /*  4-13 */
94     'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't',                   /* 14-23 */
95     'u', 'v', 'w', 'x', 'y', 'z',                                       /* 24-29 */
96     '1', '2', '3', '4', '5', '6', '7', '8', '9', '0',                   /* 30-39 */
97     CHAR_RETURN, CHAR_ESCAPE, CHAR_BACKSPACE, CHAR_TAB, ' ',            /* 40-44 */
98     '-', '=', '[', ']', '\\', CHAR_ILLEGAL, ';', '\'', 0x60, ',',       /* 45-54 */
99     '.', '/', CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL,   /* 55-60 */
100     CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL,             /* 61-64 */
101     CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL,             /* 65-68 */
102     CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL,             /* 69-72 */
103     CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL,             /* 73-76 */
104     CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL,             /* 77-80 */
105     CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL,             /* 81-84 */
106     '*', '-', '+', '\n', '1', '2', '3', '4', '5',                       /* 85-97 */
107     '6', '7', '8', '9', '0', '.', 0xa7,                                 /* 97-100 */
108 };
109 
110 static const uint8_t keytable_us_shift[] = {
111     CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL,             /*  0-3  */
112     'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',                   /*  4-13 */
113     'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',                   /* 14-23 */
114     'U', 'V', 'W', 'X', 'Y', 'Z',                                       /* 24-29 */
115     '!', '@', '#', '$', '%', '^', '&', '*', '(', ')',                   /* 30-39 */
116     CHAR_RETURN, CHAR_ESCAPE, CHAR_BACKSPACE, CHAR_TAB, ' ',            /* 40-44 */
117     '_', '+', '{', '}', '|', CHAR_ILLEGAL, ':', '"', 0x7E, '<',         /* 45-54 */
118     '>', '?', CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL,   /* 55-60 */
119     CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL,             /* 61-64 */
120     CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL,             /* 65-68 */
121     CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL,             /* 69-72 */
122     CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL,             /* 73-76 */
123     CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL,             /* 77-80 */
124     CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL, CHAR_ILLEGAL,             /* 81-84 */
125     '*', '-', '+', '\n', '1', '2', '3', '4', '5',                       /* 85-97 */
126     '6', '7', '8', '9', '0', '.', 0xb1,                                 /* 97-100 */
127 };
128 
129 
130 /* @section Main application configuration
131  *
132  * @text In the application configuration, L2CAP is initialized
133  */
134 
135 /* LISTING_START(PanuSetup): Panu setup */
136 static void packet_handler (uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size);
137 static void handle_sdp_client_query_result(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size);
138 
139 static void hid_host_setup(void){
140 
141     // register for HCI events
142     hci_event_callback_registration.callback = &packet_handler;
143     hci_add_event_handler(&hci_event_callback_registration);
144 
145     // Initialize L2CAP
146     l2cap_init();
147 
148     // Disable stdout buffering
149     setbuf(stdout, NULL);
150 }
151 /* LISTING_END */
152 
153 /* @section SDP parser callback
154  *
155  * @text The SDP parsers retrieves the BNEP PAN UUID as explained in
156  * Section [on SDP BNEP Query example](#sec:sdpbnepqueryExample}.
157  */
158 
159 static void handle_sdp_client_query_result(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size) {
160 
161     UNUSED(packet_type);
162     UNUSED(channel);
163     UNUSED(size);
164 
165     des_iterator_t attribute_list_it;
166     des_iterator_t additional_des_it;
167     des_iterator_t prot_it;
168     uint8_t       *des_element;
169     uint8_t       *element;
170     uint32_t       uuid;
171     uint8_t        status;
172 
173     switch (hci_event_packet_get_type(packet)){
174         case SDP_EVENT_QUERY_ATTRIBUTE_VALUE:
175             if (sdp_event_query_attribute_byte_get_attribute_length(packet) <= attribute_value_buffer_size) {
176                 attribute_value[sdp_event_query_attribute_byte_get_data_offset(packet)] = sdp_event_query_attribute_byte_get_data(packet);
177                 if ((uint16_t)(sdp_event_query_attribute_byte_get_data_offset(packet)+1) == sdp_event_query_attribute_byte_get_attribute_length(packet)) {
178                     switch(sdp_event_query_attribute_byte_get_attribute_id(packet)) {
179                         case BLUETOOTH_ATTRIBUTE_PROTOCOL_DESCRIPTOR_LIST:
180                             for (des_iterator_init(&attribute_list_it, attribute_value); des_iterator_has_more(&attribute_list_it); des_iterator_next(&attribute_list_it)) {
181                                 if (des_iterator_get_type(&attribute_list_it) != DE_DES) continue;
182                                 des_element = des_iterator_get_element(&attribute_list_it);
183                                 des_iterator_init(&prot_it, des_element);
184                                 element = des_iterator_get_element(&prot_it);
185                                 if (de_get_element_type(element) != DE_UUID) continue;
186                                 uuid = de_get_uuid32(element);
187                                 switch (uuid){
188                                     case BLUETOOTH_PROTOCOL_L2CAP:
189                                         if (!des_iterator_has_more(&prot_it)) continue;
190                                         des_iterator_next(&prot_it);
191                                         de_element_get_uint16(des_iterator_get_element(&prot_it), &hid_control_psm);
192                                         printf("HID Control PSM: 0x%04x\n", (int) hid_control_psm);
193                                         break;
194                                     default:
195                                         break;
196                                 }
197                             }
198                             break;
199                         case BLUETOOTH_ATTRIBUTE_ADDITIONAL_PROTOCOL_DESCRIPTOR_LISTS:
200                             for (des_iterator_init(&attribute_list_it, attribute_value); des_iterator_has_more(&attribute_list_it); des_iterator_next(&attribute_list_it)) {
201                                 if (des_iterator_get_type(&attribute_list_it) != DE_DES) continue;
202                                 des_element = des_iterator_get_element(&attribute_list_it);
203                                 for (des_iterator_init(&additional_des_it, des_element); des_iterator_has_more(&additional_des_it); des_iterator_next(&additional_des_it)) {
204                                     if (des_iterator_get_type(&additional_des_it) != DE_DES) continue;
205                                     des_element = des_iterator_get_element(&additional_des_it);
206                                     des_iterator_init(&prot_it, des_element);
207                                     element = des_iterator_get_element(&prot_it);
208                                     if (de_get_element_type(element) != DE_UUID) continue;
209                                     uuid = de_get_uuid32(element);
210                                     switch (uuid){
211                                         case BLUETOOTH_PROTOCOL_L2CAP:
212                                             if (!des_iterator_has_more(&prot_it)) continue;
213                                             des_iterator_next(&prot_it);
214                                             de_element_get_uint16(des_iterator_get_element(&prot_it), &hid_interrupt_psm);
215                                             printf("HID Interrupt PSM: 0x%04x\n", (int) hid_interrupt_psm);
216                                             break;
217                                         default:
218                                             break;
219                                     }
220                                 }
221                             }
222                             break;
223                         case BLUETOOTH_ATTRIBUTE_HID_DESCRIPTOR_LIST:
224                             for (des_iterator_init(&attribute_list_it, attribute_value); des_iterator_has_more(&attribute_list_it); des_iterator_next(&attribute_list_it)) {
225                                 if (des_iterator_get_type(&attribute_list_it) != DE_DES) continue;
226                                 des_element = des_iterator_get_element(&attribute_list_it);
227                                 for (des_iterator_init(&additional_des_it, des_element); des_iterator_has_more(&additional_des_it); des_iterator_next(&additional_des_it)) {
228                                     if (des_iterator_get_type(&additional_des_it) != DE_STRING) continue;
229                                     element = des_iterator_get_element(&additional_des_it);
230                                     const uint8_t * descriptor = de_get_string(element);
231                                     hid_descriptor_len = de_get_data_size(element);
232                                     memcpy(hid_descriptor, descriptor, hid_descriptor_len);
233                                     printf("HID Descriptor:\n");
234                                     printf_hexdump(hid_descriptor, hid_descriptor_len);
235                                 }
236                             }
237                             break;
238                         default:
239                             break;
240                     }
241                 }
242             } else {
243                 fprintf(stderr, "SDP attribute value buffer size exceeded: available %d, required %d\n", attribute_value_buffer_size, sdp_event_query_attribute_byte_get_attribute_length(packet));
244             }
245             break;
246 
247         case SDP_EVENT_QUERY_COMPLETE:
248             if (!hid_control_psm) {
249                 printf("HID Control PSM missing\n");
250                 break;
251             }
252             if (!hid_interrupt_psm) {
253                 printf("HID Interrupt PSM missing\n");
254                 break;
255             }
256             printf("Setup HID\n");
257             status = l2cap_create_channel(packet_handler, remote_addr, hid_control_psm, 48, &l2cap_hid_control_cid);
258             if (status){
259                 printf("Connecting to HID Control failed: 0x%02x\n", status);
260             }
261             break;
262     }
263 }
264 
265 /*
266  * @section HID Report Handler
267  *
268  * @text Use BTstack's compact HID Parser to process incoming HID Report
269  * Iterate over all fields and process fields with usage page = 0x07 / Keyboard
270  * Check if SHIFT is down and process first character (don't handle multiple key presses)
271  *
272  */
273 #define NUM_KEYS 6
274 static uint8_t last_keys[NUM_KEYS];
275 static void hid_host_handle_interrupt_report(const uint8_t * report, uint16_t report_len){
276     // check if HID Input Report
277     if (report_len < 1) return;
278     if (*report != 0xa1) return;
279     report++;
280     report_len--;
281     btstack_hid_parser_t parser;
282     btstack_hid_parser_init(&parser, hid_descriptor, hid_descriptor_len, BTSTACK_HID_REPORT_TYPE_INPUT, report, report_len);
283     int shift = 0;
284     uint8_t new_keys[NUM_KEYS];
285     memset(new_keys, 0, sizeof(new_keys));
286     int     new_keys_count = 0;
287     while (btstack_hid_parser_has_more(&parser)){
288         uint16_t usage_page;
289         uint16_t usage;
290         int32_t  value;
291         btstack_hid_parser_get_field(&parser, &usage_page, &usage, &value);
292         if (usage_page != 0x07) continue;
293         switch (usage){
294             case 0xe1:
295             case 0xe6:
296                 if (value){
297                     shift = 1;
298                 }
299                 continue;
300             case 0x00:
301                 continue;
302             default:
303                 break;
304         }
305         if (usage >= sizeof(keytable_us_none)) continue;
306 
307         // store new keys
308         new_keys[new_keys_count++] = usage;
309 
310         // check if usage was used last time (and ignore in that case)
311         int i;
312         for (i=0;i<NUM_KEYS;i++){
313             if (usage == last_keys[i]){
314                 usage = 0;
315             }
316         }
317         if (usage == 0) continue;
318 
319         uint8_t key;
320         if (shift){
321             key = keytable_us_shift[usage];
322         } else {
323             key = keytable_us_none[usage];
324         }
325         if (key == CHAR_ILLEGAL) continue;
326         if (key == CHAR_BACKSPACE){
327             printf("\b \b");    // go back one char, print space, go back one char again
328             continue;
329         }
330         printf("%c", key);
331     }
332     memcpy(last_keys, new_keys, NUM_KEYS);
333 }
334 
335 /*
336  * @section Packet Handler
337  *
338  * @text The packet handler responds to various HCI Events.
339  */
340 
341 /* LISTING_START(packetHandler): Packet Handler */
342 static void packet_handler (uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size)
343 {
344     /* LISTING_PAUSE */
345     uint8_t   event;
346     bd_addr_t event_addr;
347     uint8_t   status;
348     uint16_t  l2cap_cid;
349 
350     /* LISTING_RESUME */
351     switch (packet_type) {
352 		case HCI_EVENT_PACKET:
353             event = hci_event_packet_get_type(packet);
354             switch (event) {
355                 /* @text When BTSTACK_EVENT_STATE with state HCI_STATE_WORKING
356                  * is received and the example is started in client mode, the remote SDP HID query is started.
357                  */
358                 case BTSTACK_EVENT_STATE:
359                     if (btstack_event_state_get_state(packet) == HCI_STATE_WORKING){
360                         printf("Start SDP HID query for remote HID Device.\n");
361                         sdp_client_query_uuid16(&handle_sdp_client_query_result, remote_addr, BLUETOOTH_SERVICE_CLASS_HUMAN_INTERFACE_DEVICE_SERVICE);
362                     }
363                     break;
364 
365                 /* LISTING_PAUSE */
366                 case HCI_EVENT_PIN_CODE_REQUEST:
367 					// inform about pin code request
368                     printf("Pin code request - using '0000'\n");
369                     hci_event_pin_code_request_get_bd_addr(packet, event_addr);
370                     gap_pin_code_response(event_addr, "0000");
371 					break;
372 
373                 case HCI_EVENT_USER_CONFIRMATION_REQUEST:
374                     // inform about user confirmation request
375                     printf("SSP User Confirmation Request with numeric value '%"PRIu32"'\n", little_endian_read_32(packet, 8));
376                     printf("SSP User Confirmation Auto accept\n");
377                     break;
378 
379                 /* LISTING_RESUME */
380 
381                 case L2CAP_EVENT_CHANNEL_OPENED:
382                     status = packet[2];
383                     if (status){
384                         printf("L2CAP Connection failed: 0x%02x\n", status);
385                         break;
386                     }
387                     l2cap_cid  = little_endian_read_16(packet, 13);
388                     if (!l2cap_cid) break;
389                     if (l2cap_cid == l2cap_hid_control_cid){
390                         status = l2cap_create_channel(packet_handler, remote_addr, hid_interrupt_psm, 48, &l2cap_hid_interrupt_cid);
391                         if (status){
392                             printf("Connecting to HID Control failed: 0x%02x\n", status);
393                             break;
394                         }
395                     }
396                     if (l2cap_cid == l2cap_hid_interrupt_cid){
397                         printf("HID Connection established\n");
398                     }
399                     break;
400                 default:
401                     break;
402             }
403             break;
404         case L2CAP_DATA_PACKET:
405             // for now, just dump incoming data
406             if (channel == l2cap_hid_interrupt_cid){
407                 hid_host_handle_interrupt_report(packet,  size);
408             } else if (channel == l2cap_hid_control_cid){
409                 printf("HID Control: ");
410                 printf_hexdump(packet, size);
411             } else {
412                 break;
413             }
414         default:
415             break;
416     }
417 }
418 /* LISTING_END */
419 
420 int btstack_main(int argc, const char * argv[]);
421 int btstack_main(int argc, const char * argv[]){
422 
423     (void)argc;
424     (void)argv;
425 
426     hid_host_setup();
427 
428     // parse human readable Bluetooth address
429     sscanf_bd_addr(remote_addr_string, remote_addr);
430 
431     // Turn on the device
432     hci_power_control(HCI_POWER_ON);
433     return 0;
434 }
435 
436 /* EXAMPLE_END */
437