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