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