xref: /btstack/src/classic/hsp_hs.c (revision e6c9673776c7f85e24c76da7f4b1b83031102d2b)
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 = {0x04, 0x0C, 0xCE, 0xE4, 0x85, 0xD3};
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 
96 static uint8_t hs_support_custom_indications = 0;
97 static btstack_packet_callback_registration_t hci_event_callback_registration;
98 static uint8_t hsp_disconnect_rfcomm = 0;
99 static uint8_t hsp_establish_audio_connection = 0;
100 static uint8_t hsp_release_audio_connection = 0;
101 
102 typedef enum {
103     HSP_IDLE,
104     HSP_SDP_QUERY_RFCOMM_CHANNEL,
105     HSP_W4_SDP_QUERY_COMPLETE,
106     HSP_W4_RFCOMM_CONNECTED,
107 
108     HSP_RFCOMM_CONNECTION_ESTABLISHED,
109 
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 static void hsp_run(void);
126 static void packet_handler (uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size);
127 static void handle_query_rfcomm_event(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size);
128 
129 static btstack_packet_handler_t hsp_hs_callback;
130 static void dummy_notify(uint8_t packet_type, uint16_t channel, uint8_t * event, uint16_t size){
131     // ok: no code
132     UNUSED(packet_type);
133     UNUSED(channel);
134     UNUSED(event);
135     UNUSED(size);
136 }
137 
138 void hsp_hs_register_packet_handler(btstack_packet_handler_t callback){
139     if (callback == NULL){
140         callback = &dummy_notify;
141     }
142     hsp_hs_callback = callback;
143 }
144 
145 static void emit_event(uint8_t event_subtype, uint8_t value){
146     if (!hsp_hs_callback) return;
147     uint8_t event[4];
148     event[0] = HCI_EVENT_HSP_META;
149     event[1] = sizeof(event) - 2;
150     event[2] = event_subtype;
151     event[3] = value; // status 0 == OK
152     (*hsp_hs_callback)(HCI_EVENT_PACKET, 0, event, sizeof(event));
153 }
154 
155 static void emit_ring_event(void){
156     if (!hsp_hs_callback) return;
157     uint8_t event[3];
158     event[0] = HCI_EVENT_HSP_META;
159     event[1] = sizeof(event) - 2;
160     event[2] = HSP_SUBEVENT_RING;
161     (*hsp_hs_callback)(HCI_EVENT_PACKET, 0, event, sizeof(event));
162 }
163 
164 static void emit_event_audio_connected(uint8_t status, uint16_t handle){
165     if (!hsp_hs_callback) return;
166     uint8_t event[6];
167     event[0] = HCI_EVENT_HSP_META;
168     event[1] = sizeof(event) - 2;
169     event[2] = HSP_SUBEVENT_AUDIO_CONNECTION_COMPLETE;
170     event[3] = status;
171     little_endian_store_16(event, 4, handle);
172     (*hsp_hs_callback)(HCI_EVENT_PACKET, 0, event, sizeof(event));
173 }
174 
175 // remote audio volume control
176 // AG +VGM=13 [0..15] ; HS AT+VGM=6 | AG OK
177 
178 static int hsp_hs_send_str_over_rfcomm(uint16_t cid, const char * command){
179     if (!rfcomm_can_send_packet_now(rfcomm_cid)) return 1;
180     int err = rfcomm_send(cid, (uint8_t*) command, strlen(command));
181     if (err){
182         log_info("rfcomm_send_internal -> error 0X%02x", err);
183     }
184     return err;
185 }
186 
187 void hsp_hs_enable_custom_indications(int enable){
188     hs_support_custom_indications = enable;
189 }
190 
191 int hsp_hs_send_result(const char * result){
192     if (!hs_support_custom_indications) return 1;
193     return hsp_hs_send_str_over_rfcomm(rfcomm_cid, result);
194 }
195 
196 
197 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){
198     uint8_t* attribute;
199     de_create_sequence(service);
200 
201     // 0x0000 "Service Record Handle"
202     de_add_number(service, DE_UINT, DE_SIZE_16, BLUETOOTH_ATTRIBUTE_SERVICE_RECORD_HANDLE);
203     de_add_number(service, DE_UINT, DE_SIZE_32, service_record_handle);
204 
205     // 0x0001 "Service Class ID List"
206     de_add_number(service,  DE_UINT, DE_SIZE_16, BLUETOOTH_ATTRIBUTE_SERVICE_CLASS_ID_LIST);
207     attribute = de_push_sequence(service);
208     {
209         //  see Bluetooth Erratum #3507
210         de_add_number(attribute, DE_UUID, DE_SIZE_16, BLUETOOTH_SERVICE_CLASS_HEADSET);       // 0x1108
211         de_add_number(attribute, DE_UUID, DE_SIZE_16, BLUETOOTH_SERVICE_CLASS_HEADSET_HS);    // 0x1131
212         de_add_number(attribute, DE_UUID, DE_SIZE_16, BLUETOOTH_SERVICE_CLASS_GENERIC_AUDIO); // 0x1203
213     }
214     de_pop_sequence(service, attribute);
215 
216     // 0x0004 "Protocol Descriptor List"
217     de_add_number(service,  DE_UINT, DE_SIZE_16, BLUETOOTH_ATTRIBUTE_PROTOCOL_DESCRIPTOR_LIST);
218     attribute = de_push_sequence(service);
219     {
220         uint8_t* l2cpProtocol = de_push_sequence(attribute);
221         {
222             de_add_number(l2cpProtocol,  DE_UUID, DE_SIZE_16, BLUETOOTH_PROTOCOL_L2CAP);
223         }
224         de_pop_sequence(attribute, l2cpProtocol);
225 
226         uint8_t* rfcomm = de_push_sequence(attribute);
227         {
228             de_add_number(rfcomm,  DE_UUID, DE_SIZE_16, BLUETOOTH_PROTOCOL_RFCOMM);  // rfcomm_service
229             de_add_number(rfcomm,  DE_UINT, DE_SIZE_8,  rfcomm_channel_nr);  // rfcomm channel
230         }
231         de_pop_sequence(attribute, rfcomm);
232     }
233     de_pop_sequence(service, attribute);
234 
235     // 0x0005 "Public Browse Group"
236     de_add_number(service,  DE_UINT, DE_SIZE_16, BLUETOOTH_ATTRIBUTE_BROWSE_GROUP_LIST); // public browse group
237     attribute = de_push_sequence(service);
238     {
239         de_add_number(attribute,  DE_UUID, DE_SIZE_16, BLUETOOTH_ATTRIBUTE_PUBLIC_BROWSE_ROOT);
240     }
241     de_pop_sequence(service, attribute);
242 
243     // 0x0009 "Bluetooth Profile Descriptor List"
244     de_add_number(service,  DE_UINT, DE_SIZE_16, BLUETOOTH_ATTRIBUTE_BLUETOOTH_PROFILE_DESCRIPTOR_LIST);
245     attribute = de_push_sequence(service);
246     {
247         uint8_t *hsp_profile = de_push_sequence(attribute);
248         {
249             de_add_number(hsp_profile,  DE_UUID, DE_SIZE_16, BLUETOOTH_SERVICE_CLASS_HEADSET);
250             de_add_number(hsp_profile,  DE_UINT, DE_SIZE_16, 0x0102); // Verision 1.2
251         }
252         de_pop_sequence(attribute, hsp_profile);
253     }
254     de_pop_sequence(service, attribute);
255 
256     // 0x0100 "Service Name"
257     de_add_number(service,  DE_UINT, DE_SIZE_16, 0x0100);
258     if (name){
259         de_add_data(service,  DE_STRING, strlen(name), (uint8_t *) name);
260     } else {
261         de_add_data(service,  DE_STRING, strlen(default_hsp_hs_service_name), (uint8_t *) default_hsp_hs_service_name);
262     }
263 
264     // Remote audio volume control
265     de_add_number(service, DE_UINT, DE_SIZE_16, 0x030C);
266     de_add_number(service, DE_BOOL, DE_SIZE_8, have_remote_audio_control);
267 }
268 
269 static void hsp_hs_reset_state(void){
270     hsp_state = HSP_IDLE;
271     hs_microphone_gain = -1;
272     hs_speaker_gain = -1;
273 
274     hs_send_button_press = 0;
275     wait_ok = 0;
276     hs_support_custom_indications = 0;
277 
278     hsp_disconnect_rfcomm = 0;
279     hsp_establish_audio_connection = 0;
280     hsp_release_audio_connection = 0;
281 }
282 
283 void hsp_hs_init(uint8_t rfcomm_channel_nr){
284     // register for HCI events
285     hci_event_callback_registration.callback = &packet_handler;
286     hci_add_event_handler(&hci_event_callback_registration);
287 
288     rfcomm_init();
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     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 (hsp_release_audio_connection){
372         if (!rfcomm_can_send_packet_now(rfcomm_cid)) {
373             rfcomm_request_can_send_now_event(rfcomm_cid);
374             return;
375         }
376         hsp_release_audio_connection = 0;
377         wait_ok = 1;
378         hsp_hs_send_str_over_rfcomm(rfcomm_cid, HSP_HS_AT_CKPD);
379         return;
380     }
381 
382     if (hsp_disconnect_rfcomm){
383         hsp_disconnect_rfcomm = 0;
384         hsp_establish_audio_connection = 0;
385         rfcomm_disconnect(rfcomm_cid);
386         return;
387     }
388 
389     if (hsp_establish_audio_connection){
390         if (!rfcomm_can_send_packet_now(rfcomm_cid)) {
391             rfcomm_request_can_send_now_event(rfcomm_cid);
392             return;
393         }
394         hsp_establish_audio_connection = 0;
395         wait_ok = 1;
396         hsp_hs_send_str_over_rfcomm(rfcomm_cid, HSP_HS_AT_CKPD);
397         return;
398     }
399 
400     if (hs_send_button_press){
401         if (!rfcomm_can_send_packet_now(rfcomm_cid)) {
402             rfcomm_request_can_send_now_event(rfcomm_cid);
403             return;
404         }
405         hs_send_button_press = 0;
406         wait_ok = 1;
407         hsp_hs_send_str_over_rfcomm(rfcomm_cid, HSP_HS_AT_CKPD);
408         return;
409     }
410 
411     switch (hsp_state){
412         case HSP_SDP_QUERY_RFCOMM_CHANNEL:
413             hsp_state = HSP_W4_SDP_QUERY_COMPLETE;
414             sdp_client_query_rfcomm_channel_and_name_for_uuid(&handle_query_rfcomm_event, remote, BLUETOOTH_SERVICE_CLASS_HEADSET_AUDIO_GATEWAY_AG);
415             break;
416 
417         case HSP_AUDIO_CONNECTION_ESTABLISHED:
418         case HSP_RFCOMM_CONNECTION_ESTABLISHED:
419 
420             if (hs_microphone_gain >= 0){
421                 if (!rfcomm_can_send_packet_now(rfcomm_cid)) {
422                     rfcomm_request_can_send_now_event(rfcomm_cid);
423                     return;
424                 }
425                 char buffer[20];
426                 sprintf(buffer, "%s=%d\r\n", HSP_HS_MICROPHONE_GAIN, hs_microphone_gain);
427                 hsp_hs_send_str_over_rfcomm(rfcomm_cid, buffer);
428                 hs_microphone_gain = -1;
429                 break;
430             }
431 
432             if (hs_speaker_gain >= 0){
433                 if (!rfcomm_can_send_packet_now(rfcomm_cid)) {
434                     rfcomm_request_can_send_now_event(rfcomm_cid);
435                     return;
436                 }
437                 char buffer[20];
438                 sprintf(buffer, "%s=%d\r\n", HSP_HS_SPEAKER_GAIN, hs_speaker_gain);
439                 hsp_hs_send_str_over_rfcomm(rfcomm_cid, buffer);
440                 hs_speaker_gain = -1;
441                 break;
442             }
443             break;
444         case HSP_W4_RFCOMM_DISCONNECTED:
445             rfcomm_disconnect(rfcomm_cid);
446             break;
447         default:
448             break;
449     }
450 }
451 
452 
453 static void packet_handler (uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
454     UNUSED(channel);    // ok: no channel for HCI_EVENT_PACKET and only single active RFCOMM channel
455 
456     // printf("packet_handler type %u, packet[0] %x\n", packet_type, packet[0]);
457     if (packet_type == RFCOMM_DATA_PACKET){
458         // skip over leading newline
459         while (size > 0 && (packet[0] == '\n' || packet[0] == '\r')){
460             size--;
461             packet++;
462         }
463         if (strncmp((char *)packet, HSP_AG_RING, strlen(HSP_AG_RING)) == 0){
464             emit_ring_event();
465         } else if (strncmp((char *)packet, HSP_AG_OK, strlen(HSP_AG_OK)) == 0){
466            wait_ok = 0;
467         } else if (strncmp((char *)packet, HSP_MICROPHONE_GAIN, strlen(HSP_MICROPHONE_GAIN)) == 0){
468             uint8_t gain = (uint8_t)btstack_atoi((char*)&packet[strlen(HSP_MICROPHONE_GAIN)]);
469             emit_event(HSP_SUBEVENT_MICROPHONE_GAIN_CHANGED, gain);
470 
471         } else if (strncmp((char *)packet, HSP_SPEAKER_GAIN, strlen(HSP_SPEAKER_GAIN)) == 0){
472             uint8_t gain = (uint8_t)btstack_atoi((char*)&packet[strlen(HSP_SPEAKER_GAIN)]);
473             emit_event(HSP_SUBEVENT_SPEAKER_GAIN_CHANGED, gain);
474         } else {
475             if (!hsp_hs_callback) return;
476             // strip trailing newline
477             while (size > 0 && (packet[size-1] == '\n' || packet[size-1] == '\r')){
478                 size--;
479             }
480             // add trailing \0
481             packet[size] = 0;
482             // re-use incoming buffer to avoid reserving large buffers - ugly but efficient
483             uint8_t * event = packet - 4;
484             event[0] = HCI_EVENT_HSP_META;
485             event[1] = size + 2;
486             event[2] = HSP_SUBEVENT_AG_INDICATION;
487             event[3] = size;
488             (*hsp_hs_callback)(HCI_EVENT_PACKET, 0, event, size+4);
489         }
490         hsp_run();
491         return;
492     }
493 
494     if (packet_type != HCI_EVENT_PACKET) return;
495     uint8_t event = hci_event_packet_get_type(packet);
496     bd_addr_t event_addr;
497     uint16_t handle;
498 
499     switch (event) {
500         case HCI_EVENT_SYNCHRONOUS_CONNECTION_COMPLETE:{
501             if (hsp_state < HSP_RFCOMM_CONNECTION_ESTABLISHED) return;
502             int index = 2;
503             uint8_t status = packet[index++];
504             sco_handle = little_endian_read_16(packet, index);
505             index+=2;
506             bd_addr_t address;
507             memcpy(address, &packet[index], 6);
508             index+=6;
509             uint8_t link_type = packet[index++];
510             uint8_t transmission_interval = packet[index++];  // measured in slots
511             uint8_t retransmission_interval = packet[index++];// measured in slots
512             uint16_t rx_packet_length = little_endian_read_16(packet, index); // measured in bytes
513             index+=2;
514             uint16_t tx_packet_length = little_endian_read_16(packet, index); // measured in bytes
515             index+=2;
516             uint8_t air_mode = packet[index];
517 
518             if (status != 0){
519                 log_error("(e)SCO Connection failed, status %u", status);
520                 emit_event_audio_connected(status, sco_handle);
521                 hsp_state = HSP_RFCOMM_CONNECTION_ESTABLISHED ;
522                 break;
523             }
524 
525             switch (link_type){
526                 case 0x00:
527                     log_info("SCO Connection established.");
528                     if (transmission_interval != 0) log_error("SCO Connection: transmission_interval not zero: %d.", transmission_interval);
529                     if (retransmission_interval != 0) log_error("SCO Connection: retransmission_interval not zero: %d.", retransmission_interval);
530                     if (rx_packet_length != 0) log_error("SCO Connection: rx_packet_length not zero: %d.", rx_packet_length);
531                     if (tx_packet_length != 0) log_error("SCO Connection: tx_packet_length not zero: %d.", tx_packet_length);
532                     break;
533                 case 0x02:
534                     log_info("eSCO Connection established.");
535                     break;
536                 default:
537                     log_error("(e)SCO reserved link_type 0x%2x", link_type);
538                     break;
539             }
540             log_info("sco_handle 0x%2x, address %s, transmission_interval %u slots, retransmission_interval %u slots, "
541                  " rx_packet_length %u bytes, tx_packet_length %u bytes, air_mode 0x%2x (0x02 == CVSD)", sco_handle,
542                  bd_addr_to_str(address), transmission_interval, retransmission_interval, rx_packet_length, tx_packet_length, air_mode);
543 
544             hsp_state = HSP_AUDIO_CONNECTION_ESTABLISHED;
545             emit_event_audio_connected(status, sco_handle);
546             break;
547         }
548 
549         case RFCOMM_EVENT_INCOMING_CONNECTION:
550             // data: event (8), len(8), address(48), channel (8), rfcomm_cid (16)
551             if (hsp_state != HSP_IDLE) return;
552 
553             reverse_bd_addr(&packet[2], event_addr);
554             rfcomm_cid = little_endian_read_16(packet, 9);
555             log_info("RFCOMM channel %u requested for %s", packet[8], bd_addr_to_str(event_addr));
556             hsp_state = HSP_W4_RFCOMM_CONNECTED;
557             rfcomm_accept_connection(rfcomm_cid);
558             break;
559 
560         case RFCOMM_EVENT_CHANNEL_OPENED:
561             // printf("RFCOMM_EVENT_CHANNEL_OPENED packet_handler type %u, packet[0] %x\n", packet_type, packet[0]);
562             // data: event(8), len(8), status (8), address (48), handle(16), server channel(8), rfcomm_cid(16), max frame size(16)
563             if (hsp_state != HSP_W4_RFCOMM_CONNECTED) return;
564             if (packet[2]) {
565                 log_info("RFCOMM channel open failed, status %u", packet[2]);
566                 hsp_state = HSP_IDLE;
567                 hsp_hs_reset_state();
568             } else {
569                 // data: event(8) , len(8), status (8), address (48), handle (16), server channel(8), rfcomm_cid(16), max frame size(16)
570                 rfcomm_handle = little_endian_read_16(packet, 9);
571                 rfcomm_cid = little_endian_read_16(packet, 12);
572                 mtu = little_endian_read_16(packet, 14);
573                 log_info("RFCOMM channel open succeeded. New RFCOMM Channel ID %u, max frame size %u, handle %02x", rfcomm_cid, mtu, rfcomm_handle);
574                 hsp_state = HSP_RFCOMM_CONNECTION_ESTABLISHED;
575             }
576             emit_event(HSP_SUBEVENT_RFCOMM_CONNECTION_COMPLETE, packet[2]);
577             break;
578 
579         case RFCOMM_EVENT_CAN_SEND_NOW:
580             hsp_run();
581             break;
582 
583         case HCI_EVENT_DISCONNECTION_COMPLETE:
584             handle = little_endian_read_16(packet,3);
585             if (handle == sco_handle){
586                 sco_handle = 0;
587                 hsp_state = HSP_RFCOMM_CONNECTION_ESTABLISHED;
588                 emit_event(HSP_SUBEVENT_AUDIO_DISCONNECTION_COMPLETE,0);
589                 break;
590             }
591             if (handle == rfcomm_handle) {
592                 rfcomm_handle = 0;
593                 hsp_state = HSP_IDLE;
594                 emit_event(HSP_SUBEVENT_RFCOMM_DISCONNECTION_COMPLETE,0);
595                 hsp_hs_reset_state();
596             }
597             break;
598 
599         case RFCOMM_EVENT_CHANNEL_CLOSED:
600             hsp_hs_reset_state();
601             hsp_hs_callback(HCI_EVENT_PACKET, 0, packet, size);
602             break;
603 
604         default:
605             break;
606     }
607 
608     hsp_run();
609 }
610 
611 static void handle_query_rfcomm_event(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
612     UNUSED(packet_type);    // ok: handling own sdp events
613     UNUSED(channel);        // ok: no channel
614     UNUSED(size);           // ok: handling own sdp events
615 
616     switch (hci_event_packet_get_type(packet)){
617         case SDP_EVENT_QUERY_RFCOMM_SERVICE:
618             channel_nr = sdp_event_query_rfcomm_service_get_rfcomm_channel(packet);
619             log_info("** Service name: '%s', RFCOMM port %u", sdp_event_query_rfcomm_service_get_name(packet), channel_nr);
620             break;
621         case SDP_EVENT_QUERY_COMPLETE:
622             if (channel_nr > 0){
623                 hsp_state = HSP_W4_RFCOMM_CONNECTED;
624                 log_info("HSP: SDP_QUERY_COMPLETE. RFCOMM create channel, addr %s, rfcomm channel nr %d", bd_addr_to_str(remote), channel_nr);
625                 rfcomm_create_channel(packet_handler, remote, channel_nr, NULL);
626                 break;
627             }
628             hsp_hs_reset_state();
629             log_info("Service not found, status %u.", sdp_event_query_complete_get_status(packet));
630             if (sdp_event_query_complete_get_status(packet)){
631                 emit_event(HSP_SUBEVENT_AUDIO_CONNECTION_COMPLETE, sdp_event_query_complete_get_status(packet));
632             } else {
633                 emit_event(HSP_SUBEVENT_AUDIO_CONNECTION_COMPLETE, SDP_SERVICE_NOT_FOUND);
634             }
635             break;
636     }
637 }
638 
639 void hsp_hs_send_button_press(void){
640     if (hsp_state < HSP_RFCOMM_CONNECTION_ESTABLISHED || hsp_state >= HSP_W4_RFCOMM_DISCONNECTED) return;
641     hs_send_button_press = 1;
642     hsp_run();
643 }
644