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