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