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