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