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