xref: /btstack/src/classic/hsp_hs.c (revision 9ea49f801ca9d49a65636d9ce376c8a09ffa18c0)
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__ "hsp_hs.c"
39 
40 // *****************************************************************************
41 //
42 // HSP Headset
43 //
44 // *****************************************************************************
45 
46 #include "btstack_config.h"
47 
48 #include <stdint.h>
49 #include <stdio.h>
50 #include <string.h>
51 
52 #include "bluetooth_sdp.h"
53 #include "btstack_debug.h"
54 #include "btstack_event.h"
55 #include "btstack_memory.h"
56 #include "btstack_run_loop.h"
57 #include "classic/core.h"
58 #include "classic/sdp_server.h"
59 #include "classic/sdp_client_rfcomm.h"
60 #include "classic/sdp_util.h"
61 #include "classic/sdp_client.h"
62 #include "hci.h"
63 #include "hci_cmd.h"
64 #include "hci_dump.h"
65 #include "hsp_hs.h"
66 #include "l2cap.h"
67 
68 #define HSP_AG_OK "OK"
69 #define HSP_AG_ERROR "ERROR"
70 #define HSP_AG_RING "RING"
71 #define HSP_MICROPHONE_GAIN "+VGM="
72 #define HSP_SPEAKER_GAIN "+VGS="
73 
74 #define HSP_HS_AT_CKPD "AT+CKPD=200\r\n"
75 #define HSP_HS_MICROPHONE_GAIN "AT+VGM"
76 #define HSP_HS_SPEAKER_GAIN "AT+VGS"
77 
78 static const char default_hsp_hs_service_name[] = "Headset";
79 
80 static bd_addr_t remote;
81 static uint8_t channel_nr = 0;
82 
83 static uint16_t mtu;
84 static uint16_t rfcomm_cid = 0;
85 static hci_con_handle_t sco_handle;
86 static hci_con_handle_t rfcomm_handle;
87 
88 static int hs_microphone_gain;
89 static int hs_speaker_gain;
90 
91 static uint8_t hs_send_button_press;
92 static uint8_t wait_ok;
93 static uint8_t hs_accept_sco_connection;
94 
95 static uint8_t hs_support_custom_indications;
96 static btstack_packet_callback_registration_t hci_event_callback_registration;
97 static uint8_t hsp_establish_audio_connection;
98 static uint8_t hsp_release_audio_connection;
99 
100 static uint16_t hsp_hs_sco_packet_types;
101 
102 typedef enum {
103     HSP_IDLE,
104     HSP_W2_SEND_SDP_QUERY,
105     HSP_W4_SDP_QUERY_COMPLETE,
106     HSP_W4_RFCOMM_CONNECTED,
107 
108     HSP_RFCOMM_CONNECTION_ESTABLISHED,
109 
110     HSP_W2_CONNECT_SCO,
111     HSP_W4_SCO_CONNECTED,
112 
113     HSP_AUDIO_CONNECTION_ESTABLISHED,
114 
115     HSP_W2_DISCONNECT_SCO,
116     HSP_W4_SCO_DISCONNECTED,
117 
118     HSP_W2_DISCONNECT_RFCOMM,
119     HSP_W4_RFCOMM_DISCONNECTED,
120     HSP_W4_CONNECTION_ESTABLISHED_TO_SHUTDOWN
121 } hsp_state_t;
122 
123 static btstack_context_callback_registration_t hsp_hs_handle_sdp_client_query_request;
124 
125 static hsp_state_t hsp_state;
126 
127 static void hsp_run(void);
128 static void packet_handler (uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size);
129 static void handle_query_rfcomm_event(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size);
130 
131 static btstack_packet_handler_t hsp_hs_callback;
132 static void dummy_notify(uint8_t packet_type, uint16_t channel, uint8_t * event, uint16_t size){
133     // ok: no code
134     UNUSED(packet_type);
135     UNUSED(channel);
136     UNUSED(event);
137     UNUSED(size);
138 }
139 
140 void hsp_hs_register_packet_handler(btstack_packet_handler_t callback){
141     if (callback == NULL){
142         callback = &dummy_notify;
143     }
144     hsp_hs_callback = callback;
145 }
146 
147 static void emit_event(uint8_t event_subtype, uint8_t value){
148     if (!hsp_hs_callback) return;
149     uint8_t event[4];
150     event[0] = HCI_EVENT_HSP_META;
151     event[1] = sizeof(event) - 2;
152     event[2] = event_subtype;
153     event[3] = value; // status 0 == OK
154     (*hsp_hs_callback)(HCI_EVENT_PACKET, 0, event, sizeof(event));
155 }
156 
157 static void emit_ring_event(void){
158     if (!hsp_hs_callback) return;
159     uint8_t event[3];
160     event[0] = HCI_EVENT_HSP_META;
161     event[1] = sizeof(event) - 2;
162     event[2] = HSP_SUBEVENT_RING;
163     (*hsp_hs_callback)(HCI_EVENT_PACKET, 0, event, sizeof(event));
164 }
165 
166 static void emit_event_audio_connected(uint8_t status, uint16_t handle){
167     if (!hsp_hs_callback) return;
168     uint8_t event[6];
169     event[0] = HCI_EVENT_HSP_META;
170     event[1] = sizeof(event) - 2;
171     event[2] = HSP_SUBEVENT_AUDIO_CONNECTION_COMPLETE;
172     event[3] = status;
173     little_endian_store_16(event, 4, handle);
174     (*hsp_hs_callback)(HCI_EVENT_PACKET, 0, event, sizeof(event));
175 }
176 
177 // remote audio volume control
178 // AG +VGM=13 [0..15] ; HS AT+VGM=6 | AG OK
179 
180 static int hsp_hs_send_str_over_rfcomm(uint16_t cid, const char * command){
181     if (!rfcomm_can_send_packet_now(rfcomm_cid)) return 1;
182     int err = rfcomm_send(cid, (uint8_t*) command, strlen(command));
183     if (err){
184         log_info("rfcomm_send_internal -> error 0X%02x", err);
185     }
186     return err;
187 }
188 
189 void hsp_hs_enable_custom_indications(int enable){
190     hs_support_custom_indications = enable;
191 }
192 
193 int hsp_hs_send_result(const char * result){
194     if (!hs_support_custom_indications) return 1;
195     return hsp_hs_send_str_over_rfcomm(rfcomm_cid, result);
196 }
197 
198 
199 void hsp_hs_create_sdp_record(uint8_t * service,  uint32_t service_record_handle, int rfcomm_channel_nr, const char * name, uint8_t have_remote_audio_control){
200     uint8_t* attribute;
201     de_create_sequence(service);
202 
203     // 0x0000 "Service Record Handle"
204     de_add_number(service, DE_UINT, DE_SIZE_16, BLUETOOTH_ATTRIBUTE_SERVICE_RECORD_HANDLE);
205     de_add_number(service, DE_UINT, DE_SIZE_32, service_record_handle);
206 
207     // 0x0001 "Service Class ID List"
208     de_add_number(service,  DE_UINT, DE_SIZE_16, BLUETOOTH_ATTRIBUTE_SERVICE_CLASS_ID_LIST);
209     attribute = de_push_sequence(service);
210     {
211         //  see Bluetooth Erratum #3507
212         de_add_number(attribute, DE_UUID, DE_SIZE_16, BLUETOOTH_SERVICE_CLASS_HEADSET);       // 0x1108
213         de_add_number(attribute, DE_UUID, DE_SIZE_16, BLUETOOTH_SERVICE_CLASS_HEADSET_HS);    // 0x1131
214         de_add_number(attribute, DE_UUID, DE_SIZE_16, BLUETOOTH_SERVICE_CLASS_GENERIC_AUDIO); // 0x1203
215     }
216     de_pop_sequence(service, attribute);
217 
218     // 0x0004 "Protocol Descriptor List"
219     de_add_number(service,  DE_UINT, DE_SIZE_16, BLUETOOTH_ATTRIBUTE_PROTOCOL_DESCRIPTOR_LIST);
220     attribute = de_push_sequence(service);
221     {
222         uint8_t* l2cpProtocol = de_push_sequence(attribute);
223         {
224             de_add_number(l2cpProtocol,  DE_UUID, DE_SIZE_16, BLUETOOTH_PROTOCOL_L2CAP);
225         }
226         de_pop_sequence(attribute, l2cpProtocol);
227 
228         uint8_t* rfcomm = de_push_sequence(attribute);
229         {
230             de_add_number(rfcomm,  DE_UUID, DE_SIZE_16, BLUETOOTH_PROTOCOL_RFCOMM);  // rfcomm_service
231             de_add_number(rfcomm,  DE_UINT, DE_SIZE_8,  rfcomm_channel_nr);  // rfcomm channel
232         }
233         de_pop_sequence(attribute, rfcomm);
234     }
235     de_pop_sequence(service, attribute);
236 
237     // 0x0005 "Public Browse Group"
238     de_add_number(service,  DE_UINT, DE_SIZE_16, BLUETOOTH_ATTRIBUTE_BROWSE_GROUP_LIST); // public browse group
239     attribute = de_push_sequence(service);
240     {
241         de_add_number(attribute,  DE_UUID, DE_SIZE_16, BLUETOOTH_ATTRIBUTE_PUBLIC_BROWSE_ROOT);
242     }
243     de_pop_sequence(service, attribute);
244 
245     // 0x0009 "Bluetooth Profile Descriptor List"
246     de_add_number(service,  DE_UINT, DE_SIZE_16, BLUETOOTH_ATTRIBUTE_BLUETOOTH_PROFILE_DESCRIPTOR_LIST);
247     attribute = de_push_sequence(service);
248     {
249         uint8_t *hsp_profile = de_push_sequence(attribute);
250         {
251             de_add_number(hsp_profile,  DE_UUID, DE_SIZE_16, BLUETOOTH_SERVICE_CLASS_HEADSET);
252             de_add_number(hsp_profile,  DE_UINT, DE_SIZE_16, 0x0102); // Verision 1.2
253         }
254         de_pop_sequence(attribute, hsp_profile);
255     }
256     de_pop_sequence(service, attribute);
257 
258     // 0x0100 "Service Name"
259     de_add_number(service,  DE_UINT, DE_SIZE_16, 0x0100);
260     if (name){
261         de_add_data(service,  DE_STRING, strlen(name), (uint8_t *) name);
262     } else {
263         de_add_data(service,  DE_STRING, strlen(default_hsp_hs_service_name), (uint8_t *) default_hsp_hs_service_name);
264     }
265 
266     // Remote audio volume control
267     de_add_number(service, DE_UINT, DE_SIZE_16, 0x030C);
268     de_add_number(service, DE_BOOL, DE_SIZE_8, have_remote_audio_control);
269 }
270 
271 static void hsp_hs_reset_state(void){
272     hsp_state = HSP_IDLE;
273     hs_microphone_gain = -1;
274     hs_speaker_gain = -1;
275     rfcomm_cid = 0;
276     channel_nr = 0;
277     sco_handle    = HCI_CON_HANDLE_INVALID;
278     rfcomm_handle = HCI_CON_HANDLE_INVALID;
279 
280     hs_send_button_press = 0;
281     wait_ok = 0;
282     hs_support_custom_indications = 0;
283 
284     hs_accept_sco_connection = 0;
285     hsp_establish_audio_connection = 0;
286     hsp_release_audio_connection = 0;
287 }
288 
289 void hsp_hs_init(uint8_t rfcomm_channel_nr){
290     // register for HCI events
291     hci_event_callback_registration.callback = &packet_handler;
292     hci_add_event_handler(&hci_event_callback_registration);
293 
294     rfcomm_register_service(packet_handler, rfcomm_channel_nr, 0xffff);  // reserved channel, mtu limited by l2cap
295 
296     hsp_hs_sco_packet_types = SCO_PACKET_TYPES_ALL;
297     hsp_hs_reset_state();
298 }
299 
300 void hsp_hs_deinit(void){
301     (void)memset(remote, 0, 6);
302     (void)memset(&hci_event_callback_registration, 0, sizeof(btstack_packet_callback_registration_t));
303     (void)memset(&hsp_hs_handle_sdp_client_query_request, 0, sizeof(btstack_context_callback_registration_t));
304     hsp_hs_callback = NULL;
305 }
306 
307 static void hsp_hs_handle_start_sdp_client_query(void * context){
308     UNUSED(context);
309     if (hsp_state != HSP_W2_SEND_SDP_QUERY) return;
310 
311     hsp_state = HSP_W4_SDP_QUERY_COMPLETE;
312     log_info("Start SDP query %s, 0x%02x", bd_addr_to_str(remote), BLUETOOTH_SERVICE_CLASS_HEADSET_AUDIO_GATEWAY_AG);
313     sdp_client_query_rfcomm_channel_and_name_for_service_class_uuid(&handle_query_rfcomm_event, remote, BLUETOOTH_SERVICE_CLASS_HEADSET_AUDIO_GATEWAY_AG);
314 }
315 
316 void hsp_hs_connect(bd_addr_t bd_addr){
317     if (hsp_state != HSP_IDLE) return;
318 
319     (void)memcpy(remote, bd_addr, 6);
320     hsp_state = HSP_W2_SEND_SDP_QUERY;
321     hsp_hs_handle_sdp_client_query_request.callback = &hsp_hs_handle_start_sdp_client_query;
322     // ignore ERROR_CODE_COMMAND_DISALLOWED because in that case, we already have requested an SDP callback
323     (void) sdp_client_register_query_callback(&hsp_hs_handle_sdp_client_query_request);
324 }
325 
326 void hsp_hs_disconnect(void){
327     hsp_hs_release_audio_connection();
328 
329     if (hsp_state < HSP_W4_RFCOMM_CONNECTED){
330         hsp_state = HSP_IDLE;
331         return;
332     }
333 
334     if (hsp_state == HSP_W4_RFCOMM_CONNECTED){
335         hsp_state = HSP_W4_CONNECTION_ESTABLISHED_TO_SHUTDOWN;
336         return;
337     }
338 
339     hsp_establish_audio_connection = 0;
340     rfcomm_disconnect(rfcomm_cid);
341 }
342 
343 
344 void hsp_hs_establish_audio_connection(void){
345     switch (hsp_state){
346         case HSP_RFCOMM_CONNECTION_ESTABLISHED:
347             hsp_establish_audio_connection = 1;
348             hsp_state = HSP_W4_SCO_CONNECTED;
349             break;
350         case HSP_W4_RFCOMM_CONNECTED:
351             hsp_state = HSP_W4_CONNECTION_ESTABLISHED_TO_SHUTDOWN;
352             break;
353         default:
354             break;
355     }
356     hsp_run();
357 }
358 
359 void hsp_hs_release_audio_connection(void){
360     if (hsp_state >= HSP_W2_DISCONNECT_SCO) return;
361     if (hsp_state < HSP_AUDIO_CONNECTION_ESTABLISHED) return;
362     hsp_release_audio_connection = 1;
363     hsp_run();
364 }
365 
366 void hsp_hs_set_microphone_gain(uint8_t gain){
367     if (gain >15) {
368         log_info("Gain must be in interval [0..15], it is given %d", gain);
369         return;
370     }
371     hs_microphone_gain = gain;
372     hsp_run();
373 }
374 
375 // AG +VGS=5  [0..15] ; HS AT+VGM=6 | AG OK
376 void hsp_hs_set_speaker_gain(uint8_t gain){
377     if (gain >15) {
378         log_info("Gain must be in interval [0..15], it is given %d", gain);
379         return;
380     }
381     hs_speaker_gain = gain;
382     hsp_run();
383 }
384 
385 static void hsp_run_handle_state(void){
386     switch (hsp_state){
387         case HSP_AUDIO_CONNECTION_ESTABLISHED:
388         case HSP_RFCOMM_CONNECTION_ESTABLISHED:
389 
390             if (hs_microphone_gain >= 0){
391                 if (!rfcomm_can_send_packet_now(rfcomm_cid)) {
392                     rfcomm_request_can_send_now_event(rfcomm_cid);
393                     return;
394                 }
395                 char buffer[20];
396                 snprintf(buffer, sizeof(buffer), "%s=%d\r",
397                          HSP_HS_MICROPHONE_GAIN, hs_microphone_gain);
398                 buffer[sizeof(buffer) - 1] = 0;
399                 hsp_hs_send_str_over_rfcomm(rfcomm_cid, buffer);
400                 hs_microphone_gain = -1;
401                 break;
402             }
403 
404             if (hs_speaker_gain >= 0){
405                 if (!rfcomm_can_send_packet_now(rfcomm_cid)) {
406                     rfcomm_request_can_send_now_event(rfcomm_cid);
407                     return;
408                 }
409                 char buffer[20];
410                 snprintf(buffer, sizeof(buffer), "%s=%d\r",
411                          HSP_HS_SPEAKER_GAIN, hs_speaker_gain);
412                 buffer[sizeof(buffer) - 1] = 0;
413                 hsp_hs_send_str_over_rfcomm(rfcomm_cid, buffer);
414                 hs_speaker_gain = -1;
415                 break;
416             }
417             break;
418         case HSP_W4_RFCOMM_DISCONNECTED:
419             rfcomm_disconnect(rfcomm_cid);
420             break;
421         default:
422             break;
423     }
424 }
425 
426 static void hsp_run(void){
427 
428     if (wait_ok) return;
429 
430     if (hs_accept_sco_connection && hci_can_send_command_packet_now()){
431 
432         bool eSCO = hs_accept_sco_connection == 2;
433         hs_accept_sco_connection = 0;
434 
435         log_info("HSP: sending hci_accept_connection_request.");
436 
437         // pick packet types based on SCO link type (SCO vs. eSCO)
438         uint16_t packet_types;
439         if (eSCO && hci_extended_sco_link_supported() && hci_remote_esco_supported(rfcomm_handle)){
440             packet_types = 0x3F8;
441         } else {
442             packet_types = 0x0007;
443         }
444 
445         // packet type override
446         packet_types &= hsp_hs_sco_packet_types;
447 
448         // bits 6-9 are 'don't use'
449         packet_types ^= 0x03c0;
450 
451         uint16_t sco_voice_setting = hci_get_sco_voice_setting();
452 
453         log_info("HFP: sending hci_accept_connection_request, sco_voice_setting %02x", sco_voice_setting);
454         hci_send_cmd(&hci_accept_synchronous_connection, remote, 8000, 8000, 0xffff, sco_voice_setting, 0xff, packet_types);
455         return;
456     }
457 
458     if (hsp_release_audio_connection){
459         if (!rfcomm_can_send_packet_now(rfcomm_cid)) {
460             rfcomm_request_can_send_now_event(rfcomm_cid);
461             return;
462         }
463         hsp_release_audio_connection = 0;
464         wait_ok = 1;
465         hsp_hs_send_str_over_rfcomm(rfcomm_cid, HSP_HS_AT_CKPD);
466         return;
467     }
468 
469     if (hsp_establish_audio_connection){
470         if (!rfcomm_can_send_packet_now(rfcomm_cid)) {
471             rfcomm_request_can_send_now_event(rfcomm_cid);
472             return;
473         }
474         hsp_establish_audio_connection = 0;
475         wait_ok = 1;
476         hsp_hs_send_str_over_rfcomm(rfcomm_cid, HSP_HS_AT_CKPD);
477         return;
478     }
479 
480     if (hs_send_button_press){
481         if (!rfcomm_can_send_packet_now(rfcomm_cid)) {
482             rfcomm_request_can_send_now_event(rfcomm_cid);
483             return;
484         }
485         hs_send_button_press = 0;
486         wait_ok = 1;
487         hsp_hs_send_str_over_rfcomm(rfcomm_cid, HSP_HS_AT_CKPD);
488         return;
489     }
490 
491     hsp_run_handle_state();
492 }
493 
494 
495 static void packet_handler (uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
496     UNUSED(channel);    // ok: no channel for HCI_EVENT_PACKET and only single active RFCOMM channel
497     if (packet_type == RFCOMM_DATA_PACKET){
498         // skip over leading newline
499         while ((size > 0) && ((packet[0] == '\n') || (packet[0] == '\r'))){
500             size--;
501             packet++;
502         }
503         if (strncmp((char *)packet, HSP_AG_RING, strlen(HSP_AG_RING)) == 0){
504             emit_ring_event();
505         } else if (strncmp((char *)packet, HSP_AG_OK, strlen(HSP_AG_OK)) == 0){
506            wait_ok = 0;
507         } else if (strncmp((char *)packet, HSP_MICROPHONE_GAIN, strlen(HSP_MICROPHONE_GAIN)) == 0){
508             uint8_t gain = (uint8_t)btstack_atoi((char*)&packet[strlen(HSP_MICROPHONE_GAIN)]);
509             emit_event(HSP_SUBEVENT_MICROPHONE_GAIN_CHANGED, gain);
510 
511         } else if (strncmp((char *)packet, HSP_SPEAKER_GAIN, strlen(HSP_SPEAKER_GAIN)) == 0){
512             uint8_t gain = (uint8_t)btstack_atoi((char*)&packet[strlen(HSP_SPEAKER_GAIN)]);
513             emit_event(HSP_SUBEVENT_SPEAKER_GAIN_CHANGED, gain);
514         } else {
515             if (!hsp_hs_callback) return;
516             // strip trailing newline
517             while ((size > 0) && ((packet[size-1] == '\n') || (packet[size-1] == '\r'))){
518                 size--;
519             }
520             // add trailing \0
521             packet[size] = 0;
522             // re-use incoming buffer to avoid reserving large buffers - ugly but efficient
523             uint8_t * event = packet - 4;
524             event[0] = HCI_EVENT_HSP_META;
525             event[1] = size + 2;
526             event[2] = HSP_SUBEVENT_AG_INDICATION;
527             event[3] = size;
528             (*hsp_hs_callback)(HCI_EVENT_PACKET, 0, event, size+4);
529         }
530         hsp_run();
531         return;
532     }
533 
534     if (packet_type != HCI_EVENT_PACKET) return;
535 
536     uint8_t event = hci_event_packet_get_type(packet);
537     bd_addr_t event_addr;
538     uint16_t handle;
539     switch (event) {
540         case HCI_EVENT_CONNECTION_REQUEST:
541             switch(hci_event_connection_request_get_link_type(packet)){
542                 case 0: //  SCO
543                 case 2: // eSCO
544                     hci_event_connection_request_get_bd_addr(packet, event_addr);
545                     if (bd_addr_cmp(event_addr, remote) == 0){
546                         if (hci_event_connection_request_get_link_type(packet) == 2){
547                             hs_accept_sco_connection = 2;
548                         } else {
549                             hs_accept_sco_connection = 1;
550                         }
551                         log_info("hs_accept_sco_connection %u", hs_accept_sco_connection);
552                     }
553                     break;
554                 default:
555                     break;
556             }
557             break;
558 
559         case HCI_EVENT_SYNCHRONOUS_CONNECTION_COMPLETE:{
560             if (hsp_state < HSP_RFCOMM_CONNECTION_ESTABLISHED) return;
561             hci_event_synchronous_connection_complete_get_bd_addr(packet, event_addr);
562             uint8_t status                   = hci_event_synchronous_connection_complete_get_status(packet);
563             sco_handle                       = hci_event_synchronous_connection_complete_get_handle(packet);
564             uint8_t  link_type               = hci_event_synchronous_connection_complete_get_link_type(packet);
565             uint8_t  transmission_interval   = hci_event_synchronous_connection_complete_get_transmission_interval(packet);   // measured in slots
566             uint8_t  retransmission_interval = hci_event_synchronous_connection_complete_get_retransmission_interval(packet); // measured in slots
567             uint16_t rx_packet_length        = hci_event_synchronous_connection_complete_get_rx_packet_length(packet);        // measured in bytes
568             uint16_t tx_packet_length        = hci_event_synchronous_connection_complete_get_tx_packet_length(packet);        // measured in bytes
569 
570             if (status != 0){
571                 log_error("(e)SCO Connection failed, status %u", status);
572                 emit_event_audio_connected(status, sco_handle);
573                 hsp_state = HSP_RFCOMM_CONNECTION_ESTABLISHED ;
574                 break;
575             }
576 
577             switch (link_type){
578                 case 0x00:
579                     log_info("SCO Connection established.");
580                     if (transmission_interval != 0) log_error("SCO Connection: transmission_interval not zero: %d.", transmission_interval);
581                     if (retransmission_interval != 0) log_error("SCO Connection: retransmission_interval not zero: %d.", retransmission_interval);
582                     if (rx_packet_length != 0) log_error("SCO Connection: rx_packet_length not zero: %d.", rx_packet_length);
583                     if (tx_packet_length != 0) log_error("SCO Connection: tx_packet_length not zero: %d.", tx_packet_length);
584                     break;
585                 case 0x02:
586                     log_info("eSCO Connection established.");
587                     break;
588                 default:
589                     log_error("(e)SCO reserved link_type 0x%2x", link_type);
590                     break;
591             }
592             log_info("sco_handle 0x%2x, address %s, transmission_interval %u slots, retransmission_interval %u slots, "
593                  " rx_packet_length %u bytes, tx_packet_length %u bytes, air_mode 0x%2x (0x02 == CVSD)", sco_handle,
594                  bd_addr_to_str(event_addr), transmission_interval, retransmission_interval, rx_packet_length, tx_packet_length,
595                  hci_event_synchronous_connection_complete_get_air_mode(packet));
596 
597             hsp_state = HSP_AUDIO_CONNECTION_ESTABLISHED;
598             emit_event_audio_connected(status, sco_handle);
599             break;
600         }
601 
602         case RFCOMM_EVENT_INCOMING_CONNECTION:
603             if (hsp_state != HSP_IDLE) return;
604             rfcomm_event_incoming_connection_get_bd_addr(packet, event_addr);
605             rfcomm_cid = rfcomm_event_incoming_connection_get_rfcomm_cid(packet);
606             log_info("RFCOMM channel %u requested for %s", rfcomm_event_incoming_connection_get_server_channel(packet), bd_addr_to_str(event_addr));
607             hsp_state = HSP_W4_RFCOMM_CONNECTED;
608             rfcomm_accept_connection(rfcomm_cid);
609             break;
610 
611         case RFCOMM_EVENT_CHANNEL_OPENED:
612             if (hsp_state != HSP_W4_RFCOMM_CONNECTED) return;
613             if (rfcomm_event_channel_opened_get_status(packet)) {
614                 log_info("RFCOMM channel open failed, status %u", rfcomm_event_channel_opened_get_status(packet));
615                 hsp_state = HSP_IDLE;
616                 hsp_hs_reset_state();
617             } else {
618                 rfcomm_event_channel_opened_get_bd_addr(packet, remote);
619                 rfcomm_handle = rfcomm_event_channel_opened_get_con_handle(packet);
620                 rfcomm_cid    = rfcomm_event_channel_opened_get_rfcomm_cid(packet);
621                 mtu           = rfcomm_event_channel_opened_get_max_frame_size(packet);
622                 log_info("RFCOMM channel open succeeded. New RFCOMM Channel ID %u, max frame size %u, handle %02x", rfcomm_cid, mtu, rfcomm_handle);
623                 hsp_state = HSP_RFCOMM_CONNECTION_ESTABLISHED;
624             }
625             emit_event(HSP_SUBEVENT_RFCOMM_CONNECTION_COMPLETE, rfcomm_event_channel_opened_get_status(packet));
626             break;
627 
628         case RFCOMM_EVENT_CAN_SEND_NOW:
629             hsp_run();
630             break;
631 
632         case HCI_EVENT_DISCONNECTION_COMPLETE:
633             handle = hci_event_disconnection_complete_get_connection_handle(packet);
634             if (handle == sco_handle){
635                 sco_handle = 0;
636                 hsp_state = HSP_RFCOMM_CONNECTION_ESTABLISHED;
637                 emit_event(HSP_SUBEVENT_AUDIO_DISCONNECTION_COMPLETE,0);
638                 break;
639             }
640             break;
641 
642         case RFCOMM_EVENT_CHANNEL_CLOSED:
643             hsp_state = HSP_IDLE;
644             hsp_hs_reset_state();
645             emit_event(HSP_SUBEVENT_RFCOMM_DISCONNECTION_COMPLETE,0);
646             break;
647 
648         default:
649             break;
650     }
651 
652     hsp_run();
653 }
654 
655 static void handle_query_rfcomm_event(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
656     UNUSED(packet_type);    // ok: handling own sdp events
657     UNUSED(channel);        // ok: no channel
658     UNUSED(size);           // ok: handling own sdp events
659 
660     switch (hci_event_packet_get_type(packet)){
661         case SDP_EVENT_QUERY_RFCOMM_SERVICE:
662             channel_nr = sdp_event_query_rfcomm_service_get_rfcomm_channel(packet);
663             log_info("** Service name: '%s', RFCOMM port %u", sdp_event_query_rfcomm_service_get_name(packet), channel_nr);
664             break;
665         case SDP_EVENT_QUERY_COMPLETE:
666             if (channel_nr > 0){
667                 hsp_state = HSP_W4_RFCOMM_CONNECTED;
668                 log_info("HSP: SDP_QUERY_COMPLETE. RFCOMM create channel, addr %s, rfcomm channel nr %d", bd_addr_to_str(remote), channel_nr);
669                 rfcomm_create_channel(packet_handler, remote, channel_nr, NULL);
670                 break;
671             }
672             hsp_hs_reset_state();
673             log_info("Service not found, status %u.", sdp_event_query_complete_get_status(packet));
674             if (sdp_event_query_complete_get_status(packet)){
675                 emit_event(HSP_SUBEVENT_AUDIO_CONNECTION_COMPLETE, sdp_event_query_complete_get_status(packet));
676             } else {
677                 emit_event(HSP_SUBEVENT_AUDIO_CONNECTION_COMPLETE, SDP_SERVICE_NOT_FOUND);
678             }
679             break;
680         default:
681             break;
682     }
683 }
684 
685 void hsp_hs_send_button_press(void){
686     if ((hsp_state < HSP_RFCOMM_CONNECTION_ESTABLISHED) || (hsp_state >= HSP_W4_RFCOMM_DISCONNECTED)) return;
687     hs_send_button_press = 1;
688     hsp_run();
689 }
690 
691 void hsp_hs_set_sco_packet_types(uint16_t packet_types){
692     hsp_hs_sco_packet_types = packet_types;
693 }
694