xref: /btstack/example/hfp_ag_demo.c (revision f12924e0a61c0582b548a1e70cea1bd59ba21f1d)
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  * hfp_ag_demo.c
40  */
41 
42 // *****************************************************************************
43 /* EXAMPLE_START(hfp_ag_demo): HFP Audio Gateway (AG) Demo
44  *
45  * @text This HFP Audio Gateway example demonstrates how to receive
46  * an output from a remote HFP Hands-Free (HF) unit, and,
47  * if HAVE_POSIX_STDIN is defined, how to control the HFP HF.
48  */
49 // *****************************************************************************
50 
51 
52 #include <stdint.h>
53 #include <stdio.h>
54 #include <stdlib.h>
55 #include <string.h>
56 #include <unistd.h>
57 
58 #include "btstack.h"
59 #include "sco_demo_util.h"
60 #ifdef HAVE_POSIX_STDIN
61 #include "stdin_support.h"
62 #endif
63 
64 uint8_t hfp_service_buffer[150];
65 const uint8_t    rfcomm_channel_nr = 1;
66 const char hfp_ag_service_name[] = "BTstack HFP AG Test";
67 
68 static bd_addr_t device_addr;
69 static const char * device_addr_string = "00:15:83:5F:9D:46";
70 
71 static uint8_t codecs[] = {HFP_CODEC_CVSD, HFP_CODEC_MSBC};
72 // static uint8_t codecs[] = {HFP_CODEC_CVSD};
73 static uint8_t negotiated_codec = HFP_CODEC_CVSD;
74 
75 static hci_con_handle_t acl_handle = -1;
76 static hci_con_handle_t sco_handle;
77 static int memory_1_enabled = 1;
78 static btstack_packet_callback_registration_t hci_event_callback_registration;
79 
80 static int ag_indicators_nr = 7;
81 static hfp_ag_indicator_t ag_indicators[] = {
82     // index, name, min range, max range, status, mandatory, enabled, status changed
83     {1, "service",   0, 1, 1, 0, 0, 0},
84     {2, "call",      0, 1, 0, 1, 1, 0},
85     {3, "callsetup", 0, 3, 0, 1, 1, 0},
86     {4, "battchg",   0, 5, 3, 0, 0, 0},
87     {5, "signal",    0, 5, 5, 0, 1, 0},
88     {6, "roam",      0, 1, 0, 0, 1, 0},
89     {7, "callheld",  0, 2, 0, 1, 1, 0}
90 };
91 
92 static int call_hold_services_nr = 5;
93 static const char* call_hold_services[] = {"1", "1x", "2", "2x", "3"};
94 
95 static int hf_indicators_nr = 2;
96 static hfp_generic_status_indicator_t hf_indicators[] = {
97     {1, 1},
98     {2, 1},
99 };
100 
101 char cmd;
102 
103 // GAP INQUIRY
104 
105 #define MAX_DEVICES 10
106 enum DEVICE_STATE { REMOTE_NAME_REQUEST, REMOTE_NAME_INQUIRED, REMOTE_NAME_FETCHED };
107 struct device {
108     bd_addr_t  address;
109     uint16_t   clockOffset;
110     uint32_t   classOfDevice;
111     uint8_t    pageScanRepetitionMode;
112     uint8_t    rssi;
113     enum DEVICE_STATE  state;
114 };
115 
116 #define INQUIRY_INTERVAL 5
117 struct device devices[MAX_DEVICES];
118 int deviceCount = 0;
119 
120 
121 enum STATE {INIT, W4_INQUIRY_MODE_COMPLETE, ACTIVE} ;
122 enum STATE state = INIT;
123 
124 static void dump_supported_codecs(void){
125     int i;
126     int mSBC_skipped = 0;
127     printf("Supported codecs: ");
128     for (i = 0; i < sizeof(codecs); i++){
129         switch(codecs[i]){
130             case HFP_CODEC_CVSD:
131                 printf("CVSD");
132                 break;
133             case HFP_CODEC_MSBC:
134                 if (hci_extended_sco_link_supported()){
135                     printf(", mSBC");
136                 } else {
137                     mSBC_skipped = 1;
138                 }
139                 break;
140         }
141     }
142     printf("\n");
143     if (mSBC_skipped){
144         printf("mSBC codec disabled because eSCO not supported by local controller.\n");
145     }
146 }
147 
148 static int getDeviceIndexForAddress( bd_addr_t addr){
149     int j;
150     for (j=0; j< deviceCount; j++){
151         if (bd_addr_cmp(addr, devices[j].address) == 0){
152             return j;
153         }
154     }
155     return -1;
156 }
157 
158 #ifdef HAVE_POSIX_STDIN
159 static void start_scan(void){
160     printf("Starting inquiry scan..\n");
161     hci_send_cmd(&hci_inquiry, HCI_INQUIRY_LAP, INQUIRY_INTERVAL, 0);
162 }
163 #endif
164 
165 static int has_more_remote_name_requests(void){
166     int i;
167     for (i=0;i<deviceCount;i++) {
168         if (devices[i].state == REMOTE_NAME_REQUEST) return 1;
169     }
170     return 0;
171 }
172 
173 static void do_next_remote_name_request(void){
174     int i;
175     for (i=0;i<deviceCount;i++) {
176         // remote name request
177         if (devices[i].state == REMOTE_NAME_REQUEST){
178             devices[i].state = REMOTE_NAME_INQUIRED;
179             printf("Get remote name of %s...\n", bd_addr_to_str(devices[i].address));
180             hci_send_cmd(&hci_remote_name_request, devices[i].address,
181                         devices[i].pageScanRepetitionMode, 0, devices[i].clockOffset | 0x8000);
182             return;
183         }
184     }
185 }
186 
187 static void continue_remote_names(void){
188     // don't get remote names for testing
189     if (has_more_remote_name_requests()){
190         do_next_remote_name_request();
191         return;
192     }
193     // try to find PTS
194     int i;
195     for (i=0;i<deviceCount;i++){
196         if (memcmp(devices[i].address, device_addr, 6) == 0){
197             printf("Inquiry scan over, successfully found PTS at index %u\nReady to connect to it.\n", i);
198             return;
199         }
200     }
201     printf("Inquiry scan over but PTS not found :(\n");
202 }
203 
204 static void inquiry_packet_handler (uint8_t packet_type, uint8_t *packet, uint16_t size){
205     UNUSED(size);
206 
207     bd_addr_t addr;
208     int i;
209     int numResponses;
210     int index;
211 
212     // printf("packet_handler: pt: 0x%02x, packet[0]: 0x%02x\n", packet_type, packet[0]);
213     if (packet_type != HCI_EVENT_PACKET) return;
214 
215     uint8_t event = packet[0];
216 
217     switch(event){
218         case HCI_EVENT_INQUIRY_RESULT:
219         case HCI_EVENT_INQUIRY_RESULT_WITH_RSSI:{
220             numResponses = hci_event_inquiry_result_get_num_responses(packet);
221             int offset = 3;
222             for (i=0; i<numResponses && deviceCount < MAX_DEVICES;i++){
223                 reverse_bd_addr(&packet[offset], addr);
224                 offset += 6;
225                 index = getDeviceIndexForAddress(addr);
226                 if (index >= 0) continue;   // already in our list
227                 memcpy(devices[deviceCount].address, addr, 6);
228 
229                 devices[deviceCount].pageScanRepetitionMode = packet[offset];
230                 offset += 1;
231 
232                 if (event == HCI_EVENT_INQUIRY_RESULT){
233                     offset += 2; // Reserved + Reserved
234                     devices[deviceCount].classOfDevice = little_endian_read_24(packet, offset);
235                     offset += 3;
236                     devices[deviceCount].clockOffset =   little_endian_read_16(packet, offset) & 0x7fff;
237                     offset += 2;
238                     devices[deviceCount].rssi  = 0;
239                 } else {
240                     offset += 1; // Reserved
241                     devices[deviceCount].classOfDevice = little_endian_read_24(packet, offset);
242                     offset += 3;
243                     devices[deviceCount].clockOffset =   little_endian_read_16(packet, offset) & 0x7fff;
244                     offset += 2;
245                     devices[deviceCount].rssi  = packet[offset];
246                     offset += 1;
247                 }
248                 devices[deviceCount].state = REMOTE_NAME_REQUEST;
249                 printf("Device #%u found: %s with COD: 0x%06x, pageScan %d, clock offset 0x%04x, rssi 0x%02x\n",
250                     deviceCount, bd_addr_to_str(addr),
251                     devices[deviceCount].classOfDevice, devices[deviceCount].pageScanRepetitionMode,
252                     devices[deviceCount].clockOffset, devices[deviceCount].rssi);
253                 deviceCount++;
254             }
255 
256             break;
257         }
258         case HCI_EVENT_INQUIRY_COMPLETE:
259             for (i=0;i<deviceCount;i++) {
260                 // retry remote name request
261                 if (devices[i].state == REMOTE_NAME_INQUIRED)
262                     devices[i].state = REMOTE_NAME_REQUEST;
263             }
264             continue_remote_names();
265             break;
266 
267         case HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE:
268             reverse_bd_addr(&packet[3], addr);
269             index = getDeviceIndexForAddress(addr);
270             if (index >= 0) {
271                 if (packet[2] == 0) {
272                     printf("Name: '%s'\n", &packet[9]);
273                     devices[index].state = REMOTE_NAME_FETCHED;
274                 } else {
275                     printf("Failed to get name: page timeout\n");
276                 }
277             }
278             continue_remote_names();
279             break;
280 
281         default:
282             break;
283     }
284 }
285 // GAP INQUIRY END
286 #ifdef HAVE_POSIX_STDIN
287 
288 // prototypes
289 static void show_usage(void);
290 
291 // Testig User Interface
292 static void show_usage(void){
293     bd_addr_t iut_address;
294     gap_local_bd_addr(iut_address);
295 
296     printf("\n--- Bluetooth HFP Audiogateway (AG) unit Test Console %s ---\n", bd_addr_to_str(iut_address));
297     printf("\n");
298 
299     printf("a - establish HFP connection to PTS module %s\n", bd_addr_to_str(device_addr));
300     // printf("A - release HFP connection to PTS module\n");
301 
302     printf("b - establish AUDIO connection          | B - release AUDIO connection\n");
303     printf("c - simulate incoming call from 1234567 | C - simulate call from 1234567 dropped\n");
304     printf("d - report AG failure\n");
305     printf("e - answer call on AG                   | E - reject call on AG\n");
306     printf("r - disable in-band ring tone           | R - enable in-band ring tone\n");
307     printf("f - Disable cellular network            | F - Enable cellular network\n");
308     printf("g - Set signal strength to 0            | G - Set signal strength to 5\n");
309     printf("h - Disable roaming                     | H - Enable roaming\n");
310     printf("i - Set battery level to 3              | I - Set battery level to 5\n");
311     printf("j - Answering call on remote side\n");
312     printf("k - Clear memory #1                     | K - Set memory #1\n");
313     printf("l - Clear last number                   | L - Set last number\n");
314     printf("m - simulate incoming call from 7654321\n");
315     // printf("M - simulate call from 7654321 dropped\n");
316     printf("n - Disable Voice Regocnition           | N - Enable Voice Recognition\n");
317     printf("o - Set speaker volume to 0  (minimum)  | O - Set speaker volume to 9  (default)\n");
318     printf("p - Set speaker volume to 12 (higher)   | P - Set speaker volume to 15 (maximum)\n");
319     printf("q - Set microphone gain to 0  (minimum) | Q - Set microphone gain to 9  (default)\n");
320     printf("s - Set microphone gain to 12 (higher)  | S - Set microphone gain to 15 (maximum)\n");
321     printf("t - terminate connection\n");
322     printf("u - join held call\n");
323     printf("v - discover nearby HF units\n");
324     printf("w - put incoming call on hold (Response and Hold)\n");
325     printf("x - accept held incoming call (Response and Hold)\n");
326     printf("X - reject held incoming call (Response and Hold)\n");
327 
328     printf("---\n");
329     printf("Ctrl-c - exit\n");
330     printf("---\n");
331 }
332 
333 static void stdin_process(btstack_data_source_t *ds, btstack_data_source_callback_type_t callback_type){
334     UNUSED(ds);
335     UNUSED(callback_type);
336 
337     cmd = btstack_stdin_read();
338     switch (cmd){
339         case 'a':
340             log_info("USER:\'%c\'", cmd);
341             printf("Establish HFP service level connection to PTS module %s...\n", bd_addr_to_str(device_addr));
342             hfp_ag_establish_service_level_connection(device_addr);
343             break;
344         case 'A':
345             log_info("USER:\'%c\'", cmd);
346             printf("Release HFP service level connection.\n");
347             hfp_ag_release_service_level_connection(acl_handle);
348             break;
349         case 'Z':
350             log_info("USER:\'%c\'", cmd);
351             printf("Release HFP service level connection to %s...\n", bd_addr_to_str(device_addr));
352             hfp_ag_release_service_level_connection(acl_handle);
353             break;
354         case 'b':
355             log_info("USER:\'%c\'", cmd);
356             printf("Establish Audio connection %s...\n", bd_addr_to_str(device_addr));
357             hfp_ag_establish_audio_connection(acl_handle);
358             break;
359         case 'B':
360             log_info("USER:\'%c\'", cmd);
361             printf("Release Audio connection.\n");
362             hfp_ag_release_audio_connection(acl_handle);
363             break;
364         case 'c':
365             log_info("USER:\'%c\'", cmd);
366             printf("Simulate incoming call from 1234567\n");
367             hfp_ag_set_clip(129, "1234567");
368             hfp_ag_incoming_call();
369             break;
370         case 'm':
371             log_info("USER:\'%c\'", cmd);
372             printf("Simulate incoming call from 7654321\n");
373             hfp_ag_set_clip(129, "7654321");
374             hfp_ag_incoming_call();
375             break;
376         case 'C':
377             log_info("USER:\'%c\'", cmd);
378             printf("Simulate terminate call\n");
379             hfp_ag_call_dropped();
380             break;
381         case 'd':
382             log_info("USER:\'%c\'", cmd);
383             printf("Report AG failure\n");
384             hfp_ag_report_extended_audio_gateway_error_result_code(acl_handle, HFP_CME_ERROR_AG_FAILURE);
385             break;
386         case 'e':
387             log_info("USER:\'%c\'", cmd);
388             printf("Answer call on AG\n");
389             hfp_ag_answer_incoming_call();
390             break;
391         case 'E':
392             log_info("USER:\'%c\'", cmd);
393             printf("Reject call on AG\n");
394             hfp_ag_terminate_call();
395             break;
396         case 'f':
397             log_info("USER:\'%c\'", cmd);
398             printf("Disable cellular network\n");
399             hfp_ag_set_registration_status(0);
400             break;
401         case 'F':
402             log_info("USER:\'%c\'", cmd);
403             printf("Enable cellular network\n");
404             hfp_ag_set_registration_status(1);
405             break;
406         case 'g':
407             log_info("USER:\'%c\'", cmd);
408             printf("Set signal strength to 0\n");
409             hfp_ag_set_signal_strength(0);
410             break;
411         case 'G':
412             log_info("USER:\'%c\'", cmd);
413             printf("Set signal strength to 5\n");
414             hfp_ag_set_signal_strength(5);
415             break;
416         case 'h':
417             log_info("USER:\'%c\'", cmd);
418             printf("Disable roaming\n");
419             hfp_ag_set_roaming_status(0);
420             break;
421         case 'H':
422             log_info("USER:\'%c\'", cmd);
423             printf("Enable roaming\n");
424             hfp_ag_set_roaming_status(1);
425             break;
426         case 'i':
427             log_info("USER:\'%c\'", cmd);
428             printf("Set battery level to 3\n");
429             hfp_ag_set_battery_level(3);
430             break;
431         case 'I':
432             log_info("USER:\'%c\'", cmd);
433             printf("Set battery level to 5\n");
434             hfp_ag_set_battery_level(5);
435             break;
436         case 'j':
437             log_info("USER:\'%c\'", cmd);
438             printf("Answering call on remote side\n");
439             hfp_ag_outgoing_call_established();
440             break;
441         case 'r':
442             log_info("USER:\'%c\'", cmd);
443             printf("Disable in-band ring tone\n");
444             hfp_ag_set_use_in_band_ring_tone(0);
445             break;
446         case 'k':
447             log_info("USER:\'%c\'", cmd);
448             printf("Memory 1 cleared\n");
449             memory_1_enabled = 0;
450             break;
451         case 'K':
452             log_info("USER:\'%c\'", cmd);
453             printf("Memory 1 set\n");
454             memory_1_enabled = 1;
455             break;
456         case 'l':
457             log_info("USER:\'%c\'", cmd);
458             printf("Last dialed number cleared\n");
459             hfp_ag_clear_last_dialed_number();
460             break;
461         case 'L':
462             log_info("USER:\'%c\'", cmd);
463             printf("Outgoing call connected, ringing\n");
464             hfp_ag_outgoing_call_ringing();
465             break;
466         case 'n':
467             log_info("USER:\'%c\'", cmd);
468             printf("Disable Voice Recognition\n");
469             hfp_ag_activate_voice_recognition(acl_handle, 0);
470             break;
471         case 'N':
472             log_info("USER:\'%c\'", cmd);
473             printf("Enable Voice Recognition\n");
474             hfp_ag_activate_voice_recognition(acl_handle, 1);
475             break;
476         case 'o':
477             log_info("USER:\'%c\'", cmd);
478             printf("Set speaker gain to 0 (minimum)\n");
479             hfp_ag_set_speaker_gain(acl_handle, 0);
480             break;
481         case 'O':
482             log_info("USER:\'%c\'", cmd);
483             printf("Set speaker gain to 9 (default)\n");
484             hfp_ag_set_speaker_gain(acl_handle, 9);
485             break;
486         case 'p':
487             log_info("USER:\'%c\'", cmd);
488             printf("Set speaker gain to 12 (higher)\n");
489             hfp_ag_set_speaker_gain(acl_handle, 12);
490             break;
491         case 'P':
492             log_info("USER:\'%c\'", cmd);
493             printf("Set speaker gain to 15 (maximum)\n");
494             hfp_ag_set_speaker_gain(acl_handle, 15);
495             break;
496         case 'q':
497             log_info("USER:\'%c\'", cmd);
498             printf("Set microphone gain to 0\n");
499             hfp_ag_set_microphone_gain(acl_handle, 0);
500             break;
501         case 'Q':
502             log_info("USER:\'%c\'", cmd);
503             printf("Set microphone gain to 9\n");
504             hfp_ag_set_microphone_gain(acl_handle, 9);
505             break;
506         case 's':
507             log_info("USER:\'%c\'", cmd);
508             printf("Set microphone gain to 12\n");
509             hfp_ag_set_microphone_gain(acl_handle, 12);
510             break;
511         case 'S':
512             log_info("USER:\'%c\'", cmd);
513             printf("Set microphone gain to 15\n");
514             hfp_ag_set_microphone_gain(acl_handle, 15);
515             break;
516         case 'R':
517             log_info("USER:\'%c\'", cmd);
518             printf("Enable in-band ring tone\n");
519             hfp_ag_set_use_in_band_ring_tone(1);
520             break;
521         case 't':
522             log_info("USER:\'%c\'", cmd);
523             printf("Terminate HCI connection. 0x%2x\n", acl_handle);
524             gap_disconnect(acl_handle);
525             break;
526         case 'u':
527             log_info("USER:\'%c\'", cmd);
528             printf("Join held call\n");
529             hfp_ag_join_held_call();
530             break;
531         case 'v':
532             start_scan();
533             break;
534         case 'w':
535             log_info("USER:\'%c\'", cmd);
536             printf("AG: Put incoming call on hold (Response and Hold)\n");
537             hfp_ag_hold_incoming_call();
538             break;
539         case 'x':
540             log_info("USER:\'%c\'", cmd);
541             printf("AG: Accept held incoming call (Response and Hold)\n");
542             hfp_ag_accept_held_incoming_call();
543             break;
544         case 'X':
545             log_info("USER:\'%c\'", cmd);
546             printf("AG: Reject held incoming call (Response and Hold)\n");
547             hfp_ag_reject_held_incoming_call();
548             break;
549         default:
550             show_usage();
551             break;
552     }
553 }
554 #endif
555 
556 static void packet_handler(uint8_t packet_type, uint16_t channel, uint8_t * event, uint16_t event_size){
557     UNUSED(channel);
558 
559     switch (packet_type){
560         case HCI_EVENT_PACKET:
561             switch (event[0]){
562                 case HCI_EVENT_INQUIRY_RESULT:
563                 case HCI_EVENT_INQUIRY_RESULT_WITH_RSSI:
564                 case HCI_EVENT_INQUIRY_COMPLETE:
565                 case HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE:
566                     inquiry_packet_handler(HCI_EVENT_PACKET, event, event_size);
567                     break;
568                 case HCI_EVENT_SCO_CAN_SEND_NOW:
569                     sco_demo_send(sco_handle);
570                     break;
571                 case HCI_EVENT_COMMAND_COMPLETE:
572                     if (HCI_EVENT_IS_COMMAND_COMPLETE(event, hci_read_local_supported_features)){
573                         dump_supported_codecs();
574                     }
575                     break;
576                 default:
577                     break;
578             }
579 
580             if (event[0] != HCI_EVENT_HFP_META) return;
581 
582             if (event[3]
583                 && event[2] != HFP_SUBEVENT_PLACE_CALL_WITH_NUMBER
584                 && event[2] != HFP_SUBEVENT_ATTACH_NUMBER_TO_VOICE_TAG
585                 && event[2] != HFP_SUBEVENT_TRANSMIT_DTMF_CODES){
586                 printf("ERROR, status: %u\n", event[3]);
587                 return;
588             }
589 
590             switch (event[2]) {
591                 case HFP_SUBEVENT_SERVICE_LEVEL_CONNECTION_ESTABLISHED:
592                     acl_handle = hfp_subevent_service_level_connection_established_get_con_handle(event);
593                     hfp_subevent_service_level_connection_established_get_bd_addr(event, device_addr);
594                     printf("Service level connection established from %s.\n", bd_addr_to_str(device_addr));
595                     dump_supported_codecs();
596                    break;
597                 case HFP_SUBEVENT_SERVICE_LEVEL_CONNECTION_RELEASED:
598                     printf("Service level connection released.\n");
599                     sco_handle = 0;
600                     break;
601                 case HFP_SUBEVENT_AUDIO_CONNECTION_ESTABLISHED:
602                     if (hfp_subevent_audio_connection_established_get_status(event)){
603                         printf("Audio connection establishment failed with status %u\n", hfp_subevent_audio_connection_established_get_status(event));
604                         sco_handle = 0;
605                     } else {
606                         sco_handle = hfp_subevent_audio_connection_established_get_handle(event);
607                         printf("Audio connection established with SCO handle 0x%04x.\n", sco_handle);
608                         negotiated_codec = hfp_subevent_audio_connection_established_get_negotiated_codec(event);
609                         switch (negotiated_codec){
610                             case 0x01:
611                                 printf("Using CVSD codec.\n");
612                                 break;
613                             case 0x02:
614                                 printf("Using mSBC codec.\n");
615                                 break;
616                             default:
617                                 printf("Using unknown codec 0x%02x.\n", negotiated_codec);
618                                 break;
619                         }
620                         sco_demo_set_codec(negotiated_codec);
621                         hci_request_sco_can_send_now_event();
622                     }
623                     break;
624                 case HFP_SUBEVENT_AUDIO_CONNECTION_RELEASED:
625                     printf("Audio connection released\n");
626                     sco_handle = 0;
627                     sco_demo_close();
628                     break;
629                 case HFP_SUBEVENT_START_RINGINIG:
630                     printf("Start Ringing\n");
631                     break;
632                 case HFP_SUBEVENT_STOP_RINGINIG:
633                     printf("Stop Ringing\n");
634                     break;
635                 case HFP_SUBEVENT_PLACE_CALL_WITH_NUMBER:
636                     printf("Outgoing call '%s'\n", hfp_subevent_place_call_with_number_get_number(event));
637                     // validate number
638                     if ( strcmp("1234567", hfp_subevent_place_call_with_number_get_number(event)) == 0
639                       || strcmp("7654321", hfp_subevent_place_call_with_number_get_number(event)) == 0
640                       || (memory_1_enabled && strcmp(">1", hfp_subevent_place_call_with_number_get_number(event)) == 0)){
641                         printf("Dialstring valid: accept call\n");
642                         hfp_ag_outgoing_call_accepted();
643                     } else {
644                         printf("Dialstring invalid: reject call\n");
645                         hfp_ag_outgoing_call_rejected();
646                     }
647                     break;
648 
649                 case HFP_SUBEVENT_ATTACH_NUMBER_TO_VOICE_TAG:
650                     printf("Attach number to voice tag. Sending '1234567\n");
651                     hfp_ag_send_phone_number_for_voice_tag(acl_handle, "1234567");
652                     break;
653                 case HFP_SUBEVENT_TRANSMIT_DTMF_CODES:
654                     printf("Send DTMF Codes: '%s'\n", hfp_subevent_transmit_dtmf_codes_get_dtmf(event));
655                     hfp_ag_send_dtmf_code_done(acl_handle);
656                     break;
657                 case HFP_SUBEVENT_CALL_ANSWERED:
658                     printf("Call answered by HF\n");
659                     break;
660                 default:
661                     printf("Event not handled %u\n", event[2]);
662                     break;
663             }
664         case HCI_SCO_DATA_PACKET:
665             sco_demo_receive(event, event_size);
666             break;
667         default:
668             break;
669     }
670 }
671 
672 static hfp_phone_number_t subscriber_number = {
673     129, "225577"
674 };
675 
676 /* @section Main Application Setup
677  *
678  * @text Listing MainConfiguration shows main application code.
679  * To run a HFP AG service you need to initialize the SDP, and to create and register HFP AG record with it.
680  * The packet_handler is used for sending commands to the HFP HF. It also receives the HFP HF's answers.
681  * The stdin_process callback allows for sending commands to the HFP HF.
682  * At the end the Bluetooth stack is started.
683  */
684 
685 /* LISTING_START(MainConfiguration): Setup HFP Audio Gateway */
686 
687 int btstack_main(int argc, const char * argv[]);
688 int btstack_main(int argc, const char * argv[]){
689     (void)argc;
690     (void)argv;
691 
692     sco_demo_init();
693 
694     // register for HCI events
695     hci_event_callback_registration.callback = &packet_handler;
696     hci_add_event_handler(&hci_event_callback_registration);
697     hci_register_sco_packet_handler(&packet_handler);
698 
699     gap_discoverable_control(1);
700 
701     // L2CAP
702     l2cap_init();
703 
704     uint16_t supported_features                   =
705         (1<<HFP_AGSF_ESCO_S4)                     |
706         (1<<HFP_AGSF_HF_INDICATORS)               |
707         (1<<HFP_AGSF_CODEC_NEGOTIATION)           |
708         (1<<HFP_AGSF_EXTENDED_ERROR_RESULT_CODES) |
709         (1<<HFP_AGSF_ENHANCED_CALL_CONTROL)       |
710         (1<<HFP_AGSF_ENHANCED_CALL_STATUS)        |
711         (1<<HFP_AGSF_ABILITY_TO_REJECT_A_CALL)    |
712         (1<<HFP_AGSF_IN_BAND_RING_TONE)           |
713         (1<<HFP_AGSF_VOICE_RECOGNITION_FUNCTION)  |
714         (1<<HFP_AGSF_THREE_WAY_CALLING);
715     int wide_band_speech = 1;
716 
717     // HFP
718     rfcomm_init();
719     hfp_ag_init(rfcomm_channel_nr);
720     hfp_ag_init_supported_features(supported_features);
721     hfp_ag_init_codecs(sizeof(codecs), codecs);
722     hfp_ag_init_ag_indicators(ag_indicators_nr, ag_indicators);
723     hfp_ag_init_hf_indicators(hf_indicators_nr, hf_indicators);
724     hfp_ag_init_call_hold_services(call_hold_services_nr, call_hold_services);
725     hfp_ag_set_subcriber_number_information(&subscriber_number, 1);
726     hfp_ag_register_packet_handler(&packet_handler);
727     hci_register_sco_packet_handler(&packet_handler);
728 
729     // SDP Server
730     sdp_init();
731     memset(hfp_service_buffer, 0, sizeof(hfp_service_buffer));
732     hfp_ag_create_sdp_record( hfp_service_buffer, 0x10001, rfcomm_channel_nr, hfp_ag_service_name, 0, supported_features, wide_band_speech);
733     printf("SDP service record size: %u\n", de_get_len( hfp_service_buffer));
734     sdp_register_service(hfp_service_buffer);
735 
736     // parse humand readable Bluetooth address
737     sscanf_bd_addr(device_addr_string, device_addr);
738 
739 #ifdef HAVE_POSIX_STDIN
740     btstack_stdin_setup(stdin_process);
741 #endif
742     // turn on!
743     hci_power_control(HCI_POWER_ON);
744     return 0;
745 }
746 /* LISTING_END */
747 /* EXAMPLE_END */
748