xref: /btstack/src/classic/hsp_hs.c (revision 7cdc89a533ca236b2c2564b759993b788bae89d3)
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 <stdlib.h>
51 #include <string.h>
52 
53 #include "bluetooth_sdp.h"
54 #include "btstack_debug.h"
55 #include "btstack_event.h"
56 #include "btstack_memory.h"
57 #include "btstack_run_loop.h"
58 #include "classic/core.h"
59 #include "classic/sdp_server.h"
60 #include "classic/sdp_client_rfcomm.h"
61 #include "classic/sdp_util.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 uint16_t sco_handle = 0;
86 static uint16_t rfcomm_handle = 0;
87 
88 // static uint8_t connection_state = 0;
89 
90 static int hs_microphone_gain = -1;
91 static int hs_speaker_gain = -1;
92 
93 static uint8_t hs_send_button_press = 0;
94 static uint8_t wait_ok = 0;
95 static uint8_t hs_accept_sco_connection = 0;
96 
97 static uint8_t hs_support_custom_indications = 0;
98 static btstack_packet_callback_registration_t hci_event_callback_registration;
99 static uint8_t hsp_disconnect_rfcomm = 0;
100 static uint8_t hsp_establish_audio_connection = 0;
101 static uint8_t hsp_release_audio_connection = 0;
102 
103 typedef enum {
104     HSP_IDLE,
105     HSP_SDP_QUERY_RFCOMM_CHANNEL,
106     HSP_W4_SDP_QUERY_COMPLETE,
107     HSP_W4_RFCOMM_CONNECTED,
108 
109     HSP_RFCOMM_CONNECTION_ESTABLISHED,
110 
111     HSP_W2_CONNECT_SCO,
112     HSP_W4_SCO_CONNECTED,
113 
114     HSP_AUDIO_CONNECTION_ESTABLISHED,
115 
116     HSP_W2_DISCONNECT_SCO,
117     HSP_W4_SCO_DISCONNECTED,
118 
119     HSP_W2_DISCONNECT_RFCOMM,
120     HSP_W4_RFCOMM_DISCONNECTED,
121     HSP_W4_CONNECTION_ESTABLISHED_TO_SHUTDOWN
122 } hsp_state_t;
123 
124 static hsp_state_t hsp_state = HSP_IDLE;
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 
275     hs_send_button_press = 0;
276     wait_ok = 0;
277     hs_support_custom_indications = 0;
278 
279     hsp_disconnect_rfcomm = 0;
280     hsp_establish_audio_connection = 0;
281     hsp_release_audio_connection = 0;
282 }
283 
284 void hsp_hs_init(uint8_t rfcomm_channel_nr){
285     // register for HCI events
286     hci_event_callback_registration.callback = &packet_handler;
287     hci_add_event_handler(&hci_event_callback_registration);
288 
289     rfcomm_register_service(packet_handler, rfcomm_channel_nr, 0xffff);  // reserved channel, mtu limited by l2cap
290 
291     hsp_hs_reset_state();
292 }
293 
294 
295 void hsp_hs_connect(bd_addr_t bd_addr){
296     if (hsp_state != HSP_IDLE) return;
297     hsp_state = HSP_SDP_QUERY_RFCOMM_CHANNEL;
298     (void)memcpy(remote, bd_addr, 6);
299     hsp_run();
300 }
301 
302 void hsp_hs_disconnect(void){
303     hsp_hs_release_audio_connection();
304 
305     if (hsp_state < HSP_W4_RFCOMM_CONNECTED){
306         hsp_state = HSP_IDLE;
307         return;
308     }
309 
310     if (hsp_state == HSP_W4_RFCOMM_CONNECTED){
311         hsp_state = HSP_W4_CONNECTION_ESTABLISHED_TO_SHUTDOWN;
312         return;
313     }
314 
315     if (hsp_state < HSP_W4_SCO_CONNECTED){
316         hsp_state = HSP_W2_DISCONNECT_RFCOMM;
317         return;
318     }
319 
320     hsp_disconnect_rfcomm = 1;
321     hsp_run();
322 }
323 
324 
325 void hsp_hs_establish_audio_connection(void){
326     switch (hsp_state){
327         case HSP_RFCOMM_CONNECTION_ESTABLISHED:
328             hsp_establish_audio_connection = 1;
329             hsp_state = HSP_W4_SCO_CONNECTED;
330             break;
331         case HSP_W4_RFCOMM_CONNECTED:
332             hsp_state = HSP_W4_CONNECTION_ESTABLISHED_TO_SHUTDOWN;
333             break;
334         default:
335             break;
336     }
337     hsp_run();
338 }
339 
340 void hsp_hs_release_audio_connection(void){
341     if (hsp_state >= HSP_W2_DISCONNECT_SCO) return;
342     if (hsp_state < HSP_AUDIO_CONNECTION_ESTABLISHED) return;
343     hsp_release_audio_connection = 1;
344     hsp_run();
345 }
346 
347 void hsp_hs_set_microphone_gain(uint8_t gain){
348     if (gain >15) {
349         log_info("Gain must be in interval [0..15], it is given %d", gain);
350         return;
351     }
352     hs_microphone_gain = gain;
353     hsp_run();
354 }
355 
356 // AG +VGS=5  [0..15] ; HS AT+VGM=6 | AG OK
357 void hsp_hs_set_speaker_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_speaker_gain = gain;
363     hsp_run();
364 }
365 
366 
367 static void hsp_run(void){
368 
369     if (wait_ok) return;
370 
371     if (hs_accept_sco_connection && hci_can_send_command_packet_now()){
372         hs_accept_sco_connection = 0;
373 
374         log_info("HSP: sending hci_accept_connection_request.");
375         // remote supported feature eSCO is set if link type is eSCO
376         // eSCO: S4 - max latency == transmission interval = 0x000c == 12 ms,
377         uint16_t max_latency;
378         uint8_t  retransmission_effort;
379         uint16_t packet_types;
380 
381         if (hci_remote_esco_supported(rfcomm_handle)){
382             max_latency = 0x000c;
383             retransmission_effort = 0x02;
384             packet_types = 0x388;
385         } else {
386             max_latency = 0xffff;
387             retransmission_effort = 0xff;
388             packet_types = 0x003f;
389         }
390 
391         uint16_t sco_voice_setting = hci_get_sco_voice_setting();
392 
393         log_info("HFP: sending hci_accept_connection_request, sco_voice_setting %02x", sco_voice_setting);
394         hci_send_cmd(&hci_accept_synchronous_connection, remote, 8000, 8000, max_latency,
395                         sco_voice_setting, retransmission_effort, packet_types);
396         return;
397     }
398 
399     if (hsp_release_audio_connection){
400         if (!rfcomm_can_send_packet_now(rfcomm_cid)) {
401             rfcomm_request_can_send_now_event(rfcomm_cid);
402             return;
403         }
404         hsp_release_audio_connection = 0;
405         wait_ok = 1;
406         hsp_hs_send_str_over_rfcomm(rfcomm_cid, HSP_HS_AT_CKPD);
407         return;
408     }
409 
410     if (hsp_disconnect_rfcomm){
411         hsp_disconnect_rfcomm = 0;
412         hsp_establish_audio_connection = 0;
413         rfcomm_disconnect(rfcomm_cid);
414         return;
415     }
416 
417     if (hsp_establish_audio_connection){
418         if (!rfcomm_can_send_packet_now(rfcomm_cid)) {
419             rfcomm_request_can_send_now_event(rfcomm_cid);
420             return;
421         }
422         hsp_establish_audio_connection = 0;
423         wait_ok = 1;
424         hsp_hs_send_str_over_rfcomm(rfcomm_cid, HSP_HS_AT_CKPD);
425         return;
426     }
427 
428     if (hs_send_button_press){
429         if (!rfcomm_can_send_packet_now(rfcomm_cid)) {
430             rfcomm_request_can_send_now_event(rfcomm_cid);
431             return;
432         }
433         hs_send_button_press = 0;
434         wait_ok = 1;
435         hsp_hs_send_str_over_rfcomm(rfcomm_cid, HSP_HS_AT_CKPD);
436         return;
437     }
438 
439     switch (hsp_state){
440         case HSP_SDP_QUERY_RFCOMM_CHANNEL:
441             hsp_state = HSP_W4_SDP_QUERY_COMPLETE;
442             sdp_client_query_rfcomm_channel_and_name_for_uuid(&handle_query_rfcomm_event, remote, BLUETOOTH_SERVICE_CLASS_HEADSET_AUDIO_GATEWAY_AG);
443             break;
444 
445         case HSP_AUDIO_CONNECTION_ESTABLISHED:
446         case HSP_RFCOMM_CONNECTION_ESTABLISHED:
447 
448             if (hs_microphone_gain >= 0){
449                 if (!rfcomm_can_send_packet_now(rfcomm_cid)) {
450                     rfcomm_request_can_send_now_event(rfcomm_cid);
451                     return;
452                 }
453                 char buffer[20];
454                 sprintf(buffer, "%s=%d\r\n", HSP_HS_MICROPHONE_GAIN, hs_microphone_gain);
455                 hsp_hs_send_str_over_rfcomm(rfcomm_cid, buffer);
456                 hs_microphone_gain = -1;
457                 break;
458             }
459 
460             if (hs_speaker_gain >= 0){
461                 if (!rfcomm_can_send_packet_now(rfcomm_cid)) {
462                     rfcomm_request_can_send_now_event(rfcomm_cid);
463                     return;
464                 }
465                 char buffer[20];
466                 sprintf(buffer, "%s=%d\r\n", HSP_HS_SPEAKER_GAIN, hs_speaker_gain);
467                 hsp_hs_send_str_over_rfcomm(rfcomm_cid, buffer);
468                 hs_speaker_gain = -1;
469                 break;
470             }
471             break;
472         case HSP_W4_RFCOMM_DISCONNECTED:
473             rfcomm_disconnect(rfcomm_cid);
474             break;
475         default:
476             break;
477     }
478 }
479 
480 
481 static void packet_handler (uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
482     UNUSED(channel);    // ok: no channel for HCI_EVENT_PACKET and only single active RFCOMM channel
483     if (packet_type == RFCOMM_DATA_PACKET){
484         // printf("packet_handler type RFCOMM_DATA_PACKET %u, packet[0] %x\n", packet_type, packet[0]);
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     uint8_t event = hci_event_packet_get_type(packet);
523     bd_addr_t event_addr;
524     uint16_t handle;
525     // printf("packet_handler HCI_EVENT_PACKET type %u, packet[0] %x\n", packet_type, packet[0]);
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                     printf("remote device %s\n", bd_addr_to_str(remote));
533                     printf("accept sco for device %s\n", bd_addr_to_str(event_addr));
534 
535                     if (bd_addr_cmp(event_addr, remote) == 0){
536                         printf("hs_accept_sco_connection \n");
537                         hs_accept_sco_connection = 1;
538                     }
539                     break;
540                 default:
541                     break;
542             }
543             break;
544 
545         case HCI_EVENT_SYNCHRONOUS_CONNECTION_COMPLETE:{
546             if (hsp_state < HSP_RFCOMM_CONNECTION_ESTABLISHED) return;
547             int index = 2;
548             uint8_t status = packet[index++];
549             sco_handle = little_endian_read_16(packet, index);
550             index+=2;
551             bd_addr_t address;
552             (void)memcpy(address, &packet[index], 6);
553             index+=6;
554             uint8_t link_type = packet[index++];
555             uint8_t transmission_interval = packet[index++];  // measured in slots
556             uint8_t retransmission_interval = packet[index++];// measured in slots
557             uint16_t rx_packet_length = little_endian_read_16(packet, index); // measured in bytes
558             index+=2;
559             uint16_t tx_packet_length = little_endian_read_16(packet, index); // measured in bytes
560             index+=2;
561             uint8_t air_mode = packet[index];
562 
563             if (status != 0){
564                 log_error("(e)SCO Connection failed, status %u", status);
565                 emit_event_audio_connected(status, sco_handle);
566                 hsp_state = HSP_RFCOMM_CONNECTION_ESTABLISHED ;
567                 break;
568             }
569 
570             switch (link_type){
571                 case 0x00:
572                     log_info("SCO Connection established.");
573                     if (transmission_interval != 0) log_error("SCO Connection: transmission_interval not zero: %d.", transmission_interval);
574                     if (retransmission_interval != 0) log_error("SCO Connection: retransmission_interval not zero: %d.", retransmission_interval);
575                     if (rx_packet_length != 0) log_error("SCO Connection: rx_packet_length not zero: %d.", rx_packet_length);
576                     if (tx_packet_length != 0) log_error("SCO Connection: tx_packet_length not zero: %d.", tx_packet_length);
577                     break;
578                 case 0x02:
579                     log_info("eSCO Connection established.");
580                     break;
581                 default:
582                     log_error("(e)SCO reserved link_type 0x%2x", link_type);
583                     break;
584             }
585             log_info("sco_handle 0x%2x, address %s, transmission_interval %u slots, retransmission_interval %u slots, "
586                  " rx_packet_length %u bytes, tx_packet_length %u bytes, air_mode 0x%2x (0x02 == CVSD)", sco_handle,
587                  bd_addr_to_str(address), transmission_interval, retransmission_interval, rx_packet_length, tx_packet_length, air_mode);
588 
589             hsp_state = HSP_AUDIO_CONNECTION_ESTABLISHED;
590             emit_event_audio_connected(status, sco_handle);
591             break;
592         }
593 
594         case RFCOMM_EVENT_INCOMING_CONNECTION:
595             // data: event (8), len(8), address(48), channel (8), rfcomm_cid (16)
596             if (hsp_state != HSP_IDLE) return;
597 
598             reverse_bd_addr(&packet[2], event_addr);
599             rfcomm_cid = little_endian_read_16(packet, 9);
600             log_info("RFCOMM channel %u requested for %s", packet[8], bd_addr_to_str(event_addr));
601             hsp_state = HSP_W4_RFCOMM_CONNECTED;
602             rfcomm_accept_connection(rfcomm_cid);
603             break;
604 
605         case RFCOMM_EVENT_CHANNEL_OPENED:
606             // printf("RFCOMM_EVENT_CHANNEL_OPENED packet_handler type %u, packet[0] %x\n", packet_type, packet[0]);
607             // data: event(8), len(8), status (8), address (48), handle(16), server channel(8), rfcomm_cid(16), max frame size(16)
608             if (hsp_state != HSP_W4_RFCOMM_CONNECTED) return;
609             if (packet[2]) {
610                 log_info("RFCOMM channel open failed, status %u", packet[2]);
611                 hsp_state = HSP_IDLE;
612                 hsp_hs_reset_state();
613             } else {
614                 // data: event(8) , len(8), status (8), address (48), handle (16), server channel(8), rfcomm_cid(16), max frame size(16)
615                 rfcomm_handle = rfcomm_event_channel_opened_get_con_handle(packet);
616                 rfcomm_cid = rfcomm_event_channel_opened_get_rfcomm_cid(packet);
617                 mtu = rfcomm_event_channel_opened_get_max_frame_size(packet);
618                 rfcomm_event_channel_opened_get_bd_addr(packet, remote);
619                 log_info("RFCOMM channel open succeeded. New RFCOMM Channel ID %u, max frame size %u, handle %02x", rfcomm_cid, mtu, rfcomm_handle);
620                 hsp_state = HSP_RFCOMM_CONNECTION_ESTABLISHED;
621             }
622             emit_event(HSP_SUBEVENT_RFCOMM_CONNECTION_COMPLETE, packet[2]);
623             break;
624 
625         case RFCOMM_EVENT_CAN_SEND_NOW:
626             hsp_run();
627             break;
628 
629         case HCI_EVENT_DISCONNECTION_COMPLETE:
630             handle = little_endian_read_16(packet,3);
631             if (handle == sco_handle){
632                 sco_handle = 0;
633                 hsp_state = HSP_RFCOMM_CONNECTION_ESTABLISHED;
634                 emit_event(HSP_SUBEVENT_AUDIO_DISCONNECTION_COMPLETE,0);
635                 break;
636             }
637             if (handle == rfcomm_handle) {
638                 rfcomm_handle = 0;
639                 hsp_state = HSP_IDLE;
640                 emit_event(HSP_SUBEVENT_RFCOMM_DISCONNECTION_COMPLETE,0);
641                 hsp_hs_reset_state();
642             }
643             break;
644 
645         case RFCOMM_EVENT_CHANNEL_CLOSED:
646             hsp_hs_reset_state();
647             hsp_hs_callback(HCI_EVENT_PACKET, 0, packet, size);
648             break;
649 
650         default:
651             break;
652     }
653 
654     hsp_run();
655 }
656 
657 static void handle_query_rfcomm_event(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
658     UNUSED(packet_type);    // ok: handling own sdp events
659     UNUSED(channel);        // ok: no channel
660     UNUSED(size);           // ok: handling own sdp events
661 
662     switch (hci_event_packet_get_type(packet)){
663         case SDP_EVENT_QUERY_RFCOMM_SERVICE:
664             channel_nr = sdp_event_query_rfcomm_service_get_rfcomm_channel(packet);
665             log_info("** Service name: '%s', RFCOMM port %u", sdp_event_query_rfcomm_service_get_name(packet), channel_nr);
666             break;
667         case SDP_EVENT_QUERY_COMPLETE:
668             if (channel_nr > 0){
669                 hsp_state = HSP_W4_RFCOMM_CONNECTED;
670                 log_info("HSP: SDP_QUERY_COMPLETE. RFCOMM create channel, addr %s, rfcomm channel nr %d", bd_addr_to_str(remote), channel_nr);
671                 rfcomm_create_channel(packet_handler, remote, channel_nr, NULL);
672                 break;
673             }
674             hsp_hs_reset_state();
675             log_info("Service not found, status %u.", sdp_event_query_complete_get_status(packet));
676             if (sdp_event_query_complete_get_status(packet)){
677                 emit_event(HSP_SUBEVENT_AUDIO_CONNECTION_COMPLETE, sdp_event_query_complete_get_status(packet));
678             } else {
679                 emit_event(HSP_SUBEVENT_AUDIO_CONNECTION_COMPLETE, SDP_SERVICE_NOT_FOUND);
680             }
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