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