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