xref: /btstack/src/classic/hsp_ag.c (revision 4c7b5f7454ef118efc1f5c21f6607e2939cfc1cc)
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 // *****************************************************************************
39 //
40 // HSP Audio Gateway
41 //
42 // *****************************************************************************
43 
44 #include "btstack_config.h"
45 
46 #include <stdint.h>
47 #include <stdio.h>
48 #include <stdlib.h>
49 #include <string.h>
50 
51 #include "btstack_debug.h"
52 #include "btstack_event.h"
53 #include "btstack_memory.h"
54 #include "btstack_run_loop.h"
55 #include "classic/sdp_server.h"
56 #include "classic/sdp_client_rfcomm.h"
57 #include "classic/sdp_util.h"
58 #include "hci.h"
59 #include "hci_cmd.h"
60 #include "hci_dump.h"
61 #include "hsp_ag.h"
62 #include "l2cap.h"
63 
64 #define HSP_HS_BUTTON_PRESS "AT+CKPD=200"
65 #define HSP_HS_AT_CKPD "AT+CKPD\r\n"
66 #define HSP_AG_OK "\r\nOK\r\n"
67 #define HSP_AG_ERROR "\r\nERROR\r\n"
68 #define HSP_AG_RING "\r\nRING\r\n"
69 #define HSP_MICROPHONE_GAIN "+VGM"
70 #define HSP_SPEAKER_GAIN "+VGS"
71 
72 #define HSP_HS_MICROPHONE_GAIN "AT+VGM="
73 #define HSP_HS_SPEAKER_GAIN "AT+VGS="
74 
75 static const char default_hsp_ag_service_name[] = "Audio Gateway";
76 
77 static bd_addr_t remote;
78 static uint8_t channel_nr = 0;
79 
80 static uint16_t mtu;
81 static uint16_t rfcomm_cid = 0;
82 static uint16_t sco_handle = 0;
83 static uint16_t rfcomm_handle = 0;
84 static btstack_timer_source_t hs_timeout;
85 
86 static int ag_microphone_gain = -1;
87 static int ag_speaker_gain = -1;
88 static uint8_t ag_ring = 0;
89 static uint8_t ag_send_ok = 0;
90 static uint8_t ag_send_error = 0;
91 static uint8_t ag_num_button_press_received = 0;
92 static uint8_t ag_support_custom_commands = 0;
93 
94 static uint8_t hsp_disconnect_rfcomm = 0;
95 static uint8_t hsp_establish_audio_connection = 0;
96 static uint8_t hsp_release_audio_connection = 0;
97 
98 static btstack_packet_callback_registration_t hci_event_callback_registration;
99 
100 typedef enum {
101     HSP_IDLE,
102     HSP_SDP_QUERY_RFCOMM_CHANNEL,
103     HSP_W4_SDP_EVENT_QUERY_COMPLETE,
104     HSP_W4_RFCOMM_CONNECTED,
105 
106     HSP_RFCOMM_CONNECTION_ESTABLISHED,
107 
108     HSP_W4_RING_ANSWER,
109     HSP_W4_USER_ACTION,
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 hsp_state_t hsp_state = HSP_IDLE;
124 
125 
126 static hsp_ag_callback_t hsp_ag_callback;
127 
128 static void hsp_run(void);
129 static void packet_handler (uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size);
130 static void handle_query_rfcomm_event(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size);
131 
132 static void dummy_notify(uint8_t * event, uint16_t size){}
133 
134 void hsp_ag_register_packet_handler(hsp_ag_callback_t callback){
135     if (callback == NULL){
136         callback = &dummy_notify;
137     }
138     hsp_ag_callback = callback;
139 }
140 
141 static void emit_event(uint8_t event_subtype, uint8_t value){
142     if (!hsp_ag_callback) return;
143     uint8_t event[4];
144     event[0] = HCI_EVENT_HSP_META;
145     event[1] = sizeof(event) - 2;
146     event[2] = event_subtype;
147     event[3] = value; // status 0 == OK
148     (*hsp_ag_callback)(event, sizeof(event));
149 }
150 
151 static void emit_event_audio_connected(uint8_t status, uint16_t handle){
152     if (!hsp_ag_callback) return;
153     uint8_t event[6];
154     event[0] = HCI_EVENT_HSP_META;
155     event[1] = sizeof(event) - 2;
156     event[2] = HSP_SUBEVENT_AUDIO_CONNECTION_COMPLETE;
157     event[3] = status;
158     little_endian_store_16(event, 4, handle);
159     (*hsp_ag_callback)(event, sizeof(event));
160 }
161 
162 void hsp_ag_create_sdp_record(uint8_t * service, uint32_t service_record_handle, int rfcomm_channel_nr, const char * name){
163     uint8_t* attribute;
164     de_create_sequence(service);
165 
166     // 0x0000 "Service Record Handle"
167     de_add_number(service, DE_UINT, DE_SIZE_16, SDP_ServiceRecordHandle);
168     de_add_number(service, DE_UINT, DE_SIZE_32, service_record_handle);
169 
170     // 0x0001 "Service Class ID List"
171     de_add_number(service,  DE_UINT, DE_SIZE_16, SDP_ServiceClassIDList);
172     attribute = de_push_sequence(service);
173     {
174         //  "UUID for PAN Service"
175         de_add_number(attribute, DE_UUID, DE_SIZE_16, SDP_Headset_AG);
176         de_add_number(attribute, DE_UUID, DE_SIZE_16, SDP_GenericAudio);
177     }
178     de_pop_sequence(service, attribute);
179 
180     // 0x0004 "Protocol Descriptor List"
181     de_add_number(service,  DE_UINT, DE_SIZE_16, SDP_ProtocolDescriptorList);
182     attribute = de_push_sequence(service);
183     {
184         uint8_t* l2cpProtocol = de_push_sequence(attribute);
185         {
186             de_add_number(l2cpProtocol,  DE_UUID, DE_SIZE_16, SDP_L2CAPProtocol);
187         }
188         de_pop_sequence(attribute, l2cpProtocol);
189 
190         uint8_t* rfcomm = de_push_sequence(attribute);
191         {
192             de_add_number(rfcomm,  DE_UUID, DE_SIZE_16, SDP_RFCOMMProtocol);  // rfcomm_service
193             de_add_number(rfcomm,  DE_UINT, DE_SIZE_8,  rfcomm_channel_nr);  // rfcomm channel
194         }
195         de_pop_sequence(attribute, rfcomm);
196     }
197     de_pop_sequence(service, attribute);
198 
199     // 0x0005 "Public Browse Group"
200     de_add_number(service,  DE_UINT, DE_SIZE_16, SDP_BrowseGroupList); // public browse group
201     attribute = de_push_sequence(service);
202     {
203         de_add_number(attribute,  DE_UUID, DE_SIZE_16, SDP_PublicBrowseGroup);
204     }
205     de_pop_sequence(service, attribute);
206 
207     // 0x0009 "Bluetooth Profile Descriptor List"
208     de_add_number(service,  DE_UINT, DE_SIZE_16, SDP_BluetoothProfileDescriptorList);
209     attribute = de_push_sequence(service);
210     {
211         uint8_t *sppProfile = de_push_sequence(attribute);
212         {
213             de_add_number(sppProfile,  DE_UUID, DE_SIZE_16, SDP_HSP);
214             de_add_number(sppProfile,  DE_UINT, DE_SIZE_16, 0x0102); // Verision 1.2
215         }
216         de_pop_sequence(attribute, sppProfile);
217     }
218     de_pop_sequence(service, attribute);
219 
220     // 0x0100 "Service Name"
221     de_add_number(service,  DE_UINT, DE_SIZE_16, 0x0100);
222     if (name){
223         de_add_data(service,  DE_STRING, strlen(name), (uint8_t *) name);
224     } else {
225         de_add_data(service,  DE_STRING, strlen(default_hsp_ag_service_name), (uint8_t *) default_hsp_ag_service_name);
226     }
227 }
228 
229 static int hsp_ag_send_str_over_rfcomm(uint16_t cid, char * command){
230     int err = rfcomm_send(cid, (uint8_t*) command, strlen(command));
231     if (err){
232         log_error("rfcomm_send_internal -> error 0X%02x", err);
233         return err;
234     }
235     return err;
236 }
237 
238 void hsp_ag_enable_custom_commands(int enable){
239     ag_support_custom_commands = enable;
240 }
241 
242 int hsp_ag_send_result(char * result){
243     if (!ag_support_custom_commands) return 1;
244     return hsp_ag_send_str_over_rfcomm(rfcomm_cid, result);
245 }
246 
247 static void hsp_ag_reset_state(void){
248     hsp_state = HSP_IDLE;
249 
250     rfcomm_cid = 0;
251     rfcomm_handle = 0;
252     sco_handle = 0;
253 
254     ag_send_ok = 0;
255     ag_send_error = 0;
256     ag_ring = 0;
257 
258     ag_num_button_press_received = 0;
259     ag_support_custom_commands = 0;
260 
261     ag_microphone_gain = -1;
262     ag_speaker_gain = -1;
263 
264     hsp_disconnect_rfcomm = 0;
265     hsp_establish_audio_connection = 0;
266     hsp_release_audio_connection = 0;
267 }
268 
269 void hsp_ag_init(uint8_t rfcomm_channel_nr){
270     // register for HCI events
271     hci_event_callback_registration.callback = &packet_handler;
272     hci_add_event_handler(&hci_event_callback_registration);
273 
274     // init L2CAP
275     l2cap_register_packet_handler(packet_handler);
276 
277     rfcomm_register_service(packet_handler, rfcomm_channel_nr, 0xffff);  // reserved channel, mtu limited by l2cap
278 
279     hsp_ag_reset_state();
280 }
281 
282 void hsp_ag_connect(bd_addr_t bd_addr){
283     if (hsp_state != HSP_IDLE) return;
284     hsp_state = HSP_SDP_QUERY_RFCOMM_CHANNEL;
285     memcpy(remote, bd_addr, 6);
286     hsp_run();
287 }
288 
289 void hsp_ag_disconnect(void){
290     hsp_ag_release_audio_connection();
291     printf(" rfcomm diconnect %d\n", hsp_state);
292     if (hsp_state < HSP_W4_RFCOMM_CONNECTED){
293         hsp_state = HSP_IDLE;
294         return;
295     }
296 
297     if (hsp_state == HSP_W4_RFCOMM_CONNECTED){
298         hsp_state = HSP_W4_CONNECTION_ESTABLISHED_TO_SHUTDOWN;
299         return;
300     }
301     hsp_disconnect_rfcomm = 1;
302     hsp_run();
303 }
304 
305 void hsp_ag_establish_audio_connection(void){
306     printf("hsp_ag_establish_audio_connection state %d\n", hsp_state);
307 
308     switch (hsp_state){
309         case HSP_RFCOMM_CONNECTION_ESTABLISHED:
310             printf("set flag hsp_establish_audio_connection\n");
311             hsp_establish_audio_connection = 1;
312             hsp_state = HSP_W4_SCO_CONNECTED;
313             break;
314         case HSP_W4_RFCOMM_CONNECTED:
315             hsp_state = HSP_W4_CONNECTION_ESTABLISHED_TO_SHUTDOWN;
316             break;
317         default:
318             break;
319     }
320     hsp_run();
321 }
322 
323 void hsp_ag_release_audio_connection(void){
324     if (hsp_state >= HSP_W2_DISCONNECT_SCO) return;
325     if (hsp_state < HSP_AUDIO_CONNECTION_ESTABLISHED) return;
326 
327     hsp_release_audio_connection = 1;
328     hsp_run();
329 }
330 
331 
332 void hsp_ag_set_microphone_gain(uint8_t gain){
333     if (gain < 0 || gain >15) {
334         log_error("Gain must be in interval [0..15], it is given %d", gain);
335         return;
336     }
337     ag_microphone_gain = gain;
338     hsp_run();
339 }
340 
341 // AG +VGS=5  [0..15] ; HS AT+VGM=6 | AG OK
342 void hsp_ag_set_speaker_gain(uint8_t gain){
343     if (gain < 0 || gain >15) {
344         log_error("Gain must be in interval [0..15], it is given %d", gain);
345         return;
346     }
347     ag_speaker_gain = gain;
348     hsp_run();
349 }
350 
351 static void hsp_ringing_timeout_handler(btstack_timer_source_t * timer){
352     ag_ring = 1;
353     btstack_run_loop_set_timer(&hs_timeout, 2000); // 2 seconds timeout
354     btstack_run_loop_add_timer(&hs_timeout);
355 }
356 
357 static void hsp_ringing_timer_start(void){
358     btstack_run_loop_remove_timer(&hs_timeout);
359     btstack_run_loop_set_timer_handler(&hs_timeout, hsp_ringing_timeout_handler);
360     btstack_run_loop_set_timer(&hs_timeout, 2000); // 2 seconds timeout
361     btstack_run_loop_add_timer(&hs_timeout);
362 }
363 
364 static void hsp_ringing_timer_stop(void){
365     btstack_run_loop_remove_timer(&hs_timeout);
366 }
367 
368 void hsp_ag_start_ringing(void){
369     if (hsp_state != HSP_W2_CONNECT_SCO) return;
370     ag_ring = 1;
371     hsp_state = HSP_W4_RING_ANSWER;
372     hsp_ringing_timer_start();
373 }
374 
375 void hsp_ag_stop_ringing(void){
376     ag_ring = 0;
377     ag_num_button_press_received = 0;
378     hsp_state = HSP_W2_CONNECT_SCO;
379     hsp_ringing_timer_stop();
380 }
381 
382 static void hsp_run(void){
383     if (!rfcomm_can_send_packet_now(rfcomm_cid)) return;
384     int err;
385 
386     if (ag_send_ok){
387         ag_send_ok = 0;
388         err = hsp_ag_send_str_over_rfcomm(rfcomm_cid, HSP_AG_OK);
389         if (err){
390             ag_send_ok = 1;
391         }
392         return;
393     }
394 
395     if (ag_send_error){
396         ag_send_error = 0;
397         err = hsp_ag_send_str_over_rfcomm(rfcomm_cid, HSP_AG_ERROR);
398         if (err) {
399             ag_send_error = 1;
400         }
401         return;
402     }
403 
404     if (hsp_establish_audio_connection){
405         hsp_establish_audio_connection = 0;
406         hci_send_cmd(&hci_setup_synchronous_connection, rfcomm_handle, 8000, 8000, 0xFFFF, hci_get_sco_voice_setting(), 0xFF, 0x003F);
407         return;
408     }
409 
410     if (hsp_release_audio_connection){
411         hsp_release_audio_connection = 0;
412         gap_disconnect(sco_handle);
413         return;
414     }
415 
416     if (hsp_disconnect_rfcomm){
417         hsp_disconnect_rfcomm = 0;
418         hsp_establish_audio_connection = 0;
419         rfcomm_disconnect(rfcomm_cid);
420         return;
421     }
422 
423     switch (hsp_state){
424         case HSP_SDP_QUERY_RFCOMM_CHANNEL:
425             hsp_state = HSP_W4_SDP_EVENT_QUERY_COMPLETE;
426             log_info("Start SDP query %s, 0x%02x", bd_addr_to_str(remote), SDP_HSP);
427             sdp_client_query_rfcomm_channel_and_name_for_uuid(&handle_query_rfcomm_event, remote, SDP_HSP);
428             break;
429 
430         case HSP_W4_RING_ANSWER:
431             if (ag_ring){
432                 ag_ring = 0;
433                 err = hsp_ag_send_str_over_rfcomm(rfcomm_cid, HSP_AG_RING);
434                 if (err) {
435                     ag_ring = 1;
436                 }
437                 break;
438             }
439 
440             if (!ag_num_button_press_received) break;
441             ag_send_ok = 0;
442 
443             ag_num_button_press_received = 0;
444             hsp_state = HSP_W2_CONNECT_SCO;
445 
446             err = hsp_ag_send_str_over_rfcomm(rfcomm_cid, HSP_AG_OK);
447             if (err) {
448                 hsp_state = HSP_W4_RING_ANSWER;
449                 ag_num_button_press_received = 1;
450             }
451             break;
452 
453         case HSP_W2_CONNECT_SCO:
454             hsp_state = HSP_W4_SCO_CONNECTED;
455             hci_send_cmd(&hci_setup_synchronous_connection, rfcomm_handle, 8000, 8000, 0xFFFF, hci_get_sco_voice_setting(), 0xFF, 0x003F);
456             break;
457 
458         case HSP_W2_DISCONNECT_SCO:
459             ag_num_button_press_received = 0;
460 
461             hsp_state = HSP_W4_SCO_DISCONNECTED;
462             gap_disconnect(sco_handle);
463             break;
464 
465         case HSP_W2_DISCONNECT_RFCOMM:
466             rfcomm_disconnect(rfcomm_cid);
467             break;
468 
469         case HSP_AUDIO_CONNECTION_ESTABLISHED:
470         case HSP_RFCOMM_CONNECTION_ESTABLISHED:
471 
472             if (ag_microphone_gain >= 0){
473                 int gain = ag_microphone_gain;
474                 ag_microphone_gain = -1;
475                 char buffer[10];
476                 sprintf(buffer, "%s=%d\r\n", HSP_MICROPHONE_GAIN, gain);
477                 err = hsp_ag_send_str_over_rfcomm(rfcomm_cid, buffer);
478                 if (err) {
479                     ag_microphone_gain = gain;
480                 }
481                 break;
482             }
483 
484             if (ag_speaker_gain >= 0){
485                 int gain = ag_speaker_gain;
486                 ag_speaker_gain = -1;
487                 char buffer[10];
488                 sprintf(buffer, "%s=%d\r\n", HSP_SPEAKER_GAIN, gain);
489                 err = hsp_ag_send_str_over_rfcomm(rfcomm_cid, buffer);
490                 if (err) {
491                     ag_speaker_gain = gain;
492                 }
493                 break;
494             }
495             break;
496         default:
497             break;
498     }
499 }
500 
501 
502 static void packet_handler (uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
503     if (packet_type == RFCOMM_DATA_PACKET){
504         while (size > 0 && (packet[0] == '\n' || packet[0] == '\r')){
505             size--;
506             packet++;
507         }
508 
509         if (strncmp((char *)packet, HSP_HS_BUTTON_PRESS, strlen(HSP_HS_BUTTON_PRESS)) == 0){
510             log_info("Received button press %s", HSP_HS_BUTTON_PRESS);
511             ag_send_ok = 1;
512             switch (hsp_state){
513                 case HSP_AUDIO_CONNECTION_ESTABLISHED:
514                     hsp_release_audio_connection = 1;
515                     break;
516                 case HSP_RFCOMM_CONNECTION_ESTABLISHED:
517                     hsp_establish_audio_connection = 1;
518                     break;
519                 default:
520                     break;
521             }
522         } else if (strncmp((char *)packet, HSP_HS_MICROPHONE_GAIN, strlen(HSP_HS_MICROPHONE_GAIN)) == 0){
523             uint8_t gain = (uint8_t)atoi((char*)&packet[strlen(HSP_HS_MICROPHONE_GAIN)]);
524             ag_send_ok = 1;
525             emit_event(HSP_SUBEVENT_MICROPHONE_GAIN_CHANGED, gain);
526 
527         } else if (strncmp((char *)packet, HSP_HS_SPEAKER_GAIN, strlen(HSP_HS_SPEAKER_GAIN)) == 0){
528             uint8_t gain = (uint8_t)atoi((char*)&packet[strlen(HSP_HS_SPEAKER_GAIN)]);
529             ag_send_ok = 1;
530             emit_event(HSP_SUBEVENT_SPEAKER_GAIN_CHANGED, gain);
531 
532         } else if (strncmp((char *)packet, "AT+", 3) == 0){
533             ag_send_error = 1;
534             if (!hsp_ag_callback) return;
535             // re-use incoming buffer to avoid reserving large buffers - ugly but efficient
536             uint8_t * event = packet - 4;
537             event[0] = HCI_EVENT_HSP_META;
538             event[1] = size + 2;
539             event[2] = HSP_SUBEVENT_HS_COMMAND;
540             event[3] = size;
541             (*hsp_ag_callback)(event, size+4);
542         }
543 
544         hsp_run();
545         return;
546     }
547 
548     if (packet_type != HCI_EVENT_PACKET) return;
549     uint8_t event = hci_event_packet_get_type(packet);
550     bd_addr_t event_addr;
551     uint16_t handle;
552 
553     switch (event) {
554         case HCI_EVENT_SYNCHRONOUS_CONNECTION_COMPLETE:{
555             int index = 2;
556             uint8_t status = packet[index++];
557             sco_handle = little_endian_read_16(packet, index);
558             index+=2;
559             bd_addr_t address;
560             memcpy(address, &packet[index], 6);
561             index+=6;
562             uint8_t link_type = packet[index++];
563             uint8_t transmission_interval = packet[index++];  // measured in slots
564             uint8_t retransmission_interval = packet[index++];// measured in slots
565             uint16_t rx_packet_length = little_endian_read_16(packet, index); // measured in bytes
566             index+=2;
567             uint16_t tx_packet_length = little_endian_read_16(packet, index); // measured in bytes
568             index+=2;
569             uint8_t air_mode = packet[index];
570 
571             if (status != 0){
572                 log_error("(e)SCO Connection failed, status %u", status);
573                 emit_event_audio_connected(status, sco_handle);
574                 break;
575             }
576             switch (link_type){
577                 case 0x00:
578                     log_info("SCO Connection established.");
579                     if (transmission_interval != 0) log_error("SCO Connection: transmission_interval not zero: %d.", transmission_interval);
580                     if (retransmission_interval != 0) log_error("SCO Connection: retransmission_interval not zero: %d.", retransmission_interval);
581                     if (rx_packet_length != 0) log_error("SCO Connection: rx_packet_length not zero: %d.", rx_packet_length);
582                     if (tx_packet_length != 0) log_error("SCO Connection: tx_packet_length not zero: %d.", tx_packet_length);
583                     break;
584                 case 0x02:
585                     log_info("eSCO Connection established.");
586                     break;
587                 default:
588                     log_error("(e)SCO reserved link_type 0x%2x", link_type);
589                     break;
590             }
591             log_info("sco_handle 0x%2x, address %s, transmission_interval %u slots, retransmission_interval %u slots, "
592                  " rx_packet_length %u bytes, tx_packet_length %u bytes, air_mode 0x%2x (0x02 == CVSD)", sco_handle,
593                  bd_addr_to_str(address), transmission_interval, retransmission_interval, rx_packet_length, tx_packet_length, air_mode);
594 
595             if (hsp_state == HSP_W4_CONNECTION_ESTABLISHED_TO_SHUTDOWN){
596                 hsp_state = HSP_W2_DISCONNECT_SCO;
597                 break;
598             }
599 
600             hsp_state = HSP_AUDIO_CONNECTION_ESTABLISHED;
601             emit_event_audio_connected(status, sco_handle);
602             break;
603         }
604 
605         case RFCOMM_EVENT_INCOMING_CONNECTION:
606             // data: event (8), len(8), address(48), channel (8), rfcomm_cid (16)
607             if (hsp_state != HSP_IDLE) return;
608 
609             reverse_bd_addr(&packet[2], event_addr);
610             rfcomm_cid = little_endian_read_16(packet, 9);
611             log_info("RFCOMM channel %u requested for %s", packet[8], bd_addr_to_str(event_addr));
612             hsp_state = HSP_W4_RFCOMM_CONNECTED;
613             rfcomm_accept_connection(rfcomm_cid);
614             break;
615 
616         case RFCOMM_EVENT_OPEN_CHANNEL_COMPLETE:
617             log_info("RFCOMM_EVENT_OPEN_CHANNEL_COMPLETE packet_handler type %u, packet[0] %x", packet_type, packet[0]);
618             // data: event(8), len(8), status (8), address (48), handle(16), server channel(8), rfcomm_cid(16), max frame size(16)
619             if (packet[2]) {
620                 log_info("RFCOMM channel open failed, status %u§", packet[2]);
621                 hsp_ag_reset_state();
622                 hsp_state = HSP_IDLE;
623             } else {
624                 // data: event(8) , len(8), status (8), address (48), handle (16), server channel(8), rfcomm_cid(16), max frame size(16)
625                 rfcomm_handle = little_endian_read_16(packet, 9);
626                 rfcomm_cid = little_endian_read_16(packet, 12);
627                 mtu = little_endian_read_16(packet, 14);
628                 log_info("RFCOMM channel open succeeded. New RFCOMM Channel ID %u, max frame size %u, state %d", rfcomm_cid, mtu, hsp_state);
629                 hsp_state = HSP_RFCOMM_CONNECTION_ESTABLISHED;
630             }
631             emit_event(HSP_SUBEVENT_RFCOMM_CONNECTION_COMPLETE, packet[2]);
632             break;
633 
634         case HCI_EVENT_DISCONNECTION_COMPLETE:
635             handle = little_endian_read_16(packet,3);
636             if (handle == sco_handle){
637                 sco_handle = 0;
638                 hsp_state = HSP_RFCOMM_CONNECTION_ESTABLISHED;
639                 emit_event(HSP_SUBEVENT_AUDIO_DISCONNECTION_COMPLETE,0);
640                 break;
641             }
642             if (handle == rfcomm_handle) {
643                 rfcomm_handle = 0;
644                 hsp_state = HSP_IDLE;
645                 hsp_ag_reset_state();
646                 emit_event(HSP_SUBEVENT_RFCOMM_DISCONNECTION_COMPLETE,0);
647             }
648             break;
649 
650         case RFCOMM_EVENT_CHANNEL_CLOSED:
651             rfcomm_handle = 0;
652             hsp_state = HSP_IDLE;
653             hsp_ag_reset_state();
654             emit_event(HSP_SUBEVENT_RFCOMM_DISCONNECTION_COMPLETE,0);
655             break;
656         default:
657             break;
658     }
659     hsp_run();
660 }
661 
662 static void handle_query_rfcomm_event(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
663     switch (packet[0]){
664         case SDP_EVENT_QUERY_RFCOMM_SERVICE:
665             channel_nr = sdp_event_query_rfcomm_service_get_rfcomm_channel(packet);
666             log_info("** Service name: '%s', RFCOMM port %u", sdp_event_query_rfcomm_service_get_name(packet), channel_nr);
667             break;
668         case SDP_EVENT_QUERY_COMPLETE:
669             if (channel_nr > 0){
670                 hsp_state = HSP_W4_RFCOMM_CONNECTED;
671                 log_info("RFCOMM create channel. state %d", HSP_W4_RFCOMM_CONNECTED);
672                 rfcomm_create_channel(packet_handler, remote, channel_nr, NULL);
673                 break;
674             }
675             hsp_ag_reset_state();
676             log_info("Service not found, status %u.\n", sdp_event_query_complete_get_status(packet));
677             if (sdp_event_query_complete_get_status(packet)){
678                 emit_event(HSP_SUBEVENT_AUDIO_CONNECTION_COMPLETE, sdp_event_query_complete_get_status(packet));
679             } else {
680                 emit_event(HSP_SUBEVENT_AUDIO_CONNECTION_COMPLETE, SDP_SERVICE_NOT_FOUND);
681             }
682             break;
683         default:
684             break;
685     }
686 }
687 
688 
689