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