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