xref: /btstack/example/spp_streamer_client.c (revision ceed67ffe68ea5103bbc5647a2e000ed0e08b747)
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__ "spp_streamer_client.c"
39 
40 /*
41  * spp_streamer_client.c
42  */
43 
44 // *****************************************************************************
45 /* EXAMPLE_START(spp_streamer_client): Performance - Stream Data over SPP (Client)
46  *
47  * @text Note: The SPP Streamer Client scans for and connects to SPP Streamer,
48  * and measures the throughput.
49  */
50 // *****************************************************************************
51 
52 #include <stdint.h>
53 #include <stdio.h>
54 #include <stdlib.h>
55 #include <string.h>
56 #include <inttypes.h>
57 
58 #include "btstack.h"
59 
60 // prototypes
61 static void packet_handler (uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size);
62 
63 static uint8_t rfcomm_server_channel;
64 
65 #define NUM_ROWS 25
66 #define NUM_COLS 40
67 
68 #define TEST_COD 0x1234
69 
70 #define TEST_MODE_SEND      1
71 #define TEST_MODE_RECEIVE   2
72 #define TEST_MODE_DUPLEX    3
73 
74 // configure test mode: send only, receive only, full duplex
75 #define TEST_MODE TEST_MODE_SEND
76 
77 typedef enum {
78     // SPP
79     W4_PEER_COD,
80     W4_SCAN_COMPLETE,
81     W4_SDP_RESULT,
82     W2_SEND_SDP_QUERY,
83     W4_RFCOMM_CHANNEL,
84     SENDING,
85     DONE
86 } state_t;
87 
88 static uint8_t   test_data[NUM_ROWS * NUM_COLS];
89 static uint16_t  spp_test_data_len;
90 
91 static btstack_packet_callback_registration_t hci_event_callback_registration;
92 static btstack_context_callback_registration_t handle_sdp_client_query_request;
93 
94 static bd_addr_t peer_addr;
95 static state_t state;
96 
97 // SPP
98 static uint16_t  rfcomm_mtu;
99 static uint16_t  rfcomm_cid = 0;
100 // static uint32_t  data_to_send =  DATA_VOLUME;
101 
102 /**
103  * RFCOMM can make use for ERTM. Due to the need to re-transmit packets,
104  * a large buffer is needed to still get high throughput
105  */
106 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE_FOR_RFCOMM
107 static uint8_t ertm_buffer[20000];
108 static l2cap_ertm_config_t ertm_config = {
109     0,       // ertm mandatory
110     8,       // max transmit
111     2000,
112     12000,
113     1000,    // l2cap ertm mtu
114     8,
115     8,
116     0,       // No FCS
117 };
118 static int ertm_buffer_in_use;
119 static void rfcomm_ertm_request_handler(rfcomm_ertm_request_t * ertm_request){
120     printf("ERTM Buffer requested, buffer in use %u\n", ertm_buffer_in_use);
121     if (ertm_buffer_in_use) return;
122     ertm_buffer_in_use = 1;
123     ertm_request->ertm_config      = &ertm_config;
124     ertm_request->ertm_buffer      = ertm_buffer;
125     ertm_request->ertm_buffer_size = sizeof(ertm_buffer);
126 }
127 static void rfcomm_ertm_released_handler(uint16_t ertm_id){
128     printf("ERTM Buffer released, buffer in use  %u, ertm_id %x\n", ertm_buffer_in_use, ertm_id);
129     ertm_buffer_in_use = 0;
130 }
131 #endif
132 
133 /**
134  * Find remote peer by COD
135  */
136 #define INQUIRY_INTERVAL 5
137 static void start_scan(void){
138     printf("Starting inquiry scan..\n");
139     state = W4_PEER_COD;
140     gap_inquiry_start(INQUIRY_INTERVAL);
141 }
142 static void stop_scan(void){
143     printf("Stopping inquiry scan..\n");
144     state = W4_SCAN_COMPLETE;
145     gap_inquiry_stop();
146 }
147 /*
148  * @section Track throughput
149  * @text We calculate the throughput by setting a start time and measuring the amount of
150  * data sent. After a configurable REPORT_INTERVAL_MS, we print the throughput in kB/s
151  * and reset the counter and start time.
152  */
153 
154 /* LISTING_START(tracking): Tracking throughput */
155 #define REPORT_INTERVAL_MS 3000
156 static uint32_t test_data_transferred;
157 static uint32_t test_data_start;
158 
159 static void test_reset(void){
160     test_data_start = btstack_run_loop_get_time_ms();
161     test_data_transferred = 0;
162 }
163 
164 static void test_track_transferred(int bytes_sent){
165     test_data_transferred += bytes_sent;
166     // evaluate
167     uint32_t now = btstack_run_loop_get_time_ms();
168     uint32_t time_passed = now - test_data_start;
169     if (time_passed < REPORT_INTERVAL_MS) return;
170     // print speed
171     int bytes_per_second = test_data_transferred * 1000 / time_passed;
172     printf("%u bytes -> %u.%03u kB/s\n", (int) test_data_transferred, (int) bytes_per_second / 1000, bytes_per_second % 1000);
173 
174     // restart
175     test_data_start = now;
176     test_data_transferred  = 0;
177 }
178 /* LISTING_END(tracking): Tracking throughput */
179 
180 #if (TEST_MODE & TEST_MODE_SEND)
181 static void spp_create_test_data(void){
182     int x,y;
183     for (y=0;y<NUM_ROWS;y++){
184         for (x=0;x<NUM_COLS-2;x++){
185             test_data[y*NUM_COLS+x] = '0' + (x % 10);
186         }
187         test_data[y*NUM_COLS+NUM_COLS-2] = '\n';
188         test_data[y*NUM_COLS+NUM_COLS-1] = '\r';
189     }
190 }
191 static void spp_send_packet(void){
192     rfcomm_send(rfcomm_cid, (uint8_t*) test_data, spp_test_data_len);
193     test_track_transferred(spp_test_data_len);
194     rfcomm_request_can_send_now_event(rfcomm_cid);
195 }
196 #endif
197 
198 /*
199  * @section SDP Query Packet Handler
200  *
201  * @text Store RFCOMM Channel for SPP service and initiates RFCOMM connection
202  */
203 static void handle_query_rfcomm_event(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
204     UNUSED(packet_type);
205     UNUSED(channel);
206     UNUSED(size);
207 
208     switch (hci_event_packet_get_type(packet)){
209         case SDP_EVENT_QUERY_RFCOMM_SERVICE:
210             rfcomm_server_channel = sdp_event_query_rfcomm_service_get_rfcomm_channel(packet);
211             break;
212         case SDP_EVENT_QUERY_COMPLETE:
213             if (sdp_event_query_complete_get_status(packet)){
214                 printf("SDP query failed, status 0x%02x\n", sdp_event_query_complete_get_status(packet));
215                 break;
216             }
217             if (rfcomm_server_channel == 0){
218                 printf("No SPP service found\n");
219                 break;
220             }
221             printf("SDP query done, channel 0x%02x.\n", rfcomm_server_channel);
222             rfcomm_create_channel(packet_handler, peer_addr, rfcomm_server_channel, NULL);
223             break;
224         default:
225             break;
226     }
227 }
228 
229 static void handle_start_sdp_client_query(void * context){
230     UNUSED(context);
231     if (state != W2_SEND_SDP_QUERY) return;
232     state = W4_RFCOMM_CHANNEL;
233     sdp_client_query_rfcomm_channel_and_name_for_uuid(&handle_query_rfcomm_event, peer_addr, BLUETOOTH_SERVICE_CLASS_SERIAL_PORT);
234 }
235 
236 
237 /*
238  * @section Gerenal Packet Handler
239  *
240  * @text Handles startup (BTSTACK_EVENT_STATE), inquiry, pairing, starts SDP query for SPP service, and RFCOMM connection
241  */
242 
243 static void packet_handler (uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
244     UNUSED(channel);
245 
246     bd_addr_t event_addr;
247     uint8_t   rfcomm_channel_nr;
248     uint32_t class_of_device;
249 
250 	switch (packet_type) {
251 		case HCI_EVENT_PACKET:
252 			switch (hci_event_packet_get_type(packet)) {
253 
254                 case BTSTACK_EVENT_STATE:
255                     if (btstack_event_state_get_state(packet) != HCI_STATE_WORKING) return;
256                     start_scan();
257                     break;
258 
259                 case GAP_EVENT_INQUIRY_RESULT:
260                     if (state != W4_PEER_COD) break;
261                     class_of_device = gap_event_inquiry_result_get_class_of_device(packet);
262                     gap_event_inquiry_result_get_bd_addr(packet, event_addr);
263                     if (class_of_device == TEST_COD){
264                         memcpy(peer_addr, event_addr, 6);
265                         printf("Peer found: %s\n", bd_addr_to_str(peer_addr));
266                         stop_scan();
267                     } else {
268                         printf("Device found: %s with COD: 0x%06x\n", bd_addr_to_str(event_addr), (int) class_of_device);
269                     }
270                     break;
271 
272                 case GAP_EVENT_INQUIRY_COMPLETE:
273                     switch (state){
274                         case W4_PEER_COD:
275                             printf("Inquiry complete\n");
276                             printf("Peer not found, starting scan again\n");
277                             start_scan();
278                             break;
279                         case W4_SCAN_COMPLETE:
280                             printf("Start to connect and query for SPP service\n");
281                             state = W2_SEND_SDP_QUERY;
282                             handle_sdp_client_query_request.callback = &handle_start_sdp_client_query;
283                             (void) sdp_client_register_query_callback(&handle_sdp_client_query_request);
284                             break;
285                         default:
286                             break;
287                     }
288                     if (state == W4_PEER_COD){
289                     }
290                     break;
291 
292                 case HCI_EVENT_PIN_CODE_REQUEST:
293                     // inform about pin code request
294                     printf("Pin code request - using '0000'\n");
295                     hci_event_pin_code_request_get_bd_addr(packet, event_addr);
296                     gap_pin_code_response(event_addr, "0000");
297                     break;
298 
299                 case HCI_EVENT_USER_CONFIRMATION_REQUEST:
300                     // inform about user confirmation request
301                     printf("SSP User Confirmation Request with numeric value '%06"PRIu32"'\n", little_endian_read_32(packet, 8));
302                     printf("SSP User Confirmation Auto accept\n");
303                     break;
304 
305                 case RFCOMM_EVENT_INCOMING_CONNECTION:
306                     rfcomm_event_incoming_connection_get_bd_addr(packet, event_addr);
307                     rfcomm_channel_nr = rfcomm_event_incoming_connection_get_server_channel(packet);
308                     rfcomm_cid = rfcomm_event_incoming_connection_get_rfcomm_cid(packet);
309                     printf("RFCOMM channel 0x%02x requested for %s\n", rfcomm_channel_nr, bd_addr_to_str(event_addr));
310                     rfcomm_accept_connection(rfcomm_cid);
311 					break;
312 
313 				case RFCOMM_EVENT_CHANNEL_OPENED:
314 					if (rfcomm_event_channel_opened_get_status(packet)) {
315                         printf("RFCOMM channel open failed, status 0x%02x\n", rfcomm_event_channel_opened_get_status(packet));
316                     } else {
317                         rfcomm_cid = rfcomm_event_channel_opened_get_rfcomm_cid(packet);
318                         rfcomm_mtu = rfcomm_event_channel_opened_get_max_frame_size(packet);
319                         printf("RFCOMM channel open succeeded. New RFCOMM Channel ID 0x%02x, max frame size %u\n", rfcomm_cid, rfcomm_mtu);
320                         test_reset();
321 
322                         // disable page/inquiry scan to get max performance
323                         gap_discoverable_control(0);
324                         gap_connectable_control(0);
325 
326 #if (TEST_MODE & TEST_MODE_SEND)
327                         // configure test data
328                         spp_test_data_len = rfcomm_mtu;
329                         if (spp_test_data_len > sizeof(test_data)){
330                             spp_test_data_len = sizeof(test_data);
331                         }
332                         spp_create_test_data();
333                         state = SENDING;
334                         // start sending
335                         rfcomm_request_can_send_now_event(rfcomm_cid);
336 #endif
337                     }
338 					break;
339 
340 #if (TEST_MODE & TEST_MODE_SEND)
341                 case RFCOMM_EVENT_CAN_SEND_NOW:
342                     spp_send_packet();
343                     break;
344 #endif
345 
346                 case RFCOMM_EVENT_CHANNEL_CLOSED:
347                     printf("RFCOMM channel closed\n");
348                     rfcomm_cid = 0;
349 
350                     // re-enable page/inquiry scan again
351                     gap_discoverable_control(1);
352                     gap_connectable_control(1);
353                     break;
354 
355 
356 
357                 default:
358                     break;
359 			}
360             break;
361 
362         case RFCOMM_DATA_PACKET:
363             test_track_transferred(size);
364 
365 #if 0
366             // optional: print received data as ASCII text
367             printf("RCV: '");
368             for (i=0;i<size;i++){
369                 putchar(packet[i]);
370             }
371             printf("'\n");
372 #endif
373             break;
374 
375         default:
376             break;
377 	}
378 }
379 
380 /*
381  * @section Main Application Setup
382  *
383  * @text As with the packet and the heartbeat handlers, the combined app setup contains the code from the individual example setups.
384  */
385 
386 
387 /* LISTING_START(MainConfiguration): Init L2CAP RFCOMM SDO SM ATT Server and start heartbeat timer */
388 int btstack_main(int argc, const char * argv[]);
389 int btstack_main(int argc, const char * argv[]){
390     UNUSED(argc);
391     (void)argv;
392 
393     l2cap_init();
394 
395 #ifdef ENABLE_BLE
396     // Initialize LE Security Manager. Needed for cross-transport key derivation
397     sm_init();
398 #endif
399 
400     rfcomm_init();
401 
402 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE_FOR_RFCOMM
403     // setup ERTM management
404     rfcomm_enable_l2cap_ertm(&rfcomm_ertm_request_handler, &rfcomm_ertm_released_handler);
405 #endif
406 
407     // register for HCI events
408     hci_event_callback_registration.callback = &packet_handler;
409     hci_add_event_handler(&hci_event_callback_registration);
410 
411     // init SDP
412     gap_ssp_set_io_capability(SSP_IO_CAPABILITY_DISPLAY_YES_NO);
413 
414     // turn on!
415 	hci_power_control(HCI_POWER_ON);
416 
417     return 0;
418 }
419 /* LISTING_END */
420 /* EXAMPLE_END */
421