xref: /btstack/example/spp_streamer_client.c (revision db010f46202d938f930b3361e64f41193be86e6c)
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__ "spp_streamer_client.c"
39 
40 /*
41  * spp_streamer_client.c
42  */
43 
44 // *****************************************************************************
45 /* EXAMPLE_START(spp_streamer_client): Client for SPP Streamer
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 (packet[0]){
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 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 %u.\n", rfcomm_server_channel);
222             rfcomm_create_channel(packet_handler, peer_addr, rfcomm_server_channel, NULL);
223             break;
224     }
225 }
226 
227 static void handle_start_sdp_client_query(void * context){
228     UNUSED(context);
229     if (state != W2_SEND_SDP_QUERY) return;
230     state = W4_RFCOMM_CHANNEL;
231     sdp_client_query_rfcomm_channel_and_name_for_uuid(&handle_query_rfcomm_event, peer_addr, BLUETOOTH_ATTRIBUTE_PUBLIC_BROWSE_ROOT);
232 }
233 
234 
235 /*
236  * @section Gerenal Packet Handler
237  *
238  * @text Handles startup (BTSTACK_EVENT_STATE), inquiry, pairing, starts SDP query for SPP service, and RFCOMM connection
239  */
240 
241 static void packet_handler (uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
242     UNUSED(channel);
243 
244     bd_addr_t event_addr;
245     uint8_t   rfcomm_channel_nr;
246     uint32_t class_of_device;
247 
248 	switch (packet_type) {
249 		case HCI_EVENT_PACKET:
250 			switch (hci_event_packet_get_type(packet)) {
251 
252                 case BTSTACK_EVENT_STATE:
253                     if (btstack_event_state_get_state(packet) != HCI_STATE_WORKING) return;
254                     start_scan();
255                     break;
256 
257                 case GAP_EVENT_INQUIRY_RESULT:
258                     if (state != W4_PEER_COD) break;
259                     class_of_device = gap_event_inquiry_result_get_class_of_device(packet);
260                     gap_event_inquiry_result_get_bd_addr(packet, event_addr);
261                     if (class_of_device == TEST_COD){
262                         memcpy(peer_addr, event_addr, 6);
263                         printf("Peer found: %s\n", bd_addr_to_str(peer_addr));
264                         stop_scan();
265                     } else {
266                         printf("Device found: %s with COD: 0x%06x\n", bd_addr_to_str(event_addr), (int) class_of_device);
267                     }
268                     break;
269 
270                 case GAP_EVENT_INQUIRY_COMPLETE:
271                     switch (state){
272                         case W4_PEER_COD:
273                             printf("Inquiry complete\n");
274                             printf("Peer not found, starting scan again\n");
275                             start_scan();
276                             break;
277                         case W4_SCAN_COMPLETE:
278                             printf("Start to connect and query for SPP service\n");
279                             state = W2_SEND_SDP_QUERY;
280                             handle_sdp_client_query_request.callback = &handle_start_sdp_client_query;
281                             (void) sdp_client_register_query_callback(&handle_start_sdp_client_query);
282                             break;
283                         default:
284                             break;
285                     }
286                     if (state == W4_PEER_COD){
287                     }
288                     break;
289 
290                 case HCI_EVENT_PIN_CODE_REQUEST:
291                     // inform about pin code request
292                     printf("Pin code request - using '0000'\n");
293                     hci_event_pin_code_request_get_bd_addr(packet, event_addr);
294                     gap_pin_code_response(event_addr, "0000");
295                     break;
296 
297                 case HCI_EVENT_USER_CONFIRMATION_REQUEST:
298                     // inform about user confirmation request
299                     printf("SSP User Confirmation Request with numeric value '%06"PRIu32"'\n", little_endian_read_32(packet, 8));
300                     printf("SSP User Confirmation Auto accept\n");
301                     break;
302 
303                 case RFCOMM_EVENT_INCOMING_CONNECTION:
304 					// data: event (8), len(8), address(48), channel (8), rfcomm_cid (16)
305                     rfcomm_event_incoming_connection_get_bd_addr(packet, event_addr);
306                     rfcomm_channel_nr = rfcomm_event_incoming_connection_get_server_channel(packet);
307                     rfcomm_cid = rfcomm_event_incoming_connection_get_rfcomm_cid(packet);
308                     printf("RFCOMM channel %u requested for %s\n", rfcomm_channel_nr, bd_addr_to_str(event_addr));
309                     rfcomm_accept_connection(rfcomm_cid);
310 					break;
311 
312 				case RFCOMM_EVENT_CHANNEL_OPENED:
313 					// data: event(8), len(8), status (8), address (48), server channel(8), rfcomm_cid(16), max frame size(16)
314 					if (rfcomm_event_channel_opened_get_status(packet)) {
315                         printf("RFCOMM channel open failed, status %u\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 %u, 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             printf("RCV: '");
367             for (i=0;i<size;i++){
368                 putchar(packet[i]);
369             }
370             printf("'\n");
371 #endif
372             break;
373 
374         default:
375             break;
376 	}
377 }
378 
379 /*
380  * @section Main Application Setup
381  *
382  * @text As with the packet and the heartbeat handlers, the combined app setup contains the code from the individual example setups.
383  */
384 
385 
386 /* LISTING_START(MainConfiguration): Init L2CAP RFCOMM SDO SM ATT Server and start heartbeat timer */
387 int btstack_main(int argc, const char * argv[]);
388 int btstack_main(int argc, const char * argv[]){
389     UNUSED(argc);
390     (void)argv;
391 
392     l2cap_init();
393 
394     rfcomm_init();
395 
396 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE_FOR_RFCOMM
397     // setup ERTM management
398     rfcomm_enable_l2cap_ertm(&rfcomm_ertm_request_handler, &rfcomm_ertm_released_handler);
399 #endif
400 
401     // register for HCI events
402     hci_event_callback_registration.callback = &packet_handler;
403     hci_add_event_handler(&hci_event_callback_registration);
404 
405     // init SDP
406     gap_ssp_set_io_capability(SSP_IO_CAPABILITY_DISPLAY_YES_NO);
407 
408     // turn on!
409 	hci_power_control(HCI_POWER_ON);
410 
411     return 0;
412 }
413 /* LISTING_END */
414 /* EXAMPLE_END */
415