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