xref: /btstack/src/mesh/mesh_access.c (revision 7a0b74888ef999bbcd1841fb7ec715e643b41d9e)
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 static uint16_t mesh_access_dst(mesh_access_pdu_t * access_pdu){
462     return big_endian_read_16(access_pdu->network_header, 7);
463 }
464 
465 uint16_t mesh_pdu_ctl(mesh_pdu_t * pdu){
466     switch (pdu->pdu_type){
467         case MESH_PDU_TYPE_TRANSPORT:
468             return mesh_transport_ctl((mesh_transport_pdu_t*) pdu);
469         case MESH_PDU_TYPE_NETWORK:
470             return mesh_network_control((mesh_network_pdu_t *) pdu);
471         default:
472             btstack_assert(false);
473             return 0;
474     }
475 }
476 
477 uint16_t mesh_pdu_ttl(mesh_pdu_t * pdu){
478     switch (pdu->pdu_type){
479         case MESH_PDU_TYPE_TRANSPORT:
480             return mesh_transport_ttl((mesh_transport_pdu_t*) pdu);
481         case MESH_PDU_TYPE_NETWORK:
482             return mesh_network_ttl((mesh_network_pdu_t *) pdu);
483         default:
484             btstack_assert(false);
485             return 0;
486     }
487 }
488 
489 uint16_t mesh_pdu_src(mesh_pdu_t * pdu){
490     switch (pdu->pdu_type){
491         case MESH_PDU_TYPE_ACCESS:
492             return mesh_access_src((mesh_access_pdu_t *) pdu);
493         case MESH_PDU_TYPE_TRANSPORT:
494             return mesh_transport_src((mesh_transport_pdu_t*) pdu);
495         case MESH_PDU_TYPE_NETWORK:
496             return mesh_network_src((mesh_network_pdu_t *) pdu);
497         default:
498             btstack_assert(false);
499             return MESH_ADDRESS_UNSASSIGNED;
500     }
501 }
502 
503 uint16_t mesh_pdu_dst(mesh_pdu_t * pdu){
504     switch (pdu->pdu_type){
505         case MESH_PDU_TYPE_ACCESS:
506             return mesh_access_dst((mesh_access_pdu_t *) pdu);
507         case MESH_PDU_TYPE_TRANSPORT:
508             return mesh_transport_dst((mesh_transport_pdu_t*) pdu);
509         case MESH_PDU_TYPE_NETWORK:
510             return mesh_network_dst((mesh_network_pdu_t *) pdu);
511         default:
512             btstack_assert(false);
513             return MESH_ADDRESS_UNSASSIGNED;
514     }
515 }
516 
517 uint16_t mesh_pdu_netkey_index(mesh_pdu_t * pdu){
518     switch (pdu->pdu_type){
519         case MESH_PDU_TYPE_ACCESS:
520             return ((mesh_access_pdu_t*) pdu)->netkey_index;
521         case MESH_PDU_TYPE_TRANSPORT:
522             return ((mesh_transport_pdu_t*) pdu)->netkey_index;
523         case MESH_PDU_TYPE_NETWORK:
524             return ((mesh_network_pdu_t *) pdu)->netkey_index;
525         default:
526             btstack_assert(false);
527             return 0;
528     }
529 }
530 
531 uint16_t mesh_pdu_appkey_index(mesh_pdu_t * pdu){
532     switch (pdu->pdu_type){
533         case MESH_PDU_TYPE_ACCESS:
534             return ((mesh_access_pdu_t*) pdu)->appkey_index;
535         case MESH_PDU_TYPE_TRANSPORT:
536             return ((mesh_transport_pdu_t*) pdu)->appkey_index;
537         default:
538             btstack_assert(false);
539             return 0;
540     }
541 }
542 
543 uint16_t mesh_pdu_len(mesh_pdu_t * pdu){
544     switch (pdu->pdu_type){
545         case MESH_PDU_TYPE_ACCESS:
546             return ((mesh_access_pdu_t*) pdu)->len;
547         case MESH_PDU_TYPE_TRANSPORT:
548             return ((mesh_transport_pdu_t*) pdu)->len;
549         case MESH_PDU_TYPE_NETWORK:
550             return ((mesh_network_pdu_t *) pdu)->len - 10;
551         default:
552             btstack_assert(false);
553             return 0;
554     }
555 }
556 
557 uint8_t * mesh_pdu_data(mesh_pdu_t * pdu){
558     switch (pdu->pdu_type){
559         case MESH_PDU_TYPE_ACCESS:
560             return ((mesh_access_pdu_t*) pdu)->data;
561         case MESH_PDU_TYPE_TRANSPORT:
562             return ((mesh_transport_pdu_t*) pdu)->data;
563         case MESH_PDU_TYPE_NETWORK:
564             return &((mesh_network_pdu_t *) pdu)->data[10];
565         default:
566             btstack_assert(false);
567             return NULL;
568     }
569 }
570 
571 uint8_t mesh_pdu_control_opcode(mesh_pdu_t * pdu){
572     switch (pdu->pdu_type){
573         case MESH_PDU_TYPE_TRANSPORT:
574             return mesh_transport_control_opcode((mesh_transport_pdu_t*) pdu);
575         case MESH_PDU_TYPE_NETWORK:
576             return mesh_network_control_opcode((mesh_network_pdu_t *) pdu);
577         default:
578             btstack_assert(false);
579             return 0xff;
580     }
581 }
582 
583 // message parser
584 
585 static int mesh_access_get_opcode(uint8_t * buffer, uint16_t buffer_size, uint32_t * opcode, uint16_t * opcode_size){
586     switch (buffer[0] >> 6){
587         case 0:
588         case 1:
589             if (buffer[0] == 0x7f) return 0;
590             *opcode = buffer[0];
591             *opcode_size = 1;
592             return 1;
593         case 2:
594             if (buffer_size < 2) return 0;
595             *opcode = big_endian_read_16(buffer, 0);
596             *opcode_size = 2;
597             return 1;
598         case 3:
599             if (buffer_size < 3) return 0;
600             *opcode = (buffer[0] << 16) | little_endian_read_16(buffer, 1);
601             *opcode_size = 3;
602             return 1;
603         default:
604             return 0;
605     }
606 }
607 
608 int mesh_access_pdu_get_opcode(mesh_pdu_t * pdu, uint32_t * opcode, uint16_t * opcode_size){
609     btstack_assert(pdu->pdu_type == MESH_PDU_TYPE_ACCESS);
610     return mesh_access_get_opcode(((mesh_access_pdu_t *) pdu)->data, ((mesh_access_pdu_t *) pdu)->len, opcode,
611                                   opcode_size);
612 }
613 
614 void mesh_access_parser_skip(mesh_access_parser_state_t * state, uint16_t bytes_to_skip){
615     state->data += bytes_to_skip;
616     state->len  -= bytes_to_skip;
617 }
618 
619 int mesh_access_parser_init(mesh_access_parser_state_t * state, mesh_pdu_t * pdu){
620     btstack_assert(pdu->pdu_type == MESH_PDU_TYPE_ACCESS);
621     state->data = mesh_pdu_data(pdu);
622     state->len  = mesh_pdu_len(pdu);
623 
624     uint16_t opcode_size = 0;
625     int ok = mesh_access_get_opcode(state->data, state->len, &state->opcode, &opcode_size);
626     if (ok){
627         mesh_access_parser_skip(state, opcode_size);
628     }
629     return ok;
630 }
631 
632 uint16_t mesh_access_parser_available(mesh_access_parser_state_t * state){
633     return state->len;
634 }
635 
636 uint8_t mesh_access_parser_get_u8(mesh_access_parser_state_t * state){
637     uint8_t value = *state->data;
638     mesh_access_parser_skip(state, 1);
639     return value;
640 }
641 
642 uint16_t mesh_access_parser_get_u16(mesh_access_parser_state_t * state){
643     uint16_t value = little_endian_read_16(state->data, 0);
644     mesh_access_parser_skip(state, 2);
645     return value;
646 }
647 
648 uint32_t mesh_access_parser_get_u24(mesh_access_parser_state_t * state){
649     uint32_t value = little_endian_read_24(state->data, 0);
650     mesh_access_parser_skip(state, 3);
651     return value;
652 }
653 
654 uint32_t mesh_access_parser_get_u32(mesh_access_parser_state_t * state){
655     uint32_t value = little_endian_read_32(state->data, 0);
656     mesh_access_parser_skip(state, 4);
657     return value;
658 }
659 
660 void mesh_access_parser_get_u128(mesh_access_parser_state_t * state, uint8_t * dest){
661     reverse_128( state->data, dest);
662     mesh_access_parser_skip(state, 16);
663 }
664 
665 void mesh_access_parser_get_label_uuid(mesh_access_parser_state_t * state, uint8_t * dest){
666     (void)memcpy(dest, state->data, 16);
667     mesh_access_parser_skip(state, 16);
668 }
669 
670 void mesh_access_parser_get_key(mesh_access_parser_state_t * state, uint8_t * dest){
671     (void)memcpy(dest, state->data, 16);
672     mesh_access_parser_skip(state, 16);
673 }
674 
675 uint32_t mesh_access_parser_get_model_identifier(mesh_access_parser_state_t * parser){
676     uint16_t vendor_id = BLUETOOTH_COMPANY_ID_BLUETOOTH_SIG_INC;
677     if (mesh_access_parser_available(parser) == 4){
678         vendor_id = mesh_access_parser_get_u16(parser);
679     }
680     uint16_t model_id = mesh_access_parser_get_u16(parser);
681     return mesh_model_get_model_identifier(vendor_id, model_id);
682 }
683 
684 uint32_t mesh_access_parser_get_sig_model_identifier(mesh_access_parser_state_t * parser){
685     uint16_t model_id = mesh_access_parser_get_u16(parser);
686     return mesh_model_get_model_identifier(BLUETOOTH_COMPANY_ID_BLUETOOTH_SIG_INC, model_id);
687 }
688 
689 uint32_t mesh_access_parser_get_vendor_model_identifier(mesh_access_parser_state_t * parser){
690     uint16_t vendor_id = mesh_access_parser_get_u16(parser);
691     uint16_t model_id  = mesh_access_parser_get_u16(parser);
692     return mesh_model_get_model_identifier(vendor_id, model_id);
693 }
694 
695 // Mesh Access Message Builder
696 
697 // message builder
698 
699 static int mesh_access_setup_opcode(uint8_t * buffer, uint32_t opcode){
700     if (opcode < 0x100){
701         buffer[0] = opcode;
702         return 1;
703     }
704     if (opcode < 0x10000){
705         big_endian_store_16(buffer, 0, opcode);
706         return 2;
707     }
708     buffer[0] = opcode >> 16;
709     little_endian_store_16(buffer, 1, opcode & 0xffff);
710     return 3;
711 }
712 
713 mesh_transport_pdu_t * mesh_access_transport_init(uint32_t opcode){
714     mesh_transport_pdu_t * pdu = mesh_transport_pdu_get();
715     if (!pdu) return NULL;
716 
717     pdu->len  = mesh_access_setup_opcode(pdu->data, opcode);
718     pdu->ack_opcode = MESH_ACCESS_OPCODE_NOT_SET;
719     return pdu;
720 }
721 
722 void mesh_access_transport_add_uint8(mesh_transport_pdu_t * pdu, uint8_t value){
723     pdu->data[pdu->len++] = value;
724 }
725 
726 void mesh_access_transport_add_uint16(mesh_transport_pdu_t * pdu, uint16_t value){
727     little_endian_store_16(pdu->data, pdu->len, value);
728     pdu->len += 2;
729 }
730 
731 void mesh_access_transport_add_uint24(mesh_transport_pdu_t * pdu, uint32_t value){
732     little_endian_store_24(pdu->data, pdu->len, value);
733     pdu->len += 3;
734 }
735 
736 void mesh_access_transport_add_uint32(mesh_transport_pdu_t * pdu, uint32_t value){
737     little_endian_store_32(pdu->data, pdu->len, value);
738     pdu->len += 4;
739 }
740 
741 void mesh_access_transport_add_label_uuid(mesh_transport_pdu_t * pdu, uint8_t * value){
742     (void)memcpy(value, pdu->data, 16);
743     pdu->len += 16;
744 }
745 
746 void mesh_access_transport_add_model_identifier(mesh_transport_pdu_t * pdu, uint32_t model_identifier){
747     if (!mesh_model_is_bluetooth_sig(model_identifier)){
748         mesh_access_transport_add_uint16( pdu, mesh_model_get_vendor_id(model_identifier) );
749     }
750     mesh_access_transport_add_uint16( pdu, mesh_model_get_model_id(model_identifier) );
751 }
752 
753 // mesh_message_t builder
754 mesh_segmented_pdu_t * mesh_access_message_init(uint32_t opcode, bool segmented, uint8_t num_segments){
755     btstack_assert(num_segments > 0);
756     btstack_assert(segmented || (num_segments == 1));
757 
758     mesh_segmented_pdu_t * pdu = mesh_message_pdu_get();
759     if (!pdu) return NULL;
760 
761     // TODO: handle segmented messages
762     btstack_assert(segmented == false);
763 
764     // use mesh_network_t as before
765     mesh_network_pdu_t * segment = mesh_network_pdu_get();
766     if (segment == NULL){
767         mesh_message_pdu_free(pdu);
768         return NULL;
769     }
770     btstack_linked_list_add(&pdu->segments, (btstack_linked_item_t *) segment);
771 
772     pdu->len = mesh_access_setup_opcode(&segment->data[10], opcode) + 10;
773     pdu->ack_opcode = MESH_ACCESS_OPCODE_NOT_SET;
774     return pdu;
775 }
776 
777 void mesh_access_message_add_uint8(mesh_segmented_pdu_t * pdu, uint8_t value){
778     // TODO: handle segmented messages
779     mesh_network_pdu_t * segment = (mesh_network_pdu_t *) btstack_linked_list_get_first_item(&pdu->segments);
780     segment->data[pdu->len++] = value;
781 }
782 
783 void mesh_access_message_add_uint16(mesh_segmented_pdu_t * pdu, uint16_t value){
784     // TODO: handle segmented messages
785     mesh_network_pdu_t * segment = (mesh_network_pdu_t *) btstack_linked_list_get_first_item(&pdu->segments);
786     little_endian_store_16(segment->data, pdu->len, value);
787     pdu->len += 2;
788 }
789 
790 void mesh_access_message_add_uint24(mesh_segmented_pdu_t * pdu, uint16_t value){
791     // TODO: handle segmented messages
792     mesh_network_pdu_t * segment = (mesh_network_pdu_t *) btstack_linked_list_get_first_item(&pdu->segments);
793     little_endian_store_24(segment->data, pdu->len, value);
794     pdu->len += 3;
795 }
796 
797 void mesh_access_message_add_uint32(mesh_segmented_pdu_t * pdu, uint16_t value){
798     // TODO: handle segmented messages
799     mesh_network_pdu_t * segment = (mesh_network_pdu_t *) btstack_linked_list_get_first_item(&pdu->segments);
800     little_endian_store_32(segment->data, pdu->len, value);
801     pdu->len += 4;
802 }
803 
804 void mesh_access_message_add_model_identifier(mesh_segmented_pdu_t * pdu, uint32_t model_identifier){
805     if (mesh_model_is_bluetooth_sig(model_identifier)){
806         mesh_access_message_add_uint16( pdu, mesh_model_get_model_id(model_identifier) );
807     } else {
808         mesh_access_message_add_uint32( pdu, model_identifier );
809     }
810 }
811 
812 // access message template
813 mesh_segmented_pdu_t * mesh_access_setup_message(bool segmented, const mesh_access_message_t *message_template, ...){
814     btstack_assert(segmented == false);
815 
816     // TODO: handle segmented messages
817     mesh_segmented_pdu_t * message_pdu = mesh_access_message_init(message_template->opcode, segmented, 1);
818     if (!message_pdu) return NULL;
819 
820     va_list argptr;
821     va_start(argptr, message_template);
822 
823     // add params
824     const char * format = message_template->format;
825     uint16_t word;
826     uint32_t longword;
827     while (*format){
828         switch (*format){
829             case '1':
830                 word = va_arg(argptr, int);  // minimal va_arg is int: 2 bytes on 8+16 bit CPUs
831                 mesh_access_message_add_uint8( message_pdu, word);
832                 break;
833             case '2':
834                 word = va_arg(argptr, int);  // minimal va_arg is int: 2 bytes on 8+16 bit CPUs
835                 mesh_access_message_add_uint16( message_pdu, word);
836                 break;
837             case '3':
838                 longword = va_arg(argptr, uint32_t);
839                 mesh_access_message_add_uint24( message_pdu, longword);
840                 break;
841             case '4':
842                 longword = va_arg(argptr, uint32_t);
843                 mesh_access_message_add_uint32( message_pdu, longword);
844                 mesh_access_message_add_uint32( message_pdu, longword);
845                 break;
846             case 'm':
847                 longword = va_arg(argptr, uint32_t);
848                 mesh_access_message_add_model_identifier( message_pdu, longword);
849                 break;
850             default:
851                 log_error("Unsupported mesh message format specifier '%c", *format);
852                 break;
853         }
854         format++;
855     }
856 
857     va_end(argptr);
858 
859     return message_pdu;
860 }
861 
862 mesh_transport_pdu_t * mesh_access_setup_segmented_message(const mesh_access_message_t *message_template, ...){
863     mesh_transport_pdu_t * transport_pdu = mesh_access_transport_init(message_template->opcode);
864     if (!transport_pdu) return NULL;
865 
866     va_list argptr;
867     va_start(argptr, message_template);
868 
869     // add params
870     const char * format = message_template->format;
871     uint16_t word;
872     uint32_t longword;
873     uint8_t * ptr;
874     while (*format){
875         switch (*format++){
876             case '1':
877                 word = va_arg(argptr, int);  // minimal va_arg is int: 2 bytes on 8+16 bit CPUs
878                 mesh_access_transport_add_uint8( transport_pdu, word);
879                 break;
880             case '2':
881                 word = va_arg(argptr, int);  // minimal va_arg is int: 2 bytes on 8+16 bit CPUs
882                 mesh_access_transport_add_uint16( transport_pdu, word);
883                 break;
884             case '3':
885                 longword = va_arg(argptr, uint32_t);
886                 mesh_access_transport_add_uint24( transport_pdu, longword);
887                 break;
888             case '4':
889                 longword = va_arg(argptr, uint32_t);
890                 mesh_access_transport_add_uint32( transport_pdu, longword);
891                 break;
892             case 'P': // 16 byte, eg LabelUUID, in network endianess
893                 ptr = va_arg(argptr, uint8_t *);
894                 mesh_access_transport_add_label_uuid( transport_pdu, ptr);
895                 break;
896             case 'm':
897                 longword = va_arg(argptr, uint32_t);
898                 mesh_access_transport_add_model_identifier( transport_pdu, longword);
899                 break;
900             default:
901                 break;
902         }
903     }
904 
905     va_end(argptr);
906 
907     return transport_pdu;
908 }
909 
910 
911 static const mesh_operation_t * mesh_model_lookup_operation_by_opcode(mesh_model_t * model, uint32_t opcode){
912     // find opcode in table
913     const mesh_operation_t * operation = model->operations;
914     if (operation == NULL) return NULL;
915     for ( ; operation->handler != NULL ; operation++){
916         if (operation->opcode != opcode) continue;
917         return operation;
918     }
919     return NULL;
920 }
921 
922 static const mesh_operation_t * mesh_model_lookup_operation(mesh_model_t * model, mesh_pdu_t * pdu){
923 
924     uint32_t opcode = 0;
925     uint16_t opcode_size = 0;
926     int ok = mesh_access_pdu_get_opcode( pdu, &opcode, &opcode_size);
927     if (!ok) return NULL;
928 
929     uint16_t len = mesh_pdu_len(pdu);
930 
931     // find opcode in table
932     const mesh_operation_t * operation = model->operations;
933     if (operation == NULL) return NULL;
934     for ( ; operation->handler != NULL ; operation++){
935         if (operation->opcode != opcode) continue;
936         if ((opcode_size + operation->minimum_length) > len) continue;
937         return operation;
938     }
939     return NULL;
940 }
941 
942 static int mesh_access_validate_appkey_index(mesh_model_t * model, uint16_t appkey_index){
943     // DeviceKey is valid for all models
944     if (appkey_index == MESH_DEVICE_KEY_INDEX) return 1;
945     // check if AppKey that is bound to this particular model
946     return mesh_model_contains_appkey(model, appkey_index);
947 }
948 
949 // decrease use count and report as free if done
950 void mesh_access_message_processed(mesh_pdu_t * pdu){
951     if (mesh_access_received_pdu_refcount > 0){
952         mesh_access_received_pdu_refcount--;
953     }
954     if (mesh_access_received_pdu_refcount == 0){
955         mesh_upper_transport_message_processed_by_higher_layer(pdu);
956     }
957 }
958 
959 static void mesh_access_message_process_handler(mesh_pdu_t * pdu){
960 
961     // init use count
962     mesh_access_received_pdu_refcount = 1;
963 
964     // get opcode and size
965     uint32_t opcode = 0;
966     uint16_t opcode_size = 0;
967 
968     int ok = mesh_access_pdu_get_opcode( pdu, &opcode, &opcode_size);
969     if (!ok) {
970         mesh_access_message_processed(pdu);
971         return;
972     }
973 
974     uint16_t len = mesh_pdu_len(pdu);
975     printf("MESH Access Message, Opcode = %x: ", opcode);
976     printf_hexdump(mesh_pdu_data(pdu), len);
977 
978     uint16_t src = mesh_pdu_src(pdu);
979     uint16_t dst = mesh_pdu_dst(pdu);
980     uint16_t appkey_index = mesh_pdu_appkey_index(pdu);
981     if (mesh_network_address_unicast(dst)){
982         // loookup element by unicast address
983         mesh_element_t * element = mesh_node_element_for_unicast_address(dst);
984         if (element != NULL){
985             // iterate over models, look for operation
986             mesh_model_iterator_t model_it;
987             mesh_model_iterator_init(&model_it, element);
988             while (mesh_model_iterator_has_next(&model_it)){
989                 mesh_model_t * model = mesh_model_iterator_next(&model_it);
990                 // find opcode in table
991                 const mesh_operation_t * operation = mesh_model_lookup_operation(model, pdu);
992                 if (operation == NULL) continue;
993                 if (mesh_access_validate_appkey_index(model, appkey_index) == 0) continue;
994                 mesh_access_acknowledged_received(src, opcode);
995                 mesh_access_received_pdu_refcount++;
996                 operation->handler(model, pdu);
997             }
998         }
999     }
1000     else if (mesh_network_address_group(dst)){
1001 
1002         // handle fixed group address
1003         if (dst >= 0xff00){
1004             int deliver_to_primary_element = 1;
1005             switch (dst){
1006                 case MESH_ADDRESS_ALL_PROXIES:
1007                     if (mesh_foundation_gatt_proxy_get() == 1){
1008                         deliver_to_primary_element = 1;
1009                     }
1010                     break;
1011                 case MESH_ADDRESS_ALL_FRIENDS:
1012                     // TODO: not implemented
1013                     break;
1014                 case MESH_ADDRESS_ALL_RELAYS:
1015                     if (mesh_foundation_relay_get() == 1){
1016                         deliver_to_primary_element = 1;
1017                     }
1018                     break;
1019                 case MESH_ADDRESS_ALL_NODES:
1020                     deliver_to_primary_element = 1;
1021                     break;
1022                 default:
1023                     break;
1024             }
1025             if (deliver_to_primary_element){
1026                 mesh_model_iterator_t model_it;
1027                 mesh_model_iterator_init(&model_it, mesh_node_get_primary_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 {
1041             // iterate over all elements / models, check subscription list
1042             mesh_element_iterator_t it;
1043             mesh_element_iterator_init(&it);
1044             while (mesh_element_iterator_has_next(&it)){
1045                 mesh_element_t * element = (mesh_element_t *) mesh_element_iterator_next(&it);
1046                 mesh_model_iterator_t model_it;
1047                 mesh_model_iterator_init(&model_it, element);
1048                 while (mesh_model_iterator_has_next(&model_it)){
1049                     mesh_model_t * model = mesh_model_iterator_next(&model_it);
1050                     if (mesh_model_contains_subscription(model, dst)){
1051                         // find opcode in table
1052                         const mesh_operation_t * operation = mesh_model_lookup_operation(model, pdu);
1053                         if (operation == NULL) continue;
1054                         if (mesh_access_validate_appkey_index(model, appkey_index) == 0) continue;
1055                         mesh_access_acknowledged_received(src, opcode);
1056                         mesh_access_received_pdu_refcount++;
1057                         operation->handler(model, pdu);
1058                     }
1059                 }
1060             }
1061         }
1062     }
1063 
1064     // we're done
1065     mesh_access_message_processed(pdu);
1066 }
1067 
1068 // Mesh Model Publication
1069 static btstack_timer_source_t mesh_access_publication_timer;
1070 
1071 static uint32_t mesh_model_publication_retransmit_count(uint8_t retransmit){
1072     return retransmit & 0x07u;
1073 }
1074 
1075 static uint32_t mesh_model_publication_retransmission_period_ms(uint8_t retransmit){
1076     return ((uint32_t)((retransmit >> 3) + 1)) * 50;
1077 }
1078 
1079 static void mesh_model_publication_setup_publication(mesh_publication_model_t * publication_model, uint32_t now){
1080 
1081     // set retransmit counter
1082     publication_model->retransmit_count = mesh_model_publication_retransmit_count(publication_model->retransmit);
1083 
1084     // schedule next publication or retransmission
1085     uint32_t publication_period_ms = mesh_access_time_gdtt2ms(publication_model->period) >> publication_model->period_divisor;
1086 
1087     // set next publication
1088     if (publication_period_ms != 0){
1089         publication_model->next_publication_ms = now + publication_period_ms;
1090         publication_model->state = MESH_MODEL_PUBLICATION_STATE_W4_PUBLICATION_MS;
1091     } else {
1092         publication_model->state = MESH_MODEL_PUBLICATION_STATE_IDLE;
1093     }
1094 }
1095 
1096 // assumes retransmit_count is valid
1097 static void mesh_model_publication_setup_retransmission(mesh_publication_model_t * publication_model, uint32_t now){
1098     uint32_t publication_period_ms = mesh_access_time_gdtt2ms(publication_model->period) >> publication_model->period_divisor;
1099 
1100     // retransmission done
1101     if (publication_model->retransmit_count == 0) {
1102         // wait for next main event if periodic and retransmission complete
1103         if (publication_period_ms != 0){
1104             publication_model->state = MESH_MODEL_PUBLICATION_STATE_W4_PUBLICATION_MS;
1105         } else {
1106             publication_model->state = MESH_MODEL_PUBLICATION_STATE_IDLE;
1107         }
1108         return;
1109     }
1110 
1111     // calc next retransmit time
1112     uint32_t retransmission_period_ms = mesh_model_publication_retransmission_period_ms(publication_model->retransmit) >> publication_model->period_divisor;
1113     uint32_t retransmission_ms = now + retransmission_period_ms;
1114 
1115     // check next publication timeout is before next retransmission
1116     if (publication_period_ms != 0){
1117         if (btstack_time_delta(retransmission_ms, publication_model->next_publication_ms) > 0) return;
1118     }
1119 
1120     // schedule next retransmission
1121     publication_model->next_retransmit_ms = retransmission_ms;
1122     publication_model->state = MESH_MODEL_PUBLICATION_STATE_W4_RETRANSMIT_MS;
1123 }
1124 
1125 static void mesh_model_publication_publish_now_model(mesh_model_t * mesh_model){
1126     mesh_publication_model_t * publication_model = mesh_model->publication_model;
1127     if (publication_model == NULL) return;
1128     if (publication_model->publish_state_fn == NULL) return;
1129     uint16_t dest = publication_model->address;
1130     if (dest == MESH_ADDRESS_UNSASSIGNED) return;
1131     uint16_t appkey_index = publication_model->appkey_index;
1132     mesh_transport_key_t * app_key = mesh_transport_key_get(appkey_index);
1133     if (app_key == NULL) return;
1134 
1135     // compose message
1136     mesh_pdu_t * pdu = (*publication_model->publish_state_fn)(mesh_model);
1137     if (pdu == NULL) return;
1138 
1139     // handle ttl = default
1140     uint8_t ttl = publication_model->ttl;
1141     if (ttl == 0xff){
1142         ttl = mesh_foundation_default_ttl_get();
1143     }
1144 
1145     mesh_upper_transport_setup_access_pdu_header(pdu, app_key->netkey_index, appkey_index, ttl, mesh_access_get_element_address(mesh_model), dest, 0);
1146     mesh_access_send_unacknowledged_pdu(pdu);
1147 }
1148 
1149 static void mesh_model_publication_run(btstack_timer_source_t * ts){
1150 
1151     uint32_t now = btstack_run_loop_get_time_ms();
1152 
1153     // iterate over elements and models and handle time-based transitions
1154     mesh_element_iterator_t element_it;
1155     mesh_element_iterator_init(&element_it);
1156     while (mesh_element_iterator_has_next(&element_it)){
1157         mesh_element_t * element = mesh_element_iterator_next(&element_it);
1158         mesh_model_iterator_t model_it;
1159         mesh_model_iterator_init(&model_it, element);
1160         while (mesh_model_iterator_has_next(&model_it)){
1161             mesh_model_t * mesh_model = mesh_model_iterator_next(&model_it);
1162             mesh_publication_model_t * publication_model = mesh_model->publication_model;
1163             if (publication_model == NULL) continue;
1164 
1165             // check if either timer fired
1166             switch (publication_model->state){
1167                 case MESH_MODEL_PUBLICATION_STATE_W4_PUBLICATION_MS:
1168                     if (btstack_time_delta(publication_model->next_publication_ms, now) > 0) break;
1169                     publication_model->state = MESH_MODEL_PUBLICATION_STATE_PUBLICATION_READY;
1170                     break;
1171                 case MESH_MODEL_PUBLICATION_STATE_W4_RETRANSMIT_MS:
1172                     if (btstack_time_delta(publication_model->next_retransmit_ms, now) > 0) break;
1173                     publication_model->state = MESH_MODEL_PUBLICATION_STATE_RETRANSMIT_READY;
1174                     break;
1175                 default:
1176                     break;
1177             }
1178 
1179             switch (publication_model->state){
1180                 case MESH_MODEL_PUBLICATION_STATE_PUBLICATION_READY:
1181                     // schedule next publication and retransmission
1182                     mesh_model_publication_setup_publication(publication_model, now);
1183                     mesh_model_publication_setup_retransmission(publication_model, now);
1184                     mesh_model_publication_publish_now_model(mesh_model);
1185                     break;
1186                 case MESH_MODEL_PUBLICATION_STATE_RETRANSMIT_READY:
1187                     // schedule next retransmission
1188                     publication_model->retransmit_count--;
1189                     mesh_model_publication_setup_retransmission(publication_model, now);
1190                     mesh_model_publication_publish_now_model(mesh_model);
1191                     break;
1192                 default:
1193                     break;
1194             }
1195         }
1196     }
1197 
1198     int32_t next_timeout_ms = 0;
1199     mesh_element_iterator_init(&element_it);
1200     while (mesh_element_iterator_has_next(&element_it)){
1201         mesh_element_t * element = mesh_element_iterator_next(&element_it);
1202         mesh_model_iterator_t model_it;
1203         mesh_model_iterator_init(&model_it, element);
1204         while (mesh_model_iterator_has_next(&model_it)){
1205             mesh_model_t * mesh_model = mesh_model_iterator_next(&model_it);
1206             mesh_publication_model_t * publication_model = mesh_model->publication_model;
1207             if (publication_model == NULL) continue;
1208 
1209             // schedule next
1210             int32_t timeout_delta_ms;
1211             switch (publication_model->state){
1212                 case MESH_MODEL_PUBLICATION_STATE_W4_PUBLICATION_MS:
1213                     timeout_delta_ms = btstack_time_delta(publication_model->next_publication_ms, now);
1214                     if (next_timeout_ms == 0 || timeout_delta_ms < next_timeout_ms){
1215                         next_timeout_ms = timeout_delta_ms;
1216                     }
1217                     break;
1218                 case MESH_MODEL_PUBLICATION_STATE_W4_RETRANSMIT_MS:
1219                     timeout_delta_ms = btstack_time_delta(publication_model->next_retransmit_ms, now);
1220                     if (next_timeout_ms == 0 || timeout_delta_ms < next_timeout_ms){
1221                         next_timeout_ms = timeout_delta_ms;
1222                     }
1223                     break;
1224                 default:
1225                     break;
1226             }
1227         }
1228     }
1229 
1230     // remove current timer if active
1231     if (ts == NULL){
1232         btstack_run_loop_remove_timer(&mesh_access_publication_timer);
1233 
1234     }
1235 
1236     // new timeout?
1237     if (next_timeout_ms == 0) return;
1238 
1239     // set timer
1240     btstack_run_loop_set_timer(&mesh_access_publication_timer, next_timeout_ms);
1241     btstack_run_loop_set_timer_handler(&mesh_access_publication_timer, mesh_model_publication_run);
1242     btstack_run_loop_add_timer(&mesh_access_publication_timer);
1243 }
1244 
1245 void mesh_model_publication_start(mesh_model_t * mesh_model){
1246     mesh_publication_model_t * publication_model = mesh_model->publication_model;
1247     if (publication_model == NULL) return;
1248 
1249     // publish right away
1250     publication_model->state = MESH_MODEL_PUBLICATION_STATE_PUBLICATION_READY;
1251     mesh_model_publication_run(NULL);
1252 }
1253 
1254 void mesh_model_publication_stop(mesh_model_t * mesh_model){
1255     mesh_publication_model_t * publication_model = mesh_model->publication_model;
1256     if (publication_model == NULL) return;
1257 
1258     // reset state
1259     publication_model->state = MESH_MODEL_PUBLICATION_STATE_IDLE;
1260 }
1261 
1262 void mesh_access_state_changed(mesh_model_t * mesh_model){
1263     mesh_publication_model_t * publication_model = mesh_model->publication_model;
1264     if (publication_model == NULL) return;
1265     publication_model->state = MESH_MODEL_PUBLICATION_STATE_PUBLICATION_READY;
1266     mesh_model_publication_run(NULL);
1267 }
1268 
1269