xref: /btstack/example/nordic_spp_le_streamer.c (revision 046b44372d25c7bd6fe78e5cf6e5176a1979f437)
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__ "nordic_spp_le_streamer.c"
39 
40 // *****************************************************************************
41 /* EXAMPLE_START(nordic_spp_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 #include "ble/gatt-service/nordic_spp_service_server.h"
65 
66 // nordic_spp_le_streamer.gatt contains the declaration of the provided GATT Services + Characteristics
67 // nordic_spp_le_streamer.h    contains the binary representation of nordic_spp_le_streamer.gatt
68 // it is generated by the build system by calling: $BTSTACK_ROOT/tool/compile_gatt.py nordic_spp_le_streamer.gatt nordic_spp_le_streamer.h
69 // it needs to be regenerated when the GATT Database declared in nordic_spp_le_streamer.gatt file is modified
70 #include "nordic_spp_le_streamer.h"
71 
72 #define REPORT_INTERVAL_MS 3000
73 #define MAX_NR_CONNECTIONS 3
74 
75 const uint8_t adv_data[] = {
76     // Flags general discoverable, BR/EDR not supported
77     2, BLUETOOTH_DATA_TYPE_FLAGS, 0x06,
78     // Name
79     8, BLUETOOTH_DATA_TYPE_COMPLETE_LOCAL_NAME, 'n', 'R', 'F',' ', 'S', 'P', 'P',
80     // UUID ...
81     17, BLUETOOTH_DATA_TYPE_COMPLETE_LIST_OF_128_BIT_SERVICE_CLASS_UUIDS, 0x9e, 0xca, 0xdc, 0x24, 0xe, 0xe5, 0xa9, 0xe0, 0x93, 0xf3, 0xa3, 0xb5, 0x1, 0x0, 0x40, 0x6e,
82 };
83 const uint8_t adv_data_len = sizeof(adv_data);
84 
85 static btstack_packet_callback_registration_t hci_event_callback_registration;
86 
87 // support for multiple clients
88 typedef struct {
89     char name;
90     int le_notification_enabled;
91     hci_con_handle_t connection_handle;
92     int  counter;
93     char test_data[200];
94     int  test_data_len;
95     uint32_t test_data_sent;
96     uint32_t test_data_start;
97     btstack_context_callback_registration_t send_request;
98 } nordic_spp_le_streamer_connection_t;
99 
100 static nordic_spp_le_streamer_connection_t nordic_spp_le_streamer_connections[MAX_NR_CONNECTIONS];
101 
102 // round robin sending
103 static int connection_index;
104 
105 static void init_connections(void){
106     // track connections
107     int i;
108     for (i=0;i<MAX_NR_CONNECTIONS;i++){
109         nordic_spp_le_streamer_connections[i].connection_handle = HCI_CON_HANDLE_INVALID;
110         nordic_spp_le_streamer_connections[i].name = 'A' + i;
111     }
112 }
113 
114 static nordic_spp_le_streamer_connection_t * connection_for_conn_handle(hci_con_handle_t conn_handle){
115     int i;
116     for (i=0;i<MAX_NR_CONNECTIONS;i++){
117         if (nordic_spp_le_streamer_connections[i].connection_handle == conn_handle) return &nordic_spp_le_streamer_connections[i];
118     }
119     return NULL;
120 }
121 
122 static void next_connection_index(void){
123     connection_index++;
124     if (connection_index == MAX_NR_CONNECTIONS){
125         connection_index = 0;
126     }
127 }
128 
129 /*
130  * @section Track throughput
131  * @text We calculate the throughput by setting a start time and measuring the amount of
132  * data sent. After a configurable REPORT_INTERVAL_MS, we print the throughput in kB/s
133  * and reset the counter and start time.
134  */
135 
136 /* LISTING_START(tracking): Tracking throughput */
137 
138 static void test_reset(nordic_spp_le_streamer_connection_t * context){
139     context->test_data_start = btstack_run_loop_get_time_ms();
140     context->test_data_sent = 0;
141 }
142 
143 static void test_track_sent(nordic_spp_le_streamer_connection_t * context, int bytes_sent){
144     context->test_data_sent += bytes_sent;
145     // evaluate
146     uint32_t now = btstack_run_loop_get_time_ms();
147     uint32_t time_passed = now - context->test_data_start;
148     if (time_passed < REPORT_INTERVAL_MS) return;
149     // print speed
150     int bytes_per_second = context->test_data_sent * 1000 / time_passed;
151     printf("%c: %"PRIu32" bytes sent-> %u.%03u kB/s\n", context->name, context->test_data_sent, bytes_per_second / 1000, bytes_per_second % 1000);
152 
153     // restart
154     context->test_data_start = now;
155     context->test_data_sent  = 0;
156 }
157 /* LISTING_END(tracking): Tracking throughput */
158 
159 /*
160  * @section HCI Packet Handler
161  *
162  * @text The packet handler prints the welcome message and requests a connection paramter update for LE Connections
163  */
164 
165 /* LISTING_START(packetHandler): Packet Handler */
166 static void hci_packet_handler (uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
167     UNUSED(channel);
168     UNUSED(size);
169 
170     uint16_t conn_interval;
171     hci_con_handle_t con_handle;
172 
173     switch (packet_type) {
174         case HCI_EVENT_PACKET:
175             switch (hci_event_packet_get_type(packet)) {
176                 case BTSTACK_EVENT_STATE:
177                     // BTstack activated, get started
178                     if (btstack_event_state_get_state(packet) == HCI_STATE_WORKING) {
179                         printf("To start the streaming, please run nRF Toolbox -> UART to connect.\n");
180                     }
181                     break;
182                 case HCI_EVENT_LE_META:
183                     switch (hci_event_le_meta_get_subevent_code(packet)) {
184                         case HCI_SUBEVENT_LE_CONNECTION_COMPLETE:
185                             // print connection parameters (without using float operations)
186                             con_handle    = hci_subevent_le_connection_complete_get_connection_handle(packet);
187                             conn_interval = hci_subevent_le_connection_complete_get_conn_interval(packet);
188                             printf("LE Connection - Connection Interval: %u.%02u ms\n", conn_interval * 125 / 100, 25 * (conn_interval & 3));
189                             printf("LE Connection - Connection Latency: %u\n", hci_subevent_le_connection_complete_get_conn_latency(packet));
190 
191                             // request min con interval 15 ms for iOS 11+
192                             printf("LE Connection - Request 15 ms connection interval\n");
193                             gap_request_connection_parameter_update(con_handle, 12, 12, 0, 0x0048);
194                             break;
195                         case HCI_SUBEVENT_LE_CONNECTION_UPDATE_COMPLETE:
196                             // print connection parameters (without using float operations)
197                             con_handle    = hci_subevent_le_connection_update_complete_get_connection_handle(packet);
198                             conn_interval = hci_subevent_le_connection_update_complete_get_conn_interval(packet);
199                             printf("LE Connection - Connection Param update - connection interval %u.%02u ms, latency %u\n", conn_interval * 125 / 100,
200                                 25 * (conn_interval & 3), hci_subevent_le_connection_update_complete_get_conn_latency(packet));
201                             break;
202                         default:
203                             break;
204                     }
205                     break;
206                 default:
207                     break;
208             }
209     }
210 }
211 /* LISTING_END */
212 
213 /*
214  * @section ATT Packet Handler
215  *
216  * @text The packet handler is used to setup and tear down the spp-over-gatt connection and its MTU
217  */
218 
219 /* LISTING_START(packetHandler): Packet Handler */
220 static void att_packet_handler (uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
221     UNUSED(channel);
222     UNUSED(size);
223 
224     int mtu;
225     nordic_spp_le_streamer_connection_t * context;
226     switch (packet_type) {
227         case HCI_EVENT_PACKET:
228             switch (hci_event_packet_get_type(packet)) {
229                 case ATT_EVENT_CONNECTED:
230                     // setup new
231                     context = connection_for_conn_handle(HCI_CON_HANDLE_INVALID);
232                     if (!context) break;
233                     context->counter = 'A';
234                     context->test_data_len = ATT_DEFAULT_MTU - 4;   // -1 for nordic 0x01 packet type
235                     context->connection_handle = att_event_connected_get_handle(packet);
236                     break;
237                 case ATT_EVENT_MTU_EXCHANGE_COMPLETE:
238                     mtu = att_event_mtu_exchange_complete_get_MTU(packet) - 3;
239                     context = connection_for_conn_handle(att_event_mtu_exchange_complete_get_handle(packet));
240                     if (!context) break;
241                     context->test_data_len = btstack_min(mtu - 3, sizeof(context->test_data));
242                     printf("%c: ATT MTU = %u => use test data of len %u\n", context->name, mtu, context->test_data_len);
243                     break;
244                 case ATT_EVENT_DISCONNECTED:
245                     context = connection_for_conn_handle(att_event_disconnected_get_handle(packet));
246                     if (!context) break;
247                     // free connection
248                     printf("%c: Disconnect\n", context->name);
249                     context->le_notification_enabled = 0;
250                     context->connection_handle = HCI_CON_HANDLE_INVALID;
251                     break;
252                 default:
253                     break;
254             }
255     }
256 }
257 /* LISTING_END */
258 
259 
260 
261 /*
262  * @section Streamer
263  *
264  * @text The streamer function checks if notifications are enabled and if a notification can be sent now.
265  * It creates some test data - a single letter that gets increased every time - and tracks the data sent.
266  */
267 
268  /* LISTING_START(streamer): Streaming code */
269 static void nordic_can_send(void * some_context){
270     UNUSED(some_context);
271 
272     // find next active streaming connection
273     int old_connection_index = connection_index;
274     while (1){
275         // active found?
276         if ((nordic_spp_le_streamer_connections[connection_index].connection_handle != HCI_CON_HANDLE_INVALID) &&
277             (nordic_spp_le_streamer_connections[connection_index].le_notification_enabled)) break;
278 
279         // check next
280         next_connection_index();
281 
282         // none found
283         if (connection_index == old_connection_index) return;
284     }
285 
286     nordic_spp_le_streamer_connection_t * context = &nordic_spp_le_streamer_connections[connection_index];
287 
288     // create test data
289     context->counter++;
290     if (context->counter > 'Z') context->counter = 'A';
291     memset(context->test_data, context->counter, context->test_data_len);
292 
293     // send
294     nordic_spp_service_server_send(context->connection_handle, (uint8_t*) context->test_data, context->test_data_len);
295 
296     // track
297     test_track_sent(context, context->test_data_len);
298 
299     // request next send event
300     nordic_spp_service_server_request_can_send_now(&context->send_request, context->connection_handle);
301 
302     // check next
303     next_connection_index();
304 }
305 /* LISTING_END */
306 
307 static void nordic_data_received(hci_con_handle_t tx_con_handle, const uint8_t * data, uint16_t size){
308     nordic_spp_le_streamer_connection_t * context = connection_for_conn_handle(tx_con_handle);
309 
310     if (!context) return;
311 
312     if (size == 0 && context->le_notification_enabled == 0){
313         context->le_notification_enabled = 1;
314         test_reset(context);
315         context->send_request.callback = &nordic_can_send;
316         nordic_spp_service_server_request_can_send_now(&context->send_request, context->connection_handle);
317     } else {
318         printf("RECV: ");
319         printf_hexdump(data, size);
320         test_track_sent(context, size);
321    }
322 }
323 
324 int btstack_main(void);
325 int btstack_main(void){
326     // register for HCI events
327     hci_event_callback_registration.callback = &hci_packet_handler;
328     hci_add_event_handler(&hci_event_callback_registration);
329 
330     l2cap_init();
331 
332     // setup LE device DB
333     le_device_db_init();
334 
335     // setup SM: Display only
336     sm_init();
337 
338     // setup ATT server
339     att_server_init(profile_data, NULL, NULL);
340 
341     // setup Nordic SPP service
342     nordic_spp_service_server_init(&nordic_data_received);
343 
344     // register for ATT events
345     att_server_register_packet_handler(att_packet_handler);
346 
347     // setup advertisements
348     uint16_t adv_int_min = 0x0030;
349     uint16_t adv_int_max = 0x0030;
350     uint8_t adv_type = 0;
351     bd_addr_t null_addr;
352     memset(null_addr, 0, 6);
353     gap_advertisements_set_params(adv_int_min, adv_int_max, adv_type, 0, null_addr, 0x07, 0x00);
354     gap_advertisements_set_data(adv_data_len, (uint8_t*) adv_data);
355     gap_advertisements_enable(1);
356 
357     // init client state
358     init_connections();
359 
360     // turn on!
361 	hci_power_control(HCI_POWER_ON);
362 
363     return 0;
364 }
365 /* EXAMPLE_END */
366