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__ "gatt_streamer.c"
39
40 // *****************************************************************************
41 /* EXAMPLE_START(le_streamer): LE Streamer - Stream data over GATT.
42 *
43 * @text All newer operating systems provide GATT Client functionality.
44 * This example shows how to get a maximal throughput via BLE:
45 * - send whenever possible,
46 * - use the max ATT MTU.
47 *
48 * @text In theory, we should also update the connection parameters, but we already get
49 * a connection interval of 30 ms and there's no public way to use a shorter
50 * interval with iOS (if we're not implementing an HID device).
51 *
52 * @text Note: To start the streaming, run the example.
53 * On remote device use some GATT Explorer, e.g. LightBlue, BLExplr to enable notifications.
54 */
55 // *****************************************************************************
56
57 #include <inttypes.h>
58 #include <stdint.h>
59 #include <stdio.h>
60 #include <stdlib.h>
61 #include <string.h>
62
63 #include "btstack.h"
64
65 // le_streamer.gatt contains the declaration of the provided GATT Services + Characteristics
66 // le_streamer.h contains the binary representation of le_streamer.gatt
67 // it is generated by the build system by calling: $BTSTACK_ROOT/tool/compile_gatt.py le_streamer.gatt le_streamer.h
68 // it needs to be regenerated when the GATT Database declared in le_streamer.gatt file is modified
69 #include "gatt_streamer_server.h"
70
71 #define REPORT_INTERVAL_MS 3000
72 #define MAX_NR_CONNECTIONS 3
73
74
75 static void hci_packet_handler (uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size);
76 static void att_packet_handler (uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size);
77 static int att_write_callback(hci_con_handle_t con_handle, uint16_t att_handle, uint16_t transaction_mode, uint16_t offset, uint8_t *buffer, uint16_t buffer_size);
78 static void streamer(void);
79
80 const uint8_t adv_data[] = {
81 // Flags general discoverable, BR/EDR not supported
82 0x02, BLUETOOTH_DATA_TYPE_FLAGS, 0x06,
83 // Name
84 0x0c, BLUETOOTH_DATA_TYPE_COMPLETE_LOCAL_NAME, 'L', 'E', ' ', 'S', 't', 'r', 'e', 'a', 'm', 'e', 'r',
85 // Incomplete List of 16-bit Service Class UUIDs -- FF10 - only valid for testing!
86 0x03, BLUETOOTH_DATA_TYPE_INCOMPLETE_LIST_OF_16_BIT_SERVICE_CLASS_UUIDS, 0x10, 0xff,
87 };
88 const uint8_t adv_data_len = sizeof(adv_data);
89
90 static btstack_packet_callback_registration_t hci_event_callback_registration;
91
92 // support for multiple clients
93 typedef struct {
94 char name;
95 int le_notification_enabled;
96 uint16_t value_handle;
97 hci_con_handle_t connection_handle;
98 int counter;
99 char test_data[200];
100 int test_data_len;
101 uint32_t test_data_sent;
102 uint32_t test_data_start;
103 } le_streamer_connection_t;
104 static le_streamer_connection_t le_streamer_connections[MAX_NR_CONNECTIONS];
105
106 // round robin sending
107 static int connection_index;
108
109 #ifdef ENABLE_GATT_OVER_CLASSIC
110 static uint8_t gatt_service_buffer[70];
111 #endif
112
init_connections(void)113 static void init_connections(void){
114 // track connections
115 int i;
116 for (i=0;i<MAX_NR_CONNECTIONS;i++){
117 le_streamer_connections[i].connection_handle = HCI_CON_HANDLE_INVALID;
118 le_streamer_connections[i].name = 'A' + i;
119 }
120 }
121
connection_for_conn_handle(hci_con_handle_t conn_handle)122 static le_streamer_connection_t * connection_for_conn_handle(hci_con_handle_t conn_handle){
123 int i;
124 for (i=0;i<MAX_NR_CONNECTIONS;i++){
125 if (le_streamer_connections[i].connection_handle == conn_handle) return &le_streamer_connections[i];
126 }
127 return NULL;
128 }
129
next_connection_index(void)130 static void next_connection_index(void){
131 connection_index++;
132 if (connection_index == MAX_NR_CONNECTIONS){
133 connection_index = 0;
134 }
135 }
136
137 /* @section Main Application Setup
138 *
139 * @text Listing MainConfiguration shows main application code.
140 * It initializes L2CAP, the Security Manager, and configures the ATT Server with the pre-compiled
141 * ATT Database generated from $le_streamer.gatt$. Finally, it configures the advertisements
142 * and boots the Bluetooth stack.
143 */
144
145 /* LISTING_START(MainConfiguration): Init L2CAP, SM, ATT Server, and enable advertisements */
146
le_streamer_setup(void)147 static void le_streamer_setup(void){
148
149 l2cap_init();
150
151 // setup le device db
152 le_device_db_init();
153
154 // setup SM: Display only
155 sm_init();
156
157 #ifdef ENABLE_GATT_OVER_CLASSIC
158 // init SDP, create record for GATT and register with SDP
159 sdp_init();
160 memset(gatt_service_buffer, 0, sizeof(gatt_service_buffer));
161 gatt_create_sdp_record(gatt_service_buffer, 0x10001, ATT_SERVICE_GATT_SERVICE_START_HANDLE, ATT_SERVICE_GATT_SERVICE_END_HANDLE);
162 sdp_register_service(gatt_service_buffer);
163 printf("SDP service record size: %u\n", de_get_len(gatt_service_buffer));
164
165 // configure Classic GAP
166 gap_set_local_name("GATT Streamer BR/EDR 00:00:00:00:00:00");
167 gap_ssp_set_io_capability(SSP_IO_CAPABILITY_DISPLAY_YES_NO);
168 gap_discoverable_control(1);
169 #endif
170
171 // setup ATT server
172 att_server_init(profile_data, NULL, att_write_callback);
173
174 // register for HCI events
175 hci_event_callback_registration.callback = &hci_packet_handler;
176 hci_add_event_handler(&hci_event_callback_registration);
177
178 // register for ATT events
179 att_server_register_packet_handler(att_packet_handler);
180
181 // setup advertisements
182 uint16_t adv_int_min = 0x0030;
183 uint16_t adv_int_max = 0x0030;
184 uint8_t adv_type = 0;
185 bd_addr_t null_addr;
186 memset(null_addr, 0, 6);
187 gap_advertisements_set_params(adv_int_min, adv_int_max, adv_type, 0, null_addr, 0x07, 0x00);
188 gap_advertisements_set_data(adv_data_len, (uint8_t*) adv_data);
189 gap_advertisements_enable(1);
190
191 // init client state
192 init_connections();
193 }
194 /* LISTING_END */
195
196 /*
197 * @section Track throughput
198 * @text We calculate the throughput by setting a start time and measuring the amount of
199 * data sent. After a configurable REPORT_INTERVAL_MS, we print the throughput in kB/s
200 * and reset the counter and start time.
201 */
202
203 /* LISTING_START(tracking): Tracking throughput */
204
test_reset(le_streamer_connection_t * context)205 static void test_reset(le_streamer_connection_t * context){
206 context->test_data_start = btstack_run_loop_get_time_ms();
207 context->test_data_sent = 0;
208 }
209
test_track_sent(le_streamer_connection_t * context,int bytes_sent)210 static void test_track_sent(le_streamer_connection_t * context, int bytes_sent){
211 context->test_data_sent += bytes_sent;
212 // evaluate
213 uint32_t now = btstack_run_loop_get_time_ms();
214 uint32_t time_passed = now - context->test_data_start;
215 if (time_passed < REPORT_INTERVAL_MS) return;
216 // print speed
217 int bytes_per_second = context->test_data_sent * 1000 / time_passed;
218 printf("%c: %"PRIu32" bytes sent-> %u.%03u kB/s\n", context->name, context->test_data_sent, bytes_per_second / 1000, bytes_per_second % 1000);
219
220 // restart
221 context->test_data_start = now;
222 context->test_data_sent = 0;
223 }
224 /* LISTING_END(tracking): Tracking throughput */
225
226 /*
227 * @section HCI Packet Handler
228 *
229 * @text The packet handler is used track incoming connections and to stop notifications on disconnect
230 * It is also a good place to request the connection parameter update as indicated
231 * in the commented code block.
232 */
233
234 /* LISTING_START(hciPacketHandler): Packet Handler */
hci_packet_handler(uint8_t packet_type,uint16_t channel,uint8_t * packet,uint16_t size)235 static void hci_packet_handler (uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
236 UNUSED(channel);
237 UNUSED(size);
238
239 uint16_t conn_interval;
240 hci_con_handle_t con_handle;
241 switch (packet_type) {
242 case HCI_EVENT_PACKET:
243 switch (hci_event_packet_get_type(packet)) {
244 case BTSTACK_EVENT_STATE:
245 // BTstack activated, get started
246 if (btstack_event_state_get_state(packet) == HCI_STATE_WORKING) {
247 printf("To start the streaming, please run the le_streamer_client example on other device, or use some GATT Explorer, e.g. LightBlue, BLExplr.\n");
248 }
249 break;
250 case HCI_EVENT_DISCONNECTION_COMPLETE:
251 con_handle = hci_event_disconnection_complete_get_connection_handle(packet);
252 printf("- LE Connection %04x: disconnect, reason %02x\n", con_handle, hci_event_disconnection_complete_get_reason(packet));
253 break;
254 case HCI_EVENT_META_GAP:
255 // wait for connection complete
256 switch (hci_event_gap_meta_get_subevent_code(packet)) {
257 case GAP_SUBEVENT_LE_CONNECTION_COMPLETE:
258 // print connection parameters (without using float operations)
259 con_handle = gap_subevent_le_connection_complete_get_connection_handle(packet);
260 conn_interval = gap_subevent_le_connection_complete_get_conn_interval(packet);
261 printf("- LE Connection %04x: connected - connection interval %u.%02u ms, latency %u\n", con_handle, conn_interval * 125 / 100,
262 25 * (conn_interval & 3), gap_subevent_le_connection_complete_get_conn_latency(packet));
263 // request min con interval 15 ms for iOS 11+
264 // printf("- LE Connection %04x: request 15 ms connection interval\n", con_handle);
265 // gap_request_connection_parameter_update(con_handle, 12, 12, 0, 0x0048);
266 break;
267 default:
268 break;
269 }
270 break;
271 case HCI_EVENT_LE_META:
272 switch (hci_event_le_meta_get_subevent_code(packet)) {
273 case HCI_SUBEVENT_LE_CONNECTION_UPDATE_COMPLETE:
274 // print connection parameters (without using float operations)
275 con_handle = hci_subevent_le_connection_update_complete_get_connection_handle(packet);
276 conn_interval = hci_subevent_le_connection_update_complete_get_conn_interval(packet);
277 printf("- LE Connection %04x: connection update - connection interval %u.%02u ms, latency %u\n", con_handle, conn_interval * 125 / 100,
278 25 * (conn_interval & 3), hci_subevent_le_connection_update_complete_get_conn_latency(packet));
279 break;
280 default:
281 break;
282 }
283 break;
284 default:
285 break;
286 }
287 }
288 }
289
290 /* LISTING_END */
291
292 /*
293 * @section ATT Packet Handler
294 *
295 * @text The packet handler is used to track the ATT MTU Exchange and trigger ATT send
296 */
297
298 /* LISTING_START(attPacketHandler): Packet Handler */
att_packet_handler(uint8_t packet_type,uint16_t channel,uint8_t * packet,uint16_t size)299 static void att_packet_handler (uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
300 UNUSED(channel);
301 UNUSED(size);
302
303 int mtu;
304 le_streamer_connection_t * context;
305 switch (packet_type) {
306 case HCI_EVENT_PACKET:
307 switch (hci_event_packet_get_type(packet)) {
308 case ATT_EVENT_CONNECTED:
309 // setup new
310 context = connection_for_conn_handle(HCI_CON_HANDLE_INVALID);
311 if (!context) break;
312 context->counter = 'A';
313 context->connection_handle = att_event_connected_get_handle(packet);
314 context->test_data_len = btstack_min(att_server_get_mtu(context->connection_handle) - 3, sizeof(context->test_data));
315 printf("%c: ATT connected, handle %04x, test data len %u\n", context->name, context->connection_handle, context->test_data_len);
316 break;
317 case ATT_EVENT_MTU_EXCHANGE_COMPLETE:
318 mtu = att_event_mtu_exchange_complete_get_MTU(packet) - 3;
319 context = connection_for_conn_handle(att_event_mtu_exchange_complete_get_handle(packet));
320 if (!context) break;
321 context->test_data_len = btstack_min(mtu - 3, sizeof(context->test_data));
322 printf("%c: ATT MTU = %u => use test data of len %u\n", context->name, mtu, context->test_data_len);
323 break;
324 case ATT_EVENT_CAN_SEND_NOW:
325 streamer();
326 break;
327 case ATT_EVENT_DISCONNECTED:
328 context = connection_for_conn_handle(att_event_disconnected_get_handle(packet));
329 if (!context) break;
330 // free connection
331 printf("%c: ATT disconnected, handle %04x\n", context->name, context->connection_handle);
332 context->le_notification_enabled = 0;
333 context->connection_handle = HCI_CON_HANDLE_INVALID;
334 break;
335 default:
336 break;
337 }
338 break;
339 default:
340 break;
341 }
342 }
343 /* LISTING_END */
344
345 /*
346 * @section Streamer
347 *
348 * @text The streamer function checks if notifications are enabled and if a notification can be sent now.
349 * It creates some test data - a single letter that gets increased every time - and tracks the data sent.
350 */
351
352 /* LISTING_START(streamer): Streaming code */
streamer(void)353 static void streamer(void){
354
355 // find next active streaming connection
356 int old_connection_index = connection_index;
357 while (1){
358 // active found?
359 if ((le_streamer_connections[connection_index].connection_handle != HCI_CON_HANDLE_INVALID) &&
360 (le_streamer_connections[connection_index].le_notification_enabled)) break;
361
362 // check next
363 next_connection_index();
364
365 // none found
366 if (connection_index == old_connection_index) return;
367 }
368
369 le_streamer_connection_t * context = &le_streamer_connections[connection_index];
370
371 // create test data
372 context->counter++;
373 if (context->counter > 'Z') context->counter = 'A';
374 memset(context->test_data, context->counter, context->test_data_len);
375
376 // send
377 att_server_notify(context->connection_handle, context->value_handle, (uint8_t*) context->test_data, context->test_data_len);
378
379 // track
380 test_track_sent(context, context->test_data_len);
381
382 // request next send event
383 att_server_request_can_send_now_event(context->connection_handle);
384
385 // check next
386 next_connection_index();
387 }
388 /* LISTING_END */
389
390 /*
391 * @section ATT Write
392 *
393 * @text The only valid ATT write in this example is to the Client Characteristic Configuration, which configures notification
394 * and indication. If the ATT handle matches the client configuration handle, the new configuration value is stored.
395 * If notifications get enabled, an ATT_EVENT_CAN_SEND_NOW is requested. See Listing attWrite.
396 */
397
398 /* LISTING_START(attWrite): ATT Write */
att_write_callback(hci_con_handle_t con_handle,uint16_t att_handle,uint16_t transaction_mode,uint16_t offset,uint8_t * buffer,uint16_t buffer_size)399 static int att_write_callback(hci_con_handle_t con_handle, uint16_t att_handle, uint16_t transaction_mode, uint16_t offset, uint8_t *buffer, uint16_t buffer_size){
400 UNUSED(offset);
401
402 // printf("att_write_callback att_handle %04x, transaction mode %u\n", att_handle, transaction_mode);
403 if (transaction_mode != ATT_TRANSACTION_MODE_NONE) return 0;
404 le_streamer_connection_t * context = connection_for_conn_handle(con_handle);
405 switch(att_handle){
406 case ATT_CHARACTERISTIC_0000FF11_0000_1000_8000_00805F9B34FB_01_CLIENT_CONFIGURATION_HANDLE:
407 case ATT_CHARACTERISTIC_0000FF12_0000_1000_8000_00805F9B34FB_01_CLIENT_CONFIGURATION_HANDLE:
408 context->le_notification_enabled = little_endian_read_16(buffer, 0) == GATT_CLIENT_CHARACTERISTICS_CONFIGURATION_NOTIFICATION;
409 printf("%c: Notifications enabled %u\n", context->name, context->le_notification_enabled);
410 if (context->le_notification_enabled){
411 switch (att_handle){
412 case ATT_CHARACTERISTIC_0000FF11_0000_1000_8000_00805F9B34FB_01_CLIENT_CONFIGURATION_HANDLE:
413 context->value_handle = ATT_CHARACTERISTIC_0000FF11_0000_1000_8000_00805F9B34FB_01_VALUE_HANDLE;
414 break;
415 case ATT_CHARACTERISTIC_0000FF12_0000_1000_8000_00805F9B34FB_01_CLIENT_CONFIGURATION_HANDLE:
416 context->value_handle = ATT_CHARACTERISTIC_0000FF12_0000_1000_8000_00805F9B34FB_01_VALUE_HANDLE;
417 break;
418 default:
419 break;
420 }
421 att_server_request_can_send_now_event(context->connection_handle);
422 }
423 test_reset(context);
424 break;
425 case ATT_CHARACTERISTIC_0000FF11_0000_1000_8000_00805F9B34FB_01_VALUE_HANDLE:
426 case ATT_CHARACTERISTIC_0000FF12_0000_1000_8000_00805F9B34FB_01_VALUE_HANDLE:
427 test_track_sent(context, buffer_size);
428 break;
429 default:
430 printf("Write to 0x%04x, len %u\n", att_handle, buffer_size);
431 }
432 return 0;
433 }
434 /* LISTING_END */
435
436 int btstack_main(void);
btstack_main(void)437 int btstack_main(void)
438 {
439 le_streamer_setup();
440
441 // turn on!
442 hci_power_control(HCI_POWER_ON);
443
444 return 0;
445 }
446 /* EXAMPLE_END */
447