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