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