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