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