xref: /btstack/example/hsp_ag_demo.c (revision df25739fc3ea5a0a90f0f5925e6461d653697d2e)
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_ag_demo.c
40  */
41 
42 // *****************************************************************************
43 /* EXAMPLE_START(hsp_ag_demo): HSP Audio Gateway Demo
44  *
45  * @text This example implements a HSP Audio Gateway device that sends and receives
46  * audio signal over HCI SCO. It demonstrates how to receive
47  * an output from a remote headset (HS), and,
48  * if HAVE_POSIX_STDIN is defined, how to control the HS.
49  */
50 // *****************************************************************************
51 
52 
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 uint8_t       hsp_service_buffer[150];
69 static const uint8_t rfcomm_channel_nr = 1;
70 static const char    hsp_ag_service_name[] = "Audio Gateway Test";
71 static uint16_t      sco_handle = 0;
72 
73 static char hs_cmd_buffer[100];
74 
75 static bd_addr_t device_addr = {0x00,0x1b,0xDC,0x07,0x32,0xEF};
76 
77 static int phase = 0;
78 
79 // input signal: pre-computed sine wave, 160 Hz
80 static const uint8_t sine[] = {
81       0,  15,  31,  46,  61,  74,  86,  97, 107, 114,
82     120, 124, 126, 126, 124, 120, 114, 107,  97,  86,
83      74,  61,  46,  31,  15,   0, 241, 225, 210, 195,
84     182, 170, 159, 149, 142, 136, 132, 130, 130, 132,
85     136, 142, 149, 159, 170, 182, 195, 210, 225, 241,
86 };
87 
88 /* @section Audio Transfer Setup
89  *
90  * @text A pre-computed sine wave (160Hz) is used as the input audio signal. 160 Hz.
91  * To send and receive an audio signal, ENABLE_SCO_OVER_HCI has to be defined.
92  *
93  * Tested working setups:
94  * - Ubuntu 14 64-bit, CC2564B connected via FTDI USB-2-UART adapter, 921600 baud
95  * - Ubuntu 14 64-bit, CSR USB dongle
96  * - OS X 10.11, CSR USB dongle
97  *
98  * Broken setups:
99  * - OS X 10.11, CC2564B connected via FDTI USB-2-UART adapter, 921600 baud
100  * - select(..) blocks > 400 ms -> num completed is received to late -> gaps between audio
101  * - looks like bug in select->FTDI driver as it works correct on Linux
102  *
103  * SCO not routed over HCI yet:
104  * - CSR UART dongle
105  * - Broadcom USB dongle
106  * - Broadcom UART chipset
107  * - ..
108  *
109  */
110 
111 
112 static void show_usage(void){
113     bd_addr_t iut_address;
114     gap_local_bd_addr(iut_address);
115 
116     printf("\n--- Bluetooth HSP Audio Gateway Test Console %s ---\n", bd_addr_to_str(iut_address));
117 
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("m - set microphone gain 8\n");
124     printf("M - set microphone gain 15\n");
125     printf("o - set speaker gain 0\n");
126     printf("s - set speaker gain 8\n");
127     printf("S - set speaker gain 15\n");
128     printf("r - start ringing\n");
129     printf("t - stop ringing\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_ag_connect(device_addr);
144             break;
145         case 'C':
146             printf("Disconnect.\n");
147             hsp_ag_disconnect();
148             break;
149         case 'a':
150             printf("Establish audio connection\n");
151             hsp_ag_establish_audio_connection();
152             break;
153         case 'A':
154             printf("Release audio connection\n");
155             hsp_ag_release_audio_connection();
156             break;
157         case 'm':
158             printf("Setting microphone gain 8\n");
159             hsp_ag_set_microphone_gain(8);
160             break;
161         case 'M':
162             printf("Setting microphone gain 15\n");
163             hsp_ag_set_microphone_gain(15);
164             break;
165         case 'o':
166             printf("Setting speaker gain 0\n");
167             hsp_ag_set_speaker_gain(0);
168             break;
169         case 's':
170             printf("Setting speaker gain 8\n");
171             hsp_ag_set_speaker_gain(8);
172             break;
173         case 'S':
174             printf("Setting speaker gain 15\n");
175             hsp_ag_set_speaker_gain(15);
176             break;
177         case 'r':
178             printf("Start ringing\n");
179             hsp_ag_start_ringing();
180             break;
181         case 't':
182             printf("Stop ringing\n");
183             hsp_ag_stop_ringing();
184             break;
185         default:
186             show_usage();
187             break;
188 
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 & SCO_REPORT_PERIOD) == 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     return;
224     static int count = 0;
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 (event[2] != 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_HS_COMMAND:{
280                     memset(hs_cmd_buffer, 0, sizeof(hs_cmd_buffer));
281                     int cmd_length = hsp_subevent_hs_command_get_value_length(event);
282                     int size = cmd_length <= sizeof(hs_cmd_buffer)? cmd_length : sizeof(hs_cmd_buffer);
283                     memcpy(hs_cmd_buffer, hsp_subevent_hs_command_get_value(event), size - 1);
284                     printf("Received custom command: \"%s\". \nExit code or call hsp_ag_send_result.\n", hs_cmd_buffer);
285                     break;
286                 }
287                 default:
288                     printf("event not handled %u\n", event[2]);
289                     break;
290             }
291             break;
292         default:
293             break;
294     }
295 }
296 
297 /* @section Main Application Setup
298  *
299  * @text Listing MainConfiguration shows main application code.
300  * To run a HSP Audio Gateway service you need to initialize the SDP, and to create and register HSP AG record with it.
301  * In this example, the SCO over HCI is used to receive and send an audio signal.
302  *
303  * Two packet handlers are registered:
304  * - The HCI SCO packet handler receives audio data.
305  * - The HSP AG packet handler is used to trigger sending of audio data and commands to the HS. It also receives the AG's answers.
306  *
307  * The stdin_process callback allows for sending commands to the AG.
308  * At the end the Bluetooth stack is started.
309  */
310 
311 /* LISTING_START(MainConfiguration): Setup HSP Audio Gateway */
312 int btstack_main(int argc, const char * argv[]);
313 int btstack_main(int argc, const char * argv[]){
314 
315     hci_register_sco_packet_handler(&sco_packet_handler);
316 
317     l2cap_init();
318 
319     sdp_init();
320 
321     memset((uint8_t *)hsp_service_buffer, 0, sizeof(hsp_service_buffer));
322     hsp_ag_create_sdp_record(hsp_service_buffer, 0x10001, rfcomm_channel_nr, hsp_ag_service_name);
323     printf("SDP service record size: %u\n", de_get_len(hsp_service_buffer));
324     sdp_register_service(hsp_service_buffer);
325 
326     rfcomm_init();
327 
328     hsp_ag_init(rfcomm_channel_nr);
329     hsp_ag_register_packet_handler(packet_handler);
330 
331 #ifdef HAVE_POSIX_STDIN
332     btstack_stdin_setup(stdin_process);
333 #endif
334 
335     gap_set_local_name("BTstack HSP AG");
336     gap_discoverable_control(1);
337     gap_ssp_set_io_capability(SSP_IO_CAPABILITY_DISPLAY_YES_NO);
338     gap_set_class_of_device(0x400204);
339 
340     // turn on!
341     hci_power_control(HCI_POWER_ON);
342     return 0;
343 }
344 /* LISTING_END */
345 /* EXAMPLE_END */
346