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