xref: /btstack/example/hog_mouse_demo.c (revision ced70f9bfeafe291ec597a3a9cc862e39e0da3ce)
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 BLUEKITCHEN
24  * GMBH 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__ "hog_mouse_demo.c"
39 
40 // *****************************************************************************
41 /* EXAMPLE_START(hog_mouse_demo): HID Mouse LE
42  */
43 // *****************************************************************************
44 
45 #include <stdint.h>
46 #include <stdio.h>
47 #include <stdlib.h>
48 #include <string.h>
49 #include <inttypes.h>
50 
51 #include "hog_mouse_demo.h"
52 
53 #include "btstack.h"
54 
55 #include "ble/gatt-service/battery_service_server.h"
56 #include "ble/gatt-service/device_information_service_server.h"
57 #include "ble/gatt-service/hids_device.h"
58 
59 // from USB HID Specification 1.1, Appendix B.2
60 const uint8_t hid_descriptor_mouse_boot_mode[] = {
61     0x05, 0x01,                    // USAGE_PAGE (Generic Desktop)
62     0x09, 0x02,                    // USAGE (Mouse)
63     0xa1, 0x01,                    // COLLECTION (Application)
64 
65     0x85,  0x01,                    // Report ID 1
66 
67     0x09, 0x01,                    //   USAGE (Pointer)
68 
69     0xa1, 0x00,                    //   COLLECTION (Physical)
70 
71 #if 1
72     0x05, 0x09,                    //     USAGE_PAGE (Button)
73     0x19, 0x01,                    //     USAGE_MINIMUM (Button 1)
74     0x29, 0x03,                    //     USAGE_MAXIMUM (Button 3)
75     0x15, 0x00,                    //     LOGICAL_MINIMUM (0)
76     0x25, 0x01,                    //     LOGICAL_MAXIMUM (1)
77     0x95, 0x03,                    //     REPORT_COUNT (3)
78     0x75, 0x01,                    //     REPORT_SIZE (1)
79     0x81, 0x02,                    //     INPUT (Data,Var,Abs)
80     0x95, 0x01,                    //     REPORT_COUNT (1)
81     0x75, 0x05,                    //     REPORT_SIZE (5)
82     0x81, 0x03,                    //     INPUT (Cnst,Var,Abs)
83 #endif
84 
85 #if 1
86     0x05, 0x01,                    //     USAGE_PAGE (Generic Desktop)
87     0x09, 0x30,                    //     USAGE (X)
88     0x09, 0x31,                    //     USAGE (Y)
89     0x15, 0x81,                    //     LOGICAL_MINIMUM (-127)
90     0x25, 0x7f,                    //     LOGICAL_MAXIMUM (127)
91     0x75, 0x08,                    //     REPORT_SIZE (8)
92     0x95, 0x02,                    //     REPORT_COUNT (2)
93     0x81, 0x06,                    //     INPUT (Data,Var,Rel)
94 #endif
95 
96     0xc0,                          //   END_COLLECTION
97     0xc0                           // END_COLLECTION
98 };
99 
100 static btstack_packet_callback_registration_t hci_event_callback_registration;
101 static btstack_packet_callback_registration_t l2cap_event_callback_registration;
102 static btstack_packet_callback_registration_t sm_event_callback_registration;
103 static uint8_t battery = 100;
104 static hci_con_handle_t con_handle = HCI_CON_HANDLE_INVALID;
105 static uint8_t protocol_mode = 1;
106 
107 static void packet_handler (uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size);
108 
109 const uint8_t adv_data[] = {
110     // Flags general discoverable, BR/EDR not supported
111     0x02, BLUETOOTH_DATA_TYPE_FLAGS, 0x06,
112     // Name
113     0x0a, BLUETOOTH_DATA_TYPE_COMPLETE_LOCAL_NAME, 'H', 'I', 'D', ' ', 'M', 'o', 'u', 's', 'e',
114     // 16-bit Service UUIDs
115     0x03, BLUETOOTH_DATA_TYPE_COMPLETE_LIST_OF_16_BIT_SERVICE_CLASS_UUIDS, ORG_BLUETOOTH_SERVICE_HUMAN_INTERFACE_DEVICE & 0xff, ORG_BLUETOOTH_SERVICE_HUMAN_INTERFACE_DEVICE >> 8,
116     // Appearance HID - Mouse (Category 15, Sub-Category 2)
117     0x03, BLUETOOTH_DATA_TYPE_APPEARANCE, 0xC2, 0x03,
118 };
119 const uint8_t adv_data_len = sizeof(adv_data);
120 
121 static void hog_mouse_setup(void){
122 
123     // setup l2cap and
124     l2cap_init();
125 
126     // setup SM: Display only
127     sm_init();
128     sm_set_io_capabilities(IO_CAPABILITY_DISPLAY_ONLY);
129     // sm_set_authentication_requirements(SM_AUTHREQ_SECURE_CONNECTION | SM_AUTHREQ_BONDING);
130     sm_set_authentication_requirements(SM_AUTHREQ_BONDING);
131 
132     // setup ATT server
133     att_server_init(profile_data, NULL, NULL);
134 
135     // setup battery service
136     battery_service_server_init(battery);
137 
138     // setup device information service
139     device_information_service_server_init();
140 
141     // setup HID Device service
142     hids_device_init(0, hid_descriptor_mouse_boot_mode, sizeof(hid_descriptor_mouse_boot_mode));
143 
144     // setup advertisements
145     uint16_t adv_int_min = 0x0030;
146     uint16_t adv_int_max = 0x0030;
147     uint8_t adv_type = 0;
148     bd_addr_t null_addr;
149     memset(null_addr, 0, 6);
150     gap_advertisements_set_params(adv_int_min, adv_int_max, adv_type, 0, null_addr, 0x07, 0x00);
151     gap_advertisements_set_data(adv_data_len, (uint8_t*) adv_data);
152     gap_advertisements_enable(1);
153 
154     // register for events
155     hci_event_callback_registration.callback = &packet_handler;
156     hci_add_event_handler(&hci_event_callback_registration);
157 
158     // register for connection parameter updates
159     l2cap_event_callback_registration.callback = &packet_handler;
160     l2cap_add_event_handler(&l2cap_event_callback_registration);
161 
162     sm_event_callback_registration.callback = &packet_handler;
163     sm_add_event_handler(&sm_event_callback_registration);
164 
165     hids_device_register_packet_handler(packet_handler);
166 }
167 
168 // HID Report sending
169 static void send_report(uint8_t buttons, int8_t dx, int8_t dy){
170     uint8_t report[] = { buttons, (uint8_t) dx, (uint8_t) dy };
171     switch (protocol_mode){
172         case 0:
173             hids_device_send_boot_mouse_input_report(con_handle, report, sizeof(report));
174             break;
175         case 1:
176             hids_device_send_input_report(con_handle, report, sizeof(report));
177             break;
178         default:
179             break;
180     }
181     printf("Mouse: %d/%d - buttons: %02x\n", dx, dy, buttons);
182 }
183 
184 static int dx;
185 static int dy;
186 static uint8_t buttons;
187 
188 static void mousing_can_send_now(void){
189     send_report(buttons, dx, dy);
190     // reset
191     dx = 0;
192     dy = 0;
193     if (buttons){
194         buttons = 0;
195         hids_device_request_can_send_now_event(con_handle);
196     }
197 }
198 
199 // Demo Application
200 
201 #ifdef HAVE_BTSTACK_STDIN
202 
203 static const int MOUSE_SPEED = 30;
204 
205 // On systems with STDIN, we can directly type on the console
206 
207 static void stdin_process(char character){
208 
209     if (con_handle == HCI_CON_HANDLE_INVALID) {
210         printf("Mouse not connected, ignoring '%c'\n", character);
211         return;
212     }
213 
214     switch (character){
215         case 'a':
216             dx -= MOUSE_SPEED;
217             break;
218         case 's':
219             dy += MOUSE_SPEED;
220             break;
221         case 'd':
222             dx += MOUSE_SPEED;
223             break;
224         case 'w':
225             dy -= MOUSE_SPEED;
226             break;
227         case 'l':
228             buttons |= 1;
229             break;
230         case 'r':
231             buttons |= 2;
232             break;
233         default:
234             return;
235     }
236     hids_device_request_can_send_now_event(con_handle);
237 }
238 
239 #else
240 
241 // On embedded systems, simulate clicking on 4 corners of a square
242 
243 #define MOUSE_PERIOD_MS 15
244 
245 static const int STEPS_PER_DIRECTION = 50;
246 static const int MOUSE_SPEED = 10;
247 
248 static btstack_timer_source_t mousing_timer;
249 static int mousing_active = 0;
250 static int step;
251 
252 static struct {
253     int dx;
254     int dy;
255 } directions[] = {
256     {  1,  0 },
257     {  0,  1 },
258     { -1,  0 },
259     {  0, -1 },
260 };
261 
262 
263 static void mousing_timer_handler(btstack_timer_source_t * ts){
264 
265     if (con_handle == HCI_CON_HANDLE_INVALID) {
266         mousing_active = 0;
267         return;
268     }
269 
270     // simulate left click when corner reached
271     if (step % STEPS_PER_DIRECTION == 0){
272         buttons |= 1;
273     }
274     // simulate move
275     int direction_index = step / STEPS_PER_DIRECTION;
276     dx += directions[direction_index].dx * MOUSE_SPEED;
277     dy += directions[direction_index].dy * MOUSE_SPEED;
278 
279     // next
280     step++;
281     if (step >= STEPS_PER_DIRECTION * 4) {
282         step = 0;
283     }
284 
285     // trigger send
286     hids_device_request_can_send_now_event(con_handle);
287 
288     // set next timer
289     btstack_run_loop_set_timer(ts, MOUSE_PERIOD_MS);
290     btstack_run_loop_add_timer(ts);
291 }
292 
293 static void hid_embedded_start_mousing(void){
294     if (mousing_active) return;
295     mousing_active = 1;
296 
297     printf("Start mousing..\n");
298 
299     step = 0;
300 
301     // set one-shot timer
302     mousing_timer.process = &mousing_timer_handler;
303     btstack_run_loop_set_timer(&mousing_timer, MOUSE_PERIOD_MS);
304     btstack_run_loop_add_timer(&mousing_timer);
305 }
306 #endif
307 
308 static void packet_handler (uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
309     UNUSED(channel);
310     UNUSED(size);
311     uint16_t conn_interval;
312 
313     if (packet_type != HCI_EVENT_PACKET) return;
314 
315     switch (hci_event_packet_get_type(packet)) {
316         case HCI_EVENT_DISCONNECTION_COMPLETE:
317             con_handle = HCI_CON_HANDLE_INVALID;
318             printf("Disconnected\n");
319             break;
320         case SM_EVENT_JUST_WORKS_REQUEST:
321             printf("Just Works requested\n");
322             sm_just_works_confirm(sm_event_just_works_request_get_handle(packet));
323             break;
324         case SM_EVENT_NUMERIC_COMPARISON_REQUEST:
325             printf("Confirming numeric comparison: %"PRIu32"\n", sm_event_numeric_comparison_request_get_passkey(packet));
326             sm_numeric_comparison_confirm(sm_event_passkey_display_number_get_handle(packet));
327             break;
328         case SM_EVENT_PASSKEY_DISPLAY_NUMBER:
329             printf("Display Passkey: %"PRIu32"\n", sm_event_passkey_display_number_get_passkey(packet));
330             break;
331         case L2CAP_EVENT_CONNECTION_PARAMETER_UPDATE_RESPONSE:
332             printf("L2CAP Connection Parameter Update Complete, response: %x\n", l2cap_event_connection_parameter_update_response_get_result(packet));
333             break;
334         case HCI_EVENT_META_GAP:
335             switch (hci_event_gap_meta_get_subevent_code(packet)) {
336                 case GAP_SUBEVENT_LE_CONNECTION_COMPLETE:
337                     // print connection parameters (without using float operations)
338                     conn_interval = gap_subevent_le_connection_complete_get_conn_interval(packet);
339                     printf("LE Connection Complete:\n");
340                     printf("- Connection Interval: %u.%02u ms\n", conn_interval * 125 / 100, 25 * (conn_interval & 3));
341                     printf("- Connection Latency: %u\n", gap_subevent_le_connection_complete_get_conn_latency(packet));
342                     break;
343                 default:
344                     break;
345             }
346             break;
347         case HCI_EVENT_LE_META:
348             switch (hci_event_le_meta_get_subevent_code(packet)) {
349                 case HCI_SUBEVENT_LE_CONNECTION_UPDATE_COMPLETE:
350                     // print connection parameters (without using float operations)
351                     conn_interval = hci_subevent_le_connection_update_complete_get_conn_interval(packet);
352                     printf("LE Connection Update:\n");
353                     printf("- Connection Interval: %u.%02u ms\n", conn_interval * 125 / 100, 25 * (conn_interval & 3));
354                     printf("- Connection Latency: %u\n", hci_subevent_le_connection_update_complete_get_conn_latency(packet));
355                     break;
356                 default:
357                     break;
358             }
359             break;
360         case HCI_EVENT_HIDS_META:
361             switch (hci_event_hids_meta_get_subevent_code(packet)){
362                 case HIDS_SUBEVENT_INPUT_REPORT_ENABLE:
363                     con_handle = hids_subevent_input_report_enable_get_con_handle(packet);
364                     printf("Report Characteristic Subscribed %u\n", hids_subevent_input_report_enable_get_enable(packet));
365 #ifndef HAVE_BTSTACK_STDIN
366                     hid_embedded_start_mousing();
367 #endif
368                     // request connection param update via L2CAP following Apple Bluetooth Design Guidelines
369                     // gap_request_connection_parameter_update(con_handle, 12, 12, 4, 100);    // 15 ms, 4, 1s
370 
371                     // directly update connection params via HCI following Apple Bluetooth Design Guidelines
372                     // gap_update_connection_parameters(con_handle, 12, 12, 4, 100);    // 60-75 ms, 4, 1s
373 
374                     break;
375                 case HIDS_SUBEVENT_BOOT_KEYBOARD_INPUT_REPORT_ENABLE:
376                     con_handle = hids_subevent_boot_keyboard_input_report_enable_get_con_handle(packet);
377                     printf("Boot Keyboard Characteristic Subscribed %u\n", hids_subevent_boot_keyboard_input_report_enable_get_enable(packet));
378                     break;
379                 case HIDS_SUBEVENT_BOOT_MOUSE_INPUT_REPORT_ENABLE:
380                     con_handle = hids_subevent_boot_mouse_input_report_enable_get_con_handle(packet);
381                     printf("Boot Mouse Characteristic Subscribed %u\n", hids_subevent_boot_mouse_input_report_enable_get_enable(packet));
382                     break;
383                 case HIDS_SUBEVENT_PROTOCOL_MODE:
384                     protocol_mode = hids_subevent_protocol_mode_get_protocol_mode(packet);
385                     printf("Protocol Mode: %s mode\n", hids_subevent_protocol_mode_get_protocol_mode(packet) ? "Report" : "Boot");
386                     break;
387                 case HIDS_SUBEVENT_CAN_SEND_NOW:
388                     mousing_can_send_now();
389                     break;
390                 default:
391                     break;
392             }
393             break;
394 
395         default:
396             break;
397     }
398 }
399 
400 int btstack_main(void);
401 int btstack_main(void)
402 {
403     hog_mouse_setup();
404 
405 #ifdef HAVE_BTSTACK_STDIN
406     btstack_stdin_setup(stdin_process);
407 #endif
408 
409     // turn on!
410     hci_power_control(HCI_POWER_ON);
411 
412     return 0;
413 }
414