xref: /btstack/example/le_streamer_client.c (revision 44a1ebc025ccd9687b5b2f5406a2801bb753789f)
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 //
42 // LE Streamer Client - connects to 'LE Streamer' and subscribes to test characteristic
43 //
44 // *****************************************************************************
45 
46 #include <stdint.h>
47 #include <stdio.h>
48 #include <stdlib.h>
49 #include <string.h>
50 
51 #include "btstack.h"
52 
53 typedef enum {
54     TC_IDLE,
55     TC_W4_SCAN_RESULT,
56     TC_W4_CONNECT,
57     TC_W4_SERVICE_RESULT,
58     TC_W4_CHARACTERISTIC_RESULT,
59     TC_W4_TEST_DATA
60 } gc_state_t;
61 
62 static bd_addr_t cmdline_addr = { };
63 static int cmdline_addr_found = 0;
64 
65 // addr and type of device with correct name
66 static bd_addr_t      le_streamer_addr;
67 static bd_addr_type_t le_streamer_addr_type;
68 
69 static hci_con_handle_t connection_handle;
70 static uint8_t le_streamer_service_uuid[16]        = { 0x00, 0x00, 0xFF, 0x10, 0x00, 0x00, 0x10, 0x00, 0x80, 0x00, 0x00, 0x80, 0x5F, 0x9B, 0x34, 0xFB};
71 static uint8_t le_streamer_characteristic_uuid[16] = { 0x00, 0x00, 0xFF, 0x11, 0x00, 0x00, 0x10, 0x00, 0x80, 0x00, 0x00, 0x80, 0x5F, 0x9B, 0x34, 0xFB};
72 
73 static gatt_client_service_t le_streamer_service;
74 static gatt_client_characteristic_t le_streamer_characteristic;
75 
76 static gatt_client_notification_t notification_listener;
77 static int listener_registered;
78 
79 static gc_state_t state = TC_IDLE;
80 static btstack_packet_callback_registration_t hci_event_callback_registration;
81 
82 // returns 1 if name is found in advertisement
83 static int advertisement_report_contains_name(const char * name, uint8_t * advertisement_report){
84     // get advertisement from report event
85     const uint8_t * adv_data = gap_event_advertising_report_get_data(advertisement_report);
86     uint16_t        adv_len  = gap_event_advertising_report_get_data_length(advertisement_report);
87     int             name_len = strlen(name);
88 
89     // iterate over advertisement data
90     ad_context_t context;
91     for (ad_iterator_init(&context, adv_len, adv_data) ; ad_iterator_has_more(&context) ; ad_iterator_next(&context)){
92         uint8_t data_type    = ad_iterator_get_data_type(&context);
93         uint8_t data_size    = ad_iterator_get_data_len(&context);
94         const uint8_t * data = ad_iterator_get_data(&context);
95         int i;
96         switch (data_type){
97             case BLUETOOTH_DATA_TYPE_SHORTENED_LOCAL_NAME:
98             case BLUETOOTH_DATA_TYPE_COMPLETE_LOCAL_NAME:
99                 // compare common prefix
100                 for (i=0; i<data_size && i<name_len;i++){
101                     if (data[i] != name[i]) break;
102                 }
103                 // prefix match
104                 return 1;
105             default:
106                 break;
107         }
108     }
109     return 0;
110 }
111 
112 static void handle_gatt_client_event(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
113     UNUSED(packet_type);
114     UNUSED(channel);
115     UNUSED(size);
116 
117     switch(state){
118         case TC_W4_SERVICE_RESULT:
119             switch(hci_event_packet_get_type(packet)){
120                 case GATT_EVENT_SERVICE_QUERY_RESULT:
121                     // store service (we expect only one)
122                     gatt_event_service_query_result_get_service(packet, &le_streamer_service);
123                     break;
124                 case GATT_EVENT_QUERY_COMPLETE:
125                     if (packet[4] != 0){
126                         printf("SERVICE_QUERY_RESULT - Error status %x.\n", packet[4]);
127                         gap_disconnect(connection_handle);
128                         break;
129                     }
130                     // service query complete, look for characteristic
131                     state = TC_W4_CHARACTERISTIC_RESULT;
132                     printf("Search for LE Streamer test characteristic.\n");
133                     gatt_client_discover_characteristics_for_service_by_uuid128(handle_gatt_client_event, connection_handle, &le_streamer_service, le_streamer_characteristic_uuid);
134                     break;
135                 default:
136                     break;
137             }
138             break;
139 
140         case TC_W4_CHARACTERISTIC_RESULT:
141             switch(hci_event_packet_get_type(packet)){
142                 case GATT_EVENT_CHARACTERISTIC_QUERY_RESULT:
143                     gatt_event_characteristic_query_result_get_characteristic(packet, &le_streamer_characteristic);
144                     break;
145                 case GATT_EVENT_QUERY_COMPLETE:
146                     if (packet[4] != 0){
147                         printf("CHARACTERISTIC_QUERY_RESULT - Error status %x.\n", packet[4]);
148                         gap_disconnect(connection_handle);
149                         break;
150                     }
151                     // register handler for notifications
152                     listener_registered = 1;
153                     gatt_client_listen_for_characteristic_value_updates(&notification_listener, handle_gatt_client_event, connection_handle, &le_streamer_characteristic);
154                     // enable notifications
155                     state = TC_W4_TEST_DATA;
156                     printf("Start streaming - enable notify on test characteristic.\n");
157                     gatt_client_write_client_characteristic_configuration(handle_gatt_client_event, connection_handle, &le_streamer_characteristic, GATT_CLIENT_CHARACTERISTICS_CONFIGURATION_NOTIFICATION);
158                     break;
159                 default:
160                     break;
161             }
162             break;
163 
164         case TC_W4_TEST_DATA:
165             switch(hci_event_packet_get_type(packet)){
166                 case GATT_EVENT_NOTIFICATION:
167                     printf("Data: ");
168                     printf_hexdump( gatt_event_notification_get_value(packet), gatt_event_notification_get_value_length(packet));
169                 case GATT_EVENT_QUERY_COMPLETE:
170                     break;
171                 default:
172                     printf("Unknown packet type %x\n", hci_event_packet_get_type(packet));
173                     break;
174             }
175             break;
176 
177         default:
178             printf("error\n");
179             break;
180     }
181 
182 }
183 
184 // Either connect to remote specified on command line or start scan for device with "LE Streamer" in advertisement
185 static void le_streamer_client_start(void){
186     if (cmdline_addr_found){
187         printf("Connect to %s\n", bd_addr_to_str(cmdline_addr));
188         state = TC_W4_CONNECT;
189         gap_connect(cmdline_addr, 0);
190     } else {
191         printf("Start scanning!\n");
192         state = TC_W4_SCAN_RESULT;
193         gap_set_scan_parameters(0,0x0030, 0x0030);
194         gap_start_scan();
195     }
196 }
197 
198 static void hci_event_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
199     UNUSED(channel);
200     UNUSED(size);
201 
202     if (packet_type != HCI_EVENT_PACKET) return;
203 
204     uint16_t conn_interval;
205     uint8_t event = hci_event_packet_get_type(packet);
206     switch (event) {
207         case BTSTACK_EVENT_STATE:
208             // BTstack activated, get started
209             if (btstack_event_state_get_state(packet) != HCI_STATE_WORKING) break;
210             le_streamer_client_start();
211             break;
212         case GAP_EVENT_ADVERTISING_REPORT:
213             if (state != TC_W4_SCAN_RESULT) return;
214             // check name in advertisement
215             if (!advertisement_report_contains_name("LE Streamer", packet)) return;
216             // store address and type
217             gap_event_advertising_report_get_address(packet, le_streamer_addr);
218             le_streamer_addr_type = gap_event_advertising_report_get_address_type(packet);
219             // stop scanning, and connect to the device
220             state = TC_W4_CONNECT;
221             gap_stop_scan();
222             printf("Stop scan. Connect to device with addr %s.\n", bd_addr_to_str(le_streamer_addr));
223             gap_connect(le_streamer_addr,le_streamer_addr_type);
224             break;
225         case HCI_EVENT_LE_META:
226             // wait for connection complete
227             if (hci_event_le_meta_get_subevent_code(packet) !=  HCI_SUBEVENT_LE_CONNECTION_COMPLETE) break;
228             if (state != TC_W4_CONNECT) return;
229             connection_handle = hci_subevent_le_connection_complete_get_connection_handle(packet);
230             // print connection parameters (without using float operations)
231             conn_interval = hci_subevent_le_connection_complete_get_conn_interval(packet);
232             printf("Connection Interval: %u.%02u ms\n", conn_interval * 125 / 100, 25 * (conn_interval & 3));
233             printf("Connection Latency: %u\n", hci_subevent_le_connection_complete_get_conn_latency(packet));
234             // initialize gatt client context with handle, and add it to the list of active clients
235             // query primary services
236             printf("Search for LE Streamer service.\n");
237             state = TC_W4_SERVICE_RESULT;
238             gatt_client_discover_primary_services_by_uuid128(handle_gatt_client_event, connection_handle, le_streamer_service_uuid);
239             break;
240         case HCI_EVENT_DISCONNECTION_COMPLETE:
241             // unregister listener
242             if (listener_registered){
243                 listener_registered = 0;
244                 gatt_client_stop_listening_for_characteristic_value_updates(&notification_listener);
245             }
246             if (cmdline_addr_found){
247                 printf("Disconnected %s\n", bd_addr_to_str(cmdline_addr));
248                 return;
249             }
250             printf("Disconnected %s\n", bd_addr_to_str(le_streamer_addr));
251             le_streamer_client_start();
252             break;
253         default:
254             break;
255     }
256 }
257 
258 #ifdef HAVE_BTSTACK_STDIN
259 static void usage(const char *name){
260     fprintf(stderr, "Usage: %s [-a|--address aa:bb:cc:dd:ee:ff]\n", name);
261     fprintf(stderr, "If no argument is provided, LE Streamer Client will start scanning and connect to the first device named 'LE Streamer'.\n");
262     fprintf(stderr, "To connect to a specific device use argument [-a].\n\n");
263 }
264 #endif
265 
266 int btstack_main(int argc, const char * argv[]);
267 int btstack_main(int argc, const char * argv[]){
268 
269 #ifdef HAVE_BTSTACK_STDIN
270     int arg = 1;
271     cmdline_addr_found = 0;
272 
273     while (arg < argc) {
274         if(!strcmp(argv[arg], "-a") || !strcmp(argv[arg], "--address")){
275             arg++;
276             cmdline_addr_found = sscanf_bd_addr(argv[arg], cmdline_addr);
277             arg++;
278             if (!cmdline_addr_found) exit(1);
279             continue;
280         }
281         usage(argv[0]);
282         return 0;
283     }
284 #else
285     (void)argc;
286     (void)argv;
287 #endif
288 
289     hci_event_callback_registration.callback = &hci_event_handler;
290     hci_add_event_handler(&hci_event_callback_registration);
291 
292     l2cap_init();
293 
294     gatt_client_init();
295 
296     sm_init();
297     sm_set_io_capabilities(IO_CAPABILITY_NO_INPUT_NO_OUTPUT);
298 
299     // turn on!
300     hci_power_control(HCI_POWER_ON);
301 
302     return 0;
303 }
304