xref: /btstack/src/mesh/mesh_lower_transport.c (revision 9155bf8c4cc807b690bdcca57de397a366eb10e4)
1 /*
2  * Copyright (C) 2014 BlueKitchen GmbH
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  *
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. Neither the name of the copyright holders nor the names of
14  *    contributors may be used to endorse or promote products derived
15  *    from this software without specific prior written permission.
16  * 4. Any redistribution, use, or modification is done solely for
17  *    personal benefit and not for any commercial purpose or for
18  *    monetary gain.
19  *
20  * THIS SOFTWARE IS PROVIDED BY BLUEKITCHEN GMBH AND CONTRIBUTORS
21  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
23  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL MATTHIAS
24  * RINGWALD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
25  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
26  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
27  * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
28  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
29  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
30  * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  *
33  * Please inquire about commercial licensing options at
34  * [email protected]
35  *
36  */
37 
38 #define __BTSTACK_FILE__ "mesh_lower_transport.c"
39 
40 #include <stdio.h>
41 #include <stdlib.h>
42 #include <string.h>
43 
44 #include "btstack_memory.h"
45 #include "btstack_util.h"
46 
47 #include "mesh/beacon.h"
48 #include "mesh/mesh_iv_index_seq_number.h"
49 #include "mesh/mesh_lower_transport.h"
50 #include "mesh/mesh_node.h"
51 #include "mesh/mesh_peer.h"
52 
53 static void (*higher_layer_handler)( mesh_transport_callback_type_t callback_type, mesh_transport_status_t status, mesh_pdu_t * pdu);
54 
55 static void mesh_print_hex(const char * name, const uint8_t * data, uint16_t len){
56     printf("%-20s ", name);
57     printf_hexdump(data, len);
58 }
59 // static void mesh_print_x(const char * name, uint32_t value){
60 //     printf("%20s: 0x%x", name, (int) value);
61 // }
62 
63 // utility
64 
65 // Transport PDU Getter
66 uint16_t mesh_transport_nid(mesh_transport_pdu_t * transport_pdu){
67     return transport_pdu->network_header[0] & 0x7f;
68 }
69 uint16_t mesh_transport_ctl(mesh_transport_pdu_t * transport_pdu){
70     return transport_pdu->network_header[1] >> 7;
71 }
72 uint16_t mesh_transport_ttl(mesh_transport_pdu_t * transport_pdu){
73     return transport_pdu->network_header[1] & 0x7f;
74 }
75 uint32_t mesh_transport_seq(mesh_transport_pdu_t * transport_pdu){
76     return big_endian_read_24(transport_pdu->network_header, 2);
77 }
78 uint32_t mesh_transport_seq_zero(mesh_transport_pdu_t * transport_pdu){
79     return transport_pdu->seq_zero;
80 }
81 uint16_t mesh_transport_src(mesh_transport_pdu_t * transport_pdu){
82     return big_endian_read_16(transport_pdu->network_header, 5);
83 }
84 uint16_t mesh_transport_dst(mesh_transport_pdu_t * transport_pdu){
85     return big_endian_read_16(transport_pdu->network_header, 7);
86 }
87 void mesh_transport_set_nid_ivi(mesh_transport_pdu_t * transport_pdu, uint8_t nid_ivi){
88     transport_pdu->network_header[0] = nid_ivi;
89 }
90 void mesh_transport_set_ctl_ttl(mesh_transport_pdu_t * transport_pdu, uint8_t ctl_ttl){
91     transport_pdu->network_header[1] = ctl_ttl;
92 }
93 void mesh_transport_set_seq(mesh_transport_pdu_t * transport_pdu, uint32_t seq){
94     big_endian_store_24(transport_pdu->network_header, 2, seq);
95 }
96 void mesh_transport_set_src(mesh_transport_pdu_t * transport_pdu, uint16_t src){
97     big_endian_store_16(transport_pdu->network_header, 5, src);
98 }
99 void mesh_transport_set_dest(mesh_transport_pdu_t * transport_pdu, uint16_t dest){
100     big_endian_store_16(transport_pdu->network_header, 7, dest);
101 }
102 
103 // lower transport
104 
105 // prototypes
106 
107 static void mesh_lower_transport_run(void);
108 static void mesh_lower_transport_abort_transmission(void);
109 
110 // state
111 static int                    lower_transport_retry_count;
112 
113 // lower transport incoming
114 static btstack_linked_list_t  lower_transport_incoming;
115 
116 // lower transport ougoing
117 static btstack_linked_list_t lower_transport_outgoing;
118 
119 static mesh_transport_pdu_t * lower_transport_outgoing_pdu;
120 static mesh_network_pdu_t   * lower_transport_outgoing_segment;
121 static uint16_t               lower_transport_outgoing_seg_o;
122 
123 static void mesh_lower_transport_process_unsegmented_control_message(mesh_network_pdu_t *network_pdu){
124     uint8_t * lower_transport_pdu     = mesh_network_pdu_data(network_pdu);
125     uint8_t  opcode = lower_transport_pdu[0];
126     printf("Unsegmented Control message, outgoing message %p, opcode %x\n", lower_transport_outgoing_pdu, opcode);
127     uint16_t seq_zero_pdu;
128     uint16_t seq_zero_out;
129     uint32_t block_ack;
130     switch (opcode){
131         case 0:
132             if (lower_transport_outgoing_pdu == NULL) break;
133             seq_zero_pdu = big_endian_read_16(lower_transport_pdu, 1) >> 2;
134             seq_zero_out = mesh_transport_seq(lower_transport_outgoing_pdu) & 0x1fff;
135             block_ack = big_endian_read_32(lower_transport_pdu, 3);
136             printf("[+] Segment Acknowledgment message with seq_zero %06x, block_ack %08x - outgoing seq %06x, block_ack %08x\n",
137                    seq_zero_pdu, block_ack, seq_zero_out, lower_transport_outgoing_pdu->block_ack);
138             if (block_ack == 0){
139                 // If a Segment Acknowledgment message with the BlockAck field set to 0x00000000 is received,
140                 // then the Upper Transport PDU shall be immediately cancelled and the higher layers shall be notified that
141                 // the Upper Transport PDU has been cancelled.
142                 printf("[+] Block Ack == 0 => Abort\n");
143                 mesh_lower_transport_abort_transmission();
144                 break;
145             }
146             if (seq_zero_pdu != seq_zero_out){
147                 printf("[!] Seq Zero doesn't match\n");
148                 break;
149             }
150             lower_transport_outgoing_pdu->block_ack &= ~block_ack;
151             printf("[+] Updated block_ack %08x\n", lower_transport_outgoing_pdu->block_ack);
152             if (lower_transport_outgoing_pdu->block_ack == 0){
153                 printf("[+] Sent complete\n");
154                 mesh_lower_transport_abort_transmission();
155             }
156             mesh_network_message_processed_by_higher_layer(network_pdu);
157             break;
158         default:
159             higher_layer_handler(MESH_TRANSPORT_PDU_RECEIVED, MESH_TRANSPORT_STATUS_SUCCESS, (mesh_pdu_t *) network_pdu);
160             break;
161     }
162 }
163 
164 // ack / incomplete message
165 
166 static void mesh_lower_transport_setup_segmented_acknowledge_message(uint8_t * data, uint8_t obo, uint16_t seq_zero, uint32_t block_ack){
167     // printf("ACK Upper Transport, seq_zero %x\n", seq_zero);
168     data[0] = 0;    // SEG = 0, Opcode = 0
169     big_endian_store_16( data, 1, (obo << 15) | (seq_zero << 2) | 0);    // OBO, SeqZero, RFU
170     big_endian_store_32( data, 3, block_ack);
171     mesh_print_hex("ACK Upper Transport", data, 7);
172 }
173 
174 static void mesh_lower_transport_send_ack(uint16_t netkey_index, uint8_t ttl, uint16_t dest, uint16_t seq_zero, uint32_t block_ack){
175     // setup ack message
176     uint8_t  ack_msg[7];
177     mesh_lower_transport_setup_segmented_acknowledge_message(ack_msg, 0, seq_zero, block_ack);
178     //
179     // "3.4.5.2: The output filter of the interface connected to advertising or GATT bearers shall drop all messages with TTL value set to 1."
180     // if (ttl <= 1) return 0;
181 
182     // TODO: check transport_pdu_len depending on ctl
183 
184     // lookup network by netkey_index
185     const mesh_network_key_t * network_key = mesh_network_key_list_get(netkey_index);
186     if (!network_key) return;
187 
188     // allocate network_pdu
189     mesh_network_pdu_t * network_pdu = mesh_network_pdu_get();
190     if (!network_pdu) return;
191 
192     // setup network_pdu
193     mesh_network_setup_pdu(network_pdu, netkey_index, network_key->nid, 1, ttl, mesh_sequence_number_next(), mesh_node_get_primary_element_address(), dest, ack_msg, sizeof(ack_msg));
194 
195     // send network_pdu
196     mesh_network_send_pdu(network_pdu);
197 }
198 
199 static void mesh_lower_transport_send_ack_for_transport_pdu(mesh_transport_pdu_t *transport_pdu){
200     uint16_t seq_zero = mesh_transport_seq_zero(transport_pdu);
201     uint8_t ttl = mesh_transport_ttl(transport_pdu);
202     uint16_t dest = mesh_transport_src(transport_pdu);
203     uint16_t netkey_index = transport_pdu->netkey_index;
204     printf("mesh_transport_send_ack_for_transport_pdu %p with netkey_index %x, TTL = %u, SeqZero = %x, SRC = %x, DST = %x\n",
205            transport_pdu, netkey_index, ttl, seq_zero, mesh_node_get_primary_element_address(), dest);
206     mesh_lower_transport_send_ack(netkey_index, ttl, dest, seq_zero, transport_pdu->block_ack);
207 }
208 
209 static void mesh_lower_transport_send_ack_for_network_pdu(mesh_network_pdu_t *network_pdu, uint16_t seq_zero, uint32_t block_ack) {
210     uint8_t ttl = mesh_network_ttl(network_pdu);
211     uint16_t dest = mesh_network_src(network_pdu);
212     uint16_t netkey_index = network_pdu->netkey_index;
213     printf("mesh_transport_send_ack_for_network_pdu %p with netkey_index %x, TTL = %u, SeqZero = %x, SRC = %x, DST = %x\n",
214            network_pdu, netkey_index, ttl, seq_zero, mesh_node_get_primary_element_address(), dest);
215     mesh_lower_transport_send_ack(netkey_index, ttl, dest, seq_zero, block_ack);
216 }
217 
218 static void mesh_lower_transport_stop_acknowledgment_timer(mesh_transport_pdu_t *transport_pdu){
219     if (!transport_pdu->acknowledgement_timer_active) return;
220     transport_pdu->acknowledgement_timer_active = 0;
221     btstack_run_loop_remove_timer(&transport_pdu->acknowledgement_timer);
222 }
223 
224 static void mesh_lower_transport_stop_incomplete_timer(mesh_transport_pdu_t *transport_pdu){
225     if (!transport_pdu->incomplete_timer_active) return;
226     transport_pdu->incomplete_timer_active = 0;
227     btstack_run_loop_remove_timer(&transport_pdu->incomplete_timer);
228 }
229 
230 // stops timers and updates reassembly engine
231 static void mesh_lower_transport_segmented_message_complete(mesh_transport_pdu_t *transport_pdu){
232     // set flag
233     transport_pdu->message_complete = 1;
234     // stop timers
235     mesh_lower_transport_stop_acknowledgment_timer(transport_pdu);
236     mesh_lower_transport_stop_incomplete_timer(transport_pdu);
237     // stop reassembly
238     mesh_peer_t * peer = mesh_peer_for_addr(mesh_transport_src(transport_pdu));
239     if (peer){
240         peer->transport_pdu = NULL;
241     }
242 }
243 
244 static void mesh_lower_transport_rx_ack_timeout(btstack_timer_source_t *ts){
245     mesh_transport_pdu_t * transport_pdu = (mesh_transport_pdu_t *) btstack_run_loop_get_timer_context(ts);
246     printf("ACK: acknowledgement timer fired for %p, send ACK\n", transport_pdu);
247     transport_pdu->acknowledgement_timer_active = 0;
248     mesh_lower_transport_send_ack_for_transport_pdu(transport_pdu);
249 }
250 
251 static void mesh_lower_transport_rx_incomplete_timeout(btstack_timer_source_t *ts){
252     mesh_transport_pdu_t * transport_pdu = (mesh_transport_pdu_t *) btstack_run_loop_get_timer_context(ts);
253     printf("mesh_transport_rx_incomplete_timeout for %p - give up\n", transport_pdu);
254     mesh_lower_transport_segmented_message_complete(transport_pdu);
255     // free message
256     btstack_memory_mesh_transport_pdu_free(transport_pdu);
257 }
258 
259 static void mesh_lower_transport_start_acknowledgment_timer(mesh_transport_pdu_t *transport_pdu, uint32_t timeout,
260                                                             void (*callback)(btstack_timer_source_t *ts)){
261     printf("ACK: start ack timer for %p, timeout %u ms\n", transport_pdu, (int) timeout);
262     btstack_run_loop_set_timer(&transport_pdu->acknowledgement_timer, timeout);
263     btstack_run_loop_set_timer_handler(&transport_pdu->acknowledgement_timer, callback);
264     btstack_run_loop_set_timer_context(&transport_pdu->acknowledgement_timer, transport_pdu);
265     btstack_run_loop_add_timer(&transport_pdu->acknowledgement_timer);
266     transport_pdu->acknowledgement_timer_active = 1;
267 }
268 
269 static void mesh_lower_transport_restart_incomplete_timer(mesh_transport_pdu_t *transport_pdu, uint32_t timeout,
270                                                           void (*callback)(btstack_timer_source_t *ts)){
271     printf("RX-(re)start incomplete timer for %p, timeout %u ms\n", transport_pdu, (int) timeout);
272     if (transport_pdu->incomplete_timer_active){
273         btstack_run_loop_remove_timer(&transport_pdu->incomplete_timer);
274     }
275     btstack_run_loop_set_timer(&transport_pdu->incomplete_timer, timeout);
276     btstack_run_loop_set_timer_handler(&transport_pdu->incomplete_timer, callback);
277     btstack_run_loop_set_timer_context(&transport_pdu->incomplete_timer, transport_pdu);
278     btstack_run_loop_add_timer(&transport_pdu->incomplete_timer);
279     transport_pdu->incomplete_timer_active = 1;
280 }
281 
282 static void mesh_lower_transport_outgoing_complete(void){
283     mesh_transport_pdu_t * pdu   = lower_transport_outgoing_pdu;
284     lower_transport_outgoing_pdu = NULL;
285     higher_layer_handler(MESH_TRANSPORT_PDU_SENT, MESH_TRANSPORT_STATUS_SEND_ABORT_BY_REMOTE, (mesh_pdu_t *) pdu);
286 }
287 
288 static void mesh_lower_transport_abort_transmission(void){
289     // stop ack timers
290     mesh_lower_transport_stop_acknowledgment_timer(lower_transport_outgoing_pdu);
291 
292     // notify upper transport
293     mesh_lower_transport_outgoing_complete();
294 }
295 
296 static mesh_transport_pdu_t * mesh_lower_transport_pdu_for_segmented_message(mesh_network_pdu_t *network_pdu){
297     uint16_t src = mesh_network_src(network_pdu);
298     uint16_t seq_zero = ( big_endian_read_16(mesh_network_pdu_data(network_pdu), 1) >> 2) & 0x1fff;
299     printf("mesh_transport_pdu_for_segmented_message: seq_zero %x\n", seq_zero);
300     mesh_peer_t * peer = mesh_peer_for_addr(src);
301     if (!peer) {
302         return NULL;
303     }
304     printf("mesh_seq_zero_validate(%x, %x) -- last (%x, %x)\n", src, seq_zero, peer->address, peer->seq_zero);
305 
306     // reception of transport message ongoing
307     if (peer->transport_pdu){
308         // check if segment for same seq zero
309         uint16_t active_seq_zero = mesh_transport_seq_zero(peer->transport_pdu);
310         if (active_seq_zero == seq_zero) {
311             printf("mesh_transport_pdu_for_segmented_message: segment for current transport pdu with SeqZero %x\n", active_seq_zero);
312             return peer->transport_pdu;
313         } else {
314             // seq zero differs from current transport pdu, but current pdu is not complete
315             printf("mesh_transport_pdu_for_segmented_message: drop segment. current transport pdu SeqZero %x, now %x\n", active_seq_zero, seq_zero);
316             return NULL;
317         }
318     }
319 
320     // send ACK if segment for previously completed transport pdu (no ongoing reception, block ack is cleared)
321     if ((seq_zero == peer->seq_zero) && (peer->block_ack != 0)){
322         printf("mesh_transport_pdu_for_segmented_message: segment for last completed message. send ack\n");
323         mesh_lower_transport_send_ack_for_network_pdu(network_pdu, seq_zero, peer->block_ack);
324         return NULL;
325     }
326 
327     // reconstruct lowest 24 bit of SeqAuth
328     uint32_t seq = mesh_network_seq(network_pdu);
329     uint32_t seq_auth = (seq & 0xffe000) | seq_zero;
330     if (seq_auth > seq){
331         seq_auth -= 0x2000;
332     }
333 
334     // no transport pdu active, check new message: seq auth is greater OR seq auth is same but no segments
335     if (seq_auth > peer->seq_auth || (seq_auth == peer->seq_auth && peer->block_ack == 0)){
336         mesh_transport_pdu_t * pdu = mesh_transport_pdu_get();
337         if (!pdu) return NULL;
338 
339         // cache network pdu header
340         memcpy(pdu->network_header, network_pdu->data, 9);
341         // store lower 24 bit of SeqAuth for App / Device Nonce
342         big_endian_store_24(pdu->network_header, 2, seq_auth);
343 
344         // store meta data in new pdu
345         pdu->netkey_index = network_pdu->netkey_index;
346         pdu->block_ack = 0;
347         pdu->acknowledgement_timer_active = 0;
348         pdu->message_complete = 0;
349         pdu->seq_zero = seq_zero;
350 
351         // update peer info
352         peer->transport_pdu = pdu;
353         peer->seq_zero      = seq_zero;
354         peer->seq_auth      = seq_auth;
355         peer->block_ack     = 0;
356 
357         printf("mesh_transport_pdu_for_segmented_message: setup transport pdu %p for src %x, seq %06x, seq_zero %x\n", pdu, src, mesh_transport_seq(pdu), seq_zero);
358 
359         return peer->transport_pdu;
360     }  else {
361         // seq zero differs from current transport pdu
362         printf("mesh_transport_pdu_for_segmented_message: drop segment for old seq %x\n", seq_zero);
363         return NULL;
364     }
365 }
366 
367 static void mesh_lower_transport_process_segment( mesh_transport_pdu_t * transport_pdu, mesh_network_pdu_t * network_pdu){
368 
369     uint8_t * lower_transport_pdu     = mesh_network_pdu_data(network_pdu);
370     uint8_t   lower_transport_pdu_len = mesh_network_pdu_len(network_pdu);
371 
372     // get akf_aid & transmic
373     transport_pdu->akf_aid      = lower_transport_pdu[0];
374     transport_pdu->transmic_len = lower_transport_pdu[1] & 0x80 ? 8 : 4;
375 
376     // get seq_zero
377     uint16_t seq_zero =  ( big_endian_read_16(lower_transport_pdu, 1) >> 2) & 0x1fff;
378 
379     // get seg fields
380     uint8_t  seg_o    =  ( big_endian_read_16(lower_transport_pdu, 2) >> 5) & 0x001f;
381     uint8_t  seg_n    =  lower_transport_pdu[3] & 0x1f;
382     uint8_t   segment_len  =  lower_transport_pdu_len - 4;
383     uint8_t * segment_data = &lower_transport_pdu[4];
384 
385     printf("mesh_lower_transport_process_segment: seq zero %04x, seg_o %02x, seg_n %02x, transmic len: %u\n", seq_zero, seg_o, seg_n, transport_pdu->transmic_len * 8);
386     mesh_print_hex("Segment", segment_data, segment_len);
387 
388     // store segment
389     memcpy(&transport_pdu->data[seg_o * 12], segment_data, 12);
390     // mark as received
391     transport_pdu->block_ack |= (1<<seg_o);
392     // last segment -> store len
393     if (seg_o == seg_n){
394         transport_pdu->len = (seg_n * 12) + segment_len;
395         printf("Assembled payload len %u\n", transport_pdu->len);
396     }
397 
398     // check for complete
399     int i;
400     for (i=0;i<=seg_n;i++){
401         if ( (transport_pdu->block_ack & (1<<i)) == 0) return;
402     }
403 
404     mesh_print_hex("Assembled payload", transport_pdu->data, transport_pdu->len);
405 
406     // mark as done
407     mesh_lower_transport_segmented_message_complete(transport_pdu);
408 
409     // store block ack in peer info
410     mesh_peer_t * peer = mesh_peer_for_addr(mesh_transport_src(transport_pdu));
411     // TODO: check if NULL check can be removed
412     if (peer){
413         peer->block_ack = transport_pdu->block_ack;
414     }
415 
416     // send ack
417     mesh_lower_transport_send_ack_for_transport_pdu(transport_pdu);
418 
419     // forward to upper transport
420     higher_layer_handler(MESH_TRANSPORT_PDU_RECEIVED, MESH_TRANSPORT_STATUS_SUCCESS, (mesh_pdu_t*) transport_pdu);
421 }
422 
423 void mesh_lower_transport_message_processed_by_higher_layer(mesh_pdu_t * pdu){
424     switch (pdu->pdu_type){
425         case MESH_PDU_TYPE_NETWORK:
426             mesh_network_message_processed_by_higher_layer((mesh_network_pdu_t *) pdu);
427             break;
428         case MESH_PDU_TYPE_TRANSPORT:
429             mesh_transport_pdu_free((mesh_transport_pdu_t *) pdu);
430             break;
431         default:
432             break;
433     }
434 }
435 
436 static void mesh_lower_transport_network_pdu_sent(mesh_network_pdu_t *network_pdu);
437 
438 static void mesh_lower_transport_tx_ack_timeout(btstack_timer_source_t * ts);
439 
440 void mesh_lower_transport_received_message(mesh_network_callback_type_t callback_type, mesh_network_pdu_t *network_pdu){
441     mesh_peer_t * peer;
442     uint16_t src;
443     uint16_t seq;
444     switch (callback_type){
445         case MESH_NETWORK_PDU_RECEIVED:
446             src = mesh_network_src(network_pdu);
447             seq = mesh_network_seq(network_pdu);
448             peer = mesh_peer_for_addr(src);
449             printf("Transport: received message. SRC %x, SEQ %x\n", src, seq);
450             // validate seq
451             if (peer && seq > peer->seq){
452                 // track seq
453                 peer->seq = seq;
454                 // add to list and go
455                 btstack_linked_list_add_tail(&lower_transport_incoming, (btstack_linked_item_t *) network_pdu);
456                 mesh_lower_transport_run();
457             } else {
458                 // drop packet
459                 printf("Transport: drop packet - src/seq auth failed\n");
460                 mesh_network_message_processed_by_higher_layer(network_pdu);
461             }
462             break;
463         case MESH_NETWORK_PDU_SENT:
464             mesh_lower_transport_network_pdu_sent(network_pdu);
465             break;
466         default:
467             break;
468     }
469 }
470 
471 static void mesh_lower_transport_setup_segment(mesh_transport_pdu_t *transport_pdu, uint8_t seg_o, mesh_network_pdu_t *network_pdu){
472 
473     int ctl = mesh_transport_ctl(transport_pdu);
474     uint16_t max_segment_len = ctl ? 8 : 12;    // control 8 bytes (64 bit NetMic), access 12 bytes (32 bit NetMIC)
475 
476     uint32_t seq      = mesh_sequence_number_next();
477     uint16_t seq_zero = mesh_transport_seq(transport_pdu) & 0x01fff;
478     uint8_t  seg_n    = (transport_pdu->len - 1) / max_segment_len;
479     uint8_t  szmic    = ((!ctl) && (transport_pdu->transmic_len == 8)) ? 1 : 0; // only 1 for access messages with 64 bit TransMIC
480     uint8_t  nid      = mesh_transport_nid(transport_pdu);
481     uint8_t  ttl      = mesh_transport_ttl(transport_pdu);
482     uint16_t src      = mesh_transport_src(transport_pdu);
483     uint16_t dest     = mesh_transport_dst(transport_pdu);
484 
485     // current segment.
486     uint16_t seg_offset = seg_o * max_segment_len;
487 
488     uint8_t lower_transport_pdu_data[16];
489     lower_transport_pdu_data[0] = 0x80 |  transport_pdu->akf_aid;
490     big_endian_store_24(lower_transport_pdu_data, 1, (szmic << 23) | (seq_zero << 10) | (seg_o << 5) | seg_n);
491     uint16_t segment_len = btstack_min(transport_pdu->len - seg_offset, max_segment_len);
492     memcpy(&lower_transport_pdu_data[4], &transport_pdu->data[seg_offset], segment_len);
493     uint16_t lower_transport_pdu_len = 4 + segment_len;
494 
495     mesh_network_setup_pdu(network_pdu, transport_pdu->netkey_index, nid, 0, ttl, seq, src, dest, lower_transport_pdu_data, lower_transport_pdu_len);
496 }
497 
498 static void mesh_lower_transport_send_next_segment(void){
499     if (!lower_transport_outgoing_pdu) return;
500 
501     int ctl = mesh_transport_ctl(lower_transport_outgoing_pdu);
502     uint16_t max_segment_len = ctl ? 8 : 12;    // control 8 bytes (64 bit NetMic), access 12 bytes (32 bit NetMIC)
503     uint8_t  seg_n = (lower_transport_outgoing_pdu->len - 1) / max_segment_len;
504 
505     // find next unacknowledged segement
506     while ((lower_transport_outgoing_seg_o <= seg_n) && ((lower_transport_outgoing_pdu->block_ack & (1 << lower_transport_outgoing_seg_o)) == 0)){
507         lower_transport_outgoing_seg_o++;
508     }
509 
510     if (lower_transport_outgoing_seg_o > seg_n){
511         printf("[+] Lower Transport, send segmented pdu complete (dst %x)\n", mesh_transport_dst(lower_transport_outgoing_pdu));
512         lower_transport_outgoing_seg_o   = 0;
513 
514         // done for unicast, ack timer already set, too
515         if (mesh_network_address_unicast(mesh_transport_dst(lower_transport_outgoing_pdu))) return;
516 
517         // done, more?
518         if (lower_transport_retry_count == 0){
519             printf("[+] Lower Transport, message unacknowledged -> free\n");
520             // notify upper transport
521             mesh_lower_transport_outgoing_complete();
522             return;
523         }
524 
525         // start retry
526         printf("[+] Lower Transport, message unacknowledged retry count %u\n", lower_transport_retry_count);
527         lower_transport_retry_count--;
528     }
529 
530     if (mesh_network_address_unicast(mesh_transport_dst(lower_transport_outgoing_pdu))){
531         // restart acknowledgment timer for unicast dst
532         // - "This timer shall be set to a minimum of 200 + 50 * TTL milliseconds."
533         if (lower_transport_outgoing_pdu->acknowledgement_timer_active){
534             btstack_run_loop_remove_timer(&lower_transport_outgoing_pdu->incomplete_timer);
535             lower_transport_outgoing_pdu->acknowledgement_timer_active = 0;
536         }
537         uint32_t timeout = 200 + 50 * mesh_transport_ttl(lower_transport_outgoing_pdu);
538         mesh_lower_transport_start_acknowledgment_timer(lower_transport_outgoing_pdu, timeout,
539                                                         &mesh_lower_transport_tx_ack_timeout);
540     }
541 
542     mesh_lower_transport_setup_segment(lower_transport_outgoing_pdu, lower_transport_outgoing_seg_o,
543                                        lower_transport_outgoing_segment);
544 
545     printf("[+] Lower Transport, send segmented pdu: seg_o %x, seg_n %x\n", lower_transport_outgoing_seg_o, seg_n);
546     mesh_print_hex("LowerTransportPDU", lower_transport_outgoing_segment->data, lower_transport_outgoing_segment->len);
547 
548     // next segment
549     lower_transport_outgoing_seg_o++;
550 
551     // send network pdu
552     mesh_network_send_pdu(lower_transport_outgoing_segment);
553 }
554 
555 static void mesh_lower_transport_network_pdu_sent(mesh_network_pdu_t *network_pdu){
556     // figure out what pdu was sent
557 
558     // single segment of segmented message?
559     if (lower_transport_outgoing_segment == network_pdu){
560         mesh_lower_transport_send_next_segment();
561         return;
562     }
563 
564     // Segment Acknowledgment message sent by us?
565     if (mesh_network_control(network_pdu) && network_pdu->data[0] == 0){
566         btstack_memory_mesh_network_pdu_free(network_pdu);
567         return;
568     }
569 
570     // other
571     higher_layer_handler(MESH_TRANSPORT_PDU_SENT, MESH_TRANSPORT_STATUS_SUCCESS, (mesh_pdu_t *) network_pdu);
572 }
573 
574 static void mesh_lower_transport_setup_block_ack(mesh_transport_pdu_t *transport_pdu){
575     // setup block ack - set bit for segment to send, will be cleared on ack
576     int      ctl = mesh_transport_ctl(transport_pdu);
577     uint16_t max_segment_len = ctl ? 8 : 12;    // control 8 bytes (64 bit NetMic), access 12 bytes (32 bit NetMIC)
578     uint8_t  seg_n = (transport_pdu->len - 1) / max_segment_len;
579     if (seg_n < 31){
580         transport_pdu->block_ack = (1 << (seg_n+1)) - 1;
581     } else {
582         transport_pdu->block_ack = 0xffffffff;
583     }
584 }
585 
586 static void mesh_lower_transport_send_segmented_pdu_once(mesh_transport_pdu_t *transport_pdu){
587 
588     if (lower_transport_retry_count == 0){
589         printf("[!] Upper transport, send segmented pdu failed, retries exhausted\n");
590         mesh_lower_transport_outgoing_complete();
591         return;
592     }
593 
594     // chop into chunks
595     printf("[+] Lower Transport, send segmented pdu (retry count %u)\n", lower_transport_retry_count);
596     lower_transport_retry_count--;
597 
598     // setup
599     lower_transport_outgoing_pdu     = transport_pdu;
600     lower_transport_outgoing_seg_o   = 0;
601 
602     // start sending
603     mesh_lower_transport_send_next_segment();
604 }
605 
606 void mesh_lower_transport_send_pdu(mesh_pdu_t *pdu){
607     btstack_linked_list_add_tail(&lower_transport_outgoing, (btstack_linked_item_t*) pdu);
608     mesh_lower_transport_run();
609 }
610 
611 static void mesh_lower_transport_tx_ack_timeout(btstack_timer_source_t * ts){
612     mesh_transport_pdu_t * transport_pdu = (mesh_transport_pdu_t *) btstack_run_loop_get_timer_context(ts);
613     printf("[+] Lower transport, acknowledgement timer fired for %p\n", transport_pdu);
614     transport_pdu->acknowledgement_timer_active = 0;
615     // send remaining segments again
616     mesh_lower_transport_send_segmented_pdu_once(transport_pdu);
617 }
618 
619 static void mesh_lower_transport_run(void){
620     while(!btstack_linked_list_empty(&lower_transport_incoming)){
621         // get next message
622         mesh_network_pdu_t * network_pdu = (mesh_network_pdu_t *) btstack_linked_list_pop(&lower_transport_incoming);
623         // segmented?
624         if (mesh_network_segmented(network_pdu)){
625             mesh_transport_pdu_t * transport_pdu = mesh_lower_transport_pdu_for_segmented_message(network_pdu);
626             if (!transport_pdu) return;
627             // start acknowledgment timer if inactive
628             if (transport_pdu->acknowledgement_timer_active == 0){
629                 // - "The acknowledgment timer shall be set to a minimum of 150 + 50 * TTL milliseconds"
630                 uint32_t timeout = 150 + 50 * mesh_network_ttl(network_pdu);
631                 mesh_lower_transport_start_acknowledgment_timer(transport_pdu, timeout,
632                                                                 &mesh_lower_transport_rx_ack_timeout);
633             }
634             // restart incomplete timer
635             mesh_lower_transport_restart_incomplete_timer(transport_pdu, 10000,
636                                                           &mesh_lower_transport_rx_incomplete_timeout);
637             mesh_lower_transport_process_segment(transport_pdu, network_pdu);
638             mesh_network_message_processed_by_higher_layer(network_pdu);
639         } else {
640             // control?
641             if (mesh_network_control(network_pdu)){
642                 // unsegmented control message (not encrypted)
643                 mesh_lower_transport_process_unsegmented_control_message(network_pdu);
644             } else {
645                 // unsegmented access message (encrypted)
646                 higher_layer_handler(MESH_TRANSPORT_PDU_RECEIVED, MESH_TRANSPORT_STATUS_SUCCESS, (mesh_pdu_t *) network_pdu);
647             }
648         }
649     }
650 
651     // check if outgoing segmented pdu is active
652     if (lower_transport_outgoing_pdu) return;
653 
654     while(!btstack_linked_list_empty(&lower_transport_outgoing)) {
655         // get next message
656         mesh_transport_pdu_t * transport_pdu;
657         mesh_network_pdu_t   * network_pdu;
658         mesh_pdu_t * pdu = (mesh_pdu_t *) btstack_linked_list_pop(&lower_transport_outgoing);
659         switch (pdu->pdu_type) {
660             case MESH_PDU_TYPE_NETWORK:
661                 network_pdu = (mesh_network_pdu_t *) pdu;
662                 mesh_network_send_pdu(network_pdu);
663                 break;
664             case MESH_PDU_TYPE_TRANSPORT:
665                 transport_pdu = (mesh_transport_pdu_t *) pdu;
666                 // start sending segmented pdu
667                 lower_transport_retry_count = 2;
668                 mesh_lower_transport_setup_block_ack(transport_pdu);
669                 mesh_lower_transport_send_segmented_pdu_once(transport_pdu);
670                 break;
671             default:
672                 break;
673         }
674     }
675 }
676 
677 static void mesh_lower_transport_dump_network_pdus(const char *name, btstack_linked_list_t *list){
678     printf("List: %s:\n", name);
679     btstack_linked_list_iterator_t it;
680     btstack_linked_list_iterator_init(&it, list);
681     while (btstack_linked_list_iterator_has_next(&it)){
682         mesh_network_pdu_t * network_pdu = (mesh_network_pdu_t*) btstack_linked_list_iterator_next(&it);
683         printf("- %p: ", network_pdu); printf_hexdump(network_pdu->data, network_pdu->len);
684     }
685 }
686 static void mesh_lower_transport_reset_network_pdus(btstack_linked_list_t *list){
687     while (!btstack_linked_list_empty(list)){
688         mesh_network_pdu_t * pdu = (mesh_network_pdu_t *) btstack_linked_list_pop(list);
689         btstack_memory_mesh_network_pdu_free(pdu);
690     }
691 }
692 
693 void mesh_lower_transport_dump(void){
694     // static btstack_linked_list_t upper_transport_control;
695     // static btstack_linked_list_t upper_transport_access;
696     mesh_lower_transport_dump_network_pdus("lower_transport_incoming", &lower_transport_incoming);
697 }
698 
699 void mesh_lower_transport_reset(void){
700     // static btstack_linked_list_t upper_transport_control;
701     // static btstack_linked_list_t upper_transport_access;
702     mesh_lower_transport_reset_network_pdus(&lower_transport_incoming);
703     if (lower_transport_outgoing_pdu){
704         mesh_transport_pdu_free(lower_transport_outgoing_pdu);
705         lower_transport_outgoing_pdu = NULL;
706     }
707 }
708 
709 void mesh_lower_transport_init(){
710     // register with network layer
711     mesh_network_set_higher_layer_handler(&mesh_lower_transport_received_message);
712     // allocate network_pdu for segmentation
713     lower_transport_outgoing_segment = mesh_network_pdu_get();
714 }
715 
716 void mesh_lower_transport_set_higher_layer_handler(void (*pdu_handler)( mesh_transport_callback_type_t callback_type, mesh_transport_status_t status, mesh_pdu_t * pdu)){
717     higher_layer_handler = pdu_handler;
718 }
719 
720 // buffer pool
721 mesh_transport_pdu_t * mesh_transport_pdu_get(void){
722     mesh_transport_pdu_t * transport_pdu = btstack_memory_mesh_transport_pdu_get();
723     if (transport_pdu) {
724         memset(transport_pdu, 0, sizeof(mesh_transport_pdu_t));
725         transport_pdu->pdu_header.pdu_type = MESH_PDU_TYPE_TRANSPORT;
726     }
727     return transport_pdu;
728 }
729 
730 void mesh_transport_pdu_free(mesh_transport_pdu_t * transport_pdu){
731     btstack_memory_mesh_transport_pdu_free(transport_pdu);
732 }
733