xref: /btstack/example/hsp_ag_demo.c (revision 4c7b5f7454ef118efc1f5c21f6607e2939cfc1cc)
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_STDIO 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 
63 #define SCO_REPORT_PERIOD 255
64 
65 static uint8_t       hsp_service_buffer[150];
66 static const uint8_t rfcomm_channel_nr = 1;
67 static const char    hsp_ag_service_name[] = "Audio Gateway Test";
68 static uint16_t      sco_handle = 0;
69 
70 static char hs_cmd_buffer[100];
71 
72 static bd_addr_t device_addr = {0x00,0x1b,0xDC,0x07,0x32,0xEF};
73 
74 static int phase = 0;
75 
76 // input signal: pre-computed sine wave, 160 Hz
77 static const uint8_t sine[] = {
78       0,  15,  31,  46,  61,  74,  86,  97, 107, 114,
79     120, 124, 126, 126, 124, 120, 114, 107,  97,  86,
80      74,  61,  46,  31,  15,   0, 241, 225, 210, 195,
81     182, 170, 159, 149, 142, 136, 132, 130, 130, 132,
82     136, 142, 149, 159, 170, 182, 195, 210, 225, 241,
83 };
84 
85 /* @section Audio Transfer Setup
86  *
87  * @text A pre-computed sine wave (160Hz) is used as the input audio signal. 160 Hz.
88  * To send and receive an audio signal, HAVE_SCO_OVER_HCI has to be defined.
89  *
90  * Tested working setups:
91  * - Ubuntu 14 64-bit, CC2564B connected via FTDI USB-2-UART adapter, 921600 baud
92  * - Ubuntu 14 64-bit, CSR USB dongle
93  * - OS X 10.11, CSR USB dongle
94  *
95  * Broken setups:
96  * - OS X 10.11, CC2564B connected via FDTI USB-2-UART adapter, 921600 baud
97  * - select(..) blocks > 400 ms -> num completed is received to late -> gaps between audio
98  * - looks like bug in select->FTDI driver as it works correct on Linux
99  *
100  * SCO not routed over HCI yet:
101  * - CSR UART dongle
102  * - Broadcom USB dongle
103  * - Broadcom UART chipset
104  * - ..
105  *
106  */
107 
108 
109 static void show_usage(void){
110     bd_addr_t iut_address;
111     gap_local_bd_addr(iut_address);
112 
113     printf("\n--- Bluetooth HSP Audio Gateway Test Console %s ---\n", bd_addr_to_str(iut_address));
114 
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("m - set microphone gain 8\n");
121     printf("M - set microphone gain 15\n");
122     printf("o - set speaker gain 0\n");
123     printf("s - set speaker gain 8\n");
124     printf("S - set speaker gain 15\n");
125     printf("r - start ringing\n");
126     printf("t - stop ringing\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_ag_connect(device_addr);
141             break;
142         case 'C':
143             printf("Disconnect.\n");
144             hsp_ag_disconnect();
145             break;
146         case 'a':
147             printf("Establish audio connection\n");
148             hsp_ag_establish_audio_connection();
149             break;
150         case 'A':
151             printf("Release audio connection\n");
152             hsp_ag_release_audio_connection();
153             break;
154         case 'm':
155             printf("Setting microphone gain 8\n");
156             hsp_ag_set_microphone_gain(8);
157             break;
158         case 'M':
159             printf("Setting microphone gain 15\n");
160             hsp_ag_set_microphone_gain(15);
161             break;
162         case 'o':
163             printf("Setting speaker gain 0\n");
164             hsp_ag_set_speaker_gain(0);
165             break;
166         case 's':
167             printf("Setting speaker gain 8\n");
168             hsp_ag_set_speaker_gain(8);
169             break;
170         case 'S':
171             printf("Setting speaker gain 15\n");
172             hsp_ag_set_speaker_gain(15);
173             break;
174         case 'r':
175             printf("Start ringing\n");
176             hsp_ag_start_ringing();
177             break;
178         case 't':
179             printf("Stop ringing\n");
180             hsp_ag_stop_ringing();
181             break;
182         default:
183             show_usage();
184             break;
185 
186     }
187     return 0;
188 }
189 #endif
190 
191 static void try_send_sco(void){
192     return;
193     if (!sco_handle) return;
194     if (!hci_can_send_sco_packet_now()) {
195         // printf("try_send_sco, cannot send now\n");
196         return;
197     }
198 
199     const int sco_packet_length = hci_get_sco_packet_length();
200     const int sco_payload_length = sco_packet_length - 3;
201     const int frames_per_packet = sco_payload_length;    // for 8-bit data. for 16-bit data it's /2
202 
203     hci_reserve_packet_buffer();
204     uint8_t * sco_packet = hci_get_outgoing_packet_buffer();
205     // set handle + flags
206     little_endian_store_16(sco_packet, 0, sco_handle);
207     // set len
208     sco_packet[2] = sco_payload_length;
209     int i;
210     for (i=0;i<frames_per_packet;i++){
211         sco_packet[3+i] = sine[phase];
212         phase++;
213         if (phase >= sizeof(sine)) phase = 0;
214     }
215     hci_send_sco_packet_buffer(sco_packet_length);
216     static int count = 0;
217     count++;
218     if ((count & SCO_REPORT_PERIOD) == 0) printf("Sent %u\n", count);
219 }
220 
221 static void sco_packet_handler(uint8_t packet_type, uint8_t * packet, uint16_t size){
222     return;
223     static int count = 0;
224     count++;
225     if ((count & SCO_REPORT_PERIOD)) return;
226     printf("SCO packets %u\n", count);
227 }
228 
229 static void packet_handler(uint8_t * event, uint16_t event_size){
230     switch (event[0]) {
231         case BTSTACK_EVENT_STATE:
232             if (event[2] != HCI_STATE_WORKING) break;
233             printf("HCI_STATE_WORKING\n");
234             show_usage();
235             break;
236         case HCI_EVENT_SCO_CAN_SEND_NOW:
237             try_send_sco();
238             break;
239         case HCI_EVENT_HSP_META:
240             switch (event[2]) {
241                 case HSP_SUBEVENT_RFCOMM_CONNECTION_COMPLETE:
242                     if (event[3] == 0){
243                         printf("RFCOMM connection established.\n");
244                     } else {
245                         printf("RFCOMM connection establishement failed.\n");
246                     }
247                     break;
248                 case HSP_SUBEVENT_RFCOMM_DISCONNECTION_COMPLETE:
249                     if (event[3] == 0){
250                         printf("RFCOMM disconnected.\n");
251                     } else {
252                         printf("RFCOMM disconnection failed.\n");
253                     }
254                     break;
255                 case HSP_SUBEVENT_AUDIO_CONNECTION_COMPLETE:
256                     if (event[3] == 0){
257                         sco_handle = little_endian_read_16(event, 4);
258                         printf("Audio connection established with SCO handle 0x%04x.\n", sco_handle);
259                         try_send_sco();
260                     } else {
261                         printf("Audio connection establishment failed with status %u\n", event[3]);
262                         sco_handle = 0;
263                     }
264                     break;
265                 case HSP_SUBEVENT_AUDIO_DISCONNECTION_COMPLETE:
266                     if (event[3] == 0){
267                         printf("Audio connection released.\n\n");
268                         sco_handle = 0;
269                     } else {
270                         printf("Audio connection releasing failed with status %u\n", event[3]);
271                     }
272                     break;
273                 case HSP_SUBEVENT_MICROPHONE_GAIN_CHANGED:
274                     printf("Received microphone gain change %d\n", event[3]);
275                     break;
276                 case HSP_SUBEVENT_SPEAKER_GAIN_CHANGED:
277                     printf("Received speaker gain change %d\n", event[3]);
278                     break;
279                 case HSP_SUBEVENT_HS_COMMAND:{
280                     memset(hs_cmd_buffer, 0, sizeof(hs_cmd_buffer));
281                     int size = event[3] <= sizeof(hs_cmd_buffer)? event[3] : sizeof(hs_cmd_buffer);
282                     memcpy(hs_cmd_buffer, &event[4], size - 1);
283                     printf("Received custom command: \"%s\". \nExit code or call hsp_ag_send_result.\n", hs_cmd_buffer);
284                     break;
285                 }
286                 default:
287                     printf("event not handled %u\n", event[2]);
288                     break;
289             }
290             break;
291         default:
292             break;
293     }
294 }
295 
296 /* @section Main Application Setup
297  *
298  * @text Listing MainConfiguration shows main application code.
299  * To run a HSP Audio Gateway service you need to initialize the SDP, and to create and register HSP AG record with it.
300  * In this example, the SCO over HCI is used to receive and send an audio signal.
301  *
302  * Two packet handlers are registered:
303  * - The HCI SCO packet handler receives audio data.
304  * - 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.
305  *
306  * The stdin_process callback allows for sending commands to the AG.
307  * At the end the Bluetooth stack is started.
308  */
309 
310 /* LISTING_START(MainConfiguration): Setup HSP Audio Gateway */
311 int btstack_main(int argc, const char * argv[]);
312 int btstack_main(int argc, const char * argv[]){
313 
314     hci_register_sco_packet_handler(&sco_packet_handler);
315 
316     l2cap_init();
317 
318     sdp_init();
319 
320     memset((uint8_t *)hsp_service_buffer, 0, sizeof(hsp_service_buffer));
321     hsp_ag_create_sdp_record(hsp_service_buffer, 0x10001, rfcomm_channel_nr, hsp_ag_service_name);
322     printf("SDP service record size: %u\n", de_get_len(hsp_service_buffer));
323     sdp_register_service(hsp_service_buffer);
324 
325     rfcomm_init();
326 
327     hsp_ag_init(rfcomm_channel_nr);
328     hsp_ag_register_packet_handler(packet_handler);
329 
330 #ifdef HAVE_STDIO
331     btstack_stdin_setup(stdin_process);
332 #endif
333 
334     gap_set_local_name("BTstack HSP AG");
335     gap_discoverable_control(1);
336     gap_ssp_set_io_capability(SSP_IO_CAPABILITY_DISPLAY_YES_NO);
337     gap_set_class_of_device(0x400204);
338 
339     // turn on!
340     hci_power_control(HCI_POWER_ON);
341     return 0;
342 }
343 /* LISTING_END */
344