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