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