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