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