xref: /btstack/src/classic/rfcomm.c (revision 2e98e94777c5c47163576922d6cfcab3956af8f5)
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__ "rfcomm.c"
39 
40 /*
41  *  rfcomm.c
42  */
43 
44 #include <stdio.h>
45 #include <stdlib.h>
46 #include <string.h> // memcpy
47 #include <stdint.h>
48 
49 #include "bluetooth_sdp.h"
50 #include "btstack_debug.h"
51 #include "btstack_event.h"
52 #include "btstack_memory.h"
53 #include "btstack_util.h"
54 #include "classic/core.h"
55 #include "classic/rfcomm.h"
56 #include "hci.h"
57 #include "hci_cmd.h"
58 #include "hci_dump.h"
59 #include "l2cap.h"
60 
61 // workaround for missing PRIxPTR on mspgcc (16/20-bit MCU)
62 #ifndef PRIxPTR
63 #if defined(__MSP430X__)  &&  defined(__MSP430X_LARGE__)
64 #define PRIxPTR "lx"
65 #else
66 #define PRIxPTR "x"
67 #endif
68 #endif
69 
70 #define RFCOMM_MULIPLEXER_TIMEOUT_MS 60000
71 
72 #define RFCOMM_CREDITS 10
73 
74 // FCS calc
75 #define BT_RFCOMM_CODE_WORD         0xE0 // pol = x8+x2+x1+1
76 #define BT_RFCOMM_CRC_CHECK_LEN     3
77 #define BT_RFCOMM_UIHCRC_CHECK_LEN  2
78 
79 
80 typedef enum {
81     CH_EVT_RCVD_SABM = 1,
82     CH_EVT_RCVD_UA,
83     CH_EVT_RCVD_PN,
84     CH_EVT_RCVD_PN_RSP,
85     CH_EVT_RCVD_DISC,
86     CH_EVT_RCVD_DM,
87     CH_EVT_RCVD_MSC_CMD,
88     CH_EVT_RCVD_MSC_RSP,
89     CH_EVT_RCVD_NSC_RSP,
90     CH_EVT_RCVD_RLS_CMD,
91     CH_EVT_RCVD_RLS_RSP,
92     CH_EVT_RCVD_RPN_CMD,
93     CH_EVT_RCVD_RPN_REQ,
94     CH_EVT_RCVD_CREDITS,
95     CH_EVT_MULTIPLEXER_READY,
96     CH_EVT_READY_TO_SEND,
97 } RFCOMM_CHANNEL_EVENT;
98 
99 typedef struct rfcomm_channel_event {
100     RFCOMM_CHANNEL_EVENT type;
101     uint16_t dummy; // force rfcomm_channel_event to be 2-byte aligned -> avoid -Wcast-align warning
102 } rfcomm_channel_event_t;
103 
104 typedef struct rfcomm_channel_event_pn {
105     rfcomm_channel_event_t super;
106     uint16_t max_frame_size;
107     uint8_t  priority;
108     uint8_t  credits_outgoing;
109 } rfcomm_channel_event_pn_t;
110 
111 typedef struct rfcomm_channel_event_rpn {
112     rfcomm_channel_event_t super;
113     rfcomm_rpn_data_t data;
114 } rfcomm_channel_event_rpn_t;
115 
116 typedef struct rfcomm_channel_event_rls {
117     rfcomm_channel_event_t super;
118     uint8_t line_status;
119 } rfcomm_channel_event_rls_t;
120 
121 typedef struct rfcomm_channel_event_msc {
122     rfcomm_channel_event_t super;
123     uint8_t modem_status;
124 } rfcomm_channel_event_msc_t;
125 
126 
127 // global rfcomm data
128 static uint16_t      rfcomm_client_cid_generator;  // used for client channel IDs
129 
130 // linked lists for all
131 static btstack_linked_list_t rfcomm_multiplexers = NULL;
132 static btstack_linked_list_t rfcomm_channels = NULL;
133 static btstack_linked_list_t rfcomm_services = NULL;
134 
135 static gap_security_level_t rfcomm_security_level;
136 
137 #if defined(ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE) && defined(ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE_FOR_RFCOMM)
138 #define RFCOMM_USE_OUTGOING_BUFFER
139 #endif
140 
141 #ifdef RFCOMM_USE_OUTGOING_BUFFER
142 static uint8_t outgoing_buffer[1030];
143 #endif
144 
145 static int  rfcomm_channel_can_send(rfcomm_channel_t * channel);
146 static int  rfcomm_channel_ready_for_open(rfcomm_channel_t *channel);
147 static int rfcomm_channel_ready_to_send(rfcomm_channel_t * channel);
148 static void rfcomm_channel_state_machine_with_channel(rfcomm_channel_t *channel, const rfcomm_channel_event_t *event, int * out_channel_valid);
149 static void rfcomm_channel_state_machine_with_dlci(rfcomm_multiplexer_t * multiplexer, uint8_t dlci, const rfcomm_channel_event_t *event);
150 static void rfcomm_emit_can_send_now(rfcomm_channel_t *channel);
151 static int rfcomm_multiplexer_ready_to_send(rfcomm_multiplexer_t * multiplexer);
152 static void rfcomm_multiplexer_state_machine(rfcomm_multiplexer_t * multiplexer, RFCOMM_MULTIPLEXER_EVENT event);
153 
154 // MARK: RFCOMM CLIENT EVENTS
155 
156 // data: event (8), len(8), address(48), channel (8), rfcomm_cid (16)
157 static void rfcomm_emit_connection_request(rfcomm_channel_t *channel) {
158     log_info("RFCOMM_EVENT_INCOMING_CONNECTION addr %s channel #%u cid 0x%02x",
159              bd_addr_to_str(channel->multiplexer->remote_addr), channel->dlci>>1, channel->rfcomm_cid);
160     uint8_t event[11];
161     event[0] = RFCOMM_EVENT_INCOMING_CONNECTION;
162     event[1] = sizeof(event) - 2;
163     reverse_bd_addr(channel->multiplexer->remote_addr, &event[2]);
164     event[8] = channel->dlci >> 1;
165     little_endian_store_16(event, 9, channel->rfcomm_cid);
166     hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event));
167 	(channel->packet_handler)(HCI_EVENT_PACKET, 0, event, sizeof(event));
168 }
169 
170 // API Change: BTstack-0.3.50x uses
171 // data: event(8), len(8), status (8), address (48), server channel(8), rfcomm_cid(16), max frame size(16)
172 // next Cydia release will use SVN version of this
173 // data: event(8), len(8), status (8), address (48), handle (16), server channel(8), rfcomm_cid(16), max frame size(16)
174 static void rfcomm_emit_channel_opened(rfcomm_channel_t *channel, uint8_t status) {
175     log_info("RFCOMM_EVENT_CHANNEL_OPENED status 0x%x addr %s handle 0x%x channel #%u cid 0x%02x mtu %u",
176              status, bd_addr_to_str(channel->multiplexer->remote_addr), channel->multiplexer->con_handle,
177              channel->dlci>>1, channel->rfcomm_cid, channel->max_frame_size);
178     uint8_t event[18];
179     uint8_t pos = 0;
180     event[pos++] = RFCOMM_EVENT_CHANNEL_OPENED;  // 0
181     event[pos++] = sizeof(event) - 2;                   // 1
182     event[pos++] = status;                              // 2
183     reverse_bd_addr(channel->multiplexer->remote_addr, &event[pos]); pos += 6; // 3
184     little_endian_store_16(event,  pos, channel->multiplexer->con_handle);   pos += 2; // 9
185 	event[pos++] = channel->dlci >> 1;                                      // 11
186 	little_endian_store_16(event, pos, channel->rfcomm_cid); pos += 2;                 // 12 - channel ID
187 	little_endian_store_16(event, pos, channel->max_frame_size); pos += 2;   // max frame size
188     event[pos++] = channel->service ? 1 : 0;    // linked to service -> incoming
189     hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event));
190 	(channel->packet_handler)(HCI_EVENT_PACKET, 0, event, pos);
191 
192     // if channel opened successfully, also send can send now if possible
193     if (status) return;
194     if (rfcomm_channel_can_send(channel)){
195         rfcomm_emit_can_send_now(channel);
196     }
197 }
198 
199 // data: event(8), len(8), rfcomm_cid(16)
200 static void rfcomm_emit_channel_closed(rfcomm_channel_t * channel) {
201     log_info("RFCOMM_EVENT_CHANNEL_CLOSED cid 0x%02x", channel->rfcomm_cid);
202     uint8_t event[4];
203     event[0] = RFCOMM_EVENT_CHANNEL_CLOSED;
204     event[1] = sizeof(event) - 2;
205     little_endian_store_16(event, 2, channel->rfcomm_cid);
206     hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event));
207 	(channel->packet_handler)(HCI_EVENT_PACKET, 0, event, sizeof(event));
208 }
209 
210 static void rfcomm_emit_remote_line_status(rfcomm_channel_t *channel, uint8_t line_status){
211     log_info("RFCOMM_EVENT_REMOTE_LINE_STATUS cid 0x%02x c, line status 0x%x", channel->rfcomm_cid, line_status);
212     uint8_t event[5];
213     event[0] = RFCOMM_EVENT_REMOTE_LINE_STATUS;
214     event[1] = sizeof(event) - 2;
215     little_endian_store_16(event, 2, channel->rfcomm_cid);
216     event[4] = line_status;
217     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
218     (channel->packet_handler)(HCI_EVENT_PACKET, 0, event, sizeof(event));
219 }
220 
221 static void rfcomm_emit_port_configuration(rfcomm_channel_t *channel){
222     // notify client about new settings
223     uint8_t event[2+sizeof(rfcomm_rpn_data_t)];
224     event[0] = RFCOMM_EVENT_PORT_CONFIGURATION;
225     event[1] = sizeof(rfcomm_rpn_data_t);
226     memcpy(&event[2], (uint8_t*) &channel->rpn_data, sizeof(rfcomm_rpn_data_t));
227     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
228     (channel->packet_handler)(HCI_EVENT_PACKET, channel->rfcomm_cid, event, sizeof(event));
229 }
230 
231 static void rfcomm_emit_can_send_now(rfcomm_channel_t *channel) {
232     log_debug("RFCOMM_EVENT_CHANNEL_CAN_SEND_NOW local_cid 0x%x", channel->rfcomm_cid);
233     uint8_t event[4];
234     event[0] = RFCOMM_EVENT_CAN_SEND_NOW;
235     event[1] = sizeof(event) - 2;
236     little_endian_store_16(event, 2, channel->rfcomm_cid);
237     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
238     (channel->packet_handler)(HCI_EVENT_PACKET, channel->rfcomm_cid, event, sizeof(event));
239 }
240 
241 // MARK RFCOMM RPN DATA HELPER
242 static void rfcomm_rpn_data_set_defaults(rfcomm_rpn_data_t * rpn_data){
243         rpn_data->baud_rate = RPN_BAUD_9600;  /* 9600 bps */
244         rpn_data->flags = 0x03;               /* 8-n-1 */
245         rpn_data->flow_control = 0;           /* no flow control */
246         rpn_data->xon  = 0xd1;                /* XON */
247         rpn_data->xoff = 0xd3;                /* XOFF */
248         rpn_data->parameter_mask_0 = 0x7f;    /* parameter mask, all values set */
249         rpn_data->parameter_mask_1 = 0x3f;    /* parameter mask, all values set */
250 }
251 
252 static void rfcomm_rpn_data_update(rfcomm_rpn_data_t * dest, rfcomm_rpn_data_t * src){
253     if (src->parameter_mask_0 & RPN_PARAM_MASK_0_BAUD){
254         dest->baud_rate = src->baud_rate;
255     }
256     if (src->parameter_mask_0 & RPN_PARAM_MASK_0_DATA_BITS){
257         dest->flags = (dest->flags & 0xfc) | (src->flags & 0x03);
258     }
259     if (src->parameter_mask_0 & RPN_PARAM_MASK_0_STOP_BITS){
260         dest->flags = (dest->flags & 0xfb) | (src->flags & 0x04);
261     }
262     if (src->parameter_mask_0 & RPN_PARAM_MASK_0_PARITY){
263         dest->flags = (dest->flags & 0xf7) | (src->flags & 0x08);
264     }
265     if (src->parameter_mask_0 & RPN_PARAM_MASK_0_PARITY_TYPE){
266         dest->flags = (dest->flags & 0xfc) | (src->flags & 0x30);
267     }
268     if (src->parameter_mask_0 & RPN_PARAM_MASK_0_XON_CHAR){
269         dest->xon = src->xon;
270     }
271     if (src->parameter_mask_0 & RPN_PARAM_MASK_0_XOFF_CHAR){
272         dest->xoff = src->xoff;
273     }
274     int i;
275     for (i=0; i < 6 ; i++){
276         uint8_t mask = 1 << i;
277         if (src->parameter_mask_1 & mask){
278             dest->flags = (dest->flags & ~mask) | (src->flags & mask);
279         }
280     }
281     // always copy parameter mask, too. informative for client, needed for response
282     dest->parameter_mask_0 = src->parameter_mask_0;
283     dest->parameter_mask_1 = src->parameter_mask_1;
284 }
285 // MARK: RFCOMM MULTIPLEXER HELPER
286 
287 static uint16_t rfcomm_max_frame_size_for_l2cap_mtu(uint16_t l2cap_mtu){
288     // Assume RFCOMM header without credits and 2 byte (14 bit) length field
289     uint16_t max_frame_size = l2cap_mtu - 5;
290     log_info("rfcomm_max_frame_size_for_l2cap_mtu:  %u -> %u", l2cap_mtu, max_frame_size);
291     return max_frame_size;
292 }
293 
294 static void rfcomm_multiplexer_initialize(rfcomm_multiplexer_t *multiplexer){
295     multiplexer->state = RFCOMM_MULTIPLEXER_CLOSED;
296     multiplexer->fcon = 1;
297     multiplexer->send_dm_for_dlci = 0;
298     multiplexer->max_frame_size = rfcomm_max_frame_size_for_l2cap_mtu(l2cap_max_mtu());
299     multiplexer->test_data_len = 0;
300     multiplexer->nsc_command = 0;
301 }
302 
303 static rfcomm_multiplexer_t * rfcomm_multiplexer_create_for_addr(bd_addr_t addr){
304 
305     // alloc structure
306     rfcomm_multiplexer_t * multiplexer = btstack_memory_rfcomm_multiplexer_get();
307     if (!multiplexer) return NULL;
308 
309     // fill in
310     rfcomm_multiplexer_initialize(multiplexer);
311     bd_addr_copy(multiplexer->remote_addr, addr);
312 
313     // add to services list
314     btstack_linked_list_add(&rfcomm_multiplexers, (btstack_linked_item_t *) multiplexer);
315 
316     return multiplexer;
317 }
318 
319 static rfcomm_multiplexer_t * rfcomm_multiplexer_for_addr(bd_addr_t addr){
320     btstack_linked_item_t *it;
321     for (it = (btstack_linked_item_t *) rfcomm_multiplexers; it ; it = it->next){
322         rfcomm_multiplexer_t * multiplexer = ((rfcomm_multiplexer_t *) it);
323         // ignore multiplexer in shutdown
324         if (multiplexer->state == RFCOMM_MULTIPLEXER_SHUTTING_DOWN) continue;
325         if (bd_addr_cmp(addr, multiplexer->remote_addr) == 0) {
326             return multiplexer;
327         };
328     }
329     return NULL;
330 }
331 
332 static rfcomm_multiplexer_t * rfcomm_multiplexer_for_l2cap_cid(uint16_t l2cap_cid) {
333     btstack_linked_item_t *it;
334     for (it = (btstack_linked_item_t *) rfcomm_multiplexers; it ; it = it->next){
335         rfcomm_multiplexer_t * multiplexer = ((rfcomm_multiplexer_t *) it);
336         if (multiplexer->l2cap_cid == l2cap_cid) {
337             return multiplexer;
338         };
339     }
340     return NULL;
341 }
342 
343 static int rfcomm_multiplexer_has_channels(rfcomm_multiplexer_t * multiplexer){
344     btstack_linked_item_t *it;
345     for (it = (btstack_linked_item_t *) rfcomm_channels; it ; it = it->next){
346         rfcomm_channel_t * channel = ((rfcomm_channel_t *) it);
347         if (channel->multiplexer == multiplexer) {
348             return 1;
349         }
350     }
351     return 0;
352 }
353 
354 // MARK: RFCOMM CHANNEL HELPER
355 
356 static void rfcomm_dump_channels(void){
357     btstack_linked_item_t * it;
358     int channels = 0;
359     for (it = (btstack_linked_item_t *) rfcomm_channels; it ; it = it->next){
360         rfcomm_channel_t * channel = (rfcomm_channel_t *) it;
361         log_info("Channel #%u: addr %p, state %u", channels, channel, channel->state);
362         channels++;
363     }
364 }
365 
366 static void rfcomm_channel_initialize(rfcomm_channel_t *channel, rfcomm_multiplexer_t *multiplexer,
367                                rfcomm_service_t *service, uint8_t server_channel){
368 
369     // don't use 0 as channel id
370     if (rfcomm_client_cid_generator == 0) ++rfcomm_client_cid_generator;
371 
372     // set defaults for port configuration (even for services)
373     rfcomm_rpn_data_set_defaults(&channel->rpn_data);
374 
375     channel->state            = RFCOMM_CHANNEL_CLOSED;
376     channel->state_var        = RFCOMM_CHANNEL_STATE_VAR_NONE;
377 
378     channel->multiplexer      = multiplexer;
379     channel->rfcomm_cid       = rfcomm_client_cid_generator++;
380     channel->max_frame_size   = multiplexer->max_frame_size;
381 
382     channel->credits_incoming = 0;
383     channel->credits_outgoing = 0;
384 
385     // incoming flow control not active
386     channel->new_credits_incoming  = RFCOMM_CREDITS;
387     channel->incoming_flow_control = 0;
388 
389     channel->rls_line_status       = RFCOMM_RLS_STATUS_INVALID;
390 
391     channel->service = service;
392 	if (service) {
393 		// incoming connection
394     	channel->dlci = (server_channel << 1) |  multiplexer->outgoing;
395         if (channel->max_frame_size > service->max_frame_size) {
396             channel->max_frame_size = service->max_frame_size;
397         }
398         channel->incoming_flow_control = service->incoming_flow_control;
399         channel->new_credits_incoming  = service->incoming_initial_credits;
400         channel->packet_handler        = service->packet_handler;
401 	} else {
402 		// outgoing connection
403 		channel->dlci = (server_channel << 1) | (multiplexer->outgoing ^ 1);
404 	}
405 }
406 
407 // service == NULL -> outgoing channel
408 static rfcomm_channel_t * rfcomm_channel_create(rfcomm_multiplexer_t * multiplexer,
409                                                 rfcomm_service_t * service, uint8_t server_channel){
410 
411     log_info("rfcomm_channel_create for service %p, channel %u --- list of channels:", service, server_channel);
412     rfcomm_dump_channels();
413 
414     // alloc structure
415     rfcomm_channel_t * channel = btstack_memory_rfcomm_channel_get();
416     if (!channel) return NULL;
417 
418     // fill in
419     rfcomm_channel_initialize(channel, multiplexer, service, server_channel);
420 
421     // add to services list
422     btstack_linked_list_add(&rfcomm_channels, (btstack_linked_item_t *) channel);
423 
424     return channel;
425 }
426 
427 static void rfcomm_notify_channel_can_send(void){
428     btstack_linked_list_iterator_t it;
429     btstack_linked_list_iterator_init(&it, &rfcomm_channels);
430     while (btstack_linked_list_iterator_has_next(&it)){
431         rfcomm_channel_t * channel = (rfcomm_channel_t *) btstack_linked_list_iterator_next(&it);
432         if (!channel->waiting_for_can_send_now) continue; // didn't try to send yet
433         if (!rfcomm_channel_can_send(channel)) continue;  // or cannot yet either
434 
435         channel->waiting_for_can_send_now = 0;
436         rfcomm_emit_can_send_now(channel);
437     }
438 }
439 
440 static rfcomm_channel_t * rfcomm_channel_for_rfcomm_cid(uint16_t rfcomm_cid){
441     btstack_linked_item_t *it;
442     for (it = (btstack_linked_item_t *) rfcomm_channels; it ; it = it->next){
443         rfcomm_channel_t * channel = ((rfcomm_channel_t *) it);
444         if (channel->rfcomm_cid == rfcomm_cid) {
445             return channel;
446         };
447     }
448     return NULL;
449 }
450 
451 static rfcomm_channel_t * rfcomm_channel_for_multiplexer_and_dlci(rfcomm_multiplexer_t * multiplexer, uint8_t dlci){
452     btstack_linked_item_t *it;
453     for (it = (btstack_linked_item_t *) rfcomm_channels; it ; it = it->next){
454         rfcomm_channel_t * channel = ((rfcomm_channel_t *) it);
455         if (channel->dlci == dlci && channel->multiplexer == multiplexer) {
456             return channel;
457         };
458     }
459     return NULL;
460 }
461 
462 static rfcomm_service_t * rfcomm_service_for_channel(uint8_t server_channel){
463     btstack_linked_item_t *it;
464     for (it = (btstack_linked_item_t *) rfcomm_services; it ; it = it->next){
465         rfcomm_service_t * service = ((rfcomm_service_t *) it);
466         if ( service->server_channel == server_channel){
467             return service;
468         };
469     }
470     return NULL;
471 }
472 
473 // MARK: RFCOMM SEND
474 
475 /**
476  * @param credits - only used for RFCOMM flow control in UIH wiht P/F = 1
477  */
478 static int rfcomm_send_packet_for_multiplexer(rfcomm_multiplexer_t *multiplexer, uint8_t address, uint8_t control, uint8_t credits, uint8_t *data, uint16_t len){
479 
480     if (!l2cap_can_send_packet_now(multiplexer->l2cap_cid)) return BTSTACK_ACL_BUFFERS_FULL;
481 
482 #ifdef RFCOMM_USE_OUTGOING_BUFFER
483     uint8_t * rfcomm_out_buffer = outgoing_buffer;
484 #else
485     l2cap_reserve_packet_buffer();
486     uint8_t * rfcomm_out_buffer = l2cap_get_outgoing_buffer();
487 #endif
488 
489 	uint16_t pos = 0;
490 	uint8_t crc_fields = 3;
491 
492 	rfcomm_out_buffer[pos++] = address;
493 	rfcomm_out_buffer[pos++] = control;
494 
495 	// length field can be 1 or 2 octets
496 	if (len < 128){
497 		rfcomm_out_buffer[pos++] = (len << 1)| 1;     // bits 0-6
498 	} else {
499 		rfcomm_out_buffer[pos++] = (len & 0x7f) << 1; // bits 0-6
500 		rfcomm_out_buffer[pos++] = len >> 7;          // bits 7-14
501 		crc_fields++;
502 	}
503 
504 	// add credits for UIH frames when PF bit is set
505 	if (control == BT_RFCOMM_UIH_PF){
506 		rfcomm_out_buffer[pos++] = credits;
507 	}
508 
509 	// copy actual data
510 	if (len) {
511 		memcpy(&rfcomm_out_buffer[pos], data, len);
512 		pos += len;
513 	}
514 
515 	// UIH frames only calc FCS over address + control (5.1.1)
516 	if ((control & 0xef) == BT_RFCOMM_UIH){
517 		crc_fields = 2;
518 	}
519 	rfcomm_out_buffer[pos++] =  btstack_crc8_calc(rfcomm_out_buffer, crc_fields); // calc fcs
520 
521 #ifdef RFCOMM_USE_OUTGOING_BUFFER
522     int err = l2cap_send(multiplexer->l2cap_cid, rfcomm_out_buffer, pos);
523 #else
524     int err = l2cap_send_prepared(multiplexer->l2cap_cid, pos);
525 #endif
526 
527     return err;
528 }
529 
530 // simplified version of rfcomm_send_packet_for_multiplexer for prepared rfcomm packet (UIH, 2 byte len, no credits)
531 static int rfcomm_send_uih_prepared(rfcomm_multiplexer_t *multiplexer, uint8_t dlci, uint16_t len){
532 
533     uint8_t address = (1 << 0) | (multiplexer->outgoing << 1) | (dlci << 2);
534     uint8_t control = BT_RFCOMM_UIH;
535 
536 #ifdef RFCOMM_USE_OUTGOING_BUFFER
537     uint8_t * rfcomm_out_buffer = outgoing_buffer;
538 #else
539     uint8_t * rfcomm_out_buffer = l2cap_get_outgoing_buffer();
540 #endif
541 
542     uint16_t pos = 0;
543     rfcomm_out_buffer[pos++] = address;
544     rfcomm_out_buffer[pos++] = control;
545     rfcomm_out_buffer[pos++] = (len & 0x7f) << 1; // bits 0-6
546     rfcomm_out_buffer[pos++] = len >> 7;          // bits 7-14
547 
548     // actual data is already in place
549     pos += len;
550 
551     // UIH frames only calc FCS over address + control (5.1.1)
552     rfcomm_out_buffer[pos++] =  btstack_crc8_calc(rfcomm_out_buffer, 2); // calc fcs
553 
554 #ifdef RFCOMM_USE_OUTGOING_BUFFER
555     int err = l2cap_send(multiplexer->l2cap_cid, rfcomm_out_buffer, pos);
556 #else
557     int err = l2cap_send_prepared(multiplexer->l2cap_cid, pos);
558 #endif
559 
560     return err;
561 }
562 
563 // C/R Flag in Address
564 // - terms: initiator = station that creates multiplexer with SABM
565 // - terms: responder = station that responds to multiplexer setup with UA
566 // "For SABM, UA, DM and DISC frames C/R bit is set according to Table 1 in GSM 07.10, section 5.2.1.2"
567 //    - command initiator = 1 /response responder = 1
568 //    - command responder = 0 /response initiator = 0
569 // "For UIH frames, the C/R bit is always set according to section 5.4.3.1 in GSM 07.10.
570 //  This applies independently of what is contained wthin the UIH frames, either data or control messages."
571 //    - c/r = 1 for frames by initiating station, 0 = for frames by responding station
572 
573 // C/R Flag in Message
574 // "In the message level, the C/R bit in the command type field is set as stated in section 5.4.6.2 in GSM 07.10."
575 //   - If the C/R bit is set to 1 the message is a command
576 //   - if it is set to 0 the message is a response.
577 
578 // temp/old messge construction
579 
580 // new object oriented version
581 static int rfcomm_send_sabm(rfcomm_multiplexer_t *multiplexer, uint8_t dlci){
582 	uint8_t address = (1 << 0) | (multiplexer->outgoing << 1) | (dlci << 2);   // command
583     return rfcomm_send_packet_for_multiplexer(multiplexer, address, BT_RFCOMM_SABM, 0, NULL, 0);
584 }
585 
586 static int rfcomm_send_disc(rfcomm_multiplexer_t *multiplexer, uint8_t dlci){
587 	uint8_t address = (1 << 0) | (multiplexer->outgoing << 1) | (dlci << 2);  // command
588     return rfcomm_send_packet_for_multiplexer(multiplexer, address, BT_RFCOMM_DISC, 0, NULL, 0);
589 }
590 
591 static int rfcomm_send_ua(rfcomm_multiplexer_t *multiplexer, uint8_t dlci){
592 	uint8_t address = (1 << 0) | ((multiplexer->outgoing ^ 1) << 1) | (dlci << 2); // response
593     return rfcomm_send_packet_for_multiplexer(multiplexer, address, BT_RFCOMM_UA, 0, NULL, 0);
594 }
595 
596 static int rfcomm_send_dm_pf(rfcomm_multiplexer_t *multiplexer, uint8_t dlci){
597 	uint8_t address = (1 << 0) | ((multiplexer->outgoing ^ 1) << 1) | (dlci << 2); // response
598     return rfcomm_send_packet_for_multiplexer(multiplexer, address, BT_RFCOMM_DM_PF, 0, NULL, 0);
599 }
600 
601 static int rfcomm_send_uih_fc_rsp(rfcomm_multiplexer_t *multiplexer, uint8_t fcon) {
602     uint8_t address = (1 << 0) | (multiplexer->outgoing<< 1);
603     uint8_t payload[2];
604     uint8_t pos = 0;
605     payload[pos++] = fcon ? BT_RFCOMM_FCON_RSP : BT_RFCOMM_FCOFF_RSP;
606     payload[pos++] = (0 << 1) | 1;  // len
607     return rfcomm_send_packet_for_multiplexer(multiplexer, address, BT_RFCOMM_UIH, 0, (uint8_t *) payload, pos);
608 }
609 
610 // static int rfcomm_send_uih_test_cmd(rfcomm_multiplexer_t *multiplexer, uint8_t * data, uint16_t len) {
611 //     uint8_t address = (1 << 0) | (multiplexer->outgoing << 1);
612 //     uint8_t payload[2+len];
613 //     uint8_t pos = 0;
614 //     payload[pos++] = BT_RFCOMM_TEST_CMD;
615 //     payload[pos++] = (len + 1) << 1 | 1;  // len
616 //     memcpy(&payload[pos], data, len);
617 //     pos += len;
618 //     return rfcomm_send_packet_for_multiplexer(multiplexer, address, BT_RFCOMM_UIH, 0, (uint8_t *) payload, pos);
619 // }
620 
621 static int rfcomm_send_uih_test_rsp(rfcomm_multiplexer_t *multiplexer, uint8_t * data, uint16_t len) {
622     uint8_t address = (1 << 0) | (multiplexer->outgoing << 1);
623     uint8_t payload[2+RFCOMM_TEST_DATA_MAX_LEN];
624     uint8_t pos = 0;
625     payload[pos++] = BT_RFCOMM_TEST_RSP;
626     if (len > RFCOMM_TEST_DATA_MAX_LEN) {
627         len = RFCOMM_TEST_DATA_MAX_LEN;
628     }
629     payload[pos++] = (len << 1) | 1;  // len
630     memcpy(&payload[pos], data, len);
631     pos += len;
632     return rfcomm_send_packet_for_multiplexer(multiplexer, address, BT_RFCOMM_UIH, 0, (uint8_t *) payload, pos);
633 }
634 
635 static int rfcomm_send_uih_msc_cmd(rfcomm_multiplexer_t *multiplexer, uint8_t dlci, uint8_t signals) {
636 	uint8_t address = (1 << 0) | (multiplexer->outgoing << 1);
637 	uint8_t payload[4];
638 	uint8_t pos = 0;
639 	payload[pos++] = BT_RFCOMM_MSC_CMD;
640 	payload[pos++] = (2 << 1) | 1;  // len
641 	payload[pos++] = (1 << 0) | (1 << 1) | (dlci << 2); // CMD => C/R = 1
642 	payload[pos++] = signals;
643 	return rfcomm_send_packet_for_multiplexer(multiplexer, address, BT_RFCOMM_UIH, 0, (uint8_t *) payload, pos);
644 }
645 
646 static int rfcomm_send_uih_msc_rsp(rfcomm_multiplexer_t *multiplexer, uint8_t dlci, uint8_t signals) {
647 	uint8_t address = (1 << 0) | (multiplexer->outgoing<< 1);
648 	uint8_t payload[4];
649 	uint8_t pos = 0;
650 	payload[pos++] = BT_RFCOMM_MSC_RSP;
651 	payload[pos++] = (2 << 1) | 1;  // len
652 	payload[pos++] = (1 << 0) | (1 << 1) | (dlci << 2); // CMD => C/R = 1
653 	payload[pos++] = signals;
654 	return rfcomm_send_packet_for_multiplexer(multiplexer, address, BT_RFCOMM_UIH, 0, (uint8_t *) payload, pos);
655 }
656 
657 static int rfcomm_send_uih_nsc_rsp(rfcomm_multiplexer_t *multiplexer, uint8_t command) {
658     uint8_t address = (1 << 0) | (multiplexer->outgoing<< 1);
659     uint8_t payload[3];
660     uint8_t pos = 0;
661     payload[pos++] = BT_RFCOMM_NSC_RSP;
662     payload[pos++] = (1 << 1) | 1;  // len
663     payload[pos++] = command;
664     return rfcomm_send_packet_for_multiplexer(multiplexer, address, BT_RFCOMM_UIH, 0, (uint8_t *) payload, pos);
665 }
666 
667 static int rfcomm_send_uih_pn_command(rfcomm_multiplexer_t *multiplexer, uint8_t dlci, uint16_t max_frame_size){
668 	uint8_t payload[10];
669 	uint8_t address = (1 << 0) | (multiplexer->outgoing << 1);
670 	uint8_t pos = 0;
671 	payload[pos++] = BT_RFCOMM_PN_CMD;
672 	payload[pos++] = (8 << 1) | 1;  // len
673 	payload[pos++] = dlci;
674 	payload[pos++] = 0xf0; // pre-defined for Bluetooth, see 5.5.3 of TS 07.10 Adaption for RFCOMM
675 	payload[pos++] = 0; // priority
676 	payload[pos++] = 0; // max 60 seconds ack
677 	payload[pos++] = max_frame_size & 0xff; // max framesize low
678 	payload[pos++] = max_frame_size >> 8;   // max framesize high
679 	payload[pos++] = 0x00; // number of retransmissions
680 	payload[pos++] = 0x00; // (unused error recovery window) initial number of credits
681 	return rfcomm_send_packet_for_multiplexer(multiplexer, address, BT_RFCOMM_UIH, 0, (uint8_t *) payload, pos);
682 }
683 
684 // "The response may not change the DLCI, the priority, the convergence layer, or the timer value." rfcomm_tutorial.pdf
685 static int rfcomm_send_uih_pn_response(rfcomm_multiplexer_t *multiplexer, uint8_t dlci,
686                                        uint8_t priority, uint16_t max_frame_size){
687 	uint8_t payload[10];
688 	uint8_t address = (1 << 0) | (multiplexer->outgoing << 1);
689 	uint8_t pos = 0;
690 	payload[pos++] = BT_RFCOMM_PN_RSP;
691 	payload[pos++] = (8 << 1) | 1;  // len
692 	payload[pos++] = dlci;
693 	payload[pos++] = 0xe0; // pre defined for Bluetooth, see 5.5.3 of TS 07.10 Adaption for RFCOMM
694 	payload[pos++] = priority; // priority
695 	payload[pos++] = 0; // max 60 seconds ack
696 	payload[pos++] = max_frame_size & 0xff; // max framesize low
697 	payload[pos++] = max_frame_size >> 8;   // max framesize high
698 	payload[pos++] = 0x00; // number of retransmissions
699 	payload[pos++] = 0x00; // (unused error recovery window) initial number of credits
700 	return rfcomm_send_packet_for_multiplexer(multiplexer, address, BT_RFCOMM_UIH, 0, (uint8_t *) payload, pos);
701 }
702 
703 static int rfcomm_send_uih_rls_cmd(rfcomm_multiplexer_t *multiplexer, uint8_t dlci, uint8_t line_status) {
704     uint8_t address = (1 << 0) | (multiplexer->outgoing << 1);
705     uint8_t payload[4];
706     uint8_t pos = 0;
707     payload[pos++] = BT_RFCOMM_RLS_CMD;
708     payload[pos++] = (2 << 1) | 1;  // len
709     payload[pos++] = (1 << 0) | (1 << 1) | (dlci << 2); // CMD => C/R = 1
710     payload[pos++] = line_status;
711     return rfcomm_send_packet_for_multiplexer(multiplexer, address, BT_RFCOMM_UIH, 0, (uint8_t *) payload, pos);
712 }
713 
714 static int rfcomm_send_uih_rls_rsp(rfcomm_multiplexer_t *multiplexer, uint8_t dlci, uint8_t line_status) {
715     uint8_t address = (1 << 0) | (multiplexer->outgoing << 1);
716     uint8_t payload[4];
717     uint8_t pos = 0;
718     payload[pos++] = BT_RFCOMM_RLS_RSP;
719     payload[pos++] = (2 << 1) | 1;  // len
720     payload[pos++] = (1 << 0) | (1 << 1) | (dlci << 2); // CMD => C/R = 1
721     payload[pos++] = line_status;
722     return rfcomm_send_packet_for_multiplexer(multiplexer, address, BT_RFCOMM_UIH, 0, (uint8_t *) payload, pos);
723 }
724 
725 static int rfcomm_send_uih_rpn_cmd(rfcomm_multiplexer_t *multiplexer, uint8_t dlci, rfcomm_rpn_data_t *rpn_data) {
726     uint8_t payload[10];
727     uint8_t address = (1 << 0) | (multiplexer->outgoing << 1);
728     uint8_t pos = 0;
729     payload[pos++] = BT_RFCOMM_RPN_CMD;
730     payload[pos++] = (8 << 1) | 1;  // len
731     payload[pos++] = (1 << 0) | (1 << 1) | (dlci << 2); // CMD => C/R = 1
732     payload[pos++] = rpn_data->baud_rate;
733     payload[pos++] = rpn_data->flags;
734     payload[pos++] = rpn_data->flow_control;
735     payload[pos++] = rpn_data->xon;
736     payload[pos++] = rpn_data->xoff;
737     payload[pos++] = rpn_data->parameter_mask_0;
738     payload[pos++] = rpn_data->parameter_mask_1;
739     return rfcomm_send_packet_for_multiplexer(multiplexer, address, BT_RFCOMM_UIH, 0, (uint8_t *) payload, pos);
740 }
741 
742 static int rfcomm_send_uih_rpn_req(rfcomm_multiplexer_t *multiplexer, uint8_t dlci) {
743     uint8_t payload[3];
744     uint8_t address = (1 << 0) | (multiplexer->outgoing << 1);
745     uint8_t pos = 0;
746     payload[pos++] = BT_RFCOMM_RPN_CMD;
747     payload[pos++] = (1 << 1) | 1;  // len
748     payload[pos++] = (1 << 0) | (1 << 1) | (dlci << 2); // CMD => C/R = 1
749     return rfcomm_send_packet_for_multiplexer(multiplexer, address, BT_RFCOMM_UIH, 0, (uint8_t *) payload, pos);
750 }
751 
752 static int rfcomm_send_uih_rpn_rsp(rfcomm_multiplexer_t *multiplexer, uint8_t dlci, rfcomm_rpn_data_t *rpn_data) {
753 	uint8_t payload[10];
754 	uint8_t address = (1 << 0) | (multiplexer->outgoing << 1);
755 	uint8_t pos = 0;
756 	payload[pos++] = BT_RFCOMM_RPN_RSP;
757 	payload[pos++] = (8 << 1) | 1;  // len
758 	payload[pos++] = (1 << 0) | (1 << 1) | (dlci << 2); // CMD => C/R = 1
759 	payload[pos++] = rpn_data->baud_rate;
760 	payload[pos++] = rpn_data->flags;
761 	payload[pos++] = rpn_data->flow_control;
762 	payload[pos++] = rpn_data->xon;
763 	payload[pos++] = rpn_data->xoff;
764 	payload[pos++] = rpn_data->parameter_mask_0;
765 	payload[pos++] = rpn_data->parameter_mask_1;
766 	return rfcomm_send_packet_for_multiplexer(multiplexer, address, BT_RFCOMM_UIH, 0, (uint8_t *) payload, pos);
767 }
768 
769 static void rfcomm_send_uih_credits(rfcomm_multiplexer_t *multiplexer, uint8_t dlci,  uint8_t credits){
770     uint8_t address = (1 << 0) | (multiplexer->outgoing << 1) |  (dlci << 2);
771     rfcomm_send_packet_for_multiplexer(multiplexer, address, BT_RFCOMM_UIH_PF, credits, NULL, 0);
772 }
773 
774 // depending on channel state emit channel opened with status or channel closed
775 static void rfcomm_channel_emit_final_event(rfcomm_channel_t * channel, uint8_t status){
776     // emit appropriate events
777     switch(channel->state){
778         case RFCOMM_CHANNEL_OPEN:
779         case RFCOMM_CHANNEL_W4_UA_AFTER_DISC:
780             rfcomm_emit_channel_closed(channel);
781             break;
782         case RFCOMM_CHANNEL_SEND_UA_AFTER_DISC:
783             // remote didn't wait until we send the UA disc
784             // close event already emitted
785             break;
786         default:
787             rfcomm_emit_channel_opened(channel, status);
788             break;
789     }
790 }
791 
792 // MARK: RFCOMM MULTIPLEXER
793 static void rfcomm_multiplexer_stop_timer(rfcomm_multiplexer_t * multiplexer){
794     if (multiplexer->timer_active) {
795         btstack_run_loop_remove_timer(&multiplexer->timer);
796         multiplexer->timer_active = 0;
797     }
798 }
799 static void rfcomm_multiplexer_free(rfcomm_multiplexer_t * multiplexer){
800     btstack_linked_list_remove( &rfcomm_multiplexers, (btstack_linked_item_t *) multiplexer);
801     btstack_memory_rfcomm_multiplexer_free(multiplexer);
802 }
803 
804 static void rfcomm_multiplexer_finalize(rfcomm_multiplexer_t * multiplexer){
805     // remove (potential) timer
806     rfcomm_multiplexer_stop_timer(multiplexer);
807 
808     // close and remove all channels
809     btstack_linked_item_t *it = (btstack_linked_item_t *) &rfcomm_channels;
810     while (it->next){
811         rfcomm_channel_t * channel = (rfcomm_channel_t *) it->next;
812         if (channel->multiplexer == multiplexer) {
813             // emit open with status or closed
814             rfcomm_channel_emit_final_event(channel, RFCOMM_MULTIPLEXER_STOPPED);
815             // remove from list
816             it->next = it->next->next;
817             // free channel struct
818             btstack_memory_rfcomm_channel_free(channel);
819         } else {
820             it = it->next;
821         }
822     }
823 
824     // remove mutliplexer
825     rfcomm_multiplexer_free(multiplexer);
826 }
827 
828 static void rfcomm_multiplexer_timer_handler(btstack_timer_source_t *timer){
829     rfcomm_multiplexer_t * multiplexer = (rfcomm_multiplexer_t*) btstack_run_loop_get_timer_context(timer);
830     if (rfcomm_multiplexer_has_channels(multiplexer)) return;
831 
832     log_info("rfcomm_multiplexer_timer_handler timeout: shutting down multiplexer! (no channels)");
833     uint16_t l2cap_cid = multiplexer->l2cap_cid;
834     rfcomm_multiplexer_finalize(multiplexer);
835     l2cap_disconnect(l2cap_cid, 0x13);
836 }
837 
838 static void rfcomm_multiplexer_prepare_idle_timer(rfcomm_multiplexer_t * multiplexer){
839     if (multiplexer->timer_active) {
840         btstack_run_loop_remove_timer(&multiplexer->timer);
841         multiplexer->timer_active = 0;
842     }
843     if (rfcomm_multiplexer_has_channels(multiplexer)) return;
844 
845     // start idle timer for multiplexer timeout check as there are no rfcomm channels yet
846     btstack_run_loop_set_timer(&multiplexer->timer, RFCOMM_MULIPLEXER_TIMEOUT_MS);
847     btstack_run_loop_set_timer_handler(&multiplexer->timer, rfcomm_multiplexer_timer_handler);
848     btstack_run_loop_set_timer_context(&multiplexer->timer, multiplexer);
849     btstack_run_loop_add_timer(&multiplexer->timer);
850     multiplexer->timer_active = 1;
851 }
852 
853 static void rfcomm_multiplexer_opened(rfcomm_multiplexer_t *multiplexer){
854     log_info("Multiplexer up and running");
855     multiplexer->state = RFCOMM_MULTIPLEXER_OPEN;
856 
857     const rfcomm_channel_event_t event = { CH_EVT_MULTIPLEXER_READY, 0};
858 
859     // transition of channels that wait for multiplexer
860     btstack_linked_item_t *it;
861     for (it = (btstack_linked_item_t *) rfcomm_channels; it ; it = it->next){
862         rfcomm_channel_t * channel = ((rfcomm_channel_t *) it);
863         if (channel->multiplexer != multiplexer) continue;
864         int rfcomm_channel_valid = 1;
865         rfcomm_channel_state_machine_with_channel(channel, &event, &rfcomm_channel_valid);
866         if (rfcomm_channel_valid && rfcomm_channel_ready_to_send(channel)){
867             l2cap_request_can_send_now_event(multiplexer->l2cap_cid);
868         }
869     }
870     rfcomm_multiplexer_prepare_idle_timer(multiplexer);
871 
872     // request can send now for multiplexer if ready
873     if (rfcomm_multiplexer_ready_to_send(multiplexer)){
874         l2cap_request_can_send_now_event(multiplexer->l2cap_cid);
875     }
876 }
877 
878 static void rfcomm_handle_can_send_now(uint16_t l2cap_cid){
879 
880     log_debug("rfcomm_handle_can_send_now enter: %u", l2cap_cid);
881 
882     btstack_linked_list_iterator_t it;
883     int token_consumed = 0;
884 
885     // forward token to multiplexer
886     btstack_linked_list_iterator_init(&it, &rfcomm_multiplexers);
887     while (!token_consumed && btstack_linked_list_iterator_has_next(&it)){
888         rfcomm_multiplexer_t * multiplexer = (rfcomm_multiplexer_t *) btstack_linked_list_iterator_next(&it);
889         if (multiplexer->l2cap_cid != l2cap_cid) continue;
890         if (rfcomm_multiplexer_ready_to_send(multiplexer)){
891             log_debug("rfcomm_handle_can_send_now enter: multiplexer token");
892             token_consumed = 1;
893             rfcomm_multiplexer_state_machine(multiplexer, MULT_EV_READY_TO_SEND);
894         }
895     }
896 
897     // forward token to channel state machine
898     btstack_linked_list_iterator_init(&it, &rfcomm_channels);
899     while (!token_consumed && btstack_linked_list_iterator_has_next(&it)){
900         rfcomm_channel_t * channel = (rfcomm_channel_t *) btstack_linked_list_iterator_next(&it);
901         if (channel->multiplexer->l2cap_cid != l2cap_cid) continue;
902         // channel state machine
903         if (rfcomm_channel_ready_to_send(channel)){
904             log_debug("rfcomm_handle_can_send_now enter: channel token");
905             token_consumed = 1;
906             const rfcomm_channel_event_t event = { CH_EVT_READY_TO_SEND, 0 };
907             int rfcomm_channel_valid = 1;
908             rfcomm_channel_state_machine_with_channel(channel, &event, &rfcomm_channel_valid);
909         }
910     }
911 
912     // forward token to client
913     btstack_linked_list_iterator_init(&it, &rfcomm_channels);
914     while (!token_consumed && btstack_linked_list_iterator_has_next(&it)){
915         rfcomm_channel_t * channel = (rfcomm_channel_t *) btstack_linked_list_iterator_next(&it);
916         if (channel->multiplexer->l2cap_cid != l2cap_cid) continue;
917         // client waiting for can send now
918         if (!channel->waiting_for_can_send_now)    continue;
919         if ((channel->multiplexer->fcon & 1) == 0) continue;
920         if (!channel->credits_outgoing){
921             log_debug("rfcomm_handle_can_send_now waiting to send but no credits (ignore)");
922             continue;
923         }
924 
925         log_debug("rfcomm_handle_can_send_now enter: client token");
926         token_consumed = 1;
927         channel->waiting_for_can_send_now = 0;
928         rfcomm_emit_can_send_now(channel);
929     }
930 
931     // if token was consumed, request another one
932     if (token_consumed) {
933         l2cap_request_can_send_now_event(l2cap_cid);
934     }
935 
936     log_debug("rfcomm_handle_can_send_now exit");
937 }
938 
939 static void rfcomm_multiplexer_set_state_and_request_can_send_now_event(rfcomm_multiplexer_t * multiplexer, RFCOMM_MULTIPLEXER_STATE state){
940     multiplexer->state = state;
941     l2cap_request_can_send_now_event(multiplexer->l2cap_cid);
942 }
943 
944 /**
945  * @return handled packet
946  */
947 static int rfcomm_hci_event_handler(uint8_t *packet, uint16_t size){
948 
949     UNUSED(size);   // ok: handling own l2cap events
950 
951     bd_addr_t event_addr;
952     uint16_t  psm;
953     uint16_t l2cap_cid;
954     hci_con_handle_t con_handle;
955     rfcomm_multiplexer_t *multiplexer = NULL;
956     uint8_t status;
957 
958     switch (hci_event_packet_get_type(packet)) {
959 
960         // accept incoming rfcomm connection if no multiplexer exists yet
961         case L2CAP_EVENT_INCOMING_CONNECTION:
962             // data: event(8), len(8), address(48), handle (16),  psm (16), source cid(16) dest cid(16)
963             reverse_bd_addr(&packet[2], event_addr);
964             con_handle = little_endian_read_16(packet,  8);
965             psm        = little_endian_read_16(packet, 10);
966             l2cap_cid  = little_endian_read_16(packet, 12);
967 
968             if (psm != BLUETOOTH_PROTOCOL_RFCOMM) break;
969 
970             multiplexer = rfcomm_multiplexer_for_addr(event_addr);
971 
972             if (multiplexer) {
973                 log_info("INCOMING_CONNECTION (l2cap_cid 0x%02x) for BLUETOOTH_PROTOCOL_RFCOMM => decline - multiplexer already exists", l2cap_cid);
974                 l2cap_decline_connection(l2cap_cid);
975                 return 1;
976             }
977 
978             // create and inititialize new multiplexer instance (incoming)
979             multiplexer = rfcomm_multiplexer_create_for_addr(event_addr);
980             if (!multiplexer){
981                 log_info("INCOMING_CONNECTION (l2cap_cid 0x%02x) for BLUETOOTH_PROTOCOL_RFCOMM => decline - no memory left", l2cap_cid);
982                 l2cap_decline_connection(l2cap_cid);
983                 return 1;
984             }
985 
986             multiplexer->con_handle = con_handle;
987             multiplexer->l2cap_cid = l2cap_cid;
988             //
989             multiplexer->state = RFCOMM_MULTIPLEXER_W4_SABM_0;
990             log_info("L2CAP_EVENT_INCOMING_CONNECTION (l2cap_cid 0x%02x) for BLUETOOTH_PROTOCOL_RFCOMM => accept", l2cap_cid);
991             l2cap_accept_connection(l2cap_cid);
992             return 1;
993 
994         // l2cap connection opened -> store l2cap_cid, remote_addr
995         case L2CAP_EVENT_CHANNEL_OPENED:
996 
997             if (little_endian_read_16(packet, 11) != BLUETOOTH_PROTOCOL_RFCOMM) break;
998 
999             status = packet[2];
1000             log_info("L2CAP_EVENT_CHANNEL_OPENED for BLUETOOTH_PROTOCOL_RFCOMM, status %u", status);
1001 
1002             // get multiplexer for remote addr
1003             con_handle = little_endian_read_16(packet, 9);
1004             l2cap_cid = little_endian_read_16(packet, 13);
1005             reverse_bd_addr(&packet[3], event_addr);
1006             multiplexer = rfcomm_multiplexer_for_addr(event_addr);
1007             if (!multiplexer) {
1008                 log_error("L2CAP_EVENT_CHANNEL_OPENED but no multiplexer prepared");
1009                 return 1;
1010             }
1011 
1012             // on l2cap open error discard everything
1013             if (status){
1014 
1015                 // remove (potential) timer
1016                 rfcomm_multiplexer_stop_timer(multiplexer);
1017 
1018                 // mark multiplexer as shutting down
1019                 multiplexer->state = RFCOMM_MULTIPLEXER_SHUTTING_DOWN;
1020 
1021                 // emit rfcomm_channel_opened with status and free channel
1022                 // note: repeatedly go over list until full iteration causes no further change
1023                 int done;
1024                 do {
1025                     done = 1;
1026                     btstack_linked_item_t * it = (btstack_linked_item_t *) &rfcomm_channels;
1027                     while (it->next) {
1028                         rfcomm_channel_t * channel = (rfcomm_channel_t *) it->next;
1029                         if (channel->multiplexer == multiplexer){
1030                             done = 0;
1031                             rfcomm_emit_channel_opened(channel, status);
1032                             btstack_linked_list_remove(&rfcomm_channels, (btstack_linked_item_t *) channel);
1033                             btstack_memory_rfcomm_channel_free(channel);
1034                             break;
1035                         } else {
1036                             it = it->next;
1037                         }
1038                     }
1039                 } while (!done);
1040 
1041                 // free multiplexer
1042                 rfcomm_multiplexer_free(multiplexer);
1043                 return 1;
1044             }
1045 
1046             // following could be: rfcom_multiplexer_state_machein(..., EVENT_L2CAP_OPENED)
1047 
1048             if (multiplexer->state == RFCOMM_MULTIPLEXER_W4_CONNECT) {
1049                 log_info("L2CAP_EVENT_CHANNEL_OPENED: outgoing connection");
1050                 // wrong remote addr
1051                 if (bd_addr_cmp(event_addr, multiplexer->remote_addr)) break;
1052                 multiplexer->l2cap_cid = l2cap_cid;
1053                 multiplexer->con_handle = con_handle;
1054                 // send SABM #0
1055                 rfcomm_multiplexer_set_state_and_request_can_send_now_event(multiplexer, RFCOMM_MULTIPLEXER_SEND_SABM_0);
1056 
1057             } else { // multiplexer->state == RFCOMM_MULTIPLEXER_W4_SABM_0
1058 
1059                 // set max frame size based on l2cap MTU
1060                 multiplexer->max_frame_size = rfcomm_max_frame_size_for_l2cap_mtu(little_endian_read_16(packet, 17));
1061             }
1062             return 1;
1063 
1064             // l2cap disconnect -> state = RFCOMM_MULTIPLEXER_CLOSED;
1065 
1066         // Notify channel packet handler if they can send now
1067         case L2CAP_EVENT_CAN_SEND_NOW:
1068             l2cap_cid = l2cap_event_can_send_now_get_local_cid(packet);
1069             rfcomm_handle_can_send_now(l2cap_cid);
1070             return 1;
1071 
1072         case L2CAP_EVENT_CHANNEL_CLOSED:
1073             // data: event (8), len(8), channel (16)
1074             l2cap_cid = little_endian_read_16(packet, 2);
1075             multiplexer = rfcomm_multiplexer_for_l2cap_cid(l2cap_cid);
1076             log_info("L2CAP_EVENT_CHANNEL_CLOSED cid 0x%0x, mult %p", l2cap_cid, multiplexer);
1077             if (!multiplexer) break;
1078             log_info("L2CAP_EVENT_CHANNEL_CLOSED state %u", multiplexer->state);
1079             // no need to call l2cap_disconnect here, as it's already closed
1080             rfcomm_multiplexer_finalize(multiplexer);
1081             return 1;
1082 
1083         default:
1084             break;
1085     }
1086     return 0;
1087 }
1088 
1089 static int rfcomm_multiplexer_l2cap_packet_handler(uint16_t channel, uint8_t *packet, uint16_t size){
1090     // get or create a multiplexer for a certain device
1091     rfcomm_multiplexer_t *multiplexer = rfcomm_multiplexer_for_l2cap_cid(channel);
1092     if (!multiplexer) return 0;
1093 
1094     uint16_t l2cap_cid = multiplexer->l2cap_cid;
1095 
1096 	// but only care for multiplexer control channel
1097     uint8_t frame_dlci = packet[0] >> 2;
1098     if (frame_dlci) return 0;
1099     const uint8_t length_offset = (packet[2] & 1) ^ 1;  // to be used for pos >= 3
1100     const uint8_t credit_offset = ((packet[1] & BT_RFCOMM_UIH_PF) == BT_RFCOMM_UIH_PF) ? 1 : 0;   // credits for uih_pf frames
1101     const uint8_t payload_offset = 3 + length_offset + credit_offset;
1102     switch (packet[1]){
1103 
1104         case BT_RFCOMM_SABM:
1105             if (multiplexer->state == RFCOMM_MULTIPLEXER_W4_SABM_0){
1106                 log_info("Received SABM #0");
1107                 multiplexer->outgoing = 0;
1108                 rfcomm_multiplexer_set_state_and_request_can_send_now_event(multiplexer, RFCOMM_MULTIPLEXER_SEND_UA_0);
1109                 return 1;
1110             }
1111             break;
1112 
1113         case BT_RFCOMM_UA:
1114             if (multiplexer->state == RFCOMM_MULTIPLEXER_W4_UA_0) {
1115                 // UA #0 -> send UA #0, state = RFCOMM_MULTIPLEXER_OPEN
1116                 log_info("Received UA #0 ");
1117                 rfcomm_multiplexer_opened(multiplexer);
1118                 return 1;
1119             }
1120             break;
1121 
1122         case BT_RFCOMM_DISC:
1123             // DISC #0 -> send UA #0, close multiplexer
1124             log_info("Received DISC #0, (ougoing = %u)", multiplexer->outgoing);
1125             rfcomm_multiplexer_set_state_and_request_can_send_now_event(multiplexer, RFCOMM_MULTIPLEXER_SEND_UA_0_AND_DISC);
1126             return 1;
1127 
1128         case BT_RFCOMM_DM:
1129             // DM #0 - we shouldn't get this, just give up
1130             log_info("Received DM #0");
1131             log_info("-> Closing down multiplexer");
1132             rfcomm_multiplexer_finalize(multiplexer);
1133             l2cap_disconnect(l2cap_cid, 0x13);
1134             return 1;
1135 
1136         case BT_RFCOMM_UIH:
1137             if (packet[payload_offset] == BT_RFCOMM_CLD_CMD){
1138                 // Multiplexer close down (CLD) -> close mutliplexer
1139                 log_info("Received Multiplexer close down command");
1140                 log_info("-> Closing down multiplexer");
1141                 rfcomm_multiplexer_finalize(multiplexer);
1142                 l2cap_disconnect(l2cap_cid, 0x13);
1143                 return 1;
1144             }
1145             switch (packet[payload_offset]){
1146                 case BT_RFCOMM_CLD_CMD:
1147                      // Multiplexer close down (CLD) -> close mutliplexer
1148                     log_info("Received Multiplexer close down command");
1149                     log_info("-> Closing down multiplexer");
1150                     rfcomm_multiplexer_finalize(multiplexer);
1151                     l2cap_disconnect(l2cap_cid, 0x13);
1152                     return 1;
1153 
1154                 case BT_RFCOMM_FCON_CMD:
1155                     multiplexer->fcon = 0x81;
1156                     l2cap_request_can_send_now_event(multiplexer->l2cap_cid);
1157                     return 1;
1158 
1159                 case BT_RFCOMM_FCOFF_CMD:
1160                     multiplexer->fcon = 0x80;
1161                     l2cap_request_can_send_now_event(multiplexer->l2cap_cid);
1162                     return 1;
1163 
1164                 case BT_RFCOMM_TEST_CMD: {
1165                     log_info("Received test command");
1166                     int len = packet[payload_offset+1] >> 1; // length < 125
1167                     if (len > RFCOMM_TEST_DATA_MAX_LEN){
1168                         len = RFCOMM_TEST_DATA_MAX_LEN;
1169                     }
1170                     len = btstack_min(len, size - 1 - payload_offset);  // avoid information leak
1171                     multiplexer->test_data_len = len;
1172                     memcpy(multiplexer->test_data, &packet[payload_offset + 2], len);
1173                     l2cap_request_can_send_now_event(multiplexer->l2cap_cid);
1174                     return 1;
1175                 }
1176                 default:
1177                     break;
1178             }
1179             break;
1180 
1181         default:
1182             break;
1183 
1184     }
1185     return 0;
1186 }
1187 
1188 static int rfcomm_multiplexer_ready_to_send(rfcomm_multiplexer_t * multiplexer){
1189     if (multiplexer->send_dm_for_dlci) return 1;
1190     if (multiplexer->nsc_command) return 1;
1191     if (multiplexer->fcon & 0x80) return 1;
1192     switch (multiplexer->state){
1193         case RFCOMM_MULTIPLEXER_SEND_SABM_0:
1194         case RFCOMM_MULTIPLEXER_SEND_UA_0:
1195         case RFCOMM_MULTIPLEXER_SEND_UA_0_AND_DISC:
1196             return 1;
1197         case RFCOMM_MULTIPLEXER_OPEN:
1198             if (multiplexer->test_data_len) {
1199                 return 1;
1200             }
1201             break;
1202         default:
1203             break;
1204     }
1205     return 0;
1206 }
1207 
1208 static void rfcomm_multiplexer_state_machine(rfcomm_multiplexer_t * multiplexer, RFCOMM_MULTIPLEXER_EVENT event){
1209 
1210     if (event != MULT_EV_READY_TO_SEND) return;
1211 
1212     uint16_t l2cap_cid = multiplexer->l2cap_cid;
1213 
1214     // process stored DM responses
1215     if (multiplexer->send_dm_for_dlci){
1216         uint8_t dlci = multiplexer->send_dm_for_dlci;
1217         multiplexer->send_dm_for_dlci = 0;
1218         rfcomm_send_dm_pf(multiplexer, dlci);
1219         return;
1220     }
1221 
1222     if (multiplexer->nsc_command){
1223         uint8_t command = multiplexer->nsc_command;
1224         multiplexer->nsc_command = 0;
1225         rfcomm_send_uih_nsc_rsp(multiplexer, command);
1226         return;
1227     }
1228 
1229     if (multiplexer->fcon & 0x80){
1230         multiplexer->fcon &= 0x01;
1231         rfcomm_send_uih_fc_rsp(multiplexer, multiplexer->fcon);
1232 
1233         if (multiplexer->fcon == 0) return;
1234         // trigger client to send again after sending FCon Response
1235         rfcomm_notify_channel_can_send();
1236         return;
1237     }
1238 
1239     switch (multiplexer->state) {
1240         case RFCOMM_MULTIPLEXER_SEND_SABM_0:
1241             log_info("Sending SABM #0 - (multi 0x%p)", multiplexer);
1242             multiplexer->state = RFCOMM_MULTIPLEXER_W4_UA_0;
1243             rfcomm_send_sabm(multiplexer, 0);
1244             break;
1245         case RFCOMM_MULTIPLEXER_SEND_UA_0:
1246             log_info("Sending UA #0");
1247             multiplexer->state = RFCOMM_MULTIPLEXER_OPEN;
1248             rfcomm_send_ua(multiplexer, 0);
1249 
1250             rfcomm_multiplexer_opened(multiplexer);
1251             break;
1252         case RFCOMM_MULTIPLEXER_SEND_UA_0_AND_DISC:
1253             log_info("Sending UA #0");
1254             log_info("Closing down multiplexer");
1255             multiplexer->state = RFCOMM_MULTIPLEXER_CLOSED;
1256             rfcomm_send_ua(multiplexer, 0);
1257 
1258             rfcomm_multiplexer_finalize(multiplexer);
1259             l2cap_disconnect(l2cap_cid, 0x13);
1260             break;
1261         case RFCOMM_MULTIPLEXER_OPEN:
1262             // respond to test command
1263             if (multiplexer->test_data_len){
1264                 int len = multiplexer->test_data_len;
1265                 log_info("Sending TEST Response with %u bytes", len);
1266                 multiplexer->test_data_len = 0;
1267                 rfcomm_send_uih_test_rsp(multiplexer, multiplexer->test_data, len);
1268                 return;
1269             }
1270             break;
1271         default:
1272             break;
1273     }
1274 }
1275 
1276 // MARK: RFCOMM CHANNEL
1277 
1278 static void rfcomm_channel_send_credits(rfcomm_channel_t *channel, uint8_t credits){
1279     channel->credits_incoming += credits;
1280     rfcomm_send_uih_credits(channel->multiplexer, channel->dlci, credits);
1281 }
1282 
1283 static int rfcomm_channel_can_send(rfcomm_channel_t * channel){
1284     if (!channel->credits_outgoing) return 0;
1285     if ((channel->multiplexer->fcon & 1) == 0) return 0;
1286     return l2cap_can_send_packet_now(channel->multiplexer->l2cap_cid);
1287 }
1288 
1289 static void rfcomm_channel_opened(rfcomm_channel_t *rfChannel){
1290 
1291     log_info("rfcomm_channel_opened!");
1292 
1293     rfChannel->state = RFCOMM_CHANNEL_OPEN;
1294     rfcomm_emit_channel_opened(rfChannel, 0);
1295     rfcomm_emit_port_configuration(rfChannel);
1296 
1297     // remove (potential) timer
1298     rfcomm_multiplexer_t *multiplexer = rfChannel->multiplexer;
1299     if (multiplexer->timer_active) {
1300         btstack_run_loop_remove_timer(&multiplexer->timer);
1301         multiplexer->timer_active = 0;
1302     }
1303     // hack for problem detecting authentication failure
1304     multiplexer->at_least_one_connection = 1;
1305 
1306     // request can send now if channel ready
1307     if (rfcomm_channel_ready_to_send(rfChannel)){
1308         l2cap_request_can_send_now_event(multiplexer->l2cap_cid);
1309     }
1310 }
1311 
1312 static void rfcomm_channel_packet_handler_uih(rfcomm_multiplexer_t *multiplexer, uint8_t * packet, uint16_t size){
1313     const uint8_t frame_dlci = packet[0] >> 2;
1314     const uint8_t length_offset = (packet[2] & 1) ^ 1;  // to be used for pos >= 3
1315     const uint8_t credit_offset = ((packet[1] & BT_RFCOMM_UIH_PF) == BT_RFCOMM_UIH_PF) ? 1 : 0;   // credits for uih_pf frames
1316     const uint8_t payload_offset = 3 + length_offset + credit_offset;
1317     int request_can_send_now = 0;
1318 
1319     rfcomm_channel_t * channel = rfcomm_channel_for_multiplexer_and_dlci(multiplexer, frame_dlci);
1320     if (!channel) return;
1321 
1322     // handle new outgoing credits
1323     if (packet[1] == BT_RFCOMM_UIH_PF) {
1324 
1325         // add them
1326         uint16_t new_credits = packet[3+length_offset];
1327         channel->credits_outgoing += new_credits;
1328         log_info( "RFCOMM data UIH_PF, new credits channel 0x%02x: %u, now %u", channel->rfcomm_cid, new_credits, channel->credits_outgoing);
1329 
1330         // notify channel statemachine
1331         rfcomm_channel_event_t channel_event = { CH_EVT_RCVD_CREDITS, 0 };
1332         log_debug("rfcomm_channel_state_machine_with_channel, waiting_for_can_send_now %u", channel->waiting_for_can_send_now);
1333         int rfcomm_channel_valid = 1;
1334         rfcomm_channel_state_machine_with_channel(channel, &channel_event, &rfcomm_channel_valid);
1335         if (rfcomm_channel_valid){
1336             if (rfcomm_channel_ready_to_send(channel) || channel->waiting_for_can_send_now){
1337                 request_can_send_now = 1;
1338             }
1339         }
1340     }
1341 
1342     // contains payload?
1343     if (size - 1 > payload_offset){
1344 
1345         // log_info( "RFCOMM data UIH_PF, size %u, channel %p", size-payload_offset-1, rfChannel->connection);
1346 
1347         // decrease incoming credit counter
1348         if (channel->credits_incoming > 0){
1349             channel->credits_incoming--;
1350         }
1351 
1352         // deliver payload
1353         (channel->packet_handler)(RFCOMM_DATA_PACKET, channel->rfcomm_cid,
1354                               &packet[payload_offset], size-payload_offset-1);
1355     }
1356 
1357     // automatically provide new credits to remote device, if no incoming flow control
1358     if (!channel->incoming_flow_control && channel->credits_incoming < 5){
1359         channel->new_credits_incoming = RFCOMM_CREDITS;
1360         request_can_send_now = 1;
1361     }
1362 
1363     if (request_can_send_now){
1364         l2cap_request_can_send_now_event(multiplexer->l2cap_cid);
1365     }
1366 }
1367 
1368 static void rfcomm_channel_accept_pn(rfcomm_channel_t *channel, rfcomm_channel_event_pn_t *event){
1369     // priority of client request
1370     channel->pn_priority = event->priority;
1371 
1372     // new credits
1373     channel->credits_outgoing = event->credits_outgoing;
1374 
1375     // negotiate max frame size
1376     if (channel->max_frame_size > channel->multiplexer->max_frame_size) {
1377         channel->max_frame_size = channel->multiplexer->max_frame_size;
1378     }
1379     if (channel->max_frame_size > event->max_frame_size) {
1380         channel->max_frame_size = event->max_frame_size;
1381     }
1382 
1383 }
1384 
1385 static void rfcomm_channel_finalize(rfcomm_channel_t *channel){
1386 
1387     rfcomm_multiplexer_t *multiplexer = channel->multiplexer;
1388 
1389     // remove from list
1390     btstack_linked_list_remove( &rfcomm_channels, (btstack_linked_item_t *) channel);
1391 
1392     // free channel
1393     btstack_memory_rfcomm_channel_free(channel);
1394 
1395     // update multiplexer timeout after channel was removed from list
1396     rfcomm_multiplexer_prepare_idle_timer(multiplexer);
1397 }
1398 
1399 static void rfcomm_channel_state_machine_with_dlci(rfcomm_multiplexer_t * multiplexer, uint8_t dlci, const rfcomm_channel_event_t *event){
1400 
1401     // TODO: if client max frame size is smaller than RFCOMM_DEFAULT_SIZE, send PN
1402 
1403 
1404     // lookup existing channel
1405     rfcomm_channel_t * channel = rfcomm_channel_for_multiplexer_and_dlci(multiplexer, dlci);
1406 
1407     // log_info("rfcomm_channel_state_machine_with_dlci lookup dlci #%u = 0x%08x - event %u", dlci, (int) channel, event->type);
1408 
1409     if (channel) {
1410         int rfcomm_channel_valid = 1;
1411         rfcomm_channel_state_machine_with_channel(channel, event, &rfcomm_channel_valid);
1412         if (rfcomm_channel_valid && rfcomm_channel_ready_to_send(channel)){
1413             l2cap_request_can_send_now_event(multiplexer->l2cap_cid);
1414         }
1415         return;
1416     }
1417 
1418     // service registered?
1419     rfcomm_service_t * service = rfcomm_service_for_channel(dlci >> 1);
1420     // log_info("rfcomm_channel_state_machine_with_dlci service dlci #%u = 0x%08x", dlci, (int) service);
1421     if (!service) {
1422         // discard request by sending disconnected mode
1423         multiplexer->send_dm_for_dlci = dlci;
1424         l2cap_request_can_send_now_event(multiplexer->l2cap_cid);
1425         return;
1426     }
1427 
1428     // create channel for some events
1429     switch (event->type) {
1430         case CH_EVT_RCVD_SABM:
1431         case CH_EVT_RCVD_PN:
1432         case CH_EVT_RCVD_RPN_REQ:
1433         case CH_EVT_RCVD_RPN_CMD:
1434             // setup incoming channel
1435             channel = rfcomm_channel_create(multiplexer, service, dlci >> 1);
1436             if (!channel){
1437                 // discard request by sending disconnected mode
1438                 multiplexer->send_dm_for_dlci = dlci;
1439                 l2cap_request_can_send_now_event(multiplexer->l2cap_cid);
1440             }
1441             break;
1442         default:
1443             break;
1444     }
1445 
1446     if (!channel) {
1447         // discard request by sending disconnected mode
1448         multiplexer->send_dm_for_dlci = dlci;
1449         l2cap_request_can_send_now_event(multiplexer->l2cap_cid);
1450         return;
1451     }
1452 
1453     int rfcomm_channel_valid = 1;
1454     rfcomm_channel_state_machine_with_channel(channel, event, &rfcomm_channel_valid);
1455     if (rfcomm_channel_valid && rfcomm_channel_ready_to_send(channel)){
1456         l2cap_request_can_send_now_event(multiplexer->l2cap_cid);
1457     }
1458 }
1459 
1460 static void rfcomm_channel_packet_handler(rfcomm_multiplexer_t * multiplexer,  uint8_t *packet, uint16_t size){
1461 
1462     UNUSED(size);   // ok: fixed format messages
1463 
1464     // rfcomm: (0) addr [76543 server channel] [2 direction: initiator uses 1] [1 C/R: CMD by initiator = 1] [0 EA=1]
1465     const uint8_t frame_dlci = packet[0] >> 2;
1466     uint8_t message_dlci; // used by commands in UIH(_PF) packets
1467 	uint8_t message_len;  //   "
1468 
1469     // rfcomm: (1) command/control
1470     // -- credits_offset = 1 if command == BT_RFCOMM_UIH_PF
1471     const uint8_t credit_offset = ((packet[1] & BT_RFCOMM_UIH_PF) == BT_RFCOMM_UIH_PF) ? 1 : 0;   // credits for uih_pf frames
1472     // rfcomm: (2) length. if bit 0 is cleared, 2 byte length is used. (little endian)
1473     const uint8_t length_offset = (packet[2] & 1) ^ 1;  // to be used for pos >= 3
1474     // rfcomm: (3+length_offset) credits if credits_offset == 1
1475     // rfcomm: (3+length_offest+credits_offset)
1476     const uint8_t payload_offset = 3 + length_offset + credit_offset;
1477 
1478     rfcomm_channel_event_t event;
1479     rfcomm_channel_event_pn_t event_pn;
1480     rfcomm_channel_event_rpn_t event_rpn;
1481     rfcomm_channel_event_msc_t event_msc;
1482 
1483     // switch by rfcomm message type
1484     switch(packet[1]) {
1485 
1486         case BT_RFCOMM_SABM:
1487             event.type = CH_EVT_RCVD_SABM;
1488             log_info("Received SABM #%u", frame_dlci);
1489             rfcomm_channel_state_machine_with_dlci(multiplexer, frame_dlci, &event);
1490             break;
1491 
1492         case BT_RFCOMM_UA:
1493             event.type = CH_EVT_RCVD_UA;
1494             log_info("Received UA #%u",frame_dlci);
1495             rfcomm_channel_state_machine_with_dlci(multiplexer, frame_dlci, &event);
1496             break;
1497 
1498         case BT_RFCOMM_DISC:
1499             event.type = CH_EVT_RCVD_DISC;
1500             rfcomm_channel_state_machine_with_dlci(multiplexer, frame_dlci, &event);
1501             break;
1502 
1503         case BT_RFCOMM_DM:
1504         case BT_RFCOMM_DM_PF:
1505             event.type = CH_EVT_RCVD_DM;
1506             rfcomm_channel_state_machine_with_dlci(multiplexer, frame_dlci, &event);
1507             break;
1508 
1509         case BT_RFCOMM_UIH_PF:
1510         case BT_RFCOMM_UIH:
1511 
1512             message_len  = packet[payload_offset+1] >> 1;
1513 
1514             switch (packet[payload_offset]) {
1515                 case BT_RFCOMM_PN_CMD:
1516                     message_dlci = packet[payload_offset+2];
1517                     event_pn.super.type = CH_EVT_RCVD_PN;
1518                     event_pn.priority = packet[payload_offset+4];
1519                     event_pn.max_frame_size = little_endian_read_16(packet, payload_offset+6);
1520                     event_pn.credits_outgoing = packet[payload_offset+9];
1521                     log_info("Received UIH Parameter Negotiation Command for #%u, credits %u",
1522                         message_dlci, event_pn.credits_outgoing);
1523                     rfcomm_channel_state_machine_with_dlci(multiplexer, message_dlci, (rfcomm_channel_event_t*) &event_pn);
1524                     break;
1525 
1526                 case BT_RFCOMM_PN_RSP:
1527                     message_dlci = packet[payload_offset+2];
1528                     event_pn.super.type = CH_EVT_RCVD_PN_RSP;
1529                     event_pn.priority = packet[payload_offset+4];
1530                     event_pn.max_frame_size = little_endian_read_16(packet, payload_offset+6);
1531                     event_pn.credits_outgoing = packet[payload_offset+9];
1532                     log_info("Received UIH Parameter Negotiation Response max frame %u, credits %u",
1533                             event_pn.max_frame_size, event_pn.credits_outgoing);
1534                     rfcomm_channel_state_machine_with_dlci(multiplexer, message_dlci, (rfcomm_channel_event_t*) &event_pn);
1535                     break;
1536 
1537                 case BT_RFCOMM_MSC_CMD:
1538                     message_dlci = packet[payload_offset+2] >> 2;
1539                     event_msc.super.type = CH_EVT_RCVD_MSC_CMD;
1540                     event_msc.modem_status = packet[payload_offset+3];
1541                     log_info("Received MSC CMD for #%u, ", message_dlci);
1542                     rfcomm_channel_state_machine_with_dlci(multiplexer, message_dlci, (rfcomm_channel_event_t*) &event_msc);
1543                     break;
1544 
1545                 case BT_RFCOMM_MSC_RSP:
1546                     message_dlci = packet[payload_offset+2] >> 2;
1547                     event.type = CH_EVT_RCVD_MSC_RSP;
1548                     log_info("Received MSC RSP for #%u", message_dlci);
1549                     rfcomm_channel_state_machine_with_dlci(multiplexer, message_dlci, &event);
1550                     break;
1551 
1552                 case BT_RFCOMM_RPN_CMD:
1553                     message_dlci = packet[payload_offset+2] >> 2;
1554                     switch (message_len){
1555                         case 1:
1556                             log_info("Received Remote Port Negotiation Request for #%u", message_dlci);
1557                             event.type = CH_EVT_RCVD_RPN_REQ;
1558                             rfcomm_channel_state_machine_with_dlci(multiplexer, message_dlci, &event);
1559                             break;
1560                         case 8:
1561                             log_info("Received Remote Port Negotiation Update for #%u", message_dlci);
1562                             event_rpn.super.type = CH_EVT_RCVD_RPN_CMD;
1563                             event_rpn.data = *(rfcomm_rpn_data_t*) &packet[payload_offset+3];
1564                             rfcomm_channel_state_machine_with_dlci(multiplexer, message_dlci, (rfcomm_channel_event_t*) &event_rpn);
1565                             break;
1566                         default:
1567                             break;
1568                     }
1569                     break;
1570 
1571                 case BT_RFCOMM_RPN_RSP:
1572                     log_info("Received RPN response");
1573                     break;
1574 
1575                 case BT_RFCOMM_RLS_CMD: {
1576                     log_info("Received RLS command");
1577                     message_dlci = packet[payload_offset+2] >> 2;
1578                     rfcomm_channel_event_rls_t event_rls;
1579                     event_rls.super.type = CH_EVT_RCVD_RLS_CMD;
1580                     event_rls.line_status = packet[payload_offset+3];
1581                     rfcomm_channel_state_machine_with_dlci(multiplexer, message_dlci, (rfcomm_channel_event_t*) &event_rls);
1582                     break;
1583                 }
1584 
1585                 case BT_RFCOMM_RLS_RSP:
1586                     log_info("Received RLS response");
1587                     break;
1588 
1589                 // Following commands are handled by rfcomm_multiplexer_l2cap_packet_handler
1590                 // case BT_RFCOMM_TEST_CMD:
1591                 // case BT_RFCOMM_FCOFF_CMD:
1592                 // case BT_RFCOMM_FCON_CMD:
1593                 // everything else is an not supported command
1594                 default: {
1595                     log_error("Received unknown UIH command packet - 0x%02x", packet[payload_offset]);
1596                     multiplexer->nsc_command = packet[payload_offset];
1597                     break;
1598                 }
1599             }
1600             break;
1601 
1602         default:
1603             log_error("Received unknown RFCOMM message type %x", packet[1]);
1604             break;
1605     }
1606 
1607     // trigger next action - example W4_PN_RSP: transition to SEND_SABM which only depends on "can send"
1608     if (rfcomm_multiplexer_ready_to_send(multiplexer)){
1609         l2cap_request_can_send_now_event(multiplexer->l2cap_cid);
1610     }
1611 }
1612 
1613 static void rfcomm_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
1614 
1615     if (packet_type == HCI_EVENT_PACKET){
1616         rfcomm_hci_event_handler(packet, size);
1617         return;
1618     }
1619 
1620     // we only handle l2cap packets for:
1621     if (packet_type != L2CAP_DATA_PACKET) return;
1622 
1623     //  - multiplexer itself
1624     int handled = rfcomm_multiplexer_l2cap_packet_handler(channel, packet, size);
1625 
1626     if (handled) return;
1627 
1628     // - channel over open mutliplexer
1629     rfcomm_multiplexer_t * multiplexer = rfcomm_multiplexer_for_l2cap_cid(channel);
1630     if (!multiplexer || multiplexer->state != RFCOMM_MULTIPLEXER_OPEN) return;
1631 
1632     // channel data ?
1633     // rfcomm: (0) addr [76543 server channel] [2 direction: initiator uses 1] [1 C/R: CMD by initiator = 1] [0 EA=1]
1634     const uint8_t frame_dlci = packet[0] >> 2;
1635 
1636     if (frame_dlci && (packet[1] == BT_RFCOMM_UIH || packet[1] == BT_RFCOMM_UIH_PF)) {
1637         rfcomm_channel_packet_handler_uih(multiplexer, packet, size);
1638         return;
1639     }
1640 
1641     rfcomm_channel_packet_handler(multiplexer, packet, size);
1642 }
1643 
1644 static int rfcomm_channel_ready_for_open(rfcomm_channel_t *channel){
1645     // note: exchanging MSC isn't neccessary to consider channel open
1646     // note: having outgoing credits is also not necessary to consider channel open
1647     // log_info("rfcomm_channel_ready_for_open state %u, flags needed %04x, current %04x, rf credits %u, l2cap credits %u ", channel->state, RFCOMM_CHANNEL_STATE_VAR_RCVD_MSC_RSP|RFCOMM_CHANNEL_STATE_VAR_SENT_MSC_RSP|RFCOMM_CHANNEL_STATE_VAR_SENT_CREDITS, channel->state_var, channel->credits_outgoing, channel->multiplexer->l2cap_credits);
1648     // if ((channel->state_var & RFCOMM_CHANNEL_STATE_VAR_SENT_MSC_RSP) == 0) return 0;
1649     // if (channel->credits_outgoing == 0) return 0;
1650     log_info("rfcomm_channel_ready_for_open state %u, flags needed %04x, current %04x, rf credits %u",
1651          channel->state, RFCOMM_CHANNEL_STATE_VAR_RCVD_MSC_RSP, channel->state_var, channel->credits_outgoing);
1652     if ((channel->state_var & RFCOMM_CHANNEL_STATE_VAR_RCVD_MSC_RSP) == 0) return 0;
1653     if ((channel->state_var & RFCOMM_CHANNEL_STATE_VAR_SENT_CREDITS) == 0) return 0;
1654 
1655     return 1;
1656 }
1657 
1658 static int rfcomm_channel_ready_for_incoming_dlc_setup(rfcomm_channel_t * channel){
1659     log_info("rfcomm_channel_ready_for_incoming_dlc_setup state var %04x", channel->state_var);
1660     // Client accept and SABM/UA is required, PN RSP is needed if PN was received
1661     if ((channel->state_var & RFCOMM_CHANNEL_STATE_VAR_CLIENT_ACCEPTED) == 0) return 0;
1662     if ((channel->state_var & RFCOMM_CHANNEL_STATE_VAR_RCVD_SABM      ) == 0) return 0;
1663     if ((channel->state_var & RFCOMM_CHANNEL_STATE_VAR_SEND_UA        ) != 0) return 0;
1664     if ((channel->state_var & RFCOMM_CHANNEL_STATE_VAR_SEND_PN_RSP    ) != 0) return 0;
1665     return 1;
1666 }
1667 
1668 inline static void rfcomm_channel_state_add(rfcomm_channel_t *channel, RFCOMM_CHANNEL_STATE_VAR event){
1669     channel->state_var = (RFCOMM_CHANNEL_STATE_VAR) (channel->state_var | event);
1670 }
1671 inline static void rfcomm_channel_state_remove(rfcomm_channel_t *channel, RFCOMM_CHANNEL_STATE_VAR event){
1672     channel->state_var = (RFCOMM_CHANNEL_STATE_VAR) (channel->state_var & ~event);
1673 }
1674 
1675 static int rfcomm_channel_ready_to_send(rfcomm_channel_t * channel){
1676     switch (channel->state){
1677         case RFCOMM_CHANNEL_SEND_UIH_PN:
1678             log_debug("ch-ready: state %u", channel->state);
1679             return 1;
1680         case RFCOMM_CHANNEL_SEND_SABM_W4_UA:
1681             log_debug("ch-ready: state %u", channel->state);
1682             return 1;
1683         case RFCOMM_CHANNEL_SEND_UA_AFTER_DISC:
1684             log_debug("ch-ready: state %u", channel->state);
1685             return 1;
1686         case RFCOMM_CHANNEL_SEND_DISC:
1687             log_debug("ch-ready: state %u", channel->state);
1688             return 1;
1689         case RFCOMM_CHANNEL_SEND_DM:
1690             log_debug("ch-ready: state %u", channel->state);
1691             return 1;
1692         case RFCOMM_CHANNEL_OPEN:
1693             if (channel->new_credits_incoming) {
1694                 log_debug("ch-ready: channel open & new_credits_incoming") ;
1695                 return 1;
1696             }
1697             break;
1698         case RFCOMM_CHANNEL_DLC_SETUP:
1699             if (channel->state_var & (
1700                 RFCOMM_CHANNEL_STATE_VAR_SEND_MSC_CMD  |
1701                 RFCOMM_CHANNEL_STATE_VAR_SEND_CREDITS
1702              )) {
1703                 log_debug("ch-ready: channel dlc setup & send msc cmd or send credits") ;
1704                 return 1;
1705             }
1706             break;
1707 
1708         default:
1709             break;
1710     }
1711 
1712     if (channel->state_var & (
1713         RFCOMM_CHANNEL_STATE_VAR_SEND_PN_RSP   |
1714         RFCOMM_CHANNEL_STATE_VAR_SEND_RPN_INFO |
1715         RFCOMM_CHANNEL_STATE_VAR_SEND_RPN_RSP  |
1716         RFCOMM_CHANNEL_STATE_VAR_SEND_UA       |
1717         RFCOMM_CHANNEL_STATE_VAR_SEND_MSC_RSP
1718                              )){
1719         log_debug("ch-ready: state %x, state var %x", channel->state, channel->state_var);
1720         return 1;
1721     }
1722 
1723     if (channel->rls_line_status != RFCOMM_RLS_STATUS_INVALID) {
1724         log_debug("ch-ready: rls_line_status");
1725         return 1;
1726     }
1727 
1728     return 0;
1729 }
1730 
1731 
1732 static void rfcomm_channel_state_machine_with_channel(rfcomm_channel_t *channel, const rfcomm_channel_event_t *event, int * out_channel_valid){
1733 
1734     // log_info("rfcomm_channel_state_machine_with_channel: state %u, state_var %04x, event %u", channel->state, channel->state_var ,event->type);
1735 
1736     // channel != NULL -> channel valid
1737     *out_channel_valid = 1;
1738 
1739     rfcomm_multiplexer_t *multiplexer = channel->multiplexer;
1740 
1741     // TODO: integrate in common switch
1742     if (event->type == CH_EVT_RCVD_DISC){
1743         rfcomm_emit_channel_closed(channel);
1744         channel->state = RFCOMM_CHANNEL_SEND_UA_AFTER_DISC;
1745         return;
1746     }
1747 
1748     // TODO: integrate in common switch
1749     if (event->type == CH_EVT_RCVD_DM){
1750         log_info("Received DM message for #%u", channel->dlci);
1751         log_info("-> Closing channel locally for #%u", channel->dlci);
1752         rfcomm_channel_emit_final_event(channel, ERROR_CODE_CONNECTION_REJECTED_DUE_TO_LIMITED_RESOURCES);
1753         rfcomm_channel_finalize(channel);
1754         *out_channel_valid = 0;
1755         return;
1756     }
1757 
1758     // remote port negotiation command - just accept everything for now
1759     //
1760     // "The RPN command can be used before a new DLC is opened and should be used whenever the port settings change."
1761     // "The RPN command is specified as optional in TS 07.10, but it is mandatory to recognize and respond to it in RFCOMM.
1762     //   (Although the handling of individual settings are implementation-dependent.)"
1763     //
1764 
1765     // TODO: integrate in common switch
1766     if (event->type == CH_EVT_RCVD_RPN_CMD){
1767         // control port parameters
1768         rfcomm_channel_event_rpn_t *event_rpn = (rfcomm_channel_event_rpn_t*) event;
1769         rfcomm_rpn_data_update(&channel->rpn_data, &event_rpn->data);
1770         rfcomm_channel_state_add(channel, RFCOMM_CHANNEL_STATE_VAR_SEND_RPN_RSP);
1771         // notify client about new settings
1772         rfcomm_emit_port_configuration(channel);
1773         return;
1774     }
1775 
1776     // TODO: integrate in common switch
1777     if (event->type == CH_EVT_RCVD_RPN_REQ){
1778         // no values got accepted (no values have beens sent)
1779         channel->rpn_data.parameter_mask_0 = 0x00;
1780         channel->rpn_data.parameter_mask_1 = 0x00;
1781         rfcomm_channel_state_add(channel, RFCOMM_CHANNEL_STATE_VAR_SEND_RPN_RSP);
1782         return;
1783     }
1784 
1785     if (event->type == CH_EVT_RCVD_RLS_CMD){
1786         rfcomm_channel_event_rls_t * event_rls = (rfcomm_channel_event_rls_t*) event;
1787         channel->rls_line_status = event_rls->line_status & 0x0f;
1788         log_info("CH_EVT_RCVD_RLS_CMD setting line status to 0x%0x", channel->rls_line_status);
1789         rfcomm_emit_remote_line_status(channel, event_rls->line_status);
1790         return;
1791     }
1792 
1793     // TODO: integrate in common switch
1794     if (event->type == CH_EVT_READY_TO_SEND){
1795         if (channel->state_var & RFCOMM_CHANNEL_STATE_VAR_SEND_RPN_RSP){
1796             log_info("Sending Remote Port Negotiation RSP for #%u", channel->dlci);
1797             rfcomm_channel_state_remove(channel, RFCOMM_CHANNEL_STATE_VAR_SEND_RPN_RSP);
1798             rfcomm_send_uih_rpn_rsp(multiplexer, channel->dlci, &channel->rpn_data);
1799             return;
1800         }
1801         if (channel->state_var & RFCOMM_CHANNEL_STATE_VAR_SEND_MSC_RSP){
1802             log_info("Sending MSC RSP for #%u", channel->dlci);
1803             rfcomm_channel_state_remove(channel, RFCOMM_CHANNEL_STATE_VAR_SEND_MSC_RSP);
1804             rfcomm_channel_state_add(channel, RFCOMM_CHANNEL_STATE_VAR_SENT_MSC_RSP);
1805             rfcomm_send_uih_msc_rsp(multiplexer, channel->dlci, 0x8d);  // ea=1,fc=0,rtc=1,rtr=1,ic=0,dv=1
1806             return;
1807         }
1808         if (channel->rls_line_status != RFCOMM_RLS_STATUS_INVALID){
1809             log_info("Sending RLS RSP 0x%0x", channel->rls_line_status);
1810             uint8_t line_status = channel->rls_line_status;
1811             channel->rls_line_status = RFCOMM_RLS_STATUS_INVALID;
1812             rfcomm_send_uih_rls_rsp(multiplexer, channel->dlci, line_status);
1813             return;
1814         }
1815     }
1816 
1817     // emit MSC status to app
1818     if (event->type == CH_EVT_RCVD_MSC_CMD){
1819         // notify client about new settings
1820         rfcomm_channel_event_msc_t *event_msc = (rfcomm_channel_event_msc_t*) event;
1821         uint8_t modem_status_event[2+1];
1822         modem_status_event[0] = RFCOMM_EVENT_REMOTE_MODEM_STATUS;
1823         modem_status_event[1] = 1;
1824         modem_status_event[2] = event_msc->modem_status;
1825         (channel->packet_handler)(HCI_EVENT_PACKET, channel->rfcomm_cid, (uint8_t*)&modem_status_event, sizeof(modem_status_event));
1826         // no return, MSC_CMD will be handled by state machine below
1827     }
1828 
1829     rfcomm_channel_event_pn_t * event_pn = (rfcomm_channel_event_pn_t*) event;
1830 
1831     switch (channel->state) {
1832         case RFCOMM_CHANNEL_CLOSED:
1833             switch (event->type){
1834                 case CH_EVT_RCVD_SABM:
1835                     log_info("-> Inform app");
1836                     rfcomm_channel_state_add(channel, RFCOMM_CHANNEL_STATE_VAR_RCVD_SABM);
1837                     channel->state = RFCOMM_CHANNEL_INCOMING_SETUP;
1838                     rfcomm_emit_connection_request(channel);
1839                     break;
1840                 case CH_EVT_RCVD_PN:
1841                     rfcomm_channel_accept_pn(channel, event_pn);
1842                     log_info("-> Inform app");
1843                     rfcomm_channel_state_add(channel, RFCOMM_CHANNEL_STATE_VAR_RCVD_PN);
1844                     channel->state = RFCOMM_CHANNEL_INCOMING_SETUP;
1845                     rfcomm_emit_connection_request(channel);
1846                     break;
1847                 default:
1848                     break;
1849             }
1850             break;
1851 
1852         case RFCOMM_CHANNEL_INCOMING_SETUP:
1853             switch (event->type){
1854                 case CH_EVT_RCVD_SABM:
1855                     rfcomm_channel_state_add(channel, RFCOMM_CHANNEL_STATE_VAR_RCVD_SABM);
1856                     if (channel->state_var & RFCOMM_CHANNEL_STATE_VAR_CLIENT_ACCEPTED) {
1857                         rfcomm_channel_state_add(channel, RFCOMM_CHANNEL_STATE_VAR_SEND_UA);
1858                     }
1859                     break;
1860                 case CH_EVT_RCVD_PN:
1861                     rfcomm_channel_accept_pn(channel, event_pn);
1862                     rfcomm_channel_state_add(channel, RFCOMM_CHANNEL_STATE_VAR_RCVD_PN);
1863                     if (channel->state_var & RFCOMM_CHANNEL_STATE_VAR_CLIENT_ACCEPTED) {
1864                         rfcomm_channel_state_add(channel, RFCOMM_CHANNEL_STATE_VAR_SEND_PN_RSP);
1865                     }
1866                     break;
1867                 case CH_EVT_READY_TO_SEND:
1868                     // if / else if is used to check for state transition after sending
1869                     if (channel->state_var & RFCOMM_CHANNEL_STATE_VAR_SEND_PN_RSP){
1870                         log_info("Sending UIH Parameter Negotiation Respond for #%u", channel->dlci);
1871                         rfcomm_channel_state_remove(channel, RFCOMM_CHANNEL_STATE_VAR_SEND_PN_RSP);
1872                         rfcomm_send_uih_pn_response(multiplexer, channel->dlci, channel->pn_priority, channel->max_frame_size);
1873                     } else if (channel->state_var & RFCOMM_CHANNEL_STATE_VAR_SEND_UA){
1874                         log_info("Sending UA #%u", channel->dlci);
1875                         rfcomm_channel_state_remove(channel, RFCOMM_CHANNEL_STATE_VAR_SEND_UA);
1876                         rfcomm_send_ua(multiplexer, channel->dlci);
1877                     }
1878                     if (rfcomm_channel_ready_for_incoming_dlc_setup(channel)){
1879                         log_info("Incomping setup done, requesting send MSC CMD and send Credits");
1880                         rfcomm_channel_state_add(channel, RFCOMM_CHANNEL_STATE_VAR_SEND_MSC_CMD);
1881                         rfcomm_channel_state_add(channel, RFCOMM_CHANNEL_STATE_VAR_SEND_CREDITS);
1882                         channel->state = RFCOMM_CHANNEL_DLC_SETUP;
1883                      }
1884                     break;
1885                 default:
1886                     break;
1887             }
1888             break;
1889 
1890         case RFCOMM_CHANNEL_W4_MULTIPLEXER:
1891             switch (event->type) {
1892                 case CH_EVT_MULTIPLEXER_READY:
1893                     log_info("Muliplexer opened, sending UIH PN next");
1894                     channel->state = RFCOMM_CHANNEL_SEND_UIH_PN;
1895                     break;
1896                 default:
1897                     break;
1898             }
1899             break;
1900 
1901         case RFCOMM_CHANNEL_SEND_UIH_PN:
1902             switch (event->type) {
1903                 case CH_EVT_READY_TO_SEND:
1904                     log_info("Sending UIH Parameter Negotiation Command for #%u (channel 0x%p)", channel->dlci, channel );
1905                     channel->state = RFCOMM_CHANNEL_W4_PN_RSP;
1906                     rfcomm_send_uih_pn_command(multiplexer, channel->dlci, channel->max_frame_size);
1907                     break;
1908                 default:
1909                     break;
1910             }
1911             break;
1912 
1913         case RFCOMM_CHANNEL_W4_PN_RSP:
1914             switch (event->type){
1915                 case CH_EVT_RCVD_PN_RSP:
1916                     // update max frame size
1917                     if (channel->max_frame_size > event_pn->max_frame_size) {
1918                         channel->max_frame_size = event_pn->max_frame_size;
1919                     }
1920                     // new credits
1921                     channel->credits_outgoing = event_pn->credits_outgoing;
1922                     channel->state = RFCOMM_CHANNEL_SEND_SABM_W4_UA;
1923                     break;
1924                 default:
1925                     break;
1926             }
1927             break;
1928 
1929         case RFCOMM_CHANNEL_SEND_SABM_W4_UA:
1930             switch (event->type) {
1931                 case CH_EVT_READY_TO_SEND:
1932                     log_info("Sending SABM #%u", channel->dlci);
1933                     channel->state = RFCOMM_CHANNEL_W4_UA;
1934                     rfcomm_send_sabm(multiplexer, channel->dlci);
1935                     break;
1936                 default:
1937                     break;
1938             }
1939             break;
1940 
1941         case RFCOMM_CHANNEL_W4_UA:
1942             switch (event->type){
1943                 case CH_EVT_RCVD_UA:
1944                     channel->state = RFCOMM_CHANNEL_DLC_SETUP;
1945                     rfcomm_channel_state_add(channel, RFCOMM_CHANNEL_STATE_VAR_SEND_MSC_CMD);
1946                     rfcomm_channel_state_add(channel, RFCOMM_CHANNEL_STATE_VAR_SEND_CREDITS);
1947                     break;
1948                 default:
1949                     break;
1950             }
1951             break;
1952 
1953         case RFCOMM_CHANNEL_DLC_SETUP:
1954             switch (event->type){
1955                 case CH_EVT_RCVD_MSC_CMD:
1956                     rfcomm_channel_state_add(channel, RFCOMM_CHANNEL_STATE_VAR_RCVD_MSC_CMD);
1957                     rfcomm_channel_state_add(channel, RFCOMM_CHANNEL_STATE_VAR_SEND_MSC_RSP);
1958                     break;
1959                 case CH_EVT_RCVD_MSC_RSP:
1960                     rfcomm_channel_state_add(channel, RFCOMM_CHANNEL_STATE_VAR_RCVD_MSC_RSP);
1961                     break;
1962 
1963                 case CH_EVT_READY_TO_SEND:
1964                     if (channel->state_var & RFCOMM_CHANNEL_STATE_VAR_SEND_MSC_CMD){
1965                         log_info("Sending MSC CMD for #%u", channel->dlci);
1966                         rfcomm_channel_state_remove(channel, RFCOMM_CHANNEL_STATE_VAR_SEND_MSC_CMD);
1967                         rfcomm_channel_state_add(channel, RFCOMM_CHANNEL_STATE_VAR_SENT_MSC_CMD);
1968                         rfcomm_send_uih_msc_cmd(multiplexer, channel->dlci , 0x8d);  // ea=1,fc=0,rtc=1,rtr=1,ic=0,dv=1
1969                         break;
1970                     }
1971                     if (channel->state_var & RFCOMM_CHANNEL_STATE_VAR_SEND_CREDITS){
1972                         log_info("Providing credits for #%u", channel->dlci);
1973                         rfcomm_channel_state_remove(channel, RFCOMM_CHANNEL_STATE_VAR_SEND_CREDITS);
1974                         rfcomm_channel_state_add(channel, RFCOMM_CHANNEL_STATE_VAR_SENT_CREDITS);
1975 
1976                         if (channel->new_credits_incoming) {
1977                             uint8_t new_credits = channel->new_credits_incoming;
1978                             channel->new_credits_incoming = 0;
1979                             rfcomm_channel_send_credits(channel, new_credits);
1980                         }
1981                         break;
1982 
1983                     }
1984                     break;
1985                 default:
1986                     break;
1987             }
1988             // finally done?
1989             if (rfcomm_channel_ready_for_open(channel)){
1990                 channel->state = RFCOMM_CHANNEL_OPEN;
1991                 rfcomm_channel_opened(channel);
1992             }
1993             break;
1994 
1995         case RFCOMM_CHANNEL_OPEN:
1996             switch (event->type){
1997                 case CH_EVT_RCVD_MSC_CMD:
1998                     rfcomm_channel_state_add(channel, RFCOMM_CHANNEL_STATE_VAR_SEND_MSC_RSP);
1999                     break;
2000                 case CH_EVT_READY_TO_SEND:
2001                     if (channel->new_credits_incoming) {
2002                         uint8_t new_credits = channel->new_credits_incoming;
2003                         channel->new_credits_incoming = 0;
2004                         rfcomm_channel_send_credits(channel, new_credits);
2005                         break;
2006                     }
2007                     break;
2008                 case CH_EVT_RCVD_CREDITS:
2009                     rfcomm_notify_channel_can_send();
2010                     break;
2011                 default:
2012                     break;
2013             }
2014             break;
2015 
2016         case RFCOMM_CHANNEL_SEND_DM:
2017             switch (event->type) {
2018                 case CH_EVT_READY_TO_SEND:
2019                     log_info("Sending DM_PF for #%u", channel->dlci);
2020                     // don't emit channel closed - channel was never open
2021                     channel->state = RFCOMM_CHANNEL_CLOSED;
2022                     rfcomm_send_dm_pf(multiplexer, channel->dlci);
2023                     rfcomm_channel_finalize(channel);
2024                     *out_channel_valid = 0;
2025                     break;
2026                 default:
2027                     break;
2028             }
2029             break;
2030 
2031         case RFCOMM_CHANNEL_SEND_DISC:
2032             switch (event->type) {
2033                 case CH_EVT_READY_TO_SEND:
2034                     channel->state = RFCOMM_CHANNEL_W4_UA_AFTER_DISC;
2035                     rfcomm_send_disc(multiplexer, channel->dlci);
2036                     break;
2037                 default:
2038                     break;
2039             }
2040             break;
2041 
2042         case RFCOMM_CHANNEL_W4_UA_AFTER_DISC:
2043             switch (event->type){
2044                 case CH_EVT_RCVD_UA:
2045                     channel->state = RFCOMM_CHANNEL_CLOSED;
2046                     rfcomm_emit_channel_closed(channel);
2047                     rfcomm_channel_finalize(channel);
2048                     *out_channel_valid = 0;
2049                     break;
2050                 default:
2051                     break;
2052             }
2053             break;
2054 
2055         case RFCOMM_CHANNEL_SEND_UA_AFTER_DISC:
2056             switch (event->type) {
2057                 case CH_EVT_READY_TO_SEND:
2058                     log_info("Sending UA after DISC for #%u", channel->dlci);
2059                     channel->state = RFCOMM_CHANNEL_CLOSED;
2060                     rfcomm_send_ua(multiplexer, channel->dlci);
2061                     rfcomm_channel_finalize(channel);
2062                     *out_channel_valid = 0;
2063                     break;
2064                 default:
2065                     break;
2066             }
2067             break;
2068 
2069         default:
2070             break;
2071     }
2072 }
2073 
2074 // MARK: RFCOMM BTstack API
2075 
2076 void rfcomm_init(void){
2077     rfcomm_client_cid_generator = 0;
2078     rfcomm_multiplexers = NULL;
2079     rfcomm_services     = NULL;
2080     rfcomm_channels     = NULL;
2081     rfcomm_security_level = LEVEL_2;
2082 }
2083 
2084 void rfcomm_set_required_security_level(gap_security_level_t security_level){
2085     rfcomm_security_level = security_level;
2086 }
2087 
2088 int rfcomm_can_send_packet_now(uint16_t rfcomm_cid){
2089     rfcomm_channel_t * channel = rfcomm_channel_for_rfcomm_cid(rfcomm_cid);
2090     if (!channel){
2091         log_error("rfcomm_send cid 0x%02x doesn't exist!", rfcomm_cid);
2092         return 0;
2093     }
2094     return rfcomm_channel_can_send(channel);
2095 }
2096 
2097 void rfcomm_request_can_send_now_event(uint16_t rfcomm_cid){
2098     rfcomm_channel_t * channel = rfcomm_channel_for_rfcomm_cid(rfcomm_cid);
2099     if (!channel){
2100         log_error("rfcomm_send cid 0x%02x doesn't exist!", rfcomm_cid);
2101         return;
2102     }
2103     channel->waiting_for_can_send_now = 1;
2104     l2cap_request_can_send_now_event(channel->multiplexer->l2cap_cid);
2105 }
2106 
2107 static int rfcomm_assert_send_valid(rfcomm_channel_t * channel , uint16_t len){
2108     if (len > channel->max_frame_size){
2109         log_error("rfcomm_send cid 0x%02x, rfcomm data lenght exceeds MTU!", channel->rfcomm_cid);
2110         return RFCOMM_DATA_LEN_EXCEEDS_MTU;
2111     }
2112 
2113 #ifdef RFCOMM_USE_OUTGOING_BUFFER
2114     if (len > rfcomm_max_frame_size_for_l2cap_mtu(sizeof(outgoing_buffer))){
2115         log_error("rfcomm_send cid 0x%02x, length exceeds outgoing rfcomm_out_buffer", channel->rfcomm_cid);
2116         return RFCOMM_DATA_LEN_EXCEEDS_MTU;
2117     }
2118 #endif
2119 
2120     if (!channel->credits_outgoing){
2121         log_info("rfcomm_send cid 0x%02x, no rfcomm outgoing credits!", channel->rfcomm_cid);
2122         return RFCOMM_NO_OUTGOING_CREDITS;
2123     }
2124 
2125     if ((channel->multiplexer->fcon & 1) == 0){
2126         log_info("rfcomm_send cid 0x%02x, aggregate flow off!", channel->rfcomm_cid);
2127         return RFCOMM_AGGREGATE_FLOW_OFF;
2128     }
2129     return 0;
2130 }
2131 
2132 uint16_t rfcomm_get_max_frame_size(uint16_t rfcomm_cid){
2133     rfcomm_channel_t * channel = rfcomm_channel_for_rfcomm_cid(rfcomm_cid);
2134     if (!channel){
2135         log_error("rfcomm_get_max_frame_size cid 0x%02x doesn't exist!", rfcomm_cid);
2136         return 0;
2137     }
2138     return channel->max_frame_size;
2139 }
2140 
2141 // pre: rfcomm_can_send_packet_now(rfcomm_cid) == true
2142 int rfcomm_reserve_packet_buffer(void){
2143 #ifdef RFCOMM_USE_OUTGOING_BUFFER
2144     log_error("rfcomm_reserve_packet_buffer should not get called with ERTM");
2145     return 0;
2146 #else
2147     return l2cap_reserve_packet_buffer();
2148 #endif
2149 }
2150 
2151 void rfcomm_release_packet_buffer(void){
2152 #ifdef RFCOMM_USE_OUTGOING_BUFFER
2153     log_error("rfcomm_release_packet_buffer should not get called with ERTM");
2154 #else
2155     l2cap_release_packet_buffer();
2156 #endif
2157 }
2158 
2159 uint8_t * rfcomm_get_outgoing_buffer(void){
2160 #ifdef RFCOMM_USE_OUTGOING_BUFFER
2161     uint8_t * rfcomm_out_buffer = outgoing_buffer;
2162 #else
2163     uint8_t * rfcomm_out_buffer = l2cap_get_outgoing_buffer();
2164 #endif
2165     // address + control + length (16) + no credit field
2166     return &rfcomm_out_buffer[4];
2167 }
2168 
2169 int rfcomm_send_prepared(uint16_t rfcomm_cid, uint16_t len){
2170     rfcomm_channel_t * channel = rfcomm_channel_for_rfcomm_cid(rfcomm_cid);
2171     if (!channel){
2172         log_error("rfcomm_send_prepared cid 0x%02x doesn't exist!", rfcomm_cid);
2173         return 0;
2174     }
2175 
2176     int err = rfcomm_assert_send_valid(channel, len);
2177     if (err) return err;
2178 
2179 #ifdef RFCOMM_USE_OUTGOING_BUFFER
2180     if (!l2cap_can_send_packet_now(channel->multiplexer->l2cap_cid)){
2181         log_error("rfcomm_send_prepared: l2cap cannot send now");
2182         return BTSTACK_ACL_BUFFERS_FULL;
2183     }
2184 #else
2185     if (!l2cap_can_send_prepared_packet_now(channel->multiplexer->l2cap_cid)){
2186         log_error("rfcomm_send_prepared: l2cap cannot send now");
2187         return BTSTACK_ACL_BUFFERS_FULL;
2188     }
2189 #endif
2190 
2191     // send might cause l2cap to emit new credits, update counters first
2192     if (len){
2193         channel->credits_outgoing--;
2194     } else {
2195         log_info("sending empty RFCOMM packet for cid %02x", rfcomm_cid);
2196     }
2197 
2198     int result = rfcomm_send_uih_prepared(channel->multiplexer, channel->dlci, len);
2199 
2200     if (result != 0) {
2201         if (len) {
2202             channel->credits_outgoing++;
2203         }
2204         log_error("rfcomm_send_prepared: error %d", result);
2205         return result;
2206     }
2207 
2208     return result;
2209 }
2210 
2211 int rfcomm_send(uint16_t rfcomm_cid, uint8_t *data, uint16_t len){
2212     rfcomm_channel_t * channel = rfcomm_channel_for_rfcomm_cid(rfcomm_cid);
2213     if (!channel){
2214         log_error("cid 0x%02x doesn't exist!", rfcomm_cid);
2215         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
2216     }
2217 
2218     int err = rfcomm_assert_send_valid(channel, len);
2219     if (err) return err;
2220     if (!l2cap_can_send_packet_now(channel->multiplexer->l2cap_cid)){
2221         log_error("rfcomm_send_internal: l2cap cannot send now");
2222         return BTSTACK_ACL_BUFFERS_FULL;
2223     }
2224 
2225 #ifdef RFCOMM_USE_OUTGOING_BUFFER
2226 #else
2227     rfcomm_reserve_packet_buffer();
2228 #endif
2229     uint8_t * rfcomm_payload = rfcomm_get_outgoing_buffer();
2230 
2231     memcpy(rfcomm_payload, data, len);
2232     err = rfcomm_send_prepared(rfcomm_cid, len);
2233 
2234 #ifdef RFCOMM_USE_OUTGOING_BUFFER
2235 #else
2236     if (err){
2237         rfcomm_release_packet_buffer();
2238     }
2239 #endif
2240 
2241     return err;
2242 }
2243 
2244 // Sends Local Lnie Status, see LINE_STATUS_..
2245 int rfcomm_send_local_line_status(uint16_t rfcomm_cid, uint8_t line_status){
2246     rfcomm_channel_t * channel = rfcomm_channel_for_rfcomm_cid(rfcomm_cid);
2247     if (!channel){
2248         log_error("rfcomm_send_local_line_status cid 0x%02x doesn't exist!", rfcomm_cid);
2249         return 0;
2250     }
2251     return rfcomm_send_uih_rls_cmd(channel->multiplexer, channel->dlci, line_status);
2252 }
2253 
2254 // Sned local modem status. see MODEM_STAUS_..
2255 int rfcomm_send_modem_status(uint16_t rfcomm_cid, uint8_t modem_status){
2256     rfcomm_channel_t * channel = rfcomm_channel_for_rfcomm_cid(rfcomm_cid);
2257     if (!channel){
2258         log_error("rfcomm_send_modem_status cid 0x%02x doesn't exist!", rfcomm_cid);
2259         return 0;
2260     }
2261     return rfcomm_send_uih_msc_cmd(channel->multiplexer, channel->dlci, modem_status);
2262 }
2263 
2264 // Configure remote port
2265 int rfcomm_send_port_configuration(uint16_t rfcomm_cid, rpn_baud_t baud_rate, rpn_data_bits_t data_bits, rpn_stop_bits_t stop_bits, rpn_parity_t parity, rpn_flow_control_t flow_control){
2266     rfcomm_channel_t * channel = rfcomm_channel_for_rfcomm_cid(rfcomm_cid);
2267     if (!channel){
2268         log_error("rfcomm_send_port_configuration cid 0x%02x doesn't exist!", rfcomm_cid);
2269         return 0;
2270     }
2271     rfcomm_rpn_data_t rpn_data;
2272     rpn_data.baud_rate = baud_rate;
2273     rpn_data.flags = data_bits | (stop_bits << 2) | (parity << 3);
2274     rpn_data.flow_control = flow_control;
2275     rpn_data.xon = 0;
2276     rpn_data.xoff = 0;
2277     rpn_data.parameter_mask_0 = 0x1f;   // all but xon/xoff
2278     rpn_data.parameter_mask_1 = 0x3f;   // all flow control options
2279     return rfcomm_send_uih_rpn_cmd(channel->multiplexer, channel->dlci, &rpn_data);
2280 }
2281 
2282 // Query remote port
2283 int rfcomm_query_port_configuration(uint16_t rfcomm_cid){
2284     rfcomm_channel_t * channel = rfcomm_channel_for_rfcomm_cid(rfcomm_cid);
2285     if (!channel){
2286         log_error("rfcomm_query_port_configuration cid 0x%02x doesn't exist!", rfcomm_cid);
2287         return 0;
2288     }
2289     return rfcomm_send_uih_rpn_req(channel->multiplexer, channel->dlci);
2290 }
2291 
2292 
2293 static uint8_t rfcomm_channel_create_internal(btstack_packet_handler_t packet_handler, bd_addr_t addr, uint8_t server_channel, uint8_t incoming_flow_control, uint8_t initial_credits, uint16_t * out_rfcomm_cid){
2294     log_info("RFCOMM_CREATE_CHANNEL addr %s channel #%u init credits %u",  bd_addr_to_str(addr), server_channel, initial_credits);
2295 
2296     // create new multiplexer if necessary
2297     uint8_t status = 0;
2298     uint8_t dlci = 0;
2299     int new_multiplexer = 0;
2300     rfcomm_channel_t * channel = NULL;
2301     rfcomm_multiplexer_t * multiplexer = rfcomm_multiplexer_for_addr(addr);
2302     if (!multiplexer) {
2303         multiplexer = rfcomm_multiplexer_create_for_addr(addr);
2304         if (!multiplexer){
2305             status = BTSTACK_MEMORY_ALLOC_FAILED;
2306             goto fail;
2307         }
2308         multiplexer->outgoing = 1;
2309         multiplexer->state = RFCOMM_MULTIPLEXER_W4_CONNECT;
2310         new_multiplexer = 1;
2311     }
2312 
2313     // check if channel for this remote service already exists
2314     dlci = (server_channel << 1) | (multiplexer->outgoing ^ 1);
2315     channel = rfcomm_channel_for_multiplexer_and_dlci(multiplexer, dlci);
2316     if (channel){
2317         status = RFCOMM_CHANNEL_ALREADY_REGISTERED;
2318         goto fail;
2319     }
2320 
2321     // prepare channel
2322     channel = rfcomm_channel_create(multiplexer, NULL, server_channel);
2323     if (!channel){
2324         status = BTSTACK_MEMORY_ALLOC_FAILED;
2325         goto fail;
2326     }
2327 
2328     // rfcomm_cid is already assigned by rfcomm_channel_create
2329     channel->incoming_flow_control = incoming_flow_control;
2330     channel->new_credits_incoming  = initial_credits;
2331     channel->packet_handler = packet_handler;
2332 
2333     // return rfcomm_cid
2334     if (out_rfcomm_cid){
2335         *out_rfcomm_cid = channel->rfcomm_cid;
2336     }
2337 
2338     // start multiplexer setup
2339     if (multiplexer->state != RFCOMM_MULTIPLEXER_OPEN) {
2340         channel->state = RFCOMM_CHANNEL_W4_MULTIPLEXER;
2341         uint16_t l2cap_cid = 0;
2342         status = l2cap_create_channel(rfcomm_packet_handler, addr, BLUETOOTH_PROTOCOL_RFCOMM, l2cap_max_mtu(), &l2cap_cid);
2343         if (status) goto fail;
2344         multiplexer->l2cap_cid = l2cap_cid;
2345         return 0;
2346     }
2347 
2348     channel->state = RFCOMM_CHANNEL_SEND_UIH_PN;
2349 
2350     // start connecting, if multiplexer is already up and running
2351     l2cap_request_can_send_now_event(multiplexer->l2cap_cid);
2352     return 0;
2353 
2354 fail:
2355     if (new_multiplexer) btstack_memory_rfcomm_multiplexer_free(multiplexer);
2356     if (channel)         btstack_memory_rfcomm_channel_free(channel);
2357     return status;
2358 }
2359 
2360 uint8_t rfcomm_create_channel_with_initial_credits(btstack_packet_handler_t packet_handler, bd_addr_t addr, uint8_t server_channel, uint8_t initial_credits, uint16_t * out_rfcomm_cid){
2361     return rfcomm_channel_create_internal(packet_handler, addr, server_channel, 1, initial_credits, out_rfcomm_cid);
2362 }
2363 
2364 uint8_t rfcomm_create_channel(btstack_packet_handler_t packet_handler, bd_addr_t addr, uint8_t server_channel, uint16_t * out_rfcomm_cid){
2365     return rfcomm_channel_create_internal(packet_handler, addr, server_channel, 0, RFCOMM_CREDITS, out_rfcomm_cid);
2366 }
2367 
2368 void rfcomm_disconnect(uint16_t rfcomm_cid){
2369     log_info("RFCOMM_DISCONNECT cid 0x%02x", rfcomm_cid);
2370     rfcomm_channel_t * channel = rfcomm_channel_for_rfcomm_cid(rfcomm_cid);
2371     if (!channel) return;
2372 
2373     channel->state = RFCOMM_CHANNEL_SEND_DISC;
2374     l2cap_request_can_send_now_event(channel->multiplexer->l2cap_cid);
2375 }
2376 
2377 static uint8_t rfcomm_register_service_internal(btstack_packet_handler_t packet_handler,
2378     uint8_t channel, uint16_t max_frame_size, uint8_t incoming_flow_control, uint8_t initial_credits){
2379 
2380     log_info("RFCOMM_REGISTER_SERVICE channel #%u mtu %u flow_control %u credits %u",
2381              channel, max_frame_size, incoming_flow_control, initial_credits);
2382 
2383     // check if already registered
2384     rfcomm_service_t * service = rfcomm_service_for_channel(channel);
2385     if (service){
2386         return RFCOMM_CHANNEL_ALREADY_REGISTERED;
2387     }
2388 
2389     // alloc structure
2390     service = btstack_memory_rfcomm_service_get();
2391     if (!service) {
2392         return BTSTACK_MEMORY_ALLOC_FAILED;
2393     }
2394 
2395     // register with l2cap if not registered before, max MTU
2396     if (btstack_linked_list_empty(&rfcomm_services)){
2397         l2cap_register_service(rfcomm_packet_handler, BLUETOOTH_PROTOCOL_RFCOMM, 0xffff, rfcomm_security_level);
2398     }
2399 
2400     // fill in
2401     service->packet_handler = packet_handler;
2402     service->server_channel = channel;
2403     service->max_frame_size = max_frame_size;
2404     service->incoming_flow_control = incoming_flow_control;
2405     service->incoming_initial_credits = initial_credits;
2406 
2407     // add to services list
2408     btstack_linked_list_add(&rfcomm_services, (btstack_linked_item_t *) service);
2409 
2410     return 0;
2411 }
2412 
2413 uint8_t rfcomm_register_service_with_initial_credits(btstack_packet_handler_t packet_handler,
2414     uint8_t channel, uint16_t max_frame_size, uint8_t initial_credits){
2415 
2416     return rfcomm_register_service_internal(packet_handler, channel, max_frame_size, 1, initial_credits);
2417 }
2418 
2419 uint8_t rfcomm_register_service(btstack_packet_handler_t packet_handler, uint8_t channel,
2420     uint16_t max_frame_size){
2421 
2422     return rfcomm_register_service_internal(packet_handler, channel, max_frame_size, 0,RFCOMM_CREDITS);
2423 }
2424 
2425 void rfcomm_unregister_service(uint8_t service_channel){
2426     log_info("RFCOMM_UNREGISTER_SERVICE #%u", service_channel);
2427     rfcomm_service_t *service = rfcomm_service_for_channel(service_channel);
2428     if (!service) return;
2429     btstack_linked_list_remove(&rfcomm_services, (btstack_linked_item_t *) service);
2430     btstack_memory_rfcomm_service_free(service);
2431 
2432     // unregister if no services active
2433     if (btstack_linked_list_empty(&rfcomm_services)){
2434         // bt_send_cmd(&l2cap_unregister_service, BLUETOOTH_PROTOCOL_RFCOMM);
2435         l2cap_unregister_service(BLUETOOTH_PROTOCOL_RFCOMM);
2436     }
2437 }
2438 
2439 void rfcomm_accept_connection(uint16_t rfcomm_cid){
2440     log_info("RFCOMM_ACCEPT_CONNECTION cid 0x%02x", rfcomm_cid);
2441     rfcomm_channel_t * channel = rfcomm_channel_for_rfcomm_cid(rfcomm_cid);
2442     if (!channel) return;
2443     switch (channel->state) {
2444         case RFCOMM_CHANNEL_INCOMING_SETUP:
2445             rfcomm_channel_state_add(channel, RFCOMM_CHANNEL_STATE_VAR_CLIENT_ACCEPTED);
2446             if (channel->state_var & RFCOMM_CHANNEL_STATE_VAR_RCVD_PN){
2447                 rfcomm_channel_state_add(channel, RFCOMM_CHANNEL_STATE_VAR_SEND_PN_RSP);
2448                 l2cap_request_can_send_now_event(channel->multiplexer->l2cap_cid);
2449             }
2450             if (channel->state_var & RFCOMM_CHANNEL_STATE_VAR_RCVD_SABM){
2451                 rfcomm_channel_state_add(channel, RFCOMM_CHANNEL_STATE_VAR_SEND_UA);
2452                 l2cap_request_can_send_now_event(channel->multiplexer->l2cap_cid);
2453             }
2454             // at least one of { PN RSP, UA } needs to be sent
2455             // state transistion incoming setup -> dlc setup happens in rfcomm_run after these have been sent
2456             break;
2457         default:
2458             break;
2459     }
2460 
2461 }
2462 
2463 void rfcomm_decline_connection(uint16_t rfcomm_cid){
2464     log_info("RFCOMM_DECLINE_CONNECTION cid 0x%02x", rfcomm_cid);
2465     rfcomm_channel_t * channel = rfcomm_channel_for_rfcomm_cid(rfcomm_cid);
2466     if (!channel) return;
2467     switch (channel->state) {
2468         case RFCOMM_CHANNEL_INCOMING_SETUP:
2469             channel->state = RFCOMM_CHANNEL_SEND_DM;
2470             l2cap_request_can_send_now_event(channel->multiplexer->l2cap_cid);
2471             break;
2472         default:
2473             break;
2474     }
2475 }
2476 
2477 void rfcomm_grant_credits(uint16_t rfcomm_cid, uint8_t credits){
2478     log_info("RFCOMM_GRANT_CREDITS cid 0x%02x credits %u", rfcomm_cid, credits);
2479     rfcomm_channel_t * channel = rfcomm_channel_for_rfcomm_cid(rfcomm_cid);
2480     if (!channel) return;
2481     if (!channel->incoming_flow_control) return;
2482     channel->new_credits_incoming += credits;
2483 
2484     // process
2485     l2cap_request_can_send_now_event(channel->multiplexer->l2cap_cid);
2486 }
2487 
2488