xref: /btstack/example/nordic_spp_le_streamer.c (revision 62daa4413793ac9b1b00945388a2ed4faeb48481)
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 
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_spp_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
307     hci_con_handle_t con_handle;
308     nordic_spp_le_streamer_connection_t * context;
309     switch (packet_type){
310         case HCI_EVENT_PACKET:
311             if (hci_event_packet_get_type(packet) != HCI_EVENT_GATTSERVICE_META) break;
312             switch (hci_event_gattservice_meta_get_subevent_code(packet)){
313                 case GATTSERVICE_SUBEVENT_SPP_SERVICE_CONNECTED:
314                     con_handle = gattservice_subevent_spp_service_connected_get_con_handle(packet);
315                     context = connection_for_conn_handle(con_handle);
316                     if (!context) break;
317                     printf("%c: Nordic SPP connected\n", context->name);
318                     context->le_notification_enabled = 1;
319                     test_reset(context);
320                     context->send_request.callback = &nordic_can_send;
321                     nordic_spp_service_server_request_can_send_now(&context->send_request, context->connection_handle);
322                     break;
323                 case GATTSERVICE_SUBEVENT_SPP_SERVICE_DISCONNECTED:
324                     con_handle = gattservice_subevent_spp_service_disconnected_get_con_handle(packet);
325                     context = connection_for_conn_handle(con_handle);
326                     if (!context) break;
327                     // free connection
328                     printf("%c: Nordic SPP disconnected\n", context->name);
329                     context->le_notification_enabled = 0;
330                     context->connection_handle = HCI_CON_HANDLE_INVALID;
331                     break;
332                 default:
333                     break;
334             }
335             break;
336         case RFCOMM_DATA_PACKET:
337             printf("RECV: ");
338             printf_hexdump(packet, size);
339             context = connection_for_conn_handle((hci_con_handle_t) channel);
340             if (!context) break;
341             test_track_sent(context, size);
342             break;
343         default:
344             break;
345     }
346 }
347 
348 int btstack_main(void);
349 int btstack_main(void){
350     // register for HCI events
351     hci_event_callback_registration.callback = &hci_packet_handler;
352     hci_add_event_handler(&hci_event_callback_registration);
353 
354     l2cap_init();
355 
356     // setup SM: Display only
357     sm_init();
358 
359     // setup ATT server
360     att_server_init(profile_data, NULL, NULL);
361 
362     // setup Nordic SPP service
363     nordic_spp_service_server_init(&nordic_spp_packet_handler);
364 
365     // register for ATT events
366     att_server_register_packet_handler(att_packet_handler);
367 
368     // setup advertisements
369     uint16_t adv_int_min = 0x0030;
370     uint16_t adv_int_max = 0x0030;
371     uint8_t adv_type = 0;
372     bd_addr_t null_addr;
373     memset(null_addr, 0, 6);
374     gap_advertisements_set_params(adv_int_min, adv_int_max, adv_type, 0, null_addr, 0x07, 0x00);
375     gap_advertisements_set_data(adv_data_len, (uint8_t*) adv_data);
376     gap_advertisements_enable(1);
377 
378     // init client state
379     init_connections();
380 
381     // turn on!
382 	hci_power_control(HCI_POWER_ON);
383 
384     return 0;
385 }
386 /* EXAMPLE_END */
387