xref: /btstack/src/mesh/mesh_access.c (revision ba660d425163a6a574135163749bd4c879598a8d)
1 /*
2  * Copyright (C) 2019 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_access.c"
39 
40 #include <string.h>
41 #include <stdio.h>
42 #include <stdarg.h>
43 
44 #include "mesh/mesh_access.h"
45 
46 #include "btstack_debug.h"
47 #include "btstack_memory.h"
48 #include "btstack_tlv.h"
49 
50 #include "mesh/beacon.h"
51 #include "mesh/mesh_foundation.h"
52 #include "mesh/mesh_iv_index_seq_number.h"
53 #include "mesh/mesh_node.h"
54 #include "mesh/mesh_proxy.h"
55 #include "mesh/mesh_upper_transport.h"
56 #include "mesh/mesh.h"
57 
58 #define MEST_TRANSACTION_TIMEOUT_MS  6000
59 
60 static void mesh_access_message_process_handler(mesh_pdu_t * pdu);
61 static void mesh_access_upper_transport_handler(mesh_transport_callback_type_t callback_type, mesh_transport_status_t status, mesh_pdu_t * pdu);
62 static const mesh_operation_t * mesh_model_lookup_operation_by_opcode(mesh_model_t * model, uint32_t opcode);
63 
64 // receive
65 static uint16_t mesh_access_received_pdu_refcount;
66 
67 // acknowledged messages
68 static btstack_linked_list_t  mesh_access_acknowledged_messages;
69 static btstack_timer_source_t mesh_access_acknowledged_timer;
70 static int                    mesh_access_acknowledged_timer_active;
71 
72 // Transitions
73 static uint8_t mesh_transaction_id_counter = 0;
74 
75 void mesh_access_init(void){
76     // register with upper transport
77     mesh_upper_transport_register_access_message_handler(&mesh_access_upper_transport_handler);
78 }
79 
80 void mesh_access_emit_state_update_bool(btstack_packet_handler_t event_handler, uint8_t element_index, uint32_t model_identifier,
81     model_state_id_t state_identifier, model_state_update_reason_t reason, uint8_t value){
82     if (event_handler == NULL) return;
83     uint8_t event[14] = {HCI_EVENT_MESH_META, 12, MESH_SUBEVENT_STATE_UPDATE_BOOL};
84     int pos = 3;
85     event[pos++] = element_index;
86     little_endian_store_32(event, pos, model_identifier);
87     pos += 4;
88     little_endian_store_32(event, pos, (uint32_t)state_identifier);
89     pos += 4;
90     event[pos++] = (uint8_t)reason;
91     event[pos++] = value;
92     (*event_handler)(HCI_EVENT_PACKET, 0, event, sizeof(event));
93 }
94 
95 void mesh_access_emit_state_update_int16(btstack_packet_handler_t event_handler, uint8_t element_index, uint32_t model_identifier,
96     model_state_id_t state_identifier, model_state_update_reason_t reason, int16_t value){
97     if (event_handler == NULL) return;
98     uint8_t event[15] = {HCI_EVENT_MESH_META, 13, MESH_SUBEVENT_STATE_UPDATE_BOOL};
99     int pos = 3;
100     event[pos++] = element_index;
101     little_endian_store_32(event, pos, model_identifier);
102     pos += 4;
103     little_endian_store_32(event, pos, (uint32_t)state_identifier);
104     pos += 4;
105     event[pos++] = (uint8_t)reason;
106     little_endian_store_16(event, pos, (uint16_t) value);
107     pos += 2;
108     (*event_handler)(HCI_EVENT_PACKET, 0, event, sizeof(event));
109 }
110 
111 uint8_t mesh_access_acknowledged_message_retransmissions(void){
112     return 3;
113 }
114 
115 uint32_t mesh_access_acknowledged_message_timeout_ms(void){
116     return 30000;
117 }
118 
119 #define MESH_ACCESS_OPCODE_INVALID 0xFFFFFFFFu
120 #define MESH_ACCESS_OPCODE_NOT_SET 0xFFFFFFFEu
121 
122 static uint32_t mesh_access_message_ack_opcode(mesh_pdu_t * pdu){
123     switch (pdu->pdu_type){
124         case MESH_PDU_TYPE_TRANSPORT:
125             return ((mesh_transport_pdu_t *)pdu)->ack_opcode;
126         case MESH_PDU_TYPE_SEGMENTED:
127             return ((mesh_segmented_pdu_t *)pdu)->ack_opcode;
128         default:
129             btstack_assert(0);
130             return MESH_ACCESS_OPCODE_INVALID;
131     }
132 }
133 
134 static void mesh_access_message_set_ack_opcode(mesh_pdu_t * pdu, uint32_t ack_opcode){
135     switch (pdu->pdu_type){
136         case MESH_PDU_TYPE_TRANSPORT:
137             ((mesh_transport_pdu_t *)pdu)->ack_opcode = ack_opcode;
138             break;
139         case MESH_PDU_TYPE_SEGMENTED:
140             ((mesh_segmented_pdu_t *)pdu)->ack_opcode = ack_opcode;
141             break;
142         default:
143             btstack_assert(0);
144             break;
145     }
146 }
147 
148 static uint8_t mesh_access_message_retransmit_count(mesh_pdu_t * pdu){
149     switch (pdu->pdu_type){
150         case MESH_PDU_TYPE_TRANSPORT:
151             return ((mesh_transport_pdu_t *)pdu)->retransmit_count;
152         case MESH_PDU_TYPE_SEGMENTED:
153             return ((mesh_segmented_pdu_t *)pdu)->retransmit_count;
154         default:
155             btstack_assert(0);
156             return 0;
157     }
158 }
159 
160 static void mesh_access_message_set_retransmit_count(mesh_pdu_t * pdu, uint8_t retransmit_count){
161     switch (pdu->pdu_type){
162         case MESH_PDU_TYPE_TRANSPORT:
163             ((mesh_transport_pdu_t *)pdu)->retransmit_count = retransmit_count;
164             break;
165         case MESH_PDU_TYPE_SEGMENTED:
166             ((mesh_segmented_pdu_t *)pdu)->retransmit_count = retransmit_count;
167             break;
168         default:
169             btstack_assert(0);
170             break;
171     }
172 }
173 
174 static uint32_t mesh_access_message_retransmit_timeout_ms(mesh_pdu_t * pdu){
175     switch (pdu->pdu_type){
176         case MESH_PDU_TYPE_TRANSPORT:
177             return ((mesh_transport_pdu_t *)pdu)->retransmit_timeout_ms;
178         case MESH_PDU_TYPE_SEGMENTED:
179             return ((mesh_segmented_pdu_t *)pdu)->retransmit_timeout_ms;
180         default:
181             btstack_assert(0);
182             return 0;
183     }
184 }
185 
186 static void mesh_access_message_set_retransmit_timeout_ms(mesh_pdu_t * pdu, uint32_t retransmit_timeout_ms){
187     switch (pdu->pdu_type){
188         case MESH_PDU_TYPE_TRANSPORT:
189             ((mesh_transport_pdu_t *)pdu)->retransmit_timeout_ms = retransmit_timeout_ms;
190             break;
191         case MESH_PDU_TYPE_SEGMENTED:
192             ((mesh_segmented_pdu_t *)pdu)->retransmit_timeout_ms = retransmit_timeout_ms;
193             break;
194         default:
195             btstack_assert(0);
196             break;
197     }
198 }
199 
200 void mesh_access_send_unacknowledged_pdu(mesh_pdu_t * pdu){
201     mesh_access_message_set_ack_opcode(pdu, MESH_ACCESS_OPCODE_INVALID);
202     mesh_upper_transport_send_access_pdu(pdu);
203 }
204 
205 void mesh_access_send_acknowledged_pdu(mesh_pdu_t * pdu, uint8_t retransmissions, uint32_t ack_opcode){
206     mesh_access_message_set_retransmit_count(pdu, retransmissions);
207     mesh_access_message_set_ack_opcode(pdu, ack_opcode);
208 
209     mesh_upper_transport_send_access_pdu(pdu);
210 }
211 
212 #define MESH_SUBEVENT_MESSAGE_NOT_ACKNOWLEDGED                                        0x30
213 
214 static void mesh_access_acknowledged_run(btstack_timer_source_t * ts){
215     UNUSED(ts);
216 
217     uint32_t now = btstack_run_loop_get_time_ms();
218 
219     // handle timeouts
220     btstack_linked_list_iterator_t ack_it;
221     btstack_linked_list_iterator_init(&ack_it, &mesh_access_acknowledged_messages);
222     while (btstack_linked_list_iterator_has_next(&ack_it)){
223         mesh_pdu_t * pdu = (mesh_pdu_t *) btstack_linked_list_iterator_next(&ack_it);
224         uint32_t retransmit_timeout_ms = mesh_access_message_retransmit_timeout_ms(pdu);
225         if (btstack_time_delta(now, retransmit_timeout_ms) >= 0) {
226             // remove from list
227             btstack_linked_list_remove(&mesh_access_acknowledged_messages, (btstack_linked_item_t*) pdu);
228             // retransmit or report failure
229             uint8_t retransmit_count = mesh_access_message_retransmit_count(pdu);
230             if (retransmit_count){
231                 mesh_access_message_set_retransmit_count(pdu, retransmit_count - 1);
232                 mesh_upper_transport_send_access_pdu(pdu);
233             } else {
234                 // find correct model and emit error
235                 uint16_t src = mesh_pdu_src(pdu);
236                 uint16_t dst = mesh_pdu_dst(pdu);
237                 mesh_element_t * element = mesh_node_element_for_unicast_address(src);
238                 if (element){
239                     // find
240                     mesh_model_iterator_t model_it;
241                     mesh_model_iterator_init(&model_it, element);
242                     while (mesh_model_iterator_has_next(&model_it)){
243                         mesh_model_t * model = mesh_model_iterator_next(&model_it);
244                         // find opcode in table
245                         uint32_t ack_opcode = mesh_access_message_ack_opcode(pdu);
246                         const mesh_operation_t * operation = mesh_model_lookup_operation_by_opcode(model, ack_opcode);
247                         if (operation == NULL) continue;
248                         if (model->model_packet_handler == NULL) continue;
249                         // emit event
250                         uint8_t event[13];
251                         event[0] = HCI_EVENT_MESH_META;
252                         event[1] = sizeof(event) - 2;
253                         event[2] = element->element_index;
254                         little_endian_store_32(event, 3, model->model_identifier);
255                         little_endian_store_32(event, 7, ack_opcode);
256                         little_endian_store_16(event, 11, dst);
257                         (*model->model_packet_handler)(HCI_EVENT_PACKET, 0, event, sizeof(event));
258                     }
259                 }
260 
261                 // free
262                 mesh_upper_transport_pdu_free(pdu);
263             }
264         }
265     }
266 
267     if (mesh_access_acknowledged_timer_active) return;
268 
269     // find earliest timeout and set timer
270     btstack_linked_list_iterator_init(&ack_it, &mesh_access_acknowledged_messages);
271     int32_t next_timeout_ms = 0;
272     while (btstack_linked_list_iterator_has_next(&ack_it)){
273         mesh_pdu_t * pdu = (mesh_pdu_t *) btstack_linked_list_iterator_next(&ack_it);
274         uint32_t retransmit_timeout_ms = mesh_access_message_retransmit_timeout_ms(pdu);
275         int32_t timeout_delta_ms = btstack_time_delta(retransmit_timeout_ms, now);
276         if (next_timeout_ms == 0 || timeout_delta_ms < next_timeout_ms){
277             next_timeout_ms = timeout_delta_ms;
278         }
279     }
280 
281     // set timer
282     if (next_timeout_ms == 0) return;
283 
284     btstack_run_loop_set_timer(&mesh_access_acknowledged_timer, next_timeout_ms);
285     btstack_run_loop_set_timer_handler(&mesh_access_acknowledged_timer, mesh_access_acknowledged_run);
286     btstack_run_loop_add_timer(&mesh_access_acknowledged_timer);
287     mesh_access_acknowledged_timer_active = 1;
288 }
289 
290 static void mesh_access_acknowledged_received(uint16_t rx_src, uint32_t opcode){
291     // check if received src matches our dest
292     // free acknowledged messages if we were waiting for this message
293 
294     btstack_linked_list_iterator_t ack_it;
295     btstack_linked_list_iterator_init(&ack_it, &mesh_access_acknowledged_messages);
296     while (btstack_linked_list_iterator_has_next(&ack_it)){
297         mesh_pdu_t * tx_pdu = (mesh_pdu_t *) btstack_linked_list_iterator_next(&ack_it);
298         uint16_t tx_dest = mesh_pdu_dst(tx_pdu);
299         if (tx_dest != rx_src) continue;
300         if (mesh_access_message_ack_opcode(tx_pdu) != opcode) continue;
301         // got expected response from dest, remove from outgoing messages
302         mesh_upper_transport_pdu_free(tx_pdu);
303         return;
304     }
305 }
306 
307 static void mesh_access_upper_transport_handler(mesh_transport_callback_type_t callback_type, mesh_transport_status_t status, mesh_pdu_t * pdu){
308     UNUSED(status);
309     switch (callback_type){
310         case MESH_TRANSPORT_PDU_RECEIVED:
311             mesh_access_message_process_handler(pdu);
312             break;
313         case MESH_TRANSPORT_PDU_SENT:
314             // unacknowledged -> free
315             if (mesh_access_message_ack_opcode(pdu) == MESH_ACCESS_OPCODE_INVALID){
316                 mesh_upper_transport_pdu_free(pdu);
317                 break;
318             }
319             // setup timeout
320             mesh_access_message_set_retransmit_timeout_ms(pdu, btstack_run_loop_get_time_ms() + mesh_access_acknowledged_message_timeout_ms());
321             // add to mesh_access_acknowledged_messages
322             btstack_linked_list_add(&mesh_access_acknowledged_messages, (btstack_linked_item_t *) pdu);
323             // update timer
324             mesh_access_acknowledged_run(NULL);
325             break;
326         default:
327             break;
328     }
329 }
330 
331 // Mesh Model Transitions
332 
333 uint32_t mesh_access_time_gdtt2ms(uint8_t time_gdtt){
334     uint8_t num_steps  = mesh_access_transitions_num_steps_from_gdtt(time_gdtt);
335     if (num_steps > 0x3E) return 0;
336 
337     return mesh_access_transitions_step_ms_from_gdtt(time_gdtt) * num_steps;
338 }
339 
340 uint8_t mesh_access_transitions_num_steps_from_gdtt(uint8_t time_gdtt){
341     return time_gdtt & 0x3fu;
342 }
343 
344 uint32_t mesh_access_transitions_step_ms_from_gdtt(uint8_t time_gdtt){
345     mesh_default_transition_step_resolution_t step_resolution = (mesh_default_transition_step_resolution_t) (time_gdtt >> 6);
346     switch (step_resolution){
347         case MESH_DEFAULT_TRANSITION_STEP_RESOLUTION_100ms:
348             return 100;
349         case MESH_DEFAULT_TRANSITION_STEP_RESOLUTION_1s:
350             return 1000;
351         case MESH_DEFAULT_TRANSITION_STEP_RESOLUTION_10s:
352             return 10000;
353         case MESH_DEFAULT_TRANSITION_STEP_RESOLUTION_10min:
354             return 600000;
355         default:
356             return 0;
357     }
358 }
359 
360 uint8_t mesh_access_transactions_get_next_transaction_id(void){
361     mesh_transaction_id_counter++;
362     if (mesh_transaction_id_counter == 0){
363         mesh_transaction_id_counter = 1;
364     }
365     return mesh_transaction_id_counter;
366 }
367 
368 static int mesh_access_transitions_transaction_is_expired(mesh_transition_t * transition){
369     return (btstack_run_loop_get_time_ms() - transition->transaction_timestamp_ms) > MEST_TRANSACTION_TIMEOUT_MS;
370 }
371 
372 mesh_transaction_status_t mesh_access_transitions_transaction_status(mesh_transition_t * transition, uint8_t transaction_identifier, uint16_t src_address, uint16_t dst_address){
373     if (transition->src_address != src_address || transition->dst_address != dst_address) return MESH_TRANSACTION_STATUS_DIFFERENT_DST_OR_SRC;
374 
375     if (transition->transaction_identifier == transaction_identifier && !mesh_access_transitions_transaction_is_expired(transition)){
376             return MESH_TRANSACTION_STATUS_RETRANSMISSION;
377     }
378     return MESH_TRANSACTION_STATUS_NEW;
379 }
380 
381 void mesh_access_transitions_init_transaction(mesh_transition_t * transition, uint8_t transaction_identifier, uint16_t src_address, uint16_t dst_address){
382     transition->transaction_timestamp_ms = btstack_run_loop_get_time_ms();
383     transition->transaction_identifier = transaction_identifier;
384     transition->src_address = src_address;
385     transition->dst_address = dst_address;
386 }
387 
388 static void mesh_server_transition_timeout(btstack_timer_source_t * ts){
389     mesh_transition_t * base_transition = (mesh_transition_t*) btstack_run_loop_get_timer_context(ts);
390     switch (base_transition->state){
391         case MESH_TRANSITION_STATE_DELAYED:
392             base_transition->state = MESH_TRANSITION_STATE_ACTIVE;
393             (*base_transition->transition_callback)(base_transition, MODEL_STATE_UPDATE_REASON_TRANSITION_START);
394             if (base_transition->num_steps > 0){
395                 btstack_run_loop_set_timer(&base_transition->timer, base_transition->step_duration_ms);
396                 btstack_run_loop_add_timer(&base_transition->timer);
397                 return;
398             }
399             base_transition->state = MESH_TRANSITION_STATE_IDLE;
400             (*base_transition->transition_callback)(base_transition, MODEL_STATE_UPDATE_REASON_TRANSITION_END);
401             break;
402         case MESH_TRANSITION_STATE_ACTIVE:
403             if (base_transition->num_steps < MESH_TRANSITION_NUM_STEPS_INFINITE){
404                 base_transition->num_steps--;
405             }
406             (*base_transition->transition_callback)(base_transition, MODEL_STATE_UPDATE_REASON_TRANSITION_ACTIVE);
407             if (base_transition->num_steps > 0){
408                 btstack_run_loop_set_timer(&base_transition->timer, base_transition->step_duration_ms);
409                 btstack_run_loop_add_timer(&base_transition->timer);
410                 return;
411             }
412             base_transition->state = MESH_TRANSITION_STATE_IDLE;
413             (*base_transition->transition_callback)(base_transition, MODEL_STATE_UPDATE_REASON_TRANSITION_END);
414             break;
415         default:
416             break;
417     }
418 }
419 
420 void mesh_access_transition_setup(mesh_model_t *mesh_model, mesh_transition_t * base_transition, uint8_t transition_time_gdtt, uint8_t delay_time_gdtt, void (*transition_callback)(mesh_transition_t * base_transition, model_state_update_reason_t event)){
421 
422     base_transition->mesh_model          = mesh_model;
423     base_transition->num_steps           = mesh_access_transitions_num_steps_from_gdtt(transition_time_gdtt);
424     base_transition->step_resolution     = (mesh_default_transition_step_resolution_t) (transition_time_gdtt >> 6);
425     base_transition->step_duration_ms    = mesh_access_transitions_step_ms_from_gdtt(transition_time_gdtt);
426     base_transition->transition_callback = transition_callback;
427 
428     btstack_run_loop_set_timer_context(&base_transition->timer, base_transition);
429     btstack_run_loop_set_timer_handler(&base_transition->timer, &mesh_server_transition_timeout);
430 
431     // delayed
432     if (delay_time_gdtt > 0){
433         base_transition->state = MESH_TRANSITION_STATE_DELAYED;
434         btstack_run_loop_set_timer(&base_transition->timer, delay_time_gdtt * 5);
435         btstack_run_loop_add_timer(&base_transition->timer);
436         return;
437     }
438 
439     // started
440     if (base_transition->num_steps > 0){
441         base_transition->state = MESH_TRANSITION_STATE_ACTIVE;
442         btstack_run_loop_set_timer(&base_transition->timer, base_transition->step_duration_ms);
443         btstack_run_loop_add_timer(&base_transition->timer);
444         return;
445     }
446 
447     // instanteneous update
448     base_transition->state = MESH_TRANSITION_STATE_IDLE;
449     (*transition_callback)(base_transition, MODEL_STATE_UPDATE_REASON_SET);
450     return;
451 }
452 
453 void mesh_access_transitions_abort_transaction(mesh_transition_t * base_transition){
454     btstack_run_loop_add_timer(&base_transition->timer);
455 }
456 
457 static uint16_t mesh_access_src(mesh_access_pdu_t * access_pdu){
458     return big_endian_read_16(access_pdu->network_header, 5);
459 }
460 
461 #if 0
462 static uint16_t mesh_access_dst(mesh_access_pdu_t * access_pdu){
463     return big_endian_read_16(access_pdu->network_header, 7);
464 }
465 #endif
466 
467 // Transport PDU Getter
468 uint16_t mesh_transport_nid(mesh_transport_pdu_t * transport_pdu){
469     return transport_pdu->network_header[0] & 0x7f;
470 }
471 uint16_t mesh_transport_ctl(mesh_transport_pdu_t * transport_pdu){
472     return transport_pdu->network_header[1] >> 7;
473 }
474 uint16_t mesh_transport_ttl(mesh_transport_pdu_t * transport_pdu){
475     return transport_pdu->network_header[1] & 0x7f;
476 }
477 uint32_t mesh_transport_seq(mesh_transport_pdu_t * transport_pdu){
478     return big_endian_read_24(transport_pdu->network_header, 2);
479 }
480 uint16_t mesh_transport_src(mesh_transport_pdu_t * transport_pdu){
481     return big_endian_read_16(transport_pdu->network_header, 5);
482 }
483 uint16_t mesh_transport_dst(mesh_transport_pdu_t * transport_pdu){
484     return big_endian_read_16(transport_pdu->network_header, 7);
485 }
486 uint8_t  mesh_transport_control_opcode(mesh_transport_pdu_t * transport_pdu){
487     return transport_pdu->akf_aid_control & 0x7f;
488 }
489 void mesh_transport_set_nid_ivi(mesh_transport_pdu_t * transport_pdu, uint8_t nid_ivi){
490     transport_pdu->network_header[0] = nid_ivi;
491 }
492 void mesh_transport_set_ctl_ttl(mesh_transport_pdu_t * transport_pdu, uint8_t ctl_ttl){
493     transport_pdu->network_header[1] = ctl_ttl;
494 }
495 void mesh_transport_set_seq(mesh_transport_pdu_t * transport_pdu, uint32_t seq){
496     big_endian_store_24(transport_pdu->network_header, 2, seq);
497 }
498 void mesh_transport_set_src(mesh_transport_pdu_t * transport_pdu, uint16_t src){
499     big_endian_store_16(transport_pdu->network_header, 5, src);
500 }
501 void mesh_transport_set_dest(mesh_transport_pdu_t * transport_pdu, uint16_t dest){
502     big_endian_store_16(transport_pdu->network_header, 7, dest);
503 }
504 
505 uint16_t mesh_pdu_ctl(mesh_pdu_t * pdu){
506     switch (pdu->pdu_type){
507         case MESH_PDU_TYPE_TRANSPORT:
508             return mesh_transport_ctl((mesh_transport_pdu_t*) pdu);
509         case MESH_PDU_TYPE_NETWORK:
510             return mesh_network_control((mesh_network_pdu_t *) pdu);
511         default:
512             btstack_assert(false);
513             return 0;
514     }
515 }
516 
517 uint16_t mesh_pdu_ttl(mesh_pdu_t * pdu){
518     switch (pdu->pdu_type){
519         case MESH_PDU_TYPE_TRANSPORT:
520             return mesh_transport_ttl((mesh_transport_pdu_t*) pdu);
521         case MESH_PDU_TYPE_NETWORK:
522             return mesh_network_ttl((mesh_network_pdu_t *) pdu);
523         default:
524             btstack_assert(false);
525             return 0;
526     }
527 }
528 
529 uint16_t mesh_pdu_src(mesh_pdu_t * pdu){
530     switch (pdu->pdu_type){
531         case MESH_PDU_TYPE_ACCESS:
532             return mesh_access_src((mesh_access_pdu_t *) pdu);
533         case MESH_PDU_TYPE_TRANSPORT:
534             return mesh_transport_src((mesh_transport_pdu_t*) pdu);
535         case MESH_PDU_TYPE_NETWORK:
536             return mesh_network_src((mesh_network_pdu_t *) pdu);
537         default:
538             btstack_assert(false);
539             return MESH_ADDRESS_UNSASSIGNED;
540     }
541 }
542 
543 uint16_t mesh_pdu_dst(mesh_pdu_t * pdu){
544     switch (pdu->pdu_type){
545         case MESH_PDU_TYPE_ACCESS:
546             return mesh_access_dst((mesh_access_pdu_t *) pdu);
547         case MESH_PDU_TYPE_TRANSPORT:
548             return mesh_transport_dst((mesh_transport_pdu_t*) pdu);
549         case MESH_PDU_TYPE_NETWORK:
550             return mesh_network_dst((mesh_network_pdu_t *) pdu);
551         default:
552             btstack_assert(false);
553             return MESH_ADDRESS_UNSASSIGNED;
554     }
555 }
556 
557 uint16_t mesh_pdu_netkey_index(mesh_pdu_t * pdu){
558     switch (pdu->pdu_type){
559         case MESH_PDU_TYPE_ACCESS:
560             return ((mesh_access_pdu_t*) pdu)->netkey_index;
561         case MESH_PDU_TYPE_TRANSPORT:
562             return ((mesh_transport_pdu_t*) pdu)->netkey_index;
563         case MESH_PDU_TYPE_NETWORK:
564             return ((mesh_network_pdu_t *) pdu)->netkey_index;
565         default:
566             btstack_assert(false);
567             return 0;
568     }
569 }
570 
571 uint16_t mesh_pdu_appkey_index(mesh_pdu_t * pdu){
572     switch (pdu->pdu_type){
573         case MESH_PDU_TYPE_ACCESS:
574             return ((mesh_access_pdu_t*) pdu)->appkey_index;
575         case MESH_PDU_TYPE_TRANSPORT:
576             return ((mesh_transport_pdu_t*) pdu)->appkey_index;
577         default:
578             btstack_assert(false);
579             return 0;
580     }
581 }
582 
583 uint16_t mesh_pdu_len(mesh_pdu_t * pdu){
584     switch (pdu->pdu_type){
585         case MESH_PDU_TYPE_ACCESS:
586             return ((mesh_access_pdu_t*) pdu)->len;
587         case MESH_PDU_TYPE_TRANSPORT:
588             return ((mesh_transport_pdu_t*) pdu)->len;
589         case MESH_PDU_TYPE_NETWORK:
590             return ((mesh_network_pdu_t *) pdu)->len - 10;
591         default:
592             btstack_assert(false);
593             return 0;
594     }
595 }
596 
597 uint8_t * mesh_pdu_data(mesh_pdu_t * pdu){
598     switch (pdu->pdu_type){
599         case MESH_PDU_TYPE_ACCESS:
600             return ((mesh_access_pdu_t*) pdu)->data;
601         case MESH_PDU_TYPE_TRANSPORT:
602             return ((mesh_transport_pdu_t*) pdu)->data;
603         case MESH_PDU_TYPE_NETWORK:
604             return &((mesh_network_pdu_t *) pdu)->data[10];
605         default:
606             btstack_assert(false);
607             return NULL;
608     }
609 }
610 
611 uint8_t mesh_pdu_control_opcode(mesh_pdu_t * pdu){
612     switch (pdu->pdu_type){
613         case MESH_PDU_TYPE_TRANSPORT:
614             return mesh_transport_control_opcode((mesh_transport_pdu_t*) pdu);
615         case MESH_PDU_TYPE_NETWORK:
616             return mesh_network_control_opcode((mesh_network_pdu_t *) pdu);
617         default:
618             btstack_assert(false);
619             return 0xff;
620     }
621 }
622 
623 // message parser
624 
625 static int mesh_access_get_opcode(uint8_t * buffer, uint16_t buffer_size, uint32_t * opcode, uint16_t * opcode_size){
626     switch (buffer[0] >> 6){
627         case 0:
628         case 1:
629             if (buffer[0] == 0x7f) return 0;
630             *opcode = buffer[0];
631             *opcode_size = 1;
632             return 1;
633         case 2:
634             if (buffer_size < 2) return 0;
635             *opcode = big_endian_read_16(buffer, 0);
636             *opcode_size = 2;
637             return 1;
638         case 3:
639             if (buffer_size < 3) return 0;
640             *opcode = (buffer[0] << 16) | little_endian_read_16(buffer, 1);
641             *opcode_size = 3;
642             return 1;
643         default:
644             return 0;
645     }
646 }
647 
648 int mesh_access_pdu_get_opcode(mesh_pdu_t * pdu, uint32_t * opcode, uint16_t * opcode_size){
649     btstack_assert(pdu->pdu_type == MESH_PDU_TYPE_ACCESS);
650     return mesh_access_get_opcode(((mesh_access_pdu_t *) pdu)->data, ((mesh_access_pdu_t *) pdu)->len, opcode,
651                                   opcode_size);
652 }
653 
654 void mesh_access_parser_skip(mesh_access_parser_state_t * state, uint16_t bytes_to_skip){
655     state->data += bytes_to_skip;
656     state->len  -= bytes_to_skip;
657 }
658 
659 int mesh_access_parser_init(mesh_access_parser_state_t * state, mesh_pdu_t * pdu){
660     btstack_assert(pdu->pdu_type == MESH_PDU_TYPE_ACCESS);
661     state->data = mesh_pdu_data(pdu);
662     state->len  = mesh_pdu_len(pdu);
663 
664     uint16_t opcode_size = 0;
665     int ok = mesh_access_get_opcode(state->data, state->len, &state->opcode, &opcode_size);
666     if (ok){
667         mesh_access_parser_skip(state, opcode_size);
668     }
669     return ok;
670 }
671 
672 uint16_t mesh_access_parser_available(mesh_access_parser_state_t * state){
673     return state->len;
674 }
675 
676 uint8_t mesh_access_parser_get_u8(mesh_access_parser_state_t * state){
677     uint8_t value = *state->data;
678     mesh_access_parser_skip(state, 1);
679     return value;
680 }
681 
682 uint16_t mesh_access_parser_get_u16(mesh_access_parser_state_t * state){
683     uint16_t value = little_endian_read_16(state->data, 0);
684     mesh_access_parser_skip(state, 2);
685     return value;
686 }
687 
688 uint32_t mesh_access_parser_get_u24(mesh_access_parser_state_t * state){
689     uint32_t value = little_endian_read_24(state->data, 0);
690     mesh_access_parser_skip(state, 3);
691     return value;
692 }
693 
694 uint32_t mesh_access_parser_get_u32(mesh_access_parser_state_t * state){
695     uint32_t value = little_endian_read_32(state->data, 0);
696     mesh_access_parser_skip(state, 4);
697     return value;
698 }
699 
700 void mesh_access_parser_get_u128(mesh_access_parser_state_t * state, uint8_t * dest){
701     reverse_128( state->data, dest);
702     mesh_access_parser_skip(state, 16);
703 }
704 
705 void mesh_access_parser_get_label_uuid(mesh_access_parser_state_t * state, uint8_t * dest){
706     (void)memcpy(dest, state->data, 16);
707     mesh_access_parser_skip(state, 16);
708 }
709 
710 void mesh_access_parser_get_key(mesh_access_parser_state_t * state, uint8_t * dest){
711     (void)memcpy(dest, state->data, 16);
712     mesh_access_parser_skip(state, 16);
713 }
714 
715 uint32_t mesh_access_parser_get_model_identifier(mesh_access_parser_state_t * parser){
716     uint16_t vendor_id = BLUETOOTH_COMPANY_ID_BLUETOOTH_SIG_INC;
717     if (mesh_access_parser_available(parser) == 4){
718         vendor_id = mesh_access_parser_get_u16(parser);
719     }
720     uint16_t model_id = mesh_access_parser_get_u16(parser);
721     return mesh_model_get_model_identifier(vendor_id, model_id);
722 }
723 
724 uint32_t mesh_access_parser_get_sig_model_identifier(mesh_access_parser_state_t * parser){
725     uint16_t model_id = mesh_access_parser_get_u16(parser);
726     return mesh_model_get_model_identifier(BLUETOOTH_COMPANY_ID_BLUETOOTH_SIG_INC, model_id);
727 }
728 
729 uint32_t mesh_access_parser_get_vendor_model_identifier(mesh_access_parser_state_t * parser){
730     uint16_t vendor_id = mesh_access_parser_get_u16(parser);
731     uint16_t model_id  = mesh_access_parser_get_u16(parser);
732     return mesh_model_get_model_identifier(vendor_id, model_id);
733 }
734 
735 // Mesh Access Message Builder
736 
737 // message builder
738 
739 static int mesh_access_setup_opcode(uint8_t * buffer, uint32_t opcode){
740     if (opcode < 0x100){
741         buffer[0] = opcode;
742         return 1;
743     }
744     if (opcode < 0x10000){
745         big_endian_store_16(buffer, 0, opcode);
746         return 2;
747     }
748     buffer[0] = opcode >> 16;
749     little_endian_store_16(buffer, 1, opcode & 0xffff);
750     return 3;
751 }
752 
753 mesh_transport_pdu_t * mesh_access_transport_init(uint32_t opcode){
754     mesh_transport_pdu_t * pdu = mesh_transport_pdu_get();
755     if (!pdu) return NULL;
756 
757     pdu->len  = mesh_access_setup_opcode(pdu->data, opcode);
758     pdu->ack_opcode = MESH_ACCESS_OPCODE_NOT_SET;
759     return pdu;
760 }
761 
762 void mesh_access_transport_add_uint8(mesh_transport_pdu_t * pdu, uint8_t value){
763     pdu->data[pdu->len++] = value;
764 }
765 
766 void mesh_access_transport_add_uint16(mesh_transport_pdu_t * pdu, uint16_t value){
767     little_endian_store_16(pdu->data, pdu->len, value);
768     pdu->len += 2;
769 }
770 
771 void mesh_access_transport_add_uint24(mesh_transport_pdu_t * pdu, uint32_t value){
772     little_endian_store_24(pdu->data, pdu->len, value);
773     pdu->len += 3;
774 }
775 
776 void mesh_access_transport_add_uint32(mesh_transport_pdu_t * pdu, uint32_t value){
777     little_endian_store_32(pdu->data, pdu->len, value);
778     pdu->len += 4;
779 }
780 
781 void mesh_access_transport_add_label_uuid(mesh_transport_pdu_t * pdu, uint8_t * value){
782     (void)memcpy(value, pdu->data, 16);
783     pdu->len += 16;
784 }
785 
786 void mesh_access_transport_add_model_identifier(mesh_transport_pdu_t * pdu, uint32_t model_identifier){
787     if (!mesh_model_is_bluetooth_sig(model_identifier)){
788         mesh_access_transport_add_uint16( pdu, mesh_model_get_vendor_id(model_identifier) );
789     }
790     mesh_access_transport_add_uint16( pdu, mesh_model_get_model_id(model_identifier) );
791 }
792 
793 // mesh_message_t builder
794 mesh_segmented_pdu_t * mesh_access_message_init(uint32_t opcode, bool segmented, uint8_t num_segments){
795     btstack_assert(num_segments > 0);
796     btstack_assert(segmented || (num_segments == 1));
797 
798     mesh_segmented_pdu_t * pdu = mesh_message_pdu_get();
799     if (!pdu) return NULL;
800 
801     // TODO: handle segmented messages
802     btstack_assert(segmented == false);
803 
804     // use mesh_network_t as before
805     mesh_network_pdu_t * segment = mesh_network_pdu_get();
806     if (segment == NULL){
807         mesh_message_pdu_free(pdu);
808         return NULL;
809     }
810     btstack_linked_list_add(&pdu->segments, (btstack_linked_item_t *) segment);
811 
812     pdu->len = mesh_access_setup_opcode(&segment->data[10], opcode) + 10;
813     pdu->ack_opcode = MESH_ACCESS_OPCODE_NOT_SET;
814     return pdu;
815 }
816 
817 void mesh_access_message_add_uint8(mesh_segmented_pdu_t * pdu, uint8_t value){
818     // TODO: handle segmented messages
819     mesh_network_pdu_t * segment = (mesh_network_pdu_t *) btstack_linked_list_get_first_item(&pdu->segments);
820     segment->data[pdu->len++] = value;
821 }
822 
823 void mesh_access_message_add_uint16(mesh_segmented_pdu_t * pdu, uint16_t value){
824     // TODO: handle segmented messages
825     mesh_network_pdu_t * segment = (mesh_network_pdu_t *) btstack_linked_list_get_first_item(&pdu->segments);
826     little_endian_store_16(segment->data, pdu->len, value);
827     pdu->len += 2;
828 }
829 
830 void mesh_access_message_add_uint24(mesh_segmented_pdu_t * pdu, uint16_t value){
831     // TODO: handle segmented messages
832     mesh_network_pdu_t * segment = (mesh_network_pdu_t *) btstack_linked_list_get_first_item(&pdu->segments);
833     little_endian_store_24(segment->data, pdu->len, value);
834     pdu->len += 3;
835 }
836 
837 void mesh_access_message_add_uint32(mesh_segmented_pdu_t * pdu, uint16_t value){
838     // TODO: handle segmented messages
839     mesh_network_pdu_t * segment = (mesh_network_pdu_t *) btstack_linked_list_get_first_item(&pdu->segments);
840     little_endian_store_32(segment->data, pdu->len, value);
841     pdu->len += 4;
842 }
843 
844 void mesh_access_message_add_model_identifier(mesh_segmented_pdu_t * pdu, uint32_t model_identifier){
845     if (mesh_model_is_bluetooth_sig(model_identifier)){
846         mesh_access_message_add_uint16( pdu, mesh_model_get_model_id(model_identifier) );
847     } else {
848         mesh_access_message_add_uint32( pdu, model_identifier );
849     }
850 }
851 
852 // access message template
853 mesh_segmented_pdu_t * mesh_access_setup_message(bool segmented, const mesh_access_message_t *message_template, ...){
854     btstack_assert(segmented == false);
855 
856     // TODO: handle segmented messages
857     mesh_segmented_pdu_t * message_pdu = mesh_access_message_init(message_template->opcode, segmented, 1);
858     if (!message_pdu) return NULL;
859 
860     va_list argptr;
861     va_start(argptr, message_template);
862 
863     // add params
864     const char * format = message_template->format;
865     uint16_t word;
866     uint32_t longword;
867     while (*format){
868         switch (*format){
869             case '1':
870                 word = va_arg(argptr, int);  // minimal va_arg is int: 2 bytes on 8+16 bit CPUs
871                 mesh_access_message_add_uint8( message_pdu, word);
872                 break;
873             case '2':
874                 word = va_arg(argptr, int);  // minimal va_arg is int: 2 bytes on 8+16 bit CPUs
875                 mesh_access_message_add_uint16( message_pdu, word);
876                 break;
877             case '3':
878                 longword = va_arg(argptr, uint32_t);
879                 mesh_access_message_add_uint24( message_pdu, longword);
880                 break;
881             case '4':
882                 longword = va_arg(argptr, uint32_t);
883                 mesh_access_message_add_uint32( message_pdu, longword);
884                 mesh_access_message_add_uint32( message_pdu, longword);
885                 break;
886             case 'm':
887                 longword = va_arg(argptr, uint32_t);
888                 mesh_access_message_add_model_identifier( message_pdu, longword);
889                 break;
890             default:
891                 log_error("Unsupported mesh message format specifier '%c", *format);
892                 break;
893         }
894         format++;
895     }
896 
897     va_end(argptr);
898 
899     return message_pdu;
900 }
901 
902 mesh_transport_pdu_t * mesh_access_setup_segmented_message(const mesh_access_message_t *message_template, ...){
903     mesh_transport_pdu_t * transport_pdu = mesh_access_transport_init(message_template->opcode);
904     if (!transport_pdu) return NULL;
905 
906     va_list argptr;
907     va_start(argptr, message_template);
908 
909     // add params
910     const char * format = message_template->format;
911     uint16_t word;
912     uint32_t longword;
913     uint8_t * ptr;
914     while (*format){
915         switch (*format++){
916             case '1':
917                 word = va_arg(argptr, int);  // minimal va_arg is int: 2 bytes on 8+16 bit CPUs
918                 mesh_access_transport_add_uint8( transport_pdu, word);
919                 break;
920             case '2':
921                 word = va_arg(argptr, int);  // minimal va_arg is int: 2 bytes on 8+16 bit CPUs
922                 mesh_access_transport_add_uint16( transport_pdu, word);
923                 break;
924             case '3':
925                 longword = va_arg(argptr, uint32_t);
926                 mesh_access_transport_add_uint24( transport_pdu, longword);
927                 break;
928             case '4':
929                 longword = va_arg(argptr, uint32_t);
930                 mesh_access_transport_add_uint32( transport_pdu, longword);
931                 break;
932             case 'P': // 16 byte, eg LabelUUID, in network endianess
933                 ptr = va_arg(argptr, uint8_t *);
934                 mesh_access_transport_add_label_uuid( transport_pdu, ptr);
935                 break;
936             case 'm':
937                 longword = va_arg(argptr, uint32_t);
938                 mesh_access_transport_add_model_identifier( transport_pdu, longword);
939                 break;
940             default:
941                 break;
942         }
943     }
944 
945     va_end(argptr);
946 
947     return transport_pdu;
948 }
949 
950 
951 static const mesh_operation_t * mesh_model_lookup_operation_by_opcode(mesh_model_t * model, uint32_t opcode){
952     // find opcode in table
953     const mesh_operation_t * operation = model->operations;
954     if (operation == NULL) return NULL;
955     for ( ; operation->handler != NULL ; operation++){
956         if (operation->opcode != opcode) continue;
957         return operation;
958     }
959     return NULL;
960 }
961 
962 static const mesh_operation_t * mesh_model_lookup_operation(mesh_model_t * model, mesh_pdu_t * pdu){
963 
964     uint32_t opcode = 0;
965     uint16_t opcode_size = 0;
966     int ok = mesh_access_pdu_get_opcode( pdu, &opcode, &opcode_size);
967     if (!ok) return NULL;
968 
969     uint16_t len = mesh_pdu_len(pdu);
970 
971     // find opcode in table
972     const mesh_operation_t * operation = model->operations;
973     if (operation == NULL) return NULL;
974     for ( ; operation->handler != NULL ; operation++){
975         if (operation->opcode != opcode) continue;
976         if ((opcode_size + operation->minimum_length) > len) continue;
977         return operation;
978     }
979     return NULL;
980 }
981 
982 static int mesh_access_validate_appkey_index(mesh_model_t * model, uint16_t appkey_index){
983     // DeviceKey is valid for all models
984     if (appkey_index == MESH_DEVICE_KEY_INDEX) return 1;
985     // check if AppKey that is bound to this particular model
986     return mesh_model_contains_appkey(model, appkey_index);
987 }
988 
989 // decrease use count and report as free if done
990 void mesh_access_message_processed(mesh_pdu_t * pdu){
991     if (mesh_access_received_pdu_refcount > 0){
992         mesh_access_received_pdu_refcount--;
993     }
994     if (mesh_access_received_pdu_refcount == 0){
995         mesh_upper_transport_message_processed_by_higher_layer(pdu);
996     }
997 }
998 
999 static void mesh_access_message_process_handler(mesh_pdu_t * pdu){
1000 
1001     // init use count
1002     mesh_access_received_pdu_refcount = 1;
1003 
1004     // get opcode and size
1005     uint32_t opcode = 0;
1006     uint16_t opcode_size = 0;
1007 
1008     int ok = mesh_access_pdu_get_opcode( pdu, &opcode, &opcode_size);
1009     if (!ok) {
1010         mesh_access_message_processed(pdu);
1011         return;
1012     }
1013 
1014     uint16_t len = mesh_pdu_len(pdu);
1015     printf("MESH Access Message, Opcode = %x: ", opcode);
1016     printf_hexdump(mesh_pdu_data(pdu), len);
1017 
1018     uint16_t src = mesh_pdu_src(pdu);
1019     uint16_t dst = mesh_pdu_dst(pdu);
1020     uint16_t appkey_index = mesh_pdu_appkey_index(pdu);
1021     if (mesh_network_address_unicast(dst)){
1022         // loookup element by unicast address
1023         mesh_element_t * element = mesh_node_element_for_unicast_address(dst);
1024         if (element != NULL){
1025             // iterate over models, look for operation
1026             mesh_model_iterator_t model_it;
1027             mesh_model_iterator_init(&model_it, element);
1028             while (mesh_model_iterator_has_next(&model_it)){
1029                 mesh_model_t * model = mesh_model_iterator_next(&model_it);
1030                 // find opcode in table
1031                 const mesh_operation_t * operation = mesh_model_lookup_operation(model, pdu);
1032                 if (operation == NULL) continue;
1033                 if (mesh_access_validate_appkey_index(model, appkey_index) == 0) continue;
1034                 mesh_access_acknowledged_received(src, opcode);
1035                 mesh_access_received_pdu_refcount++;
1036                 operation->handler(model, pdu);
1037             }
1038         }
1039     }
1040     else if (mesh_network_address_group(dst)){
1041 
1042         // handle fixed group address
1043         if (dst >= 0xff00){
1044             int deliver_to_primary_element = 1;
1045             switch (dst){
1046                 case MESH_ADDRESS_ALL_PROXIES:
1047                     if (mesh_foundation_gatt_proxy_get() == 1){
1048                         deliver_to_primary_element = 1;
1049                     }
1050                     break;
1051                 case MESH_ADDRESS_ALL_FRIENDS:
1052                     // TODO: not implemented
1053                     break;
1054                 case MESH_ADDRESS_ALL_RELAYS:
1055                     if (mesh_foundation_relay_get() == 1){
1056                         deliver_to_primary_element = 1;
1057                     }
1058                     break;
1059                 case MESH_ADDRESS_ALL_NODES:
1060                     deliver_to_primary_element = 1;
1061                     break;
1062                 default:
1063                     break;
1064             }
1065             if (deliver_to_primary_element){
1066                 mesh_model_iterator_t model_it;
1067                 mesh_model_iterator_init(&model_it, mesh_node_get_primary_element());
1068                 while (mesh_model_iterator_has_next(&model_it)){
1069                     mesh_model_t * model = mesh_model_iterator_next(&model_it);
1070                     // find opcode in table
1071                     const mesh_operation_t * operation = mesh_model_lookup_operation(model, pdu);
1072                     if (operation == NULL) continue;
1073                     if (mesh_access_validate_appkey_index(model, appkey_index) == 0) continue;
1074                     mesh_access_acknowledged_received(src, opcode);
1075                     mesh_access_received_pdu_refcount++;
1076                     operation->handler(model, pdu);
1077                 }
1078             }
1079         }
1080         else {
1081             // iterate over all elements / models, check subscription list
1082             mesh_element_iterator_t it;
1083             mesh_element_iterator_init(&it);
1084             while (mesh_element_iterator_has_next(&it)){
1085                 mesh_element_t * element = (mesh_element_t *) mesh_element_iterator_next(&it);
1086                 mesh_model_iterator_t model_it;
1087                 mesh_model_iterator_init(&model_it, element);
1088                 while (mesh_model_iterator_has_next(&model_it)){
1089                     mesh_model_t * model = mesh_model_iterator_next(&model_it);
1090                     if (mesh_model_contains_subscription(model, dst)){
1091                         // find opcode in table
1092                         const mesh_operation_t * operation = mesh_model_lookup_operation(model, pdu);
1093                         if (operation == NULL) continue;
1094                         if (mesh_access_validate_appkey_index(model, appkey_index) == 0) continue;
1095                         mesh_access_acknowledged_received(src, opcode);
1096                         mesh_access_received_pdu_refcount++;
1097                         operation->handler(model, pdu);
1098                     }
1099                 }
1100             }
1101         }
1102     }
1103 
1104     // we're done
1105     mesh_access_message_processed(pdu);
1106 }
1107 
1108 // Mesh Model Publication
1109 static btstack_timer_source_t mesh_access_publication_timer;
1110 
1111 static uint32_t mesh_model_publication_retransmit_count(uint8_t retransmit){
1112     return retransmit & 0x07u;
1113 }
1114 
1115 static uint32_t mesh_model_publication_retransmission_period_ms(uint8_t retransmit){
1116     return ((uint32_t)((retransmit >> 3) + 1)) * 50;
1117 }
1118 
1119 static void mesh_model_publication_setup_publication(mesh_publication_model_t * publication_model, uint32_t now){
1120 
1121     // set retransmit counter
1122     publication_model->retransmit_count = mesh_model_publication_retransmit_count(publication_model->retransmit);
1123 
1124     // schedule next publication or retransmission
1125     uint32_t publication_period_ms = mesh_access_time_gdtt2ms(publication_model->period) >> publication_model->period_divisor;
1126 
1127     // set next publication
1128     if (publication_period_ms != 0){
1129         publication_model->next_publication_ms = now + publication_period_ms;
1130         publication_model->state = MESH_MODEL_PUBLICATION_STATE_W4_PUBLICATION_MS;
1131     } else {
1132         publication_model->state = MESH_MODEL_PUBLICATION_STATE_IDLE;
1133     }
1134 }
1135 
1136 // assumes retransmit_count is valid
1137 static void mesh_model_publication_setup_retransmission(mesh_publication_model_t * publication_model, uint32_t now){
1138     uint32_t publication_period_ms = mesh_access_time_gdtt2ms(publication_model->period) >> publication_model->period_divisor;
1139 
1140     // retransmission done
1141     if (publication_model->retransmit_count == 0) {
1142         // wait for next main event if periodic and retransmission complete
1143         if (publication_period_ms != 0){
1144             publication_model->state = MESH_MODEL_PUBLICATION_STATE_W4_PUBLICATION_MS;
1145         } else {
1146             publication_model->state = MESH_MODEL_PUBLICATION_STATE_IDLE;
1147         }
1148         return;
1149     }
1150 
1151     // calc next retransmit time
1152     uint32_t retransmission_period_ms = mesh_model_publication_retransmission_period_ms(publication_model->retransmit) >> publication_model->period_divisor;
1153     uint32_t retransmission_ms = now + retransmission_period_ms;
1154 
1155     // check next publication timeout is before next retransmission
1156     if (publication_period_ms != 0){
1157         if (btstack_time_delta(retransmission_ms, publication_model->next_publication_ms) > 0) return;
1158     }
1159 
1160     // schedule next retransmission
1161     publication_model->next_retransmit_ms = retransmission_ms;
1162     publication_model->state = MESH_MODEL_PUBLICATION_STATE_W4_RETRANSMIT_MS;
1163 }
1164 
1165 static void mesh_model_publication_publish_now_model(mesh_model_t * mesh_model){
1166     mesh_publication_model_t * publication_model = mesh_model->publication_model;
1167     if (publication_model == NULL) return;
1168     if (publication_model->publish_state_fn == NULL) return;
1169     uint16_t dest = publication_model->address;
1170     if (dest == MESH_ADDRESS_UNSASSIGNED) return;
1171     uint16_t appkey_index = publication_model->appkey_index;
1172     mesh_transport_key_t * app_key = mesh_transport_key_get(appkey_index);
1173     if (app_key == NULL) return;
1174 
1175     // compose message
1176     mesh_pdu_t * pdu = (*publication_model->publish_state_fn)(mesh_model);
1177     if (pdu == NULL) return;
1178 
1179     // handle ttl = default
1180     uint8_t ttl = publication_model->ttl;
1181     if (ttl == 0xff){
1182         ttl = mesh_foundation_default_ttl_get();
1183     }
1184 
1185     mesh_upper_transport_setup_access_pdu_header(pdu, app_key->netkey_index, appkey_index, ttl, mesh_access_get_element_address(mesh_model), dest, 0);
1186     mesh_access_send_unacknowledged_pdu(pdu);
1187 }
1188 
1189 static void mesh_model_publication_run(btstack_timer_source_t * ts){
1190 
1191     uint32_t now = btstack_run_loop_get_time_ms();
1192 
1193     // iterate over elements and models and handle time-based transitions
1194     mesh_element_iterator_t element_it;
1195     mesh_element_iterator_init(&element_it);
1196     while (mesh_element_iterator_has_next(&element_it)){
1197         mesh_element_t * element = mesh_element_iterator_next(&element_it);
1198         mesh_model_iterator_t model_it;
1199         mesh_model_iterator_init(&model_it, element);
1200         while (mesh_model_iterator_has_next(&model_it)){
1201             mesh_model_t * mesh_model = mesh_model_iterator_next(&model_it);
1202             mesh_publication_model_t * publication_model = mesh_model->publication_model;
1203             if (publication_model == NULL) continue;
1204 
1205             // check if either timer fired
1206             switch (publication_model->state){
1207                 case MESH_MODEL_PUBLICATION_STATE_W4_PUBLICATION_MS:
1208                     if (btstack_time_delta(publication_model->next_publication_ms, now) > 0) break;
1209                     publication_model->state = MESH_MODEL_PUBLICATION_STATE_PUBLICATION_READY;
1210                     break;
1211                 case MESH_MODEL_PUBLICATION_STATE_W4_RETRANSMIT_MS:
1212                     if (btstack_time_delta(publication_model->next_retransmit_ms, now) > 0) break;
1213                     publication_model->state = MESH_MODEL_PUBLICATION_STATE_RETRANSMIT_READY;
1214                     break;
1215                 default:
1216                     break;
1217             }
1218 
1219             switch (publication_model->state){
1220                 case MESH_MODEL_PUBLICATION_STATE_PUBLICATION_READY:
1221                     // schedule next publication and retransmission
1222                     mesh_model_publication_setup_publication(publication_model, now);
1223                     mesh_model_publication_setup_retransmission(publication_model, now);
1224                     mesh_model_publication_publish_now_model(mesh_model);
1225                     break;
1226                 case MESH_MODEL_PUBLICATION_STATE_RETRANSMIT_READY:
1227                     // schedule next retransmission
1228                     publication_model->retransmit_count--;
1229                     mesh_model_publication_setup_retransmission(publication_model, now);
1230                     mesh_model_publication_publish_now_model(mesh_model);
1231                     break;
1232                 default:
1233                     break;
1234             }
1235         }
1236     }
1237 
1238     int32_t next_timeout_ms = 0;
1239     mesh_element_iterator_init(&element_it);
1240     while (mesh_element_iterator_has_next(&element_it)){
1241         mesh_element_t * element = mesh_element_iterator_next(&element_it);
1242         mesh_model_iterator_t model_it;
1243         mesh_model_iterator_init(&model_it, element);
1244         while (mesh_model_iterator_has_next(&model_it)){
1245             mesh_model_t * mesh_model = mesh_model_iterator_next(&model_it);
1246             mesh_publication_model_t * publication_model = mesh_model->publication_model;
1247             if (publication_model == NULL) continue;
1248 
1249             // schedule next
1250             int32_t timeout_delta_ms;
1251             switch (publication_model->state){
1252                 case MESH_MODEL_PUBLICATION_STATE_W4_PUBLICATION_MS:
1253                     timeout_delta_ms = btstack_time_delta(publication_model->next_publication_ms, now);
1254                     if (next_timeout_ms == 0 || timeout_delta_ms < next_timeout_ms){
1255                         next_timeout_ms = timeout_delta_ms;
1256                     }
1257                     break;
1258                 case MESH_MODEL_PUBLICATION_STATE_W4_RETRANSMIT_MS:
1259                     timeout_delta_ms = btstack_time_delta(publication_model->next_retransmit_ms, now);
1260                     if (next_timeout_ms == 0 || timeout_delta_ms < next_timeout_ms){
1261                         next_timeout_ms = timeout_delta_ms;
1262                     }
1263                     break;
1264                 default:
1265                     break;
1266             }
1267         }
1268     }
1269 
1270     // remove current timer if active
1271     if (ts == NULL){
1272         btstack_run_loop_remove_timer(&mesh_access_publication_timer);
1273 
1274     }
1275 
1276     // new timeout?
1277     if (next_timeout_ms == 0) return;
1278 
1279     // set timer
1280     btstack_run_loop_set_timer(&mesh_access_publication_timer, next_timeout_ms);
1281     btstack_run_loop_set_timer_handler(&mesh_access_publication_timer, mesh_model_publication_run);
1282     btstack_run_loop_add_timer(&mesh_access_publication_timer);
1283 }
1284 
1285 void mesh_model_publication_start(mesh_model_t * mesh_model){
1286     mesh_publication_model_t * publication_model = mesh_model->publication_model;
1287     if (publication_model == NULL) return;
1288 
1289     // publish right away
1290     publication_model->state = MESH_MODEL_PUBLICATION_STATE_PUBLICATION_READY;
1291     mesh_model_publication_run(NULL);
1292 }
1293 
1294 void mesh_model_publication_stop(mesh_model_t * mesh_model){
1295     mesh_publication_model_t * publication_model = mesh_model->publication_model;
1296     if (publication_model == NULL) return;
1297 
1298     // reset state
1299     publication_model->state = MESH_MODEL_PUBLICATION_STATE_IDLE;
1300 }
1301 
1302 void mesh_access_state_changed(mesh_model_t * mesh_model){
1303     mesh_publication_model_t * publication_model = mesh_model->publication_model;
1304     if (publication_model == NULL) return;
1305     publication_model->state = MESH_MODEL_PUBLICATION_STATE_PUBLICATION_READY;
1306     mesh_model_publication_run(NULL);
1307 }
1308 
1309