xref: /btstack/example/hsp_hs_demo.c (revision b3fcedb9c9ccbcc9680da165cd86f394be5d84a8)
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 /*
39  * hsp_hs_demo.c
40  */
41 
42 // *****************************************************************************
43 /* EXAMPLE_START(hsp_hs_demo): HSP Headset Demo
44  *
45  * @text This example implements a HSP Headset device that sends and receives
46  * audio signal over HCI SCO. It demonstrates how to receive
47  * an output from a remote audio gateway (AG), and,
48  * if HAVE_POSIX_STDIN is defined, how to control the AG.
49  */
50 // *****************************************************************************
51 
52 #include "btstack_config.h"
53 
54 #include <stdint.h>
55 #include <stdio.h>
56 #include <stdlib.h>
57 #include <string.h>
58 #include <math.h>
59 #include <unistd.h>
60 
61 #include "btstack.h"
62 #ifdef HAVE_POSIX_STDIN
63 #include "stdin_support.h"
64 #endif
65 
66 #define SCO_REPORT_PERIOD 255
67 
68 static btstack_packet_callback_registration_t hci_event_callback_registration;
69 
70 static uint8_t hsp_service_buffer[150];
71 static const uint8_t rfcomm_channel_nr = 1;
72 static const char    hsp_hs_service_name[] = "Headset Test";
73 static hci_con_handle_t sco_handle = 0;
74 
75 static char hs_cmd_buffer[100];
76 static bd_addr_t device_addr = {0x00,0x1b,0xDC,0x07,0x32,0xEF};
77 
78 static int phase = 0;
79 
80 // input signal: pre-computed sine wave, 160 Hz
81 static const uint8_t sine[] = {
82       0,  15,  31,  46,  61,  74,  86,  97, 107, 114,
83     120, 124, 126, 126, 124, 120, 114, 107,  97,  86,
84      74,  61,  46,  31,  15,   0, 241, 225, 210, 195,
85     182, 170, 159, 149, 142, 136, 132, 130, 130, 132,
86     136, 142, 149, 159, 170, 182, 195, 210, 225, 241,
87 };
88 
89 /* @section Audio Transfer Setup
90  *
91  * @text A pre-computed sine wave (160Hz) is used as the input audio signal. 160 Hz.
92  * To send and receive an audio signal, HAVE_SCO_OVER_HCI has to be defined.
93  *
94  * Tested working setups:
95  * - Ubuntu 14 64-bit, CC2564B connected via FTDI USB-2-UART adapter, 921600 baud
96  * - Ubuntu 14 64-bit, CSR USB dongle
97  * - OS X 10.11, CSR USB dongle
98  *
99  * Broken setups:
100  * - OS X 10.11, CC2564B connected via FDTI USB-2-UART adapter, 921600 baud
101  * - select(..) blocks > 400 ms -> num completed is received to late -> gaps between audio
102  * - looks like bug in select->FTDI driver as it works correct on Linux
103  *
104  * SCO not routed over HCI yet:
105  * - CSR UART dongle
106  * - Broadcom USB dongle
107  * - Broadcom UART chipset
108  * - ..
109  *
110  */
111 
112 
113 static void show_usage(void){
114     bd_addr_t iut_address;
115     gap_local_bd_addr(iut_address);
116 
117     printf("\n--- Bluetooth HSP Headset Test Console %s ---\n", bd_addr_to_str(iut_address));
118     printf("---\n");
119     printf("c - Connect to %s\n", bd_addr_to_str(device_addr));
120     printf("C - Disconnect\n");
121     printf("a - establish audio connection\n");
122     printf("A - release audio connection\n");
123     printf("b - press user button\n");
124     printf("z - set microphone gain 0\n");
125     printf("m - set microphone gain 8\n");
126     printf("M - set microphone gain 15\n");
127     printf("o - set speaker gain 0\n");
128     printf("s - set speaker gain 8\n");
129     printf("S - set speaker gain 15\n");
130     printf("---\n");
131     printf("Ctrl-c - exit\n");
132     printf("---\n");
133 }
134 
135 #ifdef HAVE_POSIX_STDIN
136 static void stdin_process(btstack_data_source_t *ds, btstack_data_source_callback_type_t callback_type){
137     char buffer;
138     read(ds->fd, &buffer, 1);
139 
140     switch (buffer){
141         case 'c':
142             printf("Connect to %s\n", bd_addr_to_str(device_addr));
143             hsp_hs_connect(device_addr);
144             break;
145         case 'C':
146             printf("Disconnect.\n");
147             hsp_hs_disconnect();
148             break;
149         case 'a':
150             printf("Establish audio connection\n");
151             hsp_hs_establish_audio_connection();
152             break;
153         case 'A':
154             printf("Release audio connection\n");
155             hsp_hs_release_audio_connection();
156             break;
157 
158         case 'z':
159             printf("Setting microphone gain 0\n");
160             hsp_hs_set_microphone_gain(0);
161             break;
162         case 'm':
163             printf("Setting microphone gain 8\n");
164             hsp_hs_set_microphone_gain(8);
165             break;
166         case 'M':
167             printf("Setting microphone gain 15\n");
168             hsp_hs_set_microphone_gain(15);
169             break;
170         case 'o':
171             printf("Setting speaker gain 0\n");
172             hsp_hs_set_speaker_gain(0);
173             break;
174         case 's':
175             printf("Setting speaker gain 8\n");
176             hsp_hs_set_speaker_gain(8);
177             break;
178         case 'S':
179             printf("Setting speaker gain 15\n");
180             hsp_hs_set_speaker_gain(15);
181             break;
182         case 'b':
183             printf("Press user button\n");
184             hsp_hs_send_button_press();
185             break;
186         default:
187             show_usage();
188             break;
189     }
190 }
191 #endif
192 
193 static void send_sco_data(void){
194     if (!sco_handle) return;
195 
196     const int sco_packet_length = hci_get_sco_packet_length();
197     const int sco_payload_length = sco_packet_length - 3;
198     const int frames_per_packet = sco_payload_length;    // for 8-bit data. for 16-bit data it's /2
199 
200     hci_reserve_packet_buffer();
201     uint8_t * sco_packet = hci_get_outgoing_packet_buffer();
202     // set handle + flags
203     little_endian_store_16(sco_packet, 0, sco_handle);
204     // set len
205     sco_packet[2] = sco_payload_length;
206     int i;
207     for (i=0;i<frames_per_packet;i++){
208         sco_packet[3+i] = sine[phase];
209         phase++;
210         if (phase >= sizeof(sine)) phase = 0;
211     }
212     hci_send_sco_packet_buffer(sco_packet_length);
213 
214     // request another send event
215     hci_request_sco_can_send_now_event();
216 
217     static int count = 0;
218     count++;
219     if ((count & 15) == 0) printf("Sent %u\n", count);
220 }
221 
222 static void sco_packet_handler(uint8_t packet_type, uint8_t * packet, uint16_t size){
223     static int count = 0;
224     // hexdumpf(packet, size);
225     count++;
226     if ((count & SCO_REPORT_PERIOD)) return;
227     printf("SCO packets %u\n", count);
228 }
229 
230 static void packet_handler(uint8_t * event, uint16_t event_size){
231     switch (event[0]) {
232         case BTSTACK_EVENT_STATE:
233             if (btstack_event_state_get_state(event) != HCI_STATE_WORKING) break;
234             show_usage();
235             break;
236         case HCI_EVENT_SCO_CAN_SEND_NOW:
237             send_sco_data();
238             break;
239         case HCI_EVENT_HSP_META:
240             switch (event[2]) {
241                 case HSP_SUBEVENT_RFCOMM_CONNECTION_COMPLETE:
242                     if (hsp_subevent_rfcomm_connection_complete_get_status(event)){
243                         printf("RFCOMM connection establishement failed with status %u\n", hsp_subevent_audio_connection_complete_get_handle(event));
244                     } else {
245                         printf("RFCOMM connection established.\n");
246                     }
247                     break;
248                 case HSP_SUBEVENT_RFCOMM_DISCONNECTION_COMPLETE:
249                     if (hsp_subevent_rfcomm_disconnection_complete_get_status(event)){
250                         printf("RFCOMM disconnection failed with status %u.\n", hsp_subevent_rfcomm_disconnection_complete_get_status(event));
251                     } else {
252                         printf("RFCOMM disconnected.\n");
253                     }
254                     break;
255                 case HSP_SUBEVENT_AUDIO_CONNECTION_COMPLETE:
256                     if (hsp_subevent_audio_connection_complete_get_status(event)){
257                         printf("Audio connection establishment failed with status %u\n", hsp_subevent_audio_connection_complete_get_status(event));
258                         sco_handle = 0;
259                     } else {
260                         sco_handle = hsp_subevent_audio_connection_complete_get_handle(event);
261                         printf("Audio connection established with SCO handle 0x%04x.\n", sco_handle);
262                         hci_request_sco_can_send_now_event();
263                     }
264                     break;
265                 case HSP_SUBEVENT_AUDIO_DISCONNECTION_COMPLETE:
266                     if (hsp_subevent_audio_disconnection_complete_get_status(event)){
267                         printf("Audio connection releasing failed with status %u\n", hsp_subevent_audio_disconnection_complete_get_status(event));
268                     } else {
269                         printf("Audio connection released.\n\n");
270                         sco_handle = 0;
271                     }
272                     break;
273                 case HSP_SUBEVENT_MICROPHONE_GAIN_CHANGED:
274                     printf("Received microphone gain change %d\n", hsp_subevent_microphone_gain_changed_get_gain(event));
275                     break;
276                 case HSP_SUBEVENT_SPEAKER_GAIN_CHANGED:
277                     printf("Received speaker gain change %d\n", hsp_subevent_speaker_gain_changed_get_gain(event));
278                     break;
279                 case HSP_SUBEVENT_RING:
280                     printf("HS: RING RING!\n");
281                     break;
282                 case HSP_SUBEVENT_AG_INDICATION: {
283                     memset(hs_cmd_buffer, 0, sizeof(hs_cmd_buffer));
284                     int size = hsp_subevent_ag_indication_get_value_length(event);
285                     if (size >= sizeof(hs_cmd_buffer)-1){
286                         size =  sizeof(hs_cmd_buffer)-1;
287                     }
288                     memcpy(hs_cmd_buffer, hsp_subevent_ag_indication_get_value(event), size);
289                     printf("Received custom indication: \"%s\". \nExit code or call hsp_hs_send_result.\n", hs_cmd_buffer);
290 
291                 }
292                     break;
293                 default:
294                     printf("event not handled %u\n", event[2]);
295                     break;
296             }
297             break;
298         default:
299             break;
300     }
301 }
302 
303 static void handle_hci_event(uint8_t packet_type, uint16_t channel, uint8_t * packet, uint16_t size){
304     packet_handler(packet, size);
305 }
306 
307 /* @section Main Application Setup
308  *
309  * @text Listing MainConfiguration shows main application code.
310  * To run a HSP Headset service you need to initialize the SDP, and to create and register HSP HS record with it.
311  * In this example, the SCO over HCI is used to receive and send an audio signal.
312  *
313  * Two packet handlers are registered:
314  * - The HCI SCO packet handler receives audio data.
315  * - The HSP HS packet handler is used to trigger sending of audio data and commands to the AG. It also receives the AG's answers.
316  *
317  * The stdin_process callback allows for sending commands to the AG.
318  * At the end the Bluetooth stack is started.
319  */
320 
321 /* LISTING_START(MainConfiguration): Setup HSP Headset */
322 int btstack_main(int argc, const char * argv[]);
323 int btstack_main(int argc, const char * argv[]){
324 
325     // register for HCI events
326     hci_event_callback_registration.callback = &handle_hci_event;
327     hci_add_event_handler(&hci_event_callback_registration);
328     hci_register_sco_packet_handler(&sco_packet_handler);
329 
330     l2cap_init();
331 
332     sdp_init();
333     memset(hsp_service_buffer, 0, sizeof(hsp_service_buffer));
334     hsp_hs_create_sdp_record(hsp_service_buffer, 0x10001, rfcomm_channel_nr, hsp_hs_service_name, 0);
335     sdp_register_service(hsp_service_buffer);
336 
337     rfcomm_init();
338 
339     hsp_hs_init(rfcomm_channel_nr);
340     hsp_hs_register_packet_handler(packet_handler);
341 
342 #ifdef HAVE_POSIX_STDIN
343     btstack_stdin_setup(stdin_process);
344 #endif
345 
346     gap_set_local_name("BTstack HSP HS");
347     gap_discoverable_control(1);
348     gap_ssp_set_io_capability(SSP_IO_CAPABILITY_DISPLAY_YES_NO);
349     gap_set_class_of_device(0x240404);
350 
351     // turn on!
352     hci_power_control(HCI_POWER_ON);
353     return 0;
354 }
355 /* LISTING_END */
356 /* EXAMPLE_END */
357