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