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