xref: /btstack/example/le_streamer_client.c (revision 360243be41f47158adff357b9fead2686419a2df)
1 /*
2  * Copyright (C) 2014 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__ "le_streamer_client.c"
39 
40 // *****************************************************************************
41 //
42 // LE Streamer Client - connects to 'LE Streamer' and subscribes to test characteristic
43 //
44 // *****************************************************************************
45 
46 #include <stdint.h>
47 #include <stdio.h>
48 #include <stdlib.h>
49 #include <string.h>
50 
51 #include "btstack.h"
52 
53 typedef enum {
54     TC_OFF,
55     TC_IDLE,
56     TC_W4_SCAN_RESULT,
57     TC_W4_CONNECT,
58     TC_W4_SERVICE_RESULT,
59     TC_W4_CHARACTERISTIC_RESULT,
60     TC_W4_TEST_DATA
61 } gc_state_t;
62 
63 static bd_addr_t cmdline_addr = { };
64 static int cmdline_addr_found = 0;
65 
66 // addr and type of device with correct name
67 static bd_addr_t      le_streamer_addr;
68 static bd_addr_type_t le_streamer_addr_type;
69 
70 static hci_con_handle_t connection_handle;
71 static uint8_t le_streamer_service_uuid[16]        = { 0x00, 0x00, 0xFF, 0x10, 0x00, 0x00, 0x10, 0x00, 0x80, 0x00, 0x00, 0x80, 0x5F, 0x9B, 0x34, 0xFB};
72 static uint8_t le_streamer_characteristic_uuid[16] = { 0x00, 0x00, 0xFF, 0x11, 0x00, 0x00, 0x10, 0x00, 0x80, 0x00, 0x00, 0x80, 0x5F, 0x9B, 0x34, 0xFB};
73 
74 static gatt_client_service_t le_streamer_service;
75 static gatt_client_characteristic_t le_streamer_characteristic;
76 
77 static gatt_client_notification_t notification_listener;
78 static int listener_registered;
79 
80 static gc_state_t state = TC_OFF;
81 static btstack_packet_callback_registration_t hci_event_callback_registration;
82 
83 /*
84  * @section Track throughput
85  * @text We calculate the throughput by setting a start time and measuring the amount of
86  * data sent. After a configurable REPORT_INTERVAL_MS, we print the throughput in kB/s
87  * and reset the counter and start time.
88  */
89 
90 /* LISTING_START(tracking): Tracking throughput */
91 
92 #define REPORT_INTERVAL_MS 3000
93 
94 // support for multiple clients
95 typedef struct {
96     char name;
97     int le_notification_enabled;
98     hci_con_handle_t connection_handle;
99     int  counter;
100     char test_data[200];
101     int  test_data_len;
102     uint32_t test_data_sent;
103     uint32_t test_data_start;
104 } le_streamer_connection_t;
105 
106 static le_streamer_connection_t le_streamer_connection;
107 
108 static void test_reset(le_streamer_connection_t * context){
109     context->test_data_start = btstack_run_loop_get_time_ms();
110     context->test_data_sent = 0;
111 }
112 
113 static void test_track_data(le_streamer_connection_t * context, int bytes_sent){
114     context->test_data_sent += bytes_sent;
115     // evaluate
116     uint32_t now = btstack_run_loop_get_time_ms();
117     uint32_t time_passed = now - context->test_data_start;
118     if (time_passed < REPORT_INTERVAL_MS) return;
119     // print speed
120     int bytes_per_second = context->test_data_sent * 1000 / time_passed;
121     printf("%c: %u bytes -> %u.%03u kB/s\n", context->name, context->test_data_sent, bytes_per_second / 1000, bytes_per_second % 1000);
122 
123     // restart
124     context->test_data_start = now;
125     context->test_data_sent  = 0;
126 }
127 /* LISTING_END(tracking): Tracking throughput */
128 
129 
130 // returns 1 if name is found in advertisement
131 static int advertisement_report_contains_name(const char * name, uint8_t * advertisement_report){
132     // get advertisement from report event
133     const uint8_t * adv_data = gap_event_advertising_report_get_data(advertisement_report);
134     uint16_t        adv_len  = gap_event_advertising_report_get_data_length(advertisement_report);
135     int             name_len = strlen(name);
136 
137     // iterate over advertisement data
138     ad_context_t context;
139     for (ad_iterator_init(&context, adv_len, adv_data) ; ad_iterator_has_more(&context) ; ad_iterator_next(&context)){
140         uint8_t data_type    = ad_iterator_get_data_type(&context);
141         uint8_t data_size    = ad_iterator_get_data_len(&context);
142         const uint8_t * data = ad_iterator_get_data(&context);
143         int i;
144         switch (data_type){
145             case BLUETOOTH_DATA_TYPE_SHORTENED_LOCAL_NAME:
146             case BLUETOOTH_DATA_TYPE_COMPLETE_LOCAL_NAME:
147                 // compare common prefix
148                 for (i=0; i<data_size && i<name_len;i++){
149                     if (data[i] != name[i]) break;
150                 }
151                 // prefix match
152                 return 1;
153             default:
154                 break;
155         }
156     }
157     return 0;
158 }
159 
160 static void handle_gatt_client_event(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
161     UNUSED(packet_type);
162     UNUSED(channel);
163     UNUSED(size);
164 
165     switch(state){
166         case TC_W4_SERVICE_RESULT:
167             switch(hci_event_packet_get_type(packet)){
168                 case GATT_EVENT_SERVICE_QUERY_RESULT:
169                     // store service (we expect only one)
170                     gatt_event_service_query_result_get_service(packet, &le_streamer_service);
171                     break;
172                 case GATT_EVENT_QUERY_COMPLETE:
173                     if (packet[4] != 0){
174                         printf("SERVICE_QUERY_RESULT - Error status %x.\n", packet[4]);
175                         gap_disconnect(connection_handle);
176                         break;
177                     }
178                     // service query complete, look for characteristic
179                     state = TC_W4_CHARACTERISTIC_RESULT;
180                     printf("Search for LE Streamer test characteristic.\n");
181                     gatt_client_discover_characteristics_for_service_by_uuid128(handle_gatt_client_event, connection_handle, &le_streamer_service, le_streamer_characteristic_uuid);
182                     break;
183                 default:
184                     break;
185             }
186             break;
187 
188         case TC_W4_CHARACTERISTIC_RESULT:
189             switch(hci_event_packet_get_type(packet)){
190                 case GATT_EVENT_CHARACTERISTIC_QUERY_RESULT:
191                     gatt_event_characteristic_query_result_get_characteristic(packet, &le_streamer_characteristic);
192                     break;
193                 case GATT_EVENT_QUERY_COMPLETE:
194                     if (packet[4] != 0){
195                         printf("CHARACTERISTIC_QUERY_RESULT - Error status %x.\n", packet[4]);
196                         gap_disconnect(connection_handle);
197                         break;
198                     }
199                     // register handler for notifications
200                     listener_registered = 1;
201                     gatt_client_listen_for_characteristic_value_updates(&notification_listener, handle_gatt_client_event, connection_handle, &le_streamer_characteristic);
202                     // enable notifications
203                     state = TC_W4_TEST_DATA;
204                     printf("Start streaming - enable notify on test characteristic.\n");
205                     gatt_client_write_client_characteristic_configuration(handle_gatt_client_event, connection_handle, &le_streamer_characteristic, GATT_CLIENT_CHARACTERISTICS_CONFIGURATION_NOTIFICATION);
206                     // setup tracking
207                     le_streamer_connection.name = 'A';
208                     test_reset(&le_streamer_connection);
209                     break;
210                 default:
211                     break;
212             }
213             break;
214 
215         case TC_W4_TEST_DATA:
216             switch(hci_event_packet_get_type(packet)){
217                 case GATT_EVENT_NOTIFICATION:
218 #if 0
219                     printf("Data: ");
220                     printf_hexdump( gatt_event_notification_get_value(packet), gatt_event_notification_get_value_length(packet));
221 #else
222                     test_track_data(&le_streamer_connection, gatt_event_notification_get_value_length(packet));
223 #endif
224                     break;
225                 case GATT_EVENT_QUERY_COMPLETE:
226                     break;
227                 default:
228                     printf("Unknown packet type %x\n", hci_event_packet_get_type(packet));
229                     break;
230             }
231             break;
232 
233         default:
234             printf("error\n");
235             break;
236     }
237 
238 }
239 
240 // Either connect to remote specified on command line or start scan for device with "LE Streamer" in advertisement
241 static void le_streamer_client_start(void){
242     if (cmdline_addr_found){
243         printf("Connect to %s\n", bd_addr_to_str(cmdline_addr));
244         state = TC_W4_CONNECT;
245         gap_connect(cmdline_addr, 0);
246     } else {
247         printf("Start scanning!\n");
248         state = TC_W4_SCAN_RESULT;
249         gap_set_scan_parameters(0,0x0030, 0x0030);
250         gap_start_scan();
251     }
252 }
253 
254 static void hci_event_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
255     UNUSED(channel);
256     UNUSED(size);
257 
258     if (packet_type != HCI_EVENT_PACKET) return;
259 
260     uint16_t conn_interval;
261     uint8_t event = hci_event_packet_get_type(packet);
262     switch (event) {
263         case BTSTACK_EVENT_STATE:
264             // BTstack activated, get started
265             if (btstack_event_state_get_state(packet) == HCI_STATE_WORKING) {
266                 le_streamer_client_start();
267             } else {
268                 state = TC_OFF;
269             }
270             break;
271         case GAP_EVENT_ADVERTISING_REPORT:
272             if (state != TC_W4_SCAN_RESULT) return;
273             // check name in advertisement
274             if (!advertisement_report_contains_name("LE Streamer", packet)) return;
275             // store address and type
276             gap_event_advertising_report_get_address(packet, le_streamer_addr);
277             le_streamer_addr_type = gap_event_advertising_report_get_address_type(packet);
278             // stop scanning, and connect to the device
279             state = TC_W4_CONNECT;
280             gap_stop_scan();
281             printf("Stop scan. Connect to device with addr %s.\n", bd_addr_to_str(le_streamer_addr));
282             gap_connect(le_streamer_addr,le_streamer_addr_type);
283             break;
284         case HCI_EVENT_LE_META:
285             // wait for connection complete
286             if (hci_event_le_meta_get_subevent_code(packet) !=  HCI_SUBEVENT_LE_CONNECTION_COMPLETE) break;
287             if (state != TC_W4_CONNECT) return;
288             connection_handle = hci_subevent_le_connection_complete_get_connection_handle(packet);
289             // print connection parameters (without using float operations)
290             conn_interval = hci_subevent_le_connection_complete_get_conn_interval(packet);
291             printf("Connection Interval: %u.%02u ms\n", conn_interval * 125 / 100, 25 * (conn_interval & 3));
292             printf("Connection Latency: %u\n", hci_subevent_le_connection_complete_get_conn_latency(packet));
293             // initialize gatt client context with handle, and add it to the list of active clients
294             // query primary services
295             printf("Search for LE Streamer service.\n");
296             state = TC_W4_SERVICE_RESULT;
297             gatt_client_discover_primary_services_by_uuid128(handle_gatt_client_event, connection_handle, le_streamer_service_uuid);
298             break;
299         case HCI_EVENT_DISCONNECTION_COMPLETE:
300             // unregister listener
301             if (listener_registered){
302                 listener_registered = 0;
303                 gatt_client_stop_listening_for_characteristic_value_updates(&notification_listener);
304             }
305             if (cmdline_addr_found){
306                 printf("Disconnected %s\n", bd_addr_to_str(cmdline_addr));
307                 return;
308             }
309             printf("Disconnected %s\n", bd_addr_to_str(le_streamer_addr));
310             if (state == TC_OFF) break;
311             le_streamer_client_start();
312             break;
313         default:
314             break;
315     }
316 }
317 
318 #ifdef HAVE_BTSTACK_STDIN
319 static void usage(const char *name){
320     fprintf(stderr, "Usage: %s [-a|--address aa:bb:cc:dd:ee:ff]\n", name);
321     fprintf(stderr, "If no argument is provided, LE Streamer Client will start scanning and connect to the first device named 'LE Streamer'.\n");
322     fprintf(stderr, "To connect to a specific device use argument [-a].\n\n");
323 }
324 #endif
325 
326 int btstack_main(int argc, const char * argv[]);
327 int btstack_main(int argc, const char * argv[]){
328 
329 #ifdef HAVE_BTSTACK_STDIN
330     int arg = 1;
331     cmdline_addr_found = 0;
332 
333     while (arg < argc) {
334         if(!strcmp(argv[arg], "-a") || !strcmp(argv[arg], "--address")){
335             arg++;
336             cmdline_addr_found = sscanf_bd_addr(argv[arg], cmdline_addr);
337             arg++;
338             if (!cmdline_addr_found) exit(1);
339             continue;
340         }
341         usage(argv[0]);
342         return 0;
343     }
344 #else
345     (void)argc;
346     (void)argv;
347 #endif
348 
349     hci_event_callback_registration.callback = &hci_event_handler;
350     hci_add_event_handler(&hci_event_callback_registration);
351 
352     l2cap_init();
353 
354     gatt_client_init();
355 
356     sm_init();
357     sm_set_io_capabilities(IO_CAPABILITY_NO_INPUT_NO_OUTPUT);
358 
359     // use different connection parameters: conn interval min/max (* 1.25 ms), slave latency, supervision timeout, CE len min/max (* 0.6125 ms)
360     // gap_set_connection_parameters(0x06, 0x06, 4, 1000, 0x01, 0x06 * 2);
361 
362     // turn on!
363     hci_power_control(HCI_POWER_ON);
364 
365     return 0;
366 }
367