xref: /btstack/example/le_streamer_client.c (revision a8d51f092f1b660d0f6921369ad2bc3f9368296c)
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): 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     uint16_t        adv_len  = gap_event_advertising_report_get_data_length(advertisement_report);
180     int             name_len = 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         int i;
189         switch (data_type){
190             case BLUETOOTH_DATA_TYPE_SHORTENED_LOCAL_NAME:
191             case BLUETOOTH_DATA_TYPE_COMPLETE_LOCAL_NAME:
192                 // compare common prefix
193                 for (i=0; i<data_size && i<name_len;i++){
194                     if (data[i] != name[i]) break;
195                 }
196                 // prefix match
197                 return 1;
198             default:
199                 break;
200         }
201     }
202     return 0;
203 }
204 
205 static void handle_gatt_client_event(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
206     UNUSED(packet_type);
207     UNUSED(channel);
208     UNUSED(size);
209 
210     uint16_t mtu;
211     switch(state){
212         case TC_W4_SERVICE_RESULT:
213             switch(hci_event_packet_get_type(packet)){
214                 case GATT_EVENT_SERVICE_QUERY_RESULT:
215                     // store service (we expect only one)
216                     gatt_event_service_query_result_get_service(packet, &le_streamer_service);
217                     break;
218                 case GATT_EVENT_QUERY_COMPLETE:
219                     if (packet[4] != 0){
220                         printf("SERVICE_QUERY_RESULT - Error status %x.\n", packet[4]);
221                         gap_disconnect(connection_handle);
222                         break;
223                     }
224                     // service query complete, look for characteristic
225                     state = TC_W4_CHARACTERISTIC_RX_RESULT;
226                     printf("Search for LE Streamer RX characteristic.\n");
227                     gatt_client_discover_characteristics_for_service_by_uuid128(handle_gatt_client_event, connection_handle, &le_streamer_service, le_streamer_characteristic_rx_uuid);
228                     break;
229                 default:
230                     break;
231             }
232             break;
233 
234         case TC_W4_CHARACTERISTIC_RX_RESULT:
235             switch(hci_event_packet_get_type(packet)){
236                 case GATT_EVENT_CHARACTERISTIC_QUERY_RESULT:
237                     gatt_event_characteristic_query_result_get_characteristic(packet, &le_streamer_characteristic_rx);
238                     break;
239                 case GATT_EVENT_QUERY_COMPLETE:
240                     if (packet[4] != 0){
241                         printf("CHARACTERISTIC_QUERY_RESULT - Error status %x.\n", packet[4]);
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                     if (packet[4] != 0){
262                         printf("CHARACTERISTIC_QUERY_RESULT - Error status %x.\n", packet[4]);
263                         gap_disconnect(connection_handle);
264                         break;
265                     }
266                     // register handler for notifications
267                     listener_registered = 1;
268                     gatt_client_listen_for_characteristic_value_updates(&notification_listener, handle_gatt_client_event, connection_handle, &le_streamer_characteristic_tx);
269                     // setup tracking
270                     le_streamer_connection.name = 'A';
271                     le_streamer_connection.test_data_len = ATT_DEFAULT_MTU - 3;
272                     test_reset(&le_streamer_connection);
273                     gatt_client_get_mtu(connection_handle, &mtu);
274                     le_streamer_connection.test_data_len = btstack_min(mtu - 3, sizeof(le_streamer_connection.test_data));
275                     printf("%c: ATT MTU = %u => use test data of len %u\n", le_streamer_connection.name, mtu, le_streamer_connection.test_data_len);
276                     // enable notifications
277 #if (TEST_MODE & TEST_MODE_ENABLE_NOTIFICATIONS)
278                     printf("Start streaming - enable notify on test characteristic.\n");
279                     state = TC_W4_ENABLE_NOTIFICATIONS_COMPLETE;
280                     gatt_client_write_client_characteristic_configuration(handle_gatt_client_event, connection_handle,
281                         &le_streamer_characteristic_tx, GATT_CLIENT_CHARACTERISTICS_CONFIGURATION_NOTIFICATION);
282                     break;
283 #endif
284                     state = TC_W4_TEST_DATA;
285 #if (TEST_MODE & TEST_MODE_WRITE_WITHOUT_RESPONSE)
286                     printf("Start streaming - request can send now.\n");
287                     gatt_client_request_can_write_without_response_event(handle_gatt_client_event, connection_handle);
288 #endif
289                     break;
290                 default:
291                     break;
292             }
293             break;
294 
295         case TC_W4_ENABLE_NOTIFICATIONS_COMPLETE:
296             switch(hci_event_packet_get_type(packet)){
297                 case GATT_EVENT_QUERY_COMPLETE:
298                     printf("Notifications enabled, ATT status %02x\n", gatt_event_query_complete_get_att_status(packet));
299                     if (gatt_event_query_complete_get_att_status(packet) != ATT_ERROR_SUCCESS) break;
300                     state = TC_W4_TEST_DATA;
301 #if (TEST_MODE & TEST_MODE_WRITE_WITHOUT_RESPONSE)
302                     printf("Start streaming - request can send now.\n");
303                     gatt_client_request_can_write_without_response_event(handle_gatt_client_event, connection_handle);
304 #endif
305                     break;
306                 default:
307                     break;
308             }
309             break;
310 
311         case TC_W4_TEST_DATA:
312             switch(hci_event_packet_get_type(packet)){
313                 case GATT_EVENT_NOTIFICATION:
314                     test_track_data(&le_streamer_connection, gatt_event_notification_get_value_length(packet));
315                     break;
316                 case GATT_EVENT_QUERY_COMPLETE:
317                     break;
318                 case GATT_EVENT_CAN_WRITE_WITHOUT_RESPONSE:
319                     streamer(&le_streamer_connection);
320                     break;
321                 default:
322                     printf("Unknown packet type %x\n", hci_event_packet_get_type(packet));
323                     break;
324             }
325             break;
326 
327         default:
328             printf("error\n");
329             break;
330     }
331 
332 }
333 
334 // Either connect to remote specified on command line or start scan for device with "LE Streamer" in advertisement
335 static void le_streamer_client_start(void){
336     if (cmdline_addr_found){
337         printf("Connect to %s\n", bd_addr_to_str(cmdline_addr));
338         state = TC_W4_CONNECT;
339         gap_connect(cmdline_addr, 0);
340     } else {
341         printf("Start scanning!\n");
342         state = TC_W4_SCAN_RESULT;
343         gap_set_scan_parameters(0,0x0030, 0x0030);
344         gap_start_scan();
345     }
346 }
347 
348 static void hci_event_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
349     UNUSED(channel);
350     UNUSED(size);
351 
352     if (packet_type != HCI_EVENT_PACKET) return;
353 
354     uint16_t conn_interval;
355     uint8_t event = hci_event_packet_get_type(packet);
356     switch (event) {
357         case BTSTACK_EVENT_STATE:
358             // BTstack activated, get started
359             if (btstack_event_state_get_state(packet) == HCI_STATE_WORKING) {
360                 le_streamer_client_start();
361             } else {
362                 state = TC_OFF;
363             }
364             break;
365         case GAP_EVENT_ADVERTISING_REPORT:
366             if (state != TC_W4_SCAN_RESULT) return;
367             // check name in advertisement
368             if (!advertisement_report_contains_name("LE Streamer", packet)) return;
369             // store address and type
370             gap_event_advertising_report_get_address(packet, le_streamer_addr);
371             le_streamer_addr_type = gap_event_advertising_report_get_address_type(packet);
372             // stop scanning, and connect to the device
373             state = TC_W4_CONNECT;
374             gap_stop_scan();
375             printf("Stop scan. Connect to device with addr %s.\n", bd_addr_to_str(le_streamer_addr));
376             gap_connect(le_streamer_addr,le_streamer_addr_type);
377             break;
378         case HCI_EVENT_LE_META:
379             // wait for connection complete
380             if (hci_event_le_meta_get_subevent_code(packet) !=  HCI_SUBEVENT_LE_CONNECTION_COMPLETE) break;
381             if (state != TC_W4_CONNECT) return;
382             connection_handle = hci_subevent_le_connection_complete_get_connection_handle(packet);
383             // print connection parameters (without using float operations)
384             conn_interval = hci_subevent_le_connection_complete_get_conn_interval(packet);
385             printf("Connection Interval: %u.%02u ms\n", conn_interval * 125 / 100, 25 * (conn_interval & 3));
386             printf("Connection Latency: %u\n", hci_subevent_le_connection_complete_get_conn_latency(packet));
387             // initialize gatt client context with handle, and add it to the list of active clients
388             // query primary services
389             printf("Search for LE Streamer service.\n");
390             state = TC_W4_SERVICE_RESULT;
391             gatt_client_discover_primary_services_by_uuid128(handle_gatt_client_event, connection_handle, le_streamer_service_uuid);
392             break;
393         case HCI_EVENT_DISCONNECTION_COMPLETE:
394             // unregister listener
395             connection_handle = HCI_CON_HANDLE_INVALID;
396             if (listener_registered){
397                 listener_registered = 0;
398                 gatt_client_stop_listening_for_characteristic_value_updates(&notification_listener);
399             }
400             if (cmdline_addr_found){
401                 printf("Disconnected %s\n", bd_addr_to_str(cmdline_addr));
402                 return;
403             }
404             printf("Disconnected %s\n", bd_addr_to_str(le_streamer_addr));
405             if (state == TC_OFF) break;
406             le_streamer_client_start();
407             break;
408         default:
409             break;
410     }
411 }
412 
413 #ifdef HAVE_BTSTACK_STDIN
414 static void usage(const char *name){
415     fprintf(stderr, "Usage: %s [-a|--address aa:bb:cc:dd:ee:ff]\n", name);
416     fprintf(stderr, "If no argument is provided, LE Streamer Client will start scanning and connect to the first device named 'LE Streamer'.\n");
417     fprintf(stderr, "To connect to a specific device use argument [-a].\n\n");
418 }
419 #endif
420 
421 int btstack_main(int argc, const char * argv[]);
422 int btstack_main(int argc, const char * argv[]){
423 
424 #ifdef HAVE_BTSTACK_STDIN
425     int arg = 1;
426     cmdline_addr_found = 0;
427 
428     while (arg < argc) {
429         if(!strcmp(argv[arg], "-a") || !strcmp(argv[arg], "--address")){
430             arg++;
431             cmdline_addr_found = sscanf_bd_addr(argv[arg], cmdline_addr);
432             arg++;
433             if (!cmdline_addr_found) exit(1);
434             continue;
435         }
436         usage(argv[0]);
437         return 0;
438     }
439 #else
440     (void)argc;
441     (void)argv;
442 #endif
443     l2cap_init();
444 
445     sm_init();
446     sm_set_io_capabilities(IO_CAPABILITY_NO_INPUT_NO_OUTPUT);
447 
448     // sm_init needed before gatt_client_init
449     gatt_client_init();
450 
451     hci_event_callback_registration.callback = &hci_event_handler;
452     hci_add_event_handler(&hci_event_callback_registration);
453 
454     // use different connection parameters: conn interval min/max (* 1.25 ms), slave latency, supervision timeout, CE len min/max (* 0.6125 ms)
455     // gap_set_connection_parameters(0x06, 0x06, 4, 1000, 0x01, 0x06 * 2);
456 
457     // turn on!
458     hci_power_control(HCI_POWER_ON);
459 
460     return 0;
461 }
462 /* EXAMPLE_END */
463