xref: /btstack/example/nordic_spp_le_streamer.c (revision cd5f23a3250874824c01a2b3326a9522fea3f99f)
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 Nordic SPP-like Streamer Server
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     if (packet_type != HCI_EVENT_PACKET) return;
174 
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 /* LISTING_END */
211 
212 /*
213  * @section ATT Packet Handler
214  *
215  * @text The packet handler is used to setup and tear down the spp-over-gatt connection and its MTU
216  */
217 
218 /* LISTING_START(packetHandler): Packet Handler */
219 static void att_packet_handler (uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
220     UNUSED(channel);
221     UNUSED(size);
222 
223     if (packet_type != HCI_EVENT_PACKET) return;
224 
225     int mtu;
226     nordic_spp_le_streamer_connection_t * context;
227 
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 /* LISTING_END */
257 
258 
259 
260 /*
261  * @section Streamer
262  *
263  * @text The streamer function checks if notifications are enabled and if a notification can be sent now.
264  * It creates some test data - a single letter that gets increased every time - and tracks the data sent.
265  */
266 
267  /* LISTING_START(streamer): Streaming code */
268 static void nordic_can_send(void * some_context){
269     UNUSED(some_context);
270 
271     // find next active streaming connection
272     int old_connection_index = connection_index;
273     while (1){
274         // active found?
275         if ((nordic_spp_le_streamer_connections[connection_index].connection_handle != HCI_CON_HANDLE_INVALID) &&
276             (nordic_spp_le_streamer_connections[connection_index].le_notification_enabled)) break;
277 
278         // check next
279         next_connection_index();
280 
281         // none found
282         if (connection_index == old_connection_index) return;
283     }
284 
285     nordic_spp_le_streamer_connection_t * context = &nordic_spp_le_streamer_connections[connection_index];
286 
287     // create test data
288     context->counter++;
289     if (context->counter > 'Z') context->counter = 'A';
290     memset(context->test_data, context->counter, context->test_data_len);
291 
292     // send
293     nordic_spp_service_server_send(context->connection_handle, (uint8_t*) context->test_data, context->test_data_len);
294 
295     // track
296     test_track_sent(context, context->test_data_len);
297 
298     // request next send event
299     nordic_spp_service_server_request_can_send_now(&context->send_request, context->connection_handle);
300 
301     // check next
302     next_connection_index();
303 }
304 /* LISTING_END */
305 
306 static void nordic_data_received(hci_con_handle_t tx_con_handle, const uint8_t * data, uint16_t size){
307     nordic_spp_le_streamer_connection_t * context = connection_for_conn_handle(tx_con_handle);
308 
309     if (!context) return;
310 
311     if (size == 0 && context->le_notification_enabled == 0){
312         context->le_notification_enabled = 1;
313         test_reset(context);
314         context->send_request.callback = &nordic_can_send;
315         nordic_spp_service_server_request_can_send_now(&context->send_request, context->connection_handle);
316     } else {
317         printf("RECV: ");
318         printf_hexdump(data, size);
319         test_track_sent(context, size);
320    }
321 }
322 
323 int btstack_main(void);
324 int btstack_main(void){
325     // register for HCI events
326     hci_event_callback_registration.callback = &hci_packet_handler;
327     hci_add_event_handler(&hci_event_callback_registration);
328 
329     l2cap_init();
330 
331     // setup LE device DB
332     le_device_db_init();
333 
334     // setup SM: Display only
335     sm_init();
336 
337     // setup ATT server
338     att_server_init(profile_data, NULL, NULL);
339 
340     // setup Nordic SPP service
341     nordic_spp_service_server_init(&nordic_data_received);
342 
343     // register for ATT events
344     att_server_register_packet_handler(att_packet_handler);
345 
346     // setup advertisements
347     uint16_t adv_int_min = 0x0030;
348     uint16_t adv_int_max = 0x0030;
349     uint8_t adv_type = 0;
350     bd_addr_t null_addr;
351     memset(null_addr, 0, 6);
352     gap_advertisements_set_params(adv_int_min, adv_int_max, adv_type, 0, null_addr, 0x07, 0x00);
353     gap_advertisements_set_data(adv_data_len, (uint8_t*) adv_data);
354     gap_advertisements_enable(1);
355 
356     // init client state
357     init_connections();
358 
359     // turn on!
360 	hci_power_control(HCI_POWER_ON);
361 
362     return 0;
363 }
364 /* EXAMPLE_END */
365