xref: /btstack/src/classic/rfcomm.c (revision 1882d12dc36ae7b48f7f4ed3fd8d029fba3b08b1)
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                 // note: repeatedly go over list until full iteration causes no further change
992                 int done;
993                 do {
994                     done = 1;
995                     btstack_linked_item_t * it = (btstack_linked_item_t *) &rfcomm_channels;
996                     while (it->next) {
997                         rfcomm_channel_t * channel = (rfcomm_channel_t *) it->next;
998                         if (channel->multiplexer == multiplexer){
999                             done = 0;
1000                             rfcomm_emit_channel_opened(channel, status);
1001                             btstack_linked_list_remove(&rfcomm_channels, (btstack_linked_item_t *) channel);
1002                             btstack_memory_rfcomm_channel_free(channel);
1003                             break;
1004                         } else {
1005                             it = it->next;
1006                         }
1007                     }
1008                 } while (!done);
1009 
1010                 // free multiplexer
1011                 rfcomm_multiplexer_free(multiplexer);
1012                 return 1;
1013             }
1014 
1015             // following could be: rfcom_multiplexer_state_machein(..., EVENT_L2CAP_OPENED)
1016 
1017             if (multiplexer->state == RFCOMM_MULTIPLEXER_W4_CONNECT) {
1018                 log_info("L2CAP_EVENT_CHANNEL_OPENED: outgoing connection");
1019                 // wrong remote addr
1020                 if (bd_addr_cmp(event_addr, multiplexer->remote_addr)) break;
1021                 multiplexer->l2cap_cid = l2cap_cid;
1022                 multiplexer->con_handle = con_handle;
1023                 // send SABM #0
1024                 rfcomm_multiplexer_set_state_and_request_can_send_now_event(multiplexer, RFCOMM_MULTIPLEXER_SEND_SABM_0);
1025 
1026             } else { // multiplexer->state == RFCOMM_MULTIPLEXER_W4_SABM_0
1027 
1028                 // set max frame size based on l2cap MTU
1029                 multiplexer->max_frame_size = rfcomm_max_frame_size_for_l2cap_mtu(little_endian_read_16(packet, 17));
1030             }
1031             return 1;
1032 
1033             // l2cap disconnect -> state = RFCOMM_MULTIPLEXER_CLOSED;
1034 
1035         // Notify channel packet handler if they can send now
1036         case L2CAP_EVENT_CAN_SEND_NOW:
1037             l2cap_cid = l2cap_event_can_send_now_get_local_cid(packet);
1038             rfcomm_handle_can_send_now(l2cap_cid);
1039             return 1;
1040 
1041         case L2CAP_EVENT_CHANNEL_CLOSED:
1042             // data: event (8), len(8), channel (16)
1043             l2cap_cid = little_endian_read_16(packet, 2);
1044             multiplexer = rfcomm_multiplexer_for_l2cap_cid(l2cap_cid);
1045             log_info("L2CAP_EVENT_CHANNEL_CLOSED cid 0x%0x, mult %p", l2cap_cid, multiplexer);
1046             if (!multiplexer) break;
1047             log_info("L2CAP_EVENT_CHANNEL_CLOSED state %u", multiplexer->state);
1048             // no need to call l2cap_disconnect here, as it's already closed
1049             rfcomm_multiplexer_finalize(multiplexer);
1050             return 1;
1051 
1052         default:
1053             break;
1054     }
1055     return 0;
1056 }
1057 
1058 static int rfcomm_multiplexer_l2cap_packet_handler(uint16_t channel, uint8_t *packet, uint16_t size){
1059     // get or create a multiplexer for a certain device
1060     rfcomm_multiplexer_t *multiplexer = rfcomm_multiplexer_for_l2cap_cid(channel);
1061     if (!multiplexer) return 0;
1062 
1063     uint16_t l2cap_cid = multiplexer->l2cap_cid;
1064 
1065 	// but only care for multiplexer control channel
1066     uint8_t frame_dlci = packet[0] >> 2;
1067     if (frame_dlci) return 0;
1068     const uint8_t length_offset = (packet[2] & 1) ^ 1;  // to be used for pos >= 3
1069     const uint8_t credit_offset = ((packet[1] & BT_RFCOMM_UIH_PF) == BT_RFCOMM_UIH_PF) ? 1 : 0;   // credits for uih_pf frames
1070     const uint8_t payload_offset = 3 + length_offset + credit_offset;
1071     switch (packet[1]){
1072 
1073         case BT_RFCOMM_SABM:
1074             if (multiplexer->state == RFCOMM_MULTIPLEXER_W4_SABM_0){
1075                 log_info("Received SABM #0");
1076                 multiplexer->outgoing = 0;
1077                 rfcomm_multiplexer_set_state_and_request_can_send_now_event(multiplexer, RFCOMM_MULTIPLEXER_SEND_UA_0);
1078                 return 1;
1079             }
1080             break;
1081 
1082         case BT_RFCOMM_UA:
1083             if (multiplexer->state == RFCOMM_MULTIPLEXER_W4_UA_0) {
1084                 // UA #0 -> send UA #0, state = RFCOMM_MULTIPLEXER_OPEN
1085                 log_info("Received UA #0 ");
1086                 rfcomm_multiplexer_opened(multiplexer);
1087                 return 1;
1088             }
1089             break;
1090 
1091         case BT_RFCOMM_DISC:
1092             // DISC #0 -> send UA #0, close multiplexer
1093             log_info("Received DISC #0, (ougoing = %u)", multiplexer->outgoing);
1094             rfcomm_multiplexer_set_state_and_request_can_send_now_event(multiplexer, RFCOMM_MULTIPLEXER_SEND_UA_0_AND_DISC);
1095             return 1;
1096 
1097         case BT_RFCOMM_DM:
1098             // DM #0 - we shouldn't get this, just give up
1099             log_info("Received DM #0");
1100             log_info("-> Closing down multiplexer");
1101             rfcomm_multiplexer_finalize(multiplexer);
1102             l2cap_disconnect(l2cap_cid, 0x13);
1103             return 1;
1104 
1105         case BT_RFCOMM_UIH:
1106             if (packet[payload_offset] == BT_RFCOMM_CLD_CMD){
1107                 // Multiplexer close down (CLD) -> close mutliplexer
1108                 log_info("Received Multiplexer close down command");
1109                 log_info("-> Closing down multiplexer");
1110                 rfcomm_multiplexer_finalize(multiplexer);
1111                 l2cap_disconnect(l2cap_cid, 0x13);
1112                 return 1;
1113             }
1114             switch (packet[payload_offset]){
1115                 case BT_RFCOMM_CLD_CMD:
1116                      // Multiplexer close down (CLD) -> close mutliplexer
1117                     log_info("Received Multiplexer close down command");
1118                     log_info("-> Closing down multiplexer");
1119                     rfcomm_multiplexer_finalize(multiplexer);
1120                     l2cap_disconnect(l2cap_cid, 0x13);
1121                     return 1;
1122 
1123                 case BT_RFCOMM_FCON_CMD:
1124                     multiplexer->fcon = 0x81;
1125                     l2cap_request_can_send_now_event(multiplexer->l2cap_cid);
1126                     return 1;
1127 
1128                 case BT_RFCOMM_FCOFF_CMD:
1129                     multiplexer->fcon = 0x80;
1130                     l2cap_request_can_send_now_event(multiplexer->l2cap_cid);
1131                     return 1;
1132 
1133                 case BT_RFCOMM_TEST_CMD: {
1134                     log_info("Received test command");
1135                     int len = packet[payload_offset+1] >> 1; // length < 125
1136                     if (len > RFCOMM_TEST_DATA_MAX_LEN){
1137                         len = RFCOMM_TEST_DATA_MAX_LEN;
1138                     }
1139                     len = btstack_min(len, size - 1 - payload_offset);  // avoid information leak
1140                     multiplexer->test_data_len = len;
1141                     memcpy(multiplexer->test_data, &packet[payload_offset + 2], len);
1142                     l2cap_request_can_send_now_event(multiplexer->l2cap_cid);
1143                     return 1;
1144                 }
1145                 default:
1146                     break;
1147             }
1148             break;
1149 
1150         default:
1151             break;
1152 
1153     }
1154     return 0;
1155 }
1156 
1157 static int rfcomm_multiplexer_ready_to_send(rfcomm_multiplexer_t * multiplexer){
1158     if (multiplexer->send_dm_for_dlci) return 1;
1159     if (multiplexer->nsc_command) return 1;
1160     if (multiplexer->fcon & 0x80) return 1;
1161     switch (multiplexer->state){
1162         case RFCOMM_MULTIPLEXER_SEND_SABM_0:
1163         case RFCOMM_MULTIPLEXER_SEND_UA_0:
1164         case RFCOMM_MULTIPLEXER_SEND_UA_0_AND_DISC:
1165             return 1;
1166         case RFCOMM_MULTIPLEXER_OPEN:
1167             if (multiplexer->test_data_len) {
1168                 return 1;
1169             }
1170             break;
1171         default:
1172             break;
1173     }
1174     return 0;
1175 }
1176 
1177 static void rfcomm_multiplexer_state_machine(rfcomm_multiplexer_t * multiplexer, RFCOMM_MULTIPLEXER_EVENT event){
1178 
1179     if (event != MULT_EV_READY_TO_SEND) return;
1180 
1181     uint16_t l2cap_cid = multiplexer->l2cap_cid;
1182 
1183     // process stored DM responses
1184     if (multiplexer->send_dm_for_dlci){
1185         uint8_t dlci = multiplexer->send_dm_for_dlci;
1186         multiplexer->send_dm_for_dlci = 0;
1187         rfcomm_send_dm_pf(multiplexer, dlci);
1188         return;
1189     }
1190 
1191     if (multiplexer->nsc_command){
1192         uint8_t command = multiplexer->nsc_command;
1193         multiplexer->nsc_command = 0;
1194         rfcomm_send_uih_nsc_rsp(multiplexer, command);
1195         return;
1196     }
1197 
1198     if (multiplexer->fcon & 0x80){
1199         multiplexer->fcon &= 0x01;
1200         rfcomm_send_uih_fc_rsp(multiplexer, multiplexer->fcon);
1201 
1202         if (multiplexer->fcon == 0) return;
1203         // trigger client to send again after sending FCon Response
1204         rfcomm_notify_channel_can_send();
1205         return;
1206     }
1207 
1208     switch (multiplexer->state) {
1209         case RFCOMM_MULTIPLEXER_SEND_SABM_0:
1210             log_info("Sending SABM #0 - (multi 0x%p)", multiplexer);
1211             multiplexer->state = RFCOMM_MULTIPLEXER_W4_UA_0;
1212             rfcomm_send_sabm(multiplexer, 0);
1213             break;
1214         case RFCOMM_MULTIPLEXER_SEND_UA_0:
1215             log_info("Sending UA #0");
1216             multiplexer->state = RFCOMM_MULTIPLEXER_OPEN;
1217             rfcomm_send_ua(multiplexer, 0);
1218 
1219             rfcomm_multiplexer_opened(multiplexer);
1220             break;
1221         case RFCOMM_MULTIPLEXER_SEND_UA_0_AND_DISC:
1222             // try to detect authentication errors: drop link key if multiplexer closed before first channel got opened
1223             if (!multiplexer->at_least_one_connection){
1224                 log_info("TODO: no connections established - delete link key prophylactically");
1225                 // hci_send_cmd(&hci_delete_stored_link_key, multiplexer->remote_addr);
1226             }
1227             log_info("Sending UA #0");
1228             log_info("Closing down multiplexer");
1229             multiplexer->state = RFCOMM_MULTIPLEXER_CLOSED;
1230             rfcomm_send_ua(multiplexer, 0);
1231 
1232             rfcomm_multiplexer_finalize(multiplexer);
1233             l2cap_disconnect(l2cap_cid, 0x13);
1234             break;
1235         case RFCOMM_MULTIPLEXER_OPEN:
1236             // respond to test command
1237             if (multiplexer->test_data_len){
1238                 int len = multiplexer->test_data_len;
1239                 log_info("Sending TEST Response with %u bytes", len);
1240                 multiplexer->test_data_len = 0;
1241                 rfcomm_send_uih_test_rsp(multiplexer, multiplexer->test_data, len);
1242                 return;
1243             }
1244             break;
1245         default:
1246             break;
1247     }
1248 }
1249 
1250 // MARK: RFCOMM CHANNEL
1251 
1252 static void rfcomm_channel_send_credits(rfcomm_channel_t *channel, uint8_t credits){
1253     channel->credits_incoming += credits;
1254     rfcomm_send_uih_credits(channel->multiplexer, channel->dlci, credits);
1255 }
1256 
1257 static int rfcomm_channel_can_send(rfcomm_channel_t * channel){
1258     if (!channel->credits_outgoing) return 0;
1259     if ((channel->multiplexer->fcon & 1) == 0) return 0;
1260     return l2cap_can_send_packet_now(channel->multiplexer->l2cap_cid);
1261 }
1262 
1263 static void rfcomm_channel_opened(rfcomm_channel_t *rfChannel){
1264 
1265     log_info("rfcomm_channel_opened!");
1266 
1267     rfChannel->state = RFCOMM_CHANNEL_OPEN;
1268     rfcomm_emit_channel_opened(rfChannel, 0);
1269     rfcomm_emit_port_configuration(rfChannel);
1270 
1271     // remove (potential) timer
1272     rfcomm_multiplexer_t *multiplexer = rfChannel->multiplexer;
1273     if (multiplexer->timer_active) {
1274         btstack_run_loop_remove_timer(&multiplexer->timer);
1275         multiplexer->timer_active = 0;
1276     }
1277     // hack for problem detecting authentication failure
1278     multiplexer->at_least_one_connection = 1;
1279 
1280     // request can send now if channel ready
1281     if (rfcomm_channel_ready_to_send(rfChannel)){
1282         l2cap_request_can_send_now_event(multiplexer->l2cap_cid);
1283     }
1284 }
1285 
1286 static void rfcomm_channel_packet_handler_uih(rfcomm_multiplexer_t *multiplexer, uint8_t * packet, uint16_t size){
1287     const uint8_t frame_dlci = packet[0] >> 2;
1288     const uint8_t length_offset = (packet[2] & 1) ^ 1;  // to be used for pos >= 3
1289     const uint8_t credit_offset = ((packet[1] & BT_RFCOMM_UIH_PF) == BT_RFCOMM_UIH_PF) ? 1 : 0;   // credits for uih_pf frames
1290     const uint8_t payload_offset = 3 + length_offset + credit_offset;
1291 
1292     rfcomm_channel_t * channel = rfcomm_channel_for_multiplexer_and_dlci(multiplexer, frame_dlci);
1293     if (!channel) return;
1294 
1295     // handle new outgoing credits
1296     if (packet[1] == BT_RFCOMM_UIH_PF) {
1297 
1298         // add them
1299         uint16_t new_credits = packet[3+length_offset];
1300         channel->credits_outgoing += new_credits;
1301         log_info( "RFCOMM data UIH_PF, new credits: %u, now %u", new_credits, channel->credits_outgoing);
1302 
1303         // notify channel statemachine
1304         rfcomm_channel_event_t channel_event = { CH_EVT_RCVD_CREDITS, 0 };
1305         rfcomm_channel_state_machine_with_channel(channel, &channel_event);
1306         if (rfcomm_channel_ready_to_send(channel)){
1307             l2cap_request_can_send_now_event(multiplexer->l2cap_cid);
1308         }
1309     }
1310 
1311     // contains payload?
1312     if (size - 1 > payload_offset){
1313 
1314         // log_info( "RFCOMM data UIH_PF, size %u, channel %p", size-payload_offset-1, rfChannel->connection);
1315 
1316         // decrease incoming credit counter
1317         if (channel->credits_incoming > 0){
1318             channel->credits_incoming--;
1319         }
1320 
1321         // deliver payload
1322         (channel->packet_handler)(RFCOMM_DATA_PACKET, channel->rfcomm_cid,
1323                               &packet[payload_offset], size-payload_offset-1);
1324     }
1325 
1326     // automatically provide new credits to remote device, if no incoming flow control
1327     if (!channel->incoming_flow_control && channel->credits_incoming < 5){
1328         channel->new_credits_incoming = RFCOMM_CREDITS;
1329         l2cap_request_can_send_now_event(multiplexer->l2cap_cid);
1330     }
1331 }
1332 
1333 static void rfcomm_channel_accept_pn(rfcomm_channel_t *channel, rfcomm_channel_event_pn_t *event){
1334     // priority of client request
1335     channel->pn_priority = event->priority;
1336 
1337     // new credits
1338     channel->credits_outgoing = event->credits_outgoing;
1339 
1340     // negotiate max frame size
1341     if (channel->max_frame_size > channel->multiplexer->max_frame_size) {
1342         channel->max_frame_size = channel->multiplexer->max_frame_size;
1343     }
1344     if (channel->max_frame_size > event->max_frame_size) {
1345         channel->max_frame_size = event->max_frame_size;
1346     }
1347 
1348 }
1349 
1350 static void rfcomm_channel_finalize(rfcomm_channel_t *channel){
1351 
1352     rfcomm_multiplexer_t *multiplexer = channel->multiplexer;
1353 
1354     // remove from list
1355     btstack_linked_list_remove( &rfcomm_channels, (btstack_linked_item_t *) channel);
1356 
1357     // free channel
1358     btstack_memory_rfcomm_channel_free(channel);
1359 
1360     // update multiplexer timeout after channel was removed from list
1361     rfcomm_multiplexer_prepare_idle_timer(multiplexer);
1362 }
1363 
1364 static void rfcomm_channel_state_machine_with_dlci(rfcomm_multiplexer_t * multiplexer, uint8_t dlci, const rfcomm_channel_event_t *event){
1365 
1366     // TODO: if client max frame size is smaller than RFCOMM_DEFAULT_SIZE, send PN
1367 
1368 
1369     // lookup existing channel
1370     rfcomm_channel_t * channel = rfcomm_channel_for_multiplexer_and_dlci(multiplexer, dlci);
1371 
1372     // log_info("rfcomm_channel_state_machine_with_dlci lookup dlci #%u = 0x%08x - event %u", dlci, (int) channel, event->type);
1373 
1374     if (channel) {
1375         rfcomm_channel_state_machine_with_channel(channel, event);
1376         if (rfcomm_channel_ready_to_send(channel)){
1377             l2cap_request_can_send_now_event(multiplexer->l2cap_cid);
1378         }
1379         return;
1380     }
1381 
1382     // service registered?
1383     rfcomm_service_t * service = rfcomm_service_for_channel(dlci >> 1);
1384     // log_info("rfcomm_channel_state_machine_with_dlci service dlci #%u = 0x%08x", dlci, (int) service);
1385     if (!service) {
1386         // discard request by sending disconnected mode
1387         multiplexer->send_dm_for_dlci = dlci;
1388         l2cap_request_can_send_now_event(multiplexer->l2cap_cid);
1389         return;
1390     }
1391 
1392     // create channel for some events
1393     switch (event->type) {
1394         case CH_EVT_RCVD_SABM:
1395         case CH_EVT_RCVD_PN:
1396         case CH_EVT_RCVD_RPN_REQ:
1397         case CH_EVT_RCVD_RPN_CMD:
1398             // setup incoming channel
1399             channel = rfcomm_channel_create(multiplexer, service, dlci >> 1);
1400             if (!channel){
1401                 // discard request by sending disconnected mode
1402                 multiplexer->send_dm_for_dlci = dlci;
1403                 l2cap_request_can_send_now_event(multiplexer->l2cap_cid);
1404             }
1405             break;
1406         default:
1407             break;
1408     }
1409 
1410     if (!channel) {
1411         // discard request by sending disconnected mode
1412         multiplexer->send_dm_for_dlci = dlci;
1413         l2cap_request_can_send_now_event(multiplexer->l2cap_cid);
1414         return;
1415     }
1416 
1417     rfcomm_channel_state_machine_with_channel(channel, event);
1418     if (rfcomm_channel_ready_to_send(channel)){
1419         l2cap_request_can_send_now_event(multiplexer->l2cap_cid);
1420     }
1421 }
1422 
1423 static void rfcomm_channel_packet_handler(rfcomm_multiplexer_t * multiplexer,  uint8_t *packet, uint16_t size){
1424 
1425     UNUSED(size);   // ok: fixed format messages
1426 
1427     // rfcomm: (0) addr [76543 server channel] [2 direction: initiator uses 1] [1 C/R: CMD by initiator = 1] [0 EA=1]
1428     const uint8_t frame_dlci = packet[0] >> 2;
1429     uint8_t message_dlci; // used by commands in UIH(_PF) packets
1430 	uint8_t message_len;  //   "
1431 
1432     // rfcomm: (1) command/control
1433     // -- credits_offset = 1 if command == BT_RFCOMM_UIH_PF
1434     const uint8_t credit_offset = ((packet[1] & BT_RFCOMM_UIH_PF) == BT_RFCOMM_UIH_PF) ? 1 : 0;   // credits for uih_pf frames
1435     // rfcomm: (2) length. if bit 0 is cleared, 2 byte length is used. (little endian)
1436     const uint8_t length_offset = (packet[2] & 1) ^ 1;  // to be used for pos >= 3
1437     // rfcomm: (3+length_offset) credits if credits_offset == 1
1438     // rfcomm: (3+length_offest+credits_offset)
1439     const uint8_t payload_offset = 3 + length_offset + credit_offset;
1440 
1441     rfcomm_channel_event_t event;
1442     rfcomm_channel_event_pn_t event_pn;
1443     rfcomm_channel_event_rpn_t event_rpn;
1444     rfcomm_channel_event_msc_t event_msc;
1445 
1446     // switch by rfcomm message type
1447     switch(packet[1]) {
1448 
1449         case BT_RFCOMM_SABM:
1450             event.type = CH_EVT_RCVD_SABM;
1451             log_info("Received SABM #%u", frame_dlci);
1452             rfcomm_channel_state_machine_with_dlci(multiplexer, frame_dlci, &event);
1453             break;
1454 
1455         case BT_RFCOMM_UA:
1456             event.type = CH_EVT_RCVD_UA;
1457             log_info("Received UA #%u",frame_dlci);
1458             rfcomm_channel_state_machine_with_dlci(multiplexer, frame_dlci, &event);
1459             break;
1460 
1461         case BT_RFCOMM_DISC:
1462             event.type = CH_EVT_RCVD_DISC;
1463             rfcomm_channel_state_machine_with_dlci(multiplexer, frame_dlci, &event);
1464             break;
1465 
1466         case BT_RFCOMM_DM:
1467         case BT_RFCOMM_DM_PF:
1468             event.type = CH_EVT_RCVD_DM;
1469             rfcomm_channel_state_machine_with_dlci(multiplexer, frame_dlci, &event);
1470             break;
1471 
1472         case BT_RFCOMM_UIH_PF:
1473         case BT_RFCOMM_UIH:
1474 
1475             message_len  = packet[payload_offset+1] >> 1;
1476 
1477             switch (packet[payload_offset]) {
1478                 case BT_RFCOMM_PN_CMD:
1479                     message_dlci = packet[payload_offset+2];
1480                     event_pn.super.type = CH_EVT_RCVD_PN;
1481                     event_pn.priority = packet[payload_offset+4];
1482                     event_pn.max_frame_size = little_endian_read_16(packet, payload_offset+6);
1483                     event_pn.credits_outgoing = packet[payload_offset+9];
1484                     log_info("Received UIH Parameter Negotiation Command for #%u, credits %u",
1485                         message_dlci, event_pn.credits_outgoing);
1486                     rfcomm_channel_state_machine_with_dlci(multiplexer, message_dlci, (rfcomm_channel_event_t*) &event_pn);
1487                     break;
1488 
1489                 case BT_RFCOMM_PN_RSP:
1490                     message_dlci = packet[payload_offset+2];
1491                     event_pn.super.type = CH_EVT_RCVD_PN_RSP;
1492                     event_pn.priority = packet[payload_offset+4];
1493                     event_pn.max_frame_size = little_endian_read_16(packet, payload_offset+6);
1494                     event_pn.credits_outgoing = packet[payload_offset+9];
1495                     log_info("Received UIH Parameter Negotiation Response max frame %u, credits %u",
1496                             event_pn.max_frame_size, event_pn.credits_outgoing);
1497                     rfcomm_channel_state_machine_with_dlci(multiplexer, message_dlci, (rfcomm_channel_event_t*) &event_pn);
1498                     break;
1499 
1500                 case BT_RFCOMM_MSC_CMD:
1501                     message_dlci = packet[payload_offset+2] >> 2;
1502                     event_msc.super.type = CH_EVT_RCVD_MSC_CMD;
1503                     event_msc.modem_status = packet[payload_offset+3];
1504                     log_info("Received MSC CMD for #%u, ", message_dlci);
1505                     rfcomm_channel_state_machine_with_dlci(multiplexer, message_dlci, (rfcomm_channel_event_t*) &event_msc);
1506                     break;
1507 
1508                 case BT_RFCOMM_MSC_RSP:
1509                     message_dlci = packet[payload_offset+2] >> 2;
1510                     event.type = CH_EVT_RCVD_MSC_RSP;
1511                     log_info("Received MSC RSP for #%u", message_dlci);
1512                     rfcomm_channel_state_machine_with_dlci(multiplexer, message_dlci, &event);
1513                     break;
1514 
1515                 case BT_RFCOMM_RPN_CMD:
1516                     message_dlci = packet[payload_offset+2] >> 2;
1517                     switch (message_len){
1518                         case 1:
1519                             log_info("Received Remote Port Negotiation Request for #%u", message_dlci);
1520                             event.type = CH_EVT_RCVD_RPN_REQ;
1521                             rfcomm_channel_state_machine_with_dlci(multiplexer, message_dlci, &event);
1522                             break;
1523                         case 8:
1524                             log_info("Received Remote Port Negotiation Update for #%u", message_dlci);
1525                             event_rpn.super.type = CH_EVT_RCVD_RPN_CMD;
1526                             event_rpn.data = *(rfcomm_rpn_data_t*) &packet[payload_offset+3];
1527                             rfcomm_channel_state_machine_with_dlci(multiplexer, message_dlci, (rfcomm_channel_event_t*) &event_rpn);
1528                             break;
1529                         default:
1530                             break;
1531                     }
1532                     break;
1533 
1534                 case BT_RFCOMM_RPN_RSP:
1535                     log_info("Received RPN response");
1536                     break;
1537 
1538                 case BT_RFCOMM_RLS_CMD: {
1539                     log_info("Received RLS command");
1540                     message_dlci = packet[payload_offset+2] >> 2;
1541                     rfcomm_channel_event_rls_t event_rls;
1542                     event_rls.super.type = CH_EVT_RCVD_RLS_CMD;
1543                     event_rls.line_status = packet[payload_offset+3];
1544                     rfcomm_channel_state_machine_with_dlci(multiplexer, message_dlci, (rfcomm_channel_event_t*) &event_rls);
1545                     break;
1546                 }
1547 
1548                 case BT_RFCOMM_RLS_RSP:
1549                     log_info("Received RLS response");
1550                     break;
1551 
1552                 // Following commands are handled by rfcomm_multiplexer_l2cap_packet_handler
1553                 // case BT_RFCOMM_TEST_CMD:
1554                 // case BT_RFCOMM_FCOFF_CMD:
1555                 // case BT_RFCOMM_FCON_CMD:
1556                 // everything else is an not supported command
1557                 default: {
1558                     log_error("Received unknown UIH command packet - 0x%02x", packet[payload_offset]);
1559                     multiplexer->nsc_command = packet[payload_offset];
1560                     break;
1561                 }
1562             }
1563             break;
1564 
1565         default:
1566             log_error("Received unknown RFCOMM message type %x", packet[1]);
1567             break;
1568     }
1569 
1570     // trigger next action - example W4_PN_RSP: transition to SEND_SABM which only depends on "can send"
1571     if (rfcomm_multiplexer_ready_to_send(multiplexer)){
1572         l2cap_request_can_send_now_event(multiplexer->l2cap_cid);
1573     }
1574 }
1575 
1576 static void rfcomm_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
1577 
1578     if (packet_type == HCI_EVENT_PACKET){
1579         rfcomm_hci_event_handler(packet, size);
1580         return;
1581     }
1582 
1583     // we only handle l2cap packets for:
1584     if (packet_type != L2CAP_DATA_PACKET) return;
1585 
1586     //  - multiplexer itself
1587     int handled = rfcomm_multiplexer_l2cap_packet_handler(channel, packet, size);
1588 
1589     if (handled) return;
1590 
1591     // - channel over open mutliplexer
1592     rfcomm_multiplexer_t * multiplexer = rfcomm_multiplexer_for_l2cap_cid(channel);
1593     if (!multiplexer || multiplexer->state != RFCOMM_MULTIPLEXER_OPEN) return;
1594 
1595     // channel data ?
1596     // rfcomm: (0) addr [76543 server channel] [2 direction: initiator uses 1] [1 C/R: CMD by initiator = 1] [0 EA=1]
1597     const uint8_t frame_dlci = packet[0] >> 2;
1598 
1599     if (frame_dlci && (packet[1] == BT_RFCOMM_UIH || packet[1] == BT_RFCOMM_UIH_PF)) {
1600         rfcomm_channel_packet_handler_uih(multiplexer, packet, size);
1601         return;
1602     }
1603 
1604     rfcomm_channel_packet_handler(multiplexer, packet, size);
1605 }
1606 
1607 static int rfcomm_channel_ready_for_open(rfcomm_channel_t *channel){
1608     // note: exchanging MSC isn't neccessary to consider channel open
1609     // note: having outgoing credits is also not necessary to consider channel open
1610     // 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);
1611     // if ((channel->state_var & RFCOMM_CHANNEL_STATE_VAR_SENT_MSC_RSP) == 0) return 0;
1612     // if (channel->credits_outgoing == 0) return 0;
1613     log_info("rfcomm_channel_ready_for_open state %u, flags needed %04x, current %04x, rf credits %u",
1614          channel->state, RFCOMM_CHANNEL_STATE_VAR_RCVD_MSC_RSP, channel->state_var, channel->credits_outgoing);
1615     if ((channel->state_var & RFCOMM_CHANNEL_STATE_VAR_RCVD_MSC_RSP) == 0) return 0;
1616     if ((channel->state_var & RFCOMM_CHANNEL_STATE_VAR_SENT_CREDITS) == 0) return 0;
1617 
1618     return 1;
1619 }
1620 
1621 static int rfcomm_channel_ready_for_incoming_dlc_setup(rfcomm_channel_t * channel){
1622     log_info("rfcomm_channel_ready_for_incoming_dlc_setup state var %04x", channel->state_var);
1623     // Client accept and SABM/UA is required, PN RSP is needed if PN was received
1624     if ((channel->state_var & RFCOMM_CHANNEL_STATE_VAR_CLIENT_ACCEPTED) == 0) return 0;
1625     if ((channel->state_var & RFCOMM_CHANNEL_STATE_VAR_RCVD_SABM      ) == 0) return 0;
1626     if ((channel->state_var & RFCOMM_CHANNEL_STATE_VAR_SEND_UA        ) != 0) return 0;
1627     if ((channel->state_var & RFCOMM_CHANNEL_STATE_VAR_SEND_PN_RSP    ) != 0) return 0;
1628     return 1;
1629 }
1630 
1631 inline static void rfcomm_channel_state_add(rfcomm_channel_t *channel, RFCOMM_CHANNEL_STATE_VAR event){
1632     channel->state_var = (RFCOMM_CHANNEL_STATE_VAR) (channel->state_var | event);
1633 }
1634 inline static void rfcomm_channel_state_remove(rfcomm_channel_t *channel, RFCOMM_CHANNEL_STATE_VAR event){
1635     channel->state_var = (RFCOMM_CHANNEL_STATE_VAR) (channel->state_var & ~event);
1636 }
1637 
1638 static int rfcomm_channel_ready_to_send(rfcomm_channel_t * channel){
1639     switch (channel->state){
1640         case RFCOMM_CHANNEL_SEND_UIH_PN:
1641             log_debug("ch-ready: state %u", channel->state);
1642             return 1;
1643         case RFCOMM_CHANNEL_SEND_SABM_W4_UA:
1644             log_debug("ch-ready: state %u", channel->state);
1645             return 1;
1646         case RFCOMM_CHANNEL_SEND_UA_AFTER_DISC:
1647             log_debug("ch-ready: state %u", channel->state);
1648             return 1;
1649         case RFCOMM_CHANNEL_SEND_DISC:
1650             log_debug("ch-ready: state %u", channel->state);
1651             return 1;
1652         case RFCOMM_CHANNEL_SEND_DM:
1653             log_debug("ch-ready: state %u", channel->state);
1654             return 1;
1655         case RFCOMM_CHANNEL_OPEN:
1656             if (channel->new_credits_incoming) {
1657                 log_debug("ch-ready: channel open & new_credits_incoming") ;
1658                 return 1;
1659             }
1660             break;
1661         case RFCOMM_CHANNEL_DLC_SETUP:
1662             if (channel->state_var & (
1663                 RFCOMM_CHANNEL_STATE_VAR_SEND_MSC_CMD  |
1664                 RFCOMM_CHANNEL_STATE_VAR_SEND_CREDITS
1665              )) {
1666                 log_debug("ch-ready: channel dlc setup & send msc cmd or send credits") ;
1667                 return 1;
1668             }
1669             break;
1670 
1671         default:
1672             break;
1673     }
1674 
1675     if (channel->state_var & (
1676         RFCOMM_CHANNEL_STATE_VAR_SEND_PN_RSP   |
1677         RFCOMM_CHANNEL_STATE_VAR_SEND_RPN_INFO |
1678         RFCOMM_CHANNEL_STATE_VAR_SEND_RPN_RSP  |
1679         RFCOMM_CHANNEL_STATE_VAR_SEND_UA       |
1680         RFCOMM_CHANNEL_STATE_VAR_SEND_MSC_RSP
1681                              )){
1682         log_debug("ch-ready: state %x, state var %x", channel->state, channel->state_var);
1683         return 1;
1684     }
1685 
1686     if (channel->rls_line_status != RFCOMM_RLS_STATUS_INVALID) {
1687         log_debug("ch-ready: rls_line_status");
1688         return 1;
1689     }
1690 
1691     return 0;
1692 }
1693 
1694 
1695 static void rfcomm_channel_state_machine_with_channel(rfcomm_channel_t *channel, const rfcomm_channel_event_t *event){
1696 
1697     // log_info("rfcomm_channel_state_machine_with_channel: state %u, state_var %04x, event %u", channel->state, channel->state_var ,event->type);
1698 
1699     rfcomm_multiplexer_t *multiplexer = channel->multiplexer;
1700 
1701     // TODO: integrate in common switch
1702     if (event->type == CH_EVT_RCVD_DISC){
1703         rfcomm_emit_channel_closed(channel);
1704         channel->state = RFCOMM_CHANNEL_SEND_UA_AFTER_DISC;
1705         return;
1706     }
1707 
1708     // TODO: integrate in common switch
1709     if (event->type == CH_EVT_RCVD_DM){
1710         log_info("Received DM message for #%u", channel->dlci);
1711         log_info("-> Closing channel locally for #%u", channel->dlci);
1712         rfcomm_emit_channel_closed(channel);
1713         rfcomm_channel_finalize(channel);
1714         return;
1715     }
1716 
1717     // remote port negotiation command - just accept everything for now
1718     //
1719     // "The RPN command can be used before a new DLC is opened and should be used whenever the port settings change."
1720     // "The RPN command is specified as optional in TS 07.10, but it is mandatory to recognize and respond to it in RFCOMM.
1721     //   (Although the handling of individual settings are implementation-dependent.)"
1722     //
1723 
1724     // TODO: integrate in common switch
1725     if (event->type == CH_EVT_RCVD_RPN_CMD){
1726         // control port parameters
1727         rfcomm_channel_event_rpn_t *event_rpn = (rfcomm_channel_event_rpn_t*) event;
1728         rfcomm_rpn_data_update(&channel->rpn_data, &event_rpn->data);
1729         rfcomm_channel_state_add(channel, RFCOMM_CHANNEL_STATE_VAR_SEND_RPN_RSP);
1730         // notify client about new settings
1731         rfcomm_emit_port_configuration(channel);
1732         return;
1733     }
1734 
1735     // TODO: integrate in common switch
1736     if (event->type == CH_EVT_RCVD_RPN_REQ){
1737         // no values got accepted (no values have beens sent)
1738         channel->rpn_data.parameter_mask_0 = 0x00;
1739         channel->rpn_data.parameter_mask_1 = 0x00;
1740         rfcomm_channel_state_add(channel, RFCOMM_CHANNEL_STATE_VAR_SEND_RPN_RSP);
1741         return;
1742     }
1743 
1744     if (event->type == CH_EVT_RCVD_RLS_CMD){
1745         rfcomm_channel_event_rls_t * event_rls = (rfcomm_channel_event_rls_t*) event;
1746         channel->rls_line_status = event_rls->line_status & 0x0f;
1747         log_info("CH_EVT_RCVD_RLS_CMD setting line status to 0x%0x", channel->rls_line_status);
1748         rfcomm_emit_remote_line_status(channel, event_rls->line_status);
1749         return;
1750     }
1751 
1752     // TODO: integrate in common switch
1753     if (event->type == CH_EVT_READY_TO_SEND){
1754         if (channel->state_var & RFCOMM_CHANNEL_STATE_VAR_SEND_RPN_RSP){
1755             log_info("Sending Remote Port Negotiation RSP for #%u", channel->dlci);
1756             rfcomm_channel_state_remove(channel, RFCOMM_CHANNEL_STATE_VAR_SEND_RPN_RSP);
1757             rfcomm_send_uih_rpn_rsp(multiplexer, channel->dlci, &channel->rpn_data);
1758             return;
1759         }
1760         if (channel->state_var & RFCOMM_CHANNEL_STATE_VAR_SEND_MSC_RSP){
1761             log_info("Sending MSC RSP for #%u", channel->dlci);
1762             rfcomm_channel_state_remove(channel, RFCOMM_CHANNEL_STATE_VAR_SEND_MSC_RSP);
1763             rfcomm_channel_state_add(channel, RFCOMM_CHANNEL_STATE_VAR_SENT_MSC_RSP);
1764             rfcomm_send_uih_msc_rsp(multiplexer, channel->dlci, 0x8d);  // ea=1,fc=0,rtc=1,rtr=1,ic=0,dv=1
1765             return;
1766         }
1767         if (channel->rls_line_status != RFCOMM_RLS_STATUS_INVALID){
1768             log_info("Sending RLS RSP 0x%0x", channel->rls_line_status);
1769             uint8_t line_status = channel->rls_line_status;
1770             channel->rls_line_status = RFCOMM_RLS_STATUS_INVALID;
1771             rfcomm_send_uih_rls_rsp(multiplexer, channel->dlci, line_status);
1772             return;
1773         }
1774     }
1775 
1776     // emit MSC status to app
1777     if (event->type == CH_EVT_RCVD_MSC_CMD){
1778         // notify client about new settings
1779         rfcomm_channel_event_msc_t *event_msc = (rfcomm_channel_event_msc_t*) event;
1780         uint8_t modem_status_event[2+1];
1781         modem_status_event[0] = RFCOMM_EVENT_REMOTE_MODEM_STATUS;
1782         modem_status_event[1] = 1;
1783         modem_status_event[2] = event_msc->modem_status;
1784         (channel->packet_handler)(HCI_EVENT_PACKET, channel->rfcomm_cid, (uint8_t*)&modem_status_event, sizeof(modem_status_event));
1785         // no return, MSC_CMD will be handled by state machine below
1786     }
1787 
1788     rfcomm_channel_event_pn_t * event_pn = (rfcomm_channel_event_pn_t*) event;
1789 
1790     switch (channel->state) {
1791         case RFCOMM_CHANNEL_CLOSED:
1792             switch (event->type){
1793                 case CH_EVT_RCVD_SABM:
1794                     log_info("-> Inform app");
1795                     rfcomm_channel_state_add(channel, RFCOMM_CHANNEL_STATE_VAR_RCVD_SABM);
1796                     channel->state = RFCOMM_CHANNEL_INCOMING_SETUP;
1797                     rfcomm_emit_connection_request(channel);
1798                     break;
1799                 case CH_EVT_RCVD_PN:
1800                     rfcomm_channel_accept_pn(channel, event_pn);
1801                     log_info("-> Inform app");
1802                     rfcomm_channel_state_add(channel, RFCOMM_CHANNEL_STATE_VAR_RCVD_PN);
1803                     channel->state = RFCOMM_CHANNEL_INCOMING_SETUP;
1804                     rfcomm_emit_connection_request(channel);
1805                     break;
1806                 default:
1807                     break;
1808             }
1809             break;
1810 
1811         case RFCOMM_CHANNEL_INCOMING_SETUP:
1812             switch (event->type){
1813                 case CH_EVT_RCVD_SABM:
1814                     rfcomm_channel_state_add(channel, RFCOMM_CHANNEL_STATE_VAR_RCVD_SABM);
1815                     if (channel->state_var & RFCOMM_CHANNEL_STATE_VAR_CLIENT_ACCEPTED) {
1816                         rfcomm_channel_state_add(channel, RFCOMM_CHANNEL_STATE_VAR_SEND_UA);
1817                     }
1818                     break;
1819                 case CH_EVT_RCVD_PN:
1820                     rfcomm_channel_accept_pn(channel, event_pn);
1821                     rfcomm_channel_state_add(channel, RFCOMM_CHANNEL_STATE_VAR_RCVD_PN);
1822                     if (channel->state_var & RFCOMM_CHANNEL_STATE_VAR_CLIENT_ACCEPTED) {
1823                         rfcomm_channel_state_add(channel, RFCOMM_CHANNEL_STATE_VAR_SEND_PN_RSP);
1824                     }
1825                     break;
1826                 case CH_EVT_READY_TO_SEND:
1827                     // if / else if is used to check for state transition after sending
1828                     if (channel->state_var & RFCOMM_CHANNEL_STATE_VAR_SEND_PN_RSP){
1829                         log_info("Sending UIH Parameter Negotiation Respond for #%u", channel->dlci);
1830                         rfcomm_channel_state_remove(channel, RFCOMM_CHANNEL_STATE_VAR_SEND_PN_RSP);
1831                         rfcomm_send_uih_pn_response(multiplexer, channel->dlci, channel->pn_priority, channel->max_frame_size);
1832                     } else if (channel->state_var & RFCOMM_CHANNEL_STATE_VAR_SEND_UA){
1833                         log_info("Sending UA #%u", channel->dlci);
1834                         rfcomm_channel_state_remove(channel, RFCOMM_CHANNEL_STATE_VAR_SEND_UA);
1835                         rfcomm_send_ua(multiplexer, channel->dlci);
1836                     }
1837                     if (rfcomm_channel_ready_for_incoming_dlc_setup(channel)){
1838                         log_info("Incomping setup done, requesting send MSC CMD and send Credits");
1839                         rfcomm_channel_state_add(channel, RFCOMM_CHANNEL_STATE_VAR_SEND_MSC_CMD);
1840                         rfcomm_channel_state_add(channel, RFCOMM_CHANNEL_STATE_VAR_SEND_CREDITS);
1841                         channel->state = RFCOMM_CHANNEL_DLC_SETUP;
1842                      }
1843                     break;
1844                 default:
1845                     break;
1846             }
1847             break;
1848 
1849         case RFCOMM_CHANNEL_W4_MULTIPLEXER:
1850             switch (event->type) {
1851                 case CH_EVT_MULTIPLEXER_READY:
1852                     log_info("Muliplexer opened, sending UIH PN next");
1853                     channel->state = RFCOMM_CHANNEL_SEND_UIH_PN;
1854                     break;
1855                 default:
1856                     break;
1857             }
1858             break;
1859 
1860         case RFCOMM_CHANNEL_SEND_UIH_PN:
1861             switch (event->type) {
1862                 case CH_EVT_READY_TO_SEND:
1863                     log_info("Sending UIH Parameter Negotiation Command for #%u (channel 0x%p)", channel->dlci, channel );
1864                     channel->state = RFCOMM_CHANNEL_W4_PN_RSP;
1865                     rfcomm_send_uih_pn_command(multiplexer, channel->dlci, channel->max_frame_size);
1866                     break;
1867                 default:
1868                     break;
1869             }
1870             break;
1871 
1872         case RFCOMM_CHANNEL_W4_PN_RSP:
1873             switch (event->type){
1874                 case CH_EVT_RCVD_PN_RSP:
1875                     // update max frame size
1876                     if (channel->max_frame_size > event_pn->max_frame_size) {
1877                         channel->max_frame_size = event_pn->max_frame_size;
1878                     }
1879                     // new credits
1880                     channel->credits_outgoing = event_pn->credits_outgoing;
1881                     channel->state = RFCOMM_CHANNEL_SEND_SABM_W4_UA;
1882                     break;
1883                 default:
1884                     break;
1885             }
1886             break;
1887 
1888         case RFCOMM_CHANNEL_SEND_SABM_W4_UA:
1889             switch (event->type) {
1890                 case CH_EVT_READY_TO_SEND:
1891                     log_info("Sending SABM #%u", channel->dlci);
1892                     channel->state = RFCOMM_CHANNEL_W4_UA;
1893                     rfcomm_send_sabm(multiplexer, channel->dlci);
1894                     break;
1895                 default:
1896                     break;
1897             }
1898             break;
1899 
1900         case RFCOMM_CHANNEL_W4_UA:
1901             switch (event->type){
1902                 case CH_EVT_RCVD_UA:
1903                     channel->state = RFCOMM_CHANNEL_DLC_SETUP;
1904                     rfcomm_channel_state_add(channel, RFCOMM_CHANNEL_STATE_VAR_SEND_MSC_CMD);
1905                     rfcomm_channel_state_add(channel, RFCOMM_CHANNEL_STATE_VAR_SEND_CREDITS);
1906                     break;
1907                 default:
1908                     break;
1909             }
1910             break;
1911 
1912         case RFCOMM_CHANNEL_DLC_SETUP:
1913             switch (event->type){
1914                 case CH_EVT_RCVD_MSC_CMD:
1915                     rfcomm_channel_state_add(channel, RFCOMM_CHANNEL_STATE_VAR_RCVD_MSC_CMD);
1916                     rfcomm_channel_state_add(channel, RFCOMM_CHANNEL_STATE_VAR_SEND_MSC_RSP);
1917                     break;
1918                 case CH_EVT_RCVD_MSC_RSP:
1919                     rfcomm_channel_state_add(channel, RFCOMM_CHANNEL_STATE_VAR_RCVD_MSC_RSP);
1920                     break;
1921 
1922                 case CH_EVT_READY_TO_SEND:
1923                     if (channel->state_var & RFCOMM_CHANNEL_STATE_VAR_SEND_MSC_CMD){
1924                         log_info("Sending MSC CMD for #%u", channel->dlci);
1925                         rfcomm_channel_state_remove(channel, RFCOMM_CHANNEL_STATE_VAR_SEND_MSC_CMD);
1926                         rfcomm_channel_state_add(channel, RFCOMM_CHANNEL_STATE_VAR_SENT_MSC_CMD);
1927                         rfcomm_send_uih_msc_cmd(multiplexer, channel->dlci , 0x8d);  // ea=1,fc=0,rtc=1,rtr=1,ic=0,dv=1
1928                         break;
1929                     }
1930                     if (channel->state_var & RFCOMM_CHANNEL_STATE_VAR_SEND_CREDITS){
1931                         log_info("Providing credits for #%u", channel->dlci);
1932                         rfcomm_channel_state_remove(channel, RFCOMM_CHANNEL_STATE_VAR_SEND_CREDITS);
1933                         rfcomm_channel_state_add(channel, RFCOMM_CHANNEL_STATE_VAR_SENT_CREDITS);
1934 
1935                         if (channel->new_credits_incoming) {
1936                             uint8_t new_credits = channel->new_credits_incoming;
1937                             channel->new_credits_incoming = 0;
1938                             rfcomm_channel_send_credits(channel, new_credits);
1939                         }
1940                         break;
1941 
1942                     }
1943                     break;
1944                 default:
1945                     break;
1946             }
1947             // finally done?
1948             if (rfcomm_channel_ready_for_open(channel)){
1949                 channel->state = RFCOMM_CHANNEL_OPEN;
1950                 rfcomm_channel_opened(channel);
1951             }
1952             break;
1953 
1954         case RFCOMM_CHANNEL_OPEN:
1955             switch (event->type){
1956                 case CH_EVT_RCVD_MSC_CMD:
1957                     rfcomm_channel_state_add(channel, RFCOMM_CHANNEL_STATE_VAR_SEND_MSC_RSP);
1958                     break;
1959                 case CH_EVT_READY_TO_SEND:
1960                     if (channel->new_credits_incoming) {
1961                         uint8_t new_credits = channel->new_credits_incoming;
1962                         channel->new_credits_incoming = 0;
1963                         rfcomm_channel_send_credits(channel, new_credits);
1964                         break;
1965                     }
1966                     break;
1967                 case CH_EVT_RCVD_CREDITS:
1968                     rfcomm_notify_channel_can_send();
1969                     break;
1970                 default:
1971                     break;
1972             }
1973             break;
1974 
1975         case RFCOMM_CHANNEL_SEND_DM:
1976             switch (event->type) {
1977                 case CH_EVT_READY_TO_SEND:
1978                     log_info("Sending DM_PF for #%u", channel->dlci);
1979                     // don't emit channel closed - channel was never open
1980                     channel->state = RFCOMM_CHANNEL_CLOSED;
1981                     rfcomm_send_dm_pf(multiplexer, channel->dlci);
1982                     rfcomm_channel_finalize(channel);
1983                     break;
1984                 default:
1985                     break;
1986             }
1987             break;
1988 
1989         case RFCOMM_CHANNEL_SEND_DISC:
1990             switch (event->type) {
1991                 case CH_EVT_READY_TO_SEND:
1992                     channel->state = RFCOMM_CHANNEL_W4_UA_AFTER_UA;
1993                     rfcomm_send_disc(multiplexer, channel->dlci);
1994                     break;
1995                 default:
1996                     break;
1997             }
1998             break;
1999 
2000         case RFCOMM_CHANNEL_W4_UA_AFTER_UA:
2001             switch (event->type){
2002                 case CH_EVT_RCVD_UA:
2003                     channel->state = RFCOMM_CHANNEL_CLOSED;
2004                     rfcomm_emit_channel_closed(channel);
2005                     rfcomm_channel_finalize(channel);
2006                     break;
2007                 default:
2008                     break;
2009             }
2010             break;
2011 
2012         case RFCOMM_CHANNEL_SEND_UA_AFTER_DISC:
2013             switch (event->type) {
2014                 case CH_EVT_READY_TO_SEND:
2015                     log_info("Sending UA after DISC for #%u", channel->dlci);
2016                     channel->state = RFCOMM_CHANNEL_CLOSED;
2017                     rfcomm_send_ua(multiplexer, channel->dlci);
2018                     rfcomm_channel_finalize(channel);
2019                     break;
2020                 default:
2021                     break;
2022             }
2023             break;
2024 
2025         default:
2026             break;
2027     }
2028 }
2029 
2030 // MARK: RFCOMM BTstack API
2031 
2032 void rfcomm_init(void){
2033     rfcomm_client_cid_generator = 0;
2034     rfcomm_multiplexers = NULL;
2035     rfcomm_services     = NULL;
2036     rfcomm_channels     = NULL;
2037     rfcomm_security_level = LEVEL_2;
2038 }
2039 
2040 void rfcomm_set_required_security_level(gap_security_level_t security_level){
2041     rfcomm_security_level = security_level;
2042 }
2043 
2044 int rfcomm_can_send_packet_now(uint16_t rfcomm_cid){
2045     rfcomm_channel_t * channel = rfcomm_channel_for_rfcomm_cid(rfcomm_cid);
2046     if (!channel){
2047         log_error("rfcomm_send cid 0x%02x doesn't exist!", rfcomm_cid);
2048         return 0;
2049     }
2050     return rfcomm_channel_can_send(channel);
2051 }
2052 
2053 void rfcomm_request_can_send_now_event(uint16_t rfcomm_cid){
2054     rfcomm_channel_t * channel = rfcomm_channel_for_rfcomm_cid(rfcomm_cid);
2055     if (!channel){
2056         log_error("rfcomm_send cid 0x%02x doesn't exist!", rfcomm_cid);
2057         return;
2058     }
2059     channel->waiting_for_can_send_now = 1;
2060     l2cap_request_can_send_now_event(channel->multiplexer->l2cap_cid);
2061 }
2062 
2063 static int rfcomm_assert_send_valid(rfcomm_channel_t * channel , uint16_t len){
2064     if (len > channel->max_frame_size){
2065         log_error("rfcomm_send cid 0x%02x, rfcomm data lenght exceeds MTU!", channel->rfcomm_cid);
2066         return RFCOMM_DATA_LEN_EXCEEDS_MTU;
2067     }
2068 
2069     if (!channel->credits_outgoing){
2070         log_info("rfcomm_send cid 0x%02x, no rfcomm outgoing credits!", channel->rfcomm_cid);
2071         return RFCOMM_NO_OUTGOING_CREDITS;
2072     }
2073 
2074     if ((channel->multiplexer->fcon & 1) == 0){
2075         log_info("rfcomm_send cid 0x%02x, aggregate flow off!", channel->rfcomm_cid);
2076         return RFCOMM_AGGREGATE_FLOW_OFF;
2077     }
2078     return 0;
2079 }
2080 
2081 // pre: rfcomm_can_send_packet_now(rfcomm_cid) == true
2082 int rfcomm_reserve_packet_buffer(void){
2083     return l2cap_reserve_packet_buffer();
2084 }
2085 
2086 void rfcomm_release_packet_buffer(void){
2087     l2cap_release_packet_buffer();
2088 }
2089 
2090 uint8_t * rfcomm_get_outgoing_buffer(void){
2091     uint8_t * rfcomm_out_buffer = l2cap_get_outgoing_buffer();
2092     // address + control + length (16) + no credit field
2093     return &rfcomm_out_buffer[4];
2094 }
2095 
2096 uint16_t rfcomm_get_max_frame_size(uint16_t rfcomm_cid){
2097     rfcomm_channel_t * channel = rfcomm_channel_for_rfcomm_cid(rfcomm_cid);
2098     if (!channel){
2099         log_error("rfcomm_get_max_frame_size cid 0x%02x doesn't exist!", rfcomm_cid);
2100         return 0;
2101     }
2102     return channel->max_frame_size;
2103 }
2104 
2105 int rfcomm_send_prepared(uint16_t rfcomm_cid, uint16_t len){
2106     rfcomm_channel_t * channel = rfcomm_channel_for_rfcomm_cid(rfcomm_cid);
2107     if (!channel){
2108         log_error("rfcomm_send_prepared cid 0x%02x doesn't exist!", rfcomm_cid);
2109         return 0;
2110     }
2111 
2112     int err = rfcomm_assert_send_valid(channel, len);
2113     if (err) return err;
2114     if (!l2cap_can_send_prepared_packet_now(channel->multiplexer->l2cap_cid)){
2115         log_error("rfcomm_send_prepared: l2cap cannot send now");
2116         return BTSTACK_ACL_BUFFERS_FULL;
2117     }
2118 
2119     // send might cause l2cap to emit new credits, update counters first
2120     if (len){
2121         channel->credits_outgoing--;
2122     } else {
2123         log_info("sending empty RFCOMM packet for cid %02x", rfcomm_cid);
2124     }
2125 
2126     int result = rfcomm_send_uih_prepared(channel->multiplexer, channel->dlci, len);
2127 
2128     if (result != 0) {
2129         if (len) {
2130             channel->credits_outgoing++;
2131         }
2132         log_error("rfcomm_send_prepared: error %d", result);
2133         return result;
2134     }
2135 
2136     return result;
2137 }
2138 
2139 int rfcomm_send(uint16_t rfcomm_cid, uint8_t *data, uint16_t len){
2140     rfcomm_channel_t * channel = rfcomm_channel_for_rfcomm_cid(rfcomm_cid);
2141     if (!channel){
2142         log_error("cid 0x%02x doesn't exist!", rfcomm_cid);
2143         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
2144     }
2145 
2146     int err = rfcomm_assert_send_valid(channel, len);
2147     if (err) return err;
2148     if (!l2cap_can_send_packet_now(channel->multiplexer->l2cap_cid)){
2149         log_error("rfcomm_send_internal: l2cap cannot send now");
2150         return BTSTACK_ACL_BUFFERS_FULL;
2151     }
2152 
2153     rfcomm_reserve_packet_buffer();
2154     uint8_t * rfcomm_payload = rfcomm_get_outgoing_buffer();
2155     memcpy(rfcomm_payload, data, len);
2156     err = rfcomm_send_prepared(rfcomm_cid, len);
2157     if (err){
2158         rfcomm_release_packet_buffer();
2159     }
2160     return err;
2161 }
2162 
2163 // Sends Local Lnie Status, see LINE_STATUS_..
2164 int rfcomm_send_local_line_status(uint16_t rfcomm_cid, uint8_t line_status){
2165     rfcomm_channel_t * channel = rfcomm_channel_for_rfcomm_cid(rfcomm_cid);
2166     if (!channel){
2167         log_error("rfcomm_send_local_line_status cid 0x%02x doesn't exist!", rfcomm_cid);
2168         return 0;
2169     }
2170     return rfcomm_send_uih_rls_cmd(channel->multiplexer, channel->dlci, line_status);
2171 }
2172 
2173 // Sned local modem status. see MODEM_STAUS_..
2174 int rfcomm_send_modem_status(uint16_t rfcomm_cid, uint8_t modem_status){
2175     rfcomm_channel_t * channel = rfcomm_channel_for_rfcomm_cid(rfcomm_cid);
2176     if (!channel){
2177         log_error("rfcomm_send_modem_status cid 0x%02x doesn't exist!", rfcomm_cid);
2178         return 0;
2179     }
2180     return rfcomm_send_uih_msc_cmd(channel->multiplexer, channel->dlci, modem_status);
2181 }
2182 
2183 // Configure remote port
2184 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){
2185     rfcomm_channel_t * channel = rfcomm_channel_for_rfcomm_cid(rfcomm_cid);
2186     if (!channel){
2187         log_error("rfcomm_send_port_configuration cid 0x%02x doesn't exist!", rfcomm_cid);
2188         return 0;
2189     }
2190     rfcomm_rpn_data_t rpn_data;
2191     rpn_data.baud_rate = baud_rate;
2192     rpn_data.flags = data_bits | (stop_bits << 2) | (parity << 3);
2193     rpn_data.flow_control = flow_control;
2194     rpn_data.xon = 0;
2195     rpn_data.xoff = 0;
2196     rpn_data.parameter_mask_0 = 0x1f;   // all but xon/xoff
2197     rpn_data.parameter_mask_1 = 0x3f;   // all flow control options
2198     return rfcomm_send_uih_rpn_cmd(channel->multiplexer, channel->dlci, &rpn_data);
2199 }
2200 
2201 // Query remote port
2202 int rfcomm_query_port_configuration(uint16_t rfcomm_cid){
2203     rfcomm_channel_t * channel = rfcomm_channel_for_rfcomm_cid(rfcomm_cid);
2204     if (!channel){
2205         log_error("rfcomm_query_port_configuration cid 0x%02x doesn't exist!", rfcomm_cid);
2206         return 0;
2207     }
2208     return rfcomm_send_uih_rpn_req(channel->multiplexer, channel->dlci);
2209 }
2210 
2211 
2212 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){
2213     log_info("RFCOMM_CREATE_CHANNEL addr %s channel #%u init credits %u",  bd_addr_to_str(addr), server_channel, initial_credits);
2214 
2215     // create new multiplexer if necessary
2216     uint8_t status = 0;
2217     uint8_t dlci = 0;
2218     int new_multiplexer = 0;
2219     rfcomm_channel_t * channel = NULL;
2220     rfcomm_multiplexer_t * multiplexer = rfcomm_multiplexer_for_addr(addr);
2221     if (!multiplexer) {
2222         multiplexer = rfcomm_multiplexer_create_for_addr(addr);
2223         if (!multiplexer){
2224             status = BTSTACK_MEMORY_ALLOC_FAILED;
2225             goto fail;
2226         }
2227         multiplexer->outgoing = 1;
2228         multiplexer->state = RFCOMM_MULTIPLEXER_W4_CONNECT;
2229         new_multiplexer = 1;
2230     }
2231 
2232     // check if channel for this remote service already exists
2233     dlci = (server_channel << 1) | (multiplexer->outgoing ^ 1);
2234     channel = rfcomm_channel_for_multiplexer_and_dlci(multiplexer, dlci);
2235     if (channel){
2236         status = RFCOMM_CHANNEL_ALREADY_REGISTERED;
2237         goto fail;
2238     }
2239 
2240     // prepare channel
2241     channel = rfcomm_channel_create(multiplexer, NULL, server_channel);
2242     if (!channel){
2243         status = BTSTACK_MEMORY_ALLOC_FAILED;
2244         goto fail;
2245     }
2246 
2247     // rfcomm_cid is already assigned by rfcomm_channel_create
2248     channel->incoming_flow_control = incoming_flow_control;
2249     channel->new_credits_incoming  = initial_credits;
2250     channel->packet_handler = packet_handler;
2251 
2252     // return rfcomm_cid
2253     if (out_rfcomm_cid){
2254         *out_rfcomm_cid = channel->rfcomm_cid;
2255     }
2256 
2257     // start multiplexer setup
2258     if (multiplexer->state != RFCOMM_MULTIPLEXER_OPEN) {
2259         channel->state = RFCOMM_CHANNEL_W4_MULTIPLEXER;
2260         uint16_t l2cap_cid = 0;
2261         status = l2cap_create_channel(rfcomm_packet_handler, addr, BLUETOOTH_PROTOCOL_RFCOMM, l2cap_max_mtu(), &l2cap_cid);
2262         if (status) goto fail;
2263         multiplexer->l2cap_cid = l2cap_cid;
2264         return 0;
2265     }
2266 
2267     channel->state = RFCOMM_CHANNEL_SEND_UIH_PN;
2268 
2269     // start connecting, if multiplexer is already up and running
2270     l2cap_request_can_send_now_event(multiplexer->l2cap_cid);
2271     return 0;
2272 
2273 fail:
2274     if (new_multiplexer) btstack_memory_rfcomm_multiplexer_free(multiplexer);
2275     if (channel)         btstack_memory_rfcomm_channel_free(channel);
2276     return status;
2277 }
2278 
2279 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){
2280     return rfcomm_channel_create_internal(packet_handler, addr, server_channel, 1, initial_credits, out_rfcomm_cid);
2281 }
2282 
2283 uint8_t rfcomm_create_channel(btstack_packet_handler_t packet_handler, bd_addr_t addr, uint8_t server_channel, uint16_t * out_rfcomm_cid){
2284     return rfcomm_channel_create_internal(packet_handler, addr, server_channel, 0, RFCOMM_CREDITS, out_rfcomm_cid);
2285 }
2286 
2287 void rfcomm_disconnect(uint16_t rfcomm_cid){
2288     log_info("RFCOMM_DISCONNECT cid 0x%02x", rfcomm_cid);
2289     rfcomm_channel_t * channel = rfcomm_channel_for_rfcomm_cid(rfcomm_cid);
2290     if (!channel) return;
2291 
2292     channel->state = RFCOMM_CHANNEL_SEND_DISC;
2293     l2cap_request_can_send_now_event(channel->multiplexer->l2cap_cid);
2294 }
2295 
2296 static uint8_t rfcomm_register_service_internal(btstack_packet_handler_t packet_handler,
2297     uint8_t channel, uint16_t max_frame_size, uint8_t incoming_flow_control, uint8_t initial_credits){
2298 
2299     log_info("RFCOMM_REGISTER_SERVICE channel #%u mtu %u flow_control %u credits %u",
2300              channel, max_frame_size, incoming_flow_control, initial_credits);
2301 
2302     // check if already registered
2303     rfcomm_service_t * service = rfcomm_service_for_channel(channel);
2304     if (service){
2305         return RFCOMM_CHANNEL_ALREADY_REGISTERED;
2306     }
2307 
2308     // alloc structure
2309     service = btstack_memory_rfcomm_service_get();
2310     if (!service) {
2311         return BTSTACK_MEMORY_ALLOC_FAILED;
2312     }
2313 
2314     // register with l2cap if not registered before, max MTU
2315     if (btstack_linked_list_empty(&rfcomm_services)){
2316         l2cap_register_service(rfcomm_packet_handler, BLUETOOTH_PROTOCOL_RFCOMM, 0xffff, rfcomm_security_level);
2317     }
2318 
2319     // fill in
2320     service->packet_handler = packet_handler;
2321     service->server_channel = channel;
2322     service->max_frame_size = max_frame_size;
2323     service->incoming_flow_control = incoming_flow_control;
2324     service->incoming_initial_credits = initial_credits;
2325 
2326     // add to services list
2327     btstack_linked_list_add(&rfcomm_services, (btstack_linked_item_t *) service);
2328 
2329     return 0;
2330 }
2331 
2332 uint8_t rfcomm_register_service_with_initial_credits(btstack_packet_handler_t packet_handler,
2333     uint8_t channel, uint16_t max_frame_size, uint8_t initial_credits){
2334 
2335     return rfcomm_register_service_internal(packet_handler, channel, max_frame_size, 1, initial_credits);
2336 }
2337 
2338 uint8_t rfcomm_register_service(btstack_packet_handler_t packet_handler, uint8_t channel,
2339     uint16_t max_frame_size){
2340 
2341     return rfcomm_register_service_internal(packet_handler, channel, max_frame_size, 0,RFCOMM_CREDITS);
2342 }
2343 
2344 void rfcomm_unregister_service(uint8_t service_channel){
2345     log_info("RFCOMM_UNREGISTER_SERVICE #%u", service_channel);
2346     rfcomm_service_t *service = rfcomm_service_for_channel(service_channel);
2347     if (!service) return;
2348     btstack_linked_list_remove(&rfcomm_services, (btstack_linked_item_t *) service);
2349     btstack_memory_rfcomm_service_free(service);
2350 
2351     // unregister if no services active
2352     if (btstack_linked_list_empty(&rfcomm_services)){
2353         // bt_send_cmd(&l2cap_unregister_service, BLUETOOTH_PROTOCOL_RFCOMM);
2354         l2cap_unregister_service(BLUETOOTH_PROTOCOL_RFCOMM);
2355     }
2356 }
2357 
2358 void rfcomm_accept_connection(uint16_t rfcomm_cid){
2359     log_info("RFCOMM_ACCEPT_CONNECTION cid 0x%02x", rfcomm_cid);
2360     rfcomm_channel_t * channel = rfcomm_channel_for_rfcomm_cid(rfcomm_cid);
2361     if (!channel) return;
2362     switch (channel->state) {
2363         case RFCOMM_CHANNEL_INCOMING_SETUP:
2364             rfcomm_channel_state_add(channel, RFCOMM_CHANNEL_STATE_VAR_CLIENT_ACCEPTED);
2365             if (channel->state_var & RFCOMM_CHANNEL_STATE_VAR_RCVD_PN){
2366                 rfcomm_channel_state_add(channel, RFCOMM_CHANNEL_STATE_VAR_SEND_PN_RSP);
2367                 l2cap_request_can_send_now_event(channel->multiplexer->l2cap_cid);
2368             }
2369             if (channel->state_var & RFCOMM_CHANNEL_STATE_VAR_RCVD_SABM){
2370                 rfcomm_channel_state_add(channel, RFCOMM_CHANNEL_STATE_VAR_SEND_UA);
2371                 l2cap_request_can_send_now_event(channel->multiplexer->l2cap_cid);
2372             }
2373             // at least one of { PN RSP, UA } needs to be sent
2374             // state transistion incoming setup -> dlc setup happens in rfcomm_run after these have been sent
2375             break;
2376         default:
2377             break;
2378     }
2379 
2380 }
2381 
2382 void rfcomm_decline_connection(uint16_t rfcomm_cid){
2383     log_info("RFCOMM_DECLINE_CONNECTION cid 0x%02x", rfcomm_cid);
2384     rfcomm_channel_t * channel = rfcomm_channel_for_rfcomm_cid(rfcomm_cid);
2385     if (!channel) return;
2386     switch (channel->state) {
2387         case RFCOMM_CHANNEL_INCOMING_SETUP:
2388             channel->state = RFCOMM_CHANNEL_SEND_DM;
2389             l2cap_request_can_send_now_event(channel->multiplexer->l2cap_cid);
2390             break;
2391         default:
2392             break;
2393     }
2394 }
2395 
2396 void rfcomm_grant_credits(uint16_t rfcomm_cid, uint8_t credits){
2397     log_info("RFCOMM_GRANT_CREDITS cid 0x%02x credits %u", rfcomm_cid, credits);
2398     rfcomm_channel_t * channel = rfcomm_channel_for_rfcomm_cid(rfcomm_cid);
2399     if (!channel) return;
2400     if (!channel->incoming_flow_control) return;
2401     channel->new_credits_incoming += credits;
2402 
2403     // process
2404     l2cap_request_can_send_now_event(channel->multiplexer->l2cap_cid);
2405 }
2406 
2407 
2408