xref: /btstack/example/nordic_spp_le_streamer.c (revision 4163d2eb57800152df2d8adc265fabbe20bbf6e9)
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 "nordic_spp_le_streamer.h"
65 #include "ble/gatt-service/nordic_spp_service_server.h"
66 
67 #define REPORT_INTERVAL_MS 3000
68 #define MAX_NR_CONNECTIONS 3
69 
70 static void  packet_handler (uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size);
71 
72 const uint8_t adv_data[] = {
73     // Flags general discoverable, BR/EDR not supported
74     2, BLUETOOTH_DATA_TYPE_FLAGS, 0x06,
75     // Name
76     8, BLUETOOTH_DATA_TYPE_COMPLETE_LOCAL_NAME, 'n', 'R', 'F',' ', 'S', 'P', 'P',
77     // UUID ...
78     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,
79 };
80 const uint8_t adv_data_len = sizeof(adv_data);
81 
82 static btstack_packet_callback_registration_t hci_event_callback_registration;
83 
84 // support for multiple clients
85 typedef struct {
86     char name;
87     int le_notification_enabled;
88     hci_con_handle_t connection_handle;
89     int  counter;
90     char test_data[200];
91     int  test_data_len;
92     uint32_t test_data_sent;
93     uint32_t test_data_start;
94     btstack_context_callback_registration_t send_request;
95 } nordic_spp_le_streamer_connection_t;
96 
97 static nordic_spp_le_streamer_connection_t nordic_spp_le_streamer_connections[MAX_NR_CONNECTIONS];
98 
99 // round robin sending
100 static int connection_index;
101 
102 static void init_connections(void){
103     // track connections
104     int i;
105     for (i=0;i<MAX_NR_CONNECTIONS;i++){
106         nordic_spp_le_streamer_connections[i].connection_handle = HCI_CON_HANDLE_INVALID;
107         nordic_spp_le_streamer_connections[i].name = 'A' + i;
108     }
109 }
110 
111 static nordic_spp_le_streamer_connection_t * connection_for_conn_handle(hci_con_handle_t conn_handle){
112     int i;
113     for (i=0;i<MAX_NR_CONNECTIONS;i++){
114         if (nordic_spp_le_streamer_connections[i].connection_handle == conn_handle) return &nordic_spp_le_streamer_connections[i];
115     }
116     return NULL;
117 }
118 
119 static void next_connection_index(void){
120     connection_index++;
121     if (connection_index == MAX_NR_CONNECTIONS){
122         connection_index = 0;
123     }
124 }
125 
126 /*
127  * @section Track throughput
128  * @text We calculate the throughput by setting a start time and measuring the amount of
129  * data sent. After a configurable REPORT_INTERVAL_MS, we print the throughput in kB/s
130  * and reset the counter and start time.
131  */
132 
133 /* LISTING_START(tracking): Tracking throughput */
134 
135 static void test_reset(nordic_spp_le_streamer_connection_t * context){
136     context->test_data_start = btstack_run_loop_get_time_ms();
137     context->test_data_sent = 0;
138 }
139 
140 static void test_track_sent(nordic_spp_le_streamer_connection_t * context, int bytes_sent){
141     context->test_data_sent += bytes_sent;
142     // evaluate
143     uint32_t now = btstack_run_loop_get_time_ms();
144     uint32_t time_passed = now - context->test_data_start;
145     if (time_passed < REPORT_INTERVAL_MS) return;
146     // print speed
147     int bytes_per_second = context->test_data_sent * 1000 / time_passed;
148     printf("%c: %"PRIu32" bytes sent-> %u.%03u kB/s\n", context->name, context->test_data_sent, bytes_per_second / 1000, bytes_per_second % 1000);
149 
150     // restart
151     context->test_data_start = now;
152     context->test_data_sent  = 0;
153 }
154 /* LISTING_END(tracking): Tracking throughput */
155 
156 /*
157  * @section Packet Handler
158  *
159  * @text The packet handler is used to stop the notifications and reset the MTU on connect
160  * It would also be a good place to request the connection parameter update as indicated
161  * in the commented code block.
162  */
163 
164 /* LISTING_START(packetHandler): Packet Handler */
165 static void packet_handler (uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
166     UNUSED(channel);
167     UNUSED(size);
168 
169     int mtu;
170     uint16_t conn_interval;
171     nordic_spp_le_streamer_connection_t * context;
172     switch (packet_type) {
173         case HCI_EVENT_PACKET:
174             switch (hci_event_packet_get_type(packet)) {
175                 case BTSTACK_EVENT_STATE:
176                     // BTstack activated, get started
177                     if (btstack_event_state_get_state(packet) == HCI_STATE_WORKING) {
178                         printf("To start the streaming, please run the AMB2621 Toolbox to connect.\n");
179                     }
180                     break;
181                 case HCI_EVENT_DISCONNECTION_COMPLETE:
182                     context = connection_for_conn_handle(hci_event_disconnection_complete_get_connection_handle(packet));
183                     if (!context) break;
184                     // free connection
185                     printf("%c: Disconnect, reason %02x\n", context->name, hci_event_disconnection_complete_get_reason(packet));
186                     context->le_notification_enabled = 0;
187                     context->connection_handle = HCI_CON_HANDLE_INVALID;
188                     break;
189                 case HCI_EVENT_LE_META:
190                     switch (hci_event_le_meta_get_subevent_code(packet)) {
191                         case HCI_SUBEVENT_LE_CONNECTION_COMPLETE:
192                             // setup new
193                             context = connection_for_conn_handle(HCI_CON_HANDLE_INVALID);
194                             if (!context) break;
195                             context->counter = 'A';
196                             context->test_data_len = ATT_DEFAULT_MTU - 4;   // -1 for nordic 0x01 packet type
197                             context->connection_handle = hci_subevent_le_connection_complete_get_connection_handle(packet);
198                             // print connection parameters (without using float operations)
199                             conn_interval = hci_subevent_le_connection_complete_get_conn_interval(packet);
200                             printf("%c: Connection Interval: %u.%02u ms\n", context->name, conn_interval * 125 / 100, 25 * (conn_interval & 3));
201                             printf("%c: Connection Latency: %u\n", context->name, hci_subevent_le_connection_complete_get_conn_latency(packet));
202                             break;
203                     }
204                     break;
205                 case ATT_EVENT_MTU_EXCHANGE_COMPLETE:
206                     mtu = att_event_mtu_exchange_complete_get_MTU(packet) - 3;
207                     context = connection_for_conn_handle(att_event_mtu_exchange_complete_get_handle(packet));
208                     if (!context) break;
209                     context->test_data_len = btstack_min(mtu - 3, sizeof(context->test_data));
210                     printf("%c: ATT MTU = %u => use test data of len %u\n", context->name, mtu, context->test_data_len);
211                     break;
212                 default:
213                     break;
214             }
215     }
216 }
217 
218 /* LISTING_END */
219 /*
220  * @section Streamer
221  *
222  * @text The streamer function checks if notifications are enabled and if a notification can be sent now.
223  * It creates some test data - a single letter that gets increased every time - and tracks the data sent.
224  */
225 
226  /* LISTING_START(streamer): Streaming code */
227 static void nordic_can_send(void * some_context){
228     UNUSED(some_context);
229 
230     // find next active streaming connection
231     int old_connection_index = connection_index;
232     while (1){
233         // active found?
234         if ((nordic_spp_le_streamer_connections[connection_index].connection_handle != HCI_CON_HANDLE_INVALID) &&
235             (nordic_spp_le_streamer_connections[connection_index].le_notification_enabled)) break;
236 
237         // check next
238         next_connection_index();
239 
240         // none found
241         if (connection_index == old_connection_index) return;
242     }
243 
244     nordic_spp_le_streamer_connection_t * context = &nordic_spp_le_streamer_connections[connection_index];
245 
246     // create test data
247     context->counter++;
248     if (context->counter > 'Z') context->counter = 'A';
249     memset(context->test_data, context->counter, context->test_data_len);
250 
251     // send
252     nordic_spp_service_server_send(context->connection_handle, (uint8_t*) context->test_data, context->test_data_len);
253 
254     // track
255     test_track_sent(context, context->test_data_len);
256 
257     // request next send event
258     nordic_spp_service_server_request_can_send_now(&context->send_request, context->connection_handle);
259 
260     // check next
261     next_connection_index();
262 }
263 /* LISTING_END */
264 
265 static void nordic_data_received(hci_con_handle_t tx_con_handle, const uint8_t * data, uint16_t size){
266     nordic_spp_le_streamer_connection_t * context = connection_for_conn_handle(tx_con_handle);
267 
268     if (!context) return;
269 
270     if (size == 0 && context->le_notification_enabled == 0){
271         context->le_notification_enabled = 1;
272         test_reset(context);
273         context->send_request.callback = &nordic_can_send;
274         nordic_spp_service_server_request_can_send_now(&context->send_request, context->connection_handle);
275     } else {
276         printf("RECV: ");
277         printf_hexdump(data, size);
278         test_track_sent(context, size);
279    }
280 }
281 
282 int btstack_main(void);
283 int btstack_main(void){
284     // register for HCI events
285     hci_event_callback_registration.callback = &packet_handler;
286     hci_add_event_handler(&hci_event_callback_registration);
287 
288     l2cap_init();
289 
290     // setup LE device DB
291     le_device_db_init();
292 
293     // setup SM: Display only
294     sm_init();
295 
296     // setup ATT server
297     att_server_init(profile_data, NULL, NULL);
298 
299     // setup Nordic SPP service
300     nordic_spp_service_server_init(&nordic_data_received);
301 
302     // setup advertisements
303     uint16_t adv_int_min = 0x0030;
304     uint16_t adv_int_max = 0x0030;
305     uint8_t adv_type = 0;
306     bd_addr_t null_addr;
307     memset(null_addr, 0, 6);
308     gap_advertisements_set_params(adv_int_min, adv_int_max, adv_type, 0, null_addr, 0x07, 0x00);
309     gap_advertisements_set_data(adv_data_len, (uint8_t*) adv_data);
310     gap_advertisements_enable(1);
311 
312     // init client state
313     init_connections();
314 
315     // turn on!
316 	hci_power_control(HCI_POWER_ON);
317 
318     return 0;
319 }
320 /* EXAMPLE_END */
321