xref: /btstack/example/nordic_spp_le_streamer.c (revision ced70f9bfeafe291ec597a3a9cc862e39e0da3ce)
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__ "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_META_GAP:
183             switch (hci_event_gap_meta_get_subevent_code(packet)) {
184                 case GAP_SUBEVENT_LE_CONNECTION_COMPLETE:
185                     switch (hci_event_gap_meta_get_subevent_code(packet)) {
186                         case GAP_SUBEVENT_LE_CONNECTION_COMPLETE:
187                             // print connection parameters (without using float operations)
188                             con_handle    = gap_subevent_le_connection_complete_get_connection_handle(packet);
189                             conn_interval = gap_subevent_le_connection_complete_get_conn_interval(packet);
190                             printf("LE Connection - Connection Interval: %u.%02u ms\n", conn_interval * 125 / 100, 25 * (conn_interval & 3));
191                             printf("LE Connection - Connection Latency: %u\n", gap_subevent_le_connection_complete_get_conn_latency(packet));
192 
193                             // request min con interval 15 ms for iOS 11+
194                             printf("LE Connection - Request 15 ms connection interval\n");
195                             gap_request_connection_parameter_update(con_handle, 12, 12, 4, 0x0048);
196                             break;
197                         default:
198                             break;
199                     }
200                 break;
201                 default:
202                     break;
203             }
204             break;
205 
206         case HCI_EVENT_LE_META:
207             switch (hci_event_le_meta_get_subevent_code(packet)) {
208                 case HCI_SUBEVENT_LE_CONNECTION_UPDATE_COMPLETE:
209                     // print connection parameters (without using float operations)
210                     con_handle    = hci_subevent_le_connection_update_complete_get_connection_handle(packet);
211                     conn_interval = hci_subevent_le_connection_update_complete_get_conn_interval(packet);
212                     printf("LE Connection - Connection Param update - connection interval %u.%02u ms, latency %u\n", conn_interval * 125 / 100,
213                         25 * (conn_interval & 3), hci_subevent_le_connection_update_complete_get_conn_latency(packet));
214                     break;
215                 default:
216                     break;
217             }
218             break;
219         default:
220             break;
221     }
222 }
223 /* LISTING_END */
224 
225 /*
226  * @section ATT Packet Handler
227  *
228  * @text The packet handler is used to setup and tear down the spp-over-gatt connection and its MTU
229  */
230 
231 /* LISTING_START(packetHandler): Packet Handler */
232 static void att_packet_handler (uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
233     UNUSED(channel);
234     UNUSED(size);
235 
236     if (packet_type != HCI_EVENT_PACKET) return;
237 
238     int mtu;
239     nordic_spp_le_streamer_connection_t * context;
240 
241     switch (hci_event_packet_get_type(packet)) {
242         case ATT_EVENT_CONNECTED:
243             // setup new
244             context = connection_for_conn_handle(HCI_CON_HANDLE_INVALID);
245             if (!context) break;
246             context->counter = 'A';
247             context->test_data_len = ATT_DEFAULT_MTU - 4;   // -1 for nordic 0x01 packet type
248             context->connection_handle = att_event_connected_get_handle(packet);
249             break;
250         case ATT_EVENT_MTU_EXCHANGE_COMPLETE:
251             mtu = att_event_mtu_exchange_complete_get_MTU(packet) - 3;
252             context = connection_for_conn_handle(att_event_mtu_exchange_complete_get_handle(packet));
253             if (!context) break;
254             context->test_data_len = btstack_min(mtu - 3, sizeof(context->test_data));
255             printf("%c: ATT MTU = %u => use test data of len %u\n", context->name, mtu, context->test_data_len);
256             break;
257         case ATT_EVENT_DISCONNECTED:
258             context = connection_for_conn_handle(att_event_disconnected_get_handle(packet));
259             if (!context) break;
260             // free connection
261             printf("%c: Disconnect\n", context->name);
262             context->le_notification_enabled = 0;
263             context->connection_handle = HCI_CON_HANDLE_INVALID;
264             break;
265         default:
266             break;
267     }
268 }
269 /* LISTING_END */
270 
271 
272 
273 /*
274  * @section Streamer
275  *
276  * @text The streamer function checks if notifications are enabled and if a notification can be sent now.
277  * It creates some test data - a single letter that gets increased every time - and tracks the data sent.
278  */
279 
280  /* LISTING_START(streamer): Streaming code */
281 static void nordic_can_send(void * some_context){
282     UNUSED(some_context);
283 
284     // find next active streaming connection
285     int old_connection_index = connection_index;
286     while (1){
287         // active found?
288         if ((nordic_spp_le_streamer_connections[connection_index].connection_handle != HCI_CON_HANDLE_INVALID) &&
289             (nordic_spp_le_streamer_connections[connection_index].le_notification_enabled)) break;
290 
291         // check next
292         next_connection_index();
293 
294         // none found
295         if (connection_index == old_connection_index) return;
296     }
297 
298     nordic_spp_le_streamer_connection_t * context = &nordic_spp_le_streamer_connections[connection_index];
299 
300     // create test data
301     context->counter++;
302     if (context->counter > 'Z') context->counter = 'A';
303     memset(context->test_data, context->counter, context->test_data_len);
304 
305     // send
306     nordic_spp_service_server_send(context->connection_handle, (uint8_t*) context->test_data, context->test_data_len);
307 
308     // track
309     test_track_sent(context, context->test_data_len);
310 
311     // request next send event
312     nordic_spp_service_server_request_can_send_now(&context->send_request, context->connection_handle);
313 
314     // check next
315     next_connection_index();
316 }
317 /* LISTING_END */
318 
319 static void nordic_spp_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
320     hci_con_handle_t con_handle;
321     nordic_spp_le_streamer_connection_t * context;
322     switch (packet_type){
323         case HCI_EVENT_PACKET:
324             if (hci_event_packet_get_type(packet) != HCI_EVENT_GATTSERVICE_META) break;
325             switch (hci_event_gattservice_meta_get_subevent_code(packet)){
326                 case GATTSERVICE_SUBEVENT_SPP_SERVICE_CONNECTED:
327                     con_handle = gattservice_subevent_spp_service_connected_get_con_handle(packet);
328                     context = connection_for_conn_handle(con_handle);
329                     if (!context) break;
330                     context->le_notification_enabled = 1;
331                     test_reset(context);
332                     context->send_request.callback = &nordic_can_send;
333                     nordic_spp_service_server_request_can_send_now(&context->send_request, context->connection_handle);
334                     break;
335                 case GATTSERVICE_SUBEVENT_SPP_SERVICE_DISCONNECTED:
336                     con_handle = HCI_CON_HANDLE_INVALID;
337                     context = connection_for_conn_handle(con_handle);
338                     if (!context) break;
339                     context->le_notification_enabled = 0;
340                     break;
341                 default:
342                     break;
343             }
344             break;
345         case RFCOMM_DATA_PACKET:
346             printf("RECV: ");
347             printf_hexdump(packet, size);
348             context = connection_for_conn_handle((hci_con_handle_t) channel);
349             if (!context) break;
350             test_track_sent(context, size);
351             break;
352         default:
353             break;
354     }
355 }
356 
357 int btstack_main(void);
358 int btstack_main(void){
359     // register for HCI events
360     hci_event_callback_registration.callback = &hci_packet_handler;
361     hci_add_event_handler(&hci_event_callback_registration);
362 
363     l2cap_init();
364 
365     // setup SM: Display only
366     sm_init();
367 
368     // setup ATT server
369     att_server_init(profile_data, NULL, NULL);
370 
371     // setup Nordic SPP service
372     nordic_spp_service_server_init(&nordic_spp_packet_handler);
373 
374     // register for ATT events
375     att_server_register_packet_handler(att_packet_handler);
376 
377     // setup advertisements
378     uint16_t adv_int_min = 0x0030;
379     uint16_t adv_int_max = 0x0030;
380     uint8_t adv_type = 0;
381     bd_addr_t null_addr;
382     memset(null_addr, 0, 6);
383     gap_advertisements_set_params(adv_int_min, adv_int_max, adv_type, 0, null_addr, 0x07, 0x00);
384     gap_advertisements_set_data(adv_data_len, (uint8_t*) adv_data);
385     gap_advertisements_enable(1);
386 
387     // init client state
388     init_connections();
389 
390     // turn on!
391 	hci_power_control(HCI_POWER_ON);
392 
393     return 0;
394 }
395 /* EXAMPLE_END */
396