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