xref: /btstack/src/mesh/mesh_access.c (revision 3e081242c081e2d135e9df51786f7963e85cdaf4)
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_message_t builder
738 mesh_message_pdu_t * mesh_access_message_init(uint32_t opcode, bool segmented, uint8_t num_segments){
739     btstack_assert(num_segments > 0);
740     btstack_assert(segmented || (num_segments == 1));
741 
742     mesh_message_pdu_t * pdu = mesh_message_pdu_get();
743     if (!pdu) return NULL;
744 
745     // TODO: handle segmented messages
746     btstack_assert(segmented == false);
747 
748     // use mesh_network_t as before
749     mesh_network_pdu_t * segment = mesh_network_pdu_get();
750     if (segment == NULL){
751         mesh_message_pdu_free(pdu);
752         return NULL;
753     }
754     btstack_linked_list_add(&pdu->segments, (btstack_linked_item_t *) segment);
755 
756     pdu->len = mesh_access_setup_opcode(&segment->data[10], opcode) + 10;
757     pdu->ack_opcode = MESH_ACCESS_OPCODE_NOT_SET;
758     return pdu;
759 }
760 
761 void mesh_access_message_add_uint8(mesh_message_pdu_t * pdu, uint8_t value){
762     // TODO: handle segmented messages
763     mesh_network_pdu_t * segment = (mesh_network_pdu_t *) btstack_linked_list_get_first_item(&pdu->segments);
764     segment->data[pdu->len++] = value;
765 }
766 
767 void mesh_access_message_add_uint16(mesh_message_pdu_t * pdu, uint16_t value){
768     // TODO: handle segmented messages
769     mesh_network_pdu_t * segment = (mesh_network_pdu_t *) btstack_linked_list_get_first_item(&pdu->segments);
770     little_endian_store_16(segment->data, pdu->len, value);
771     pdu->len += 2;
772 }
773 
774 void mesh_access_message_add_uint24(mesh_message_pdu_t * pdu, uint16_t value){
775     // TODO: handle segmented messages
776     mesh_network_pdu_t * segment = (mesh_network_pdu_t *) btstack_linked_list_get_first_item(&pdu->segments);
777     little_endian_store_24(segment->data, pdu->len, value);
778     pdu->len += 3;
779 }
780 
781 void mesh_access_message_add_uint32(mesh_message_pdu_t * pdu, uint16_t value){
782     // TODO: handle segmented messages
783     mesh_network_pdu_t * segment = (mesh_network_pdu_t *) btstack_linked_list_get_first_item(&pdu->segments);
784     little_endian_store_32(segment->data, pdu->len, value);
785     pdu->len += 4;
786 }
787 
788 void mesh_access_message_add_model_identifier(mesh_message_pdu_t * pdu, uint32_t model_identifier){
789     if (mesh_model_is_bluetooth_sig(model_identifier)){
790         mesh_access_message_add_uint16( pdu, mesh_model_get_model_id(model_identifier) );
791     } else {
792         mesh_access_message_add_uint32( pdu, model_identifier );
793     }
794 }
795 
796 // access message template
797 mesh_message_pdu_t * mesh_access_setup_message(bool segmented, const mesh_access_message_t *message_template, ...){
798     btstack_assert(segmented == false);
799 
800     // TODO: handle segmented messages
801     mesh_message_pdu_t * message_pdu = mesh_access_message_init(message_template->opcode, segmented, 1);
802     if (!message_pdu) return NULL;
803 
804     va_list argptr;
805     va_start(argptr, message_template);
806 
807     // add params
808     const char * format = message_template->format;
809     uint16_t word;
810     uint32_t longword;
811     while (*format){
812         switch (*format){
813             case '1':
814                 word = va_arg(argptr, int);  // minimal va_arg is int: 2 bytes on 8+16 bit CPUs
815                 mesh_access_message_add_uint8( message_pdu, word);
816                 break;
817             case '2':
818                 word = va_arg(argptr, int);  // minimal va_arg is int: 2 bytes on 8+16 bit CPUs
819                 mesh_access_message_add_uint16( message_pdu, word);
820                 break;
821             case '3':
822                 longword = va_arg(argptr, uint32_t);
823                 mesh_access_message_add_uint24( message_pdu, longword);
824                 break;
825             case '4':
826                 longword = va_arg(argptr, uint32_t);
827                 mesh_access_message_add_uint32( message_pdu, longword);
828                 mesh_access_message_add_uint32( message_pdu, longword);
829                 break;
830             case 'm':
831                 longword = va_arg(argptr, uint32_t);
832                 mesh_access_message_add_model_identifier( message_pdu, longword);
833                 break;
834             default:
835                 log_error("Unsupported mesh message format specifier '%c", *format);
836                 break;
837         }
838         format++;
839     }
840 
841     va_end(argptr);
842 
843     return message_pdu;
844 }
845 
846 mesh_transport_pdu_t * mesh_access_setup_segmented_message(const mesh_access_message_t *message_template, ...){
847     mesh_transport_pdu_t * transport_pdu = mesh_access_transport_init(message_template->opcode);
848     if (!transport_pdu) return NULL;
849 
850     va_list argptr;
851     va_start(argptr, message_template);
852 
853     // add params
854     const char * format = message_template->format;
855     uint16_t word;
856     uint32_t longword;
857     uint8_t * ptr;
858     while (*format){
859         switch (*format++){
860             case '1':
861                 word = va_arg(argptr, int);  // minimal va_arg is int: 2 bytes on 8+16 bit CPUs
862                 mesh_access_transport_add_uint8( transport_pdu, word);
863                 break;
864             case '2':
865                 word = va_arg(argptr, int);  // minimal va_arg is int: 2 bytes on 8+16 bit CPUs
866                 mesh_access_transport_add_uint16( transport_pdu, word);
867                 break;
868             case '3':
869                 longword = va_arg(argptr, uint32_t);
870                 mesh_access_transport_add_uint24( transport_pdu, longword);
871                 break;
872             case '4':
873                 longword = va_arg(argptr, uint32_t);
874                 mesh_access_transport_add_uint32( transport_pdu, longword);
875                 break;
876             case 'P': // 16 byte, eg LabelUUID, in network endianess
877                 ptr = va_arg(argptr, uint8_t *);
878                 mesh_access_transport_add_label_uuid( transport_pdu, ptr);
879                 break;
880             case 'm':
881                 longword = va_arg(argptr, uint32_t);
882                 mesh_access_transport_add_model_identifier( transport_pdu, longword);
883                 break;
884             default:
885                 break;
886         }
887     }
888 
889     va_end(argptr);
890 
891     return transport_pdu;
892 }
893 
894 
895 static const mesh_operation_t * mesh_model_lookup_operation_by_opcode(mesh_model_t * model, uint32_t opcode){
896     // find opcode in table
897     const mesh_operation_t * operation = model->operations;
898     if (operation == NULL) return NULL;
899     for ( ; operation->handler != NULL ; operation++){
900         if (operation->opcode != opcode) continue;
901         return operation;
902     }
903     return NULL;
904 }
905 
906 static const mesh_operation_t * mesh_model_lookup_operation(mesh_model_t * model, mesh_pdu_t * pdu){
907 
908     uint32_t opcode = 0;
909     uint16_t opcode_size = 0;
910     int ok = mesh_access_pdu_get_opcode( pdu, &opcode, &opcode_size);
911     if (!ok) return NULL;
912 
913     uint16_t len = mesh_pdu_len(pdu);
914 
915     // find opcode in table
916     const mesh_operation_t * operation = model->operations;
917     if (operation == NULL) return NULL;
918     for ( ; operation->handler != NULL ; operation++){
919         if (operation->opcode != opcode) continue;
920         if ((opcode_size + operation->minimum_length) > len) continue;
921         return operation;
922     }
923     return NULL;
924 }
925 
926 static int mesh_access_validate_appkey_index(mesh_model_t * model, uint16_t appkey_index){
927     // DeviceKey is valid for all models
928     if (appkey_index == MESH_DEVICE_KEY_INDEX) return 1;
929     // check if AppKey that is bound to this particular model
930     return mesh_model_contains_appkey(model, appkey_index);
931 }
932 
933 // decrease use count and report as free if done
934 void mesh_access_message_processed(mesh_pdu_t * pdu){
935     if (mesh_access_received_pdu_refcount > 0){
936         mesh_access_received_pdu_refcount--;
937     }
938     if (mesh_access_received_pdu_refcount == 0){
939         mesh_upper_transport_message_processed_by_higher_layer(pdu);
940     }
941 }
942 
943 static void mesh_access_message_process_handler(mesh_pdu_t * pdu){
944 
945     // init use count
946     mesh_access_received_pdu_refcount = 1;
947 
948     // get opcode and size
949     uint32_t opcode = 0;
950     uint16_t opcode_size = 0;
951 
952     int ok = mesh_access_pdu_get_opcode( pdu, &opcode, &opcode_size);
953     if (!ok) {
954         mesh_access_message_processed(pdu);
955         return;
956     }
957 
958     uint16_t len = mesh_pdu_len(pdu);
959     printf("MESH Access Message, Opcode = %x: ", opcode);
960     printf_hexdump(mesh_pdu_data(pdu), len);
961 
962     uint16_t src = mesh_pdu_src(pdu);
963     uint16_t dst = mesh_pdu_dst(pdu);
964     uint16_t appkey_index = mesh_pdu_appkey_index(pdu);
965     if (mesh_network_address_unicast(dst)){
966         // loookup element by unicast address
967         mesh_element_t * element = mesh_node_element_for_unicast_address(dst);
968         if (element != NULL){
969             // iterate over models, look for operation
970             mesh_model_iterator_t model_it;
971             mesh_model_iterator_init(&model_it, element);
972             while (mesh_model_iterator_has_next(&model_it)){
973                 mesh_model_t * model = mesh_model_iterator_next(&model_it);
974                 // find opcode in table
975                 const mesh_operation_t * operation = mesh_model_lookup_operation(model, pdu);
976                 if (operation == NULL) continue;
977                 if (mesh_access_validate_appkey_index(model, appkey_index) == 0) continue;
978                 mesh_access_acknowledged_received(src, opcode);
979                 mesh_access_received_pdu_refcount++;
980                 operation->handler(model, pdu);
981             }
982         }
983     }
984     else if (mesh_network_address_group(dst)){
985 
986         // handle fixed group address
987         if (dst >= 0xff00){
988             int deliver_to_primary_element = 1;
989             switch (dst){
990                 case MESH_ADDRESS_ALL_PROXIES:
991                     if (mesh_foundation_gatt_proxy_get() == 1){
992                         deliver_to_primary_element = 1;
993                     }
994                     break;
995                 case MESH_ADDRESS_ALL_FRIENDS:
996                     // TODO: not implemented
997                     break;
998                 case MESH_ADDRESS_ALL_RELAYS:
999                     if (mesh_foundation_relay_get() == 1){
1000                         deliver_to_primary_element = 1;
1001                     }
1002                     break;
1003                 case MESH_ADDRESS_ALL_NODES:
1004                     deliver_to_primary_element = 1;
1005                     break;
1006                 default:
1007                     break;
1008             }
1009             if (deliver_to_primary_element){
1010                 mesh_model_iterator_t model_it;
1011                 mesh_model_iterator_init(&model_it, mesh_node_get_primary_element());
1012                 while (mesh_model_iterator_has_next(&model_it)){
1013                     mesh_model_t * model = mesh_model_iterator_next(&model_it);
1014                     // find opcode in table
1015                     const mesh_operation_t * operation = mesh_model_lookup_operation(model, pdu);
1016                     if (operation == NULL) continue;
1017                     if (mesh_access_validate_appkey_index(model, appkey_index) == 0) continue;
1018                     mesh_access_acknowledged_received(src, opcode);
1019                     mesh_access_received_pdu_refcount++;
1020                     operation->handler(model, pdu);
1021                 }
1022             }
1023         }
1024         else {
1025             // iterate over all elements / models, check subscription list
1026             mesh_element_iterator_t it;
1027             mesh_element_iterator_init(&it);
1028             while (mesh_element_iterator_has_next(&it)){
1029                 mesh_element_t * element = (mesh_element_t *) mesh_element_iterator_next(&it);
1030                 mesh_model_iterator_t model_it;
1031                 mesh_model_iterator_init(&model_it, element);
1032                 while (mesh_model_iterator_has_next(&model_it)){
1033                     mesh_model_t * model = mesh_model_iterator_next(&model_it);
1034                     if (mesh_model_contains_subscription(model, dst)){
1035                         // find opcode in table
1036                         const mesh_operation_t * operation = mesh_model_lookup_operation(model, pdu);
1037                         if (operation == NULL) continue;
1038                         if (mesh_access_validate_appkey_index(model, appkey_index) == 0) continue;
1039                         mesh_access_acknowledged_received(src, opcode);
1040                         mesh_access_received_pdu_refcount++;
1041                         operation->handler(model, pdu);
1042                     }
1043                 }
1044             }
1045         }
1046     }
1047 
1048     // we're done
1049     mesh_access_message_processed(pdu);
1050 }
1051 
1052 // Mesh Model Publication
1053 static btstack_timer_source_t mesh_access_publication_timer;
1054 
1055 static uint32_t mesh_model_publication_retransmit_count(uint8_t retransmit){
1056     return retransmit & 0x07u;
1057 }
1058 
1059 static uint32_t mesh_model_publication_retransmission_period_ms(uint8_t retransmit){
1060     return ((uint32_t)((retransmit >> 3) + 1)) * 50;
1061 }
1062 
1063 static void mesh_model_publication_setup_publication(mesh_publication_model_t * publication_model, uint32_t now){
1064 
1065     // set retransmit counter
1066     publication_model->retransmit_count = mesh_model_publication_retransmit_count(publication_model->retransmit);
1067 
1068     // schedule next publication or retransmission
1069     uint32_t publication_period_ms = mesh_access_time_gdtt2ms(publication_model->period) >> publication_model->period_divisor;
1070 
1071     // set next publication
1072     if (publication_period_ms != 0){
1073         publication_model->next_publication_ms = now + publication_period_ms;
1074         publication_model->state = MESH_MODEL_PUBLICATION_STATE_W4_PUBLICATION_MS;
1075     } else {
1076         publication_model->state = MESH_MODEL_PUBLICATION_STATE_IDLE;
1077     }
1078 }
1079 
1080 // assumes retransmit_count is valid
1081 static void mesh_model_publication_setup_retransmission(mesh_publication_model_t * publication_model, uint32_t now){
1082     uint32_t publication_period_ms = mesh_access_time_gdtt2ms(publication_model->period) >> publication_model->period_divisor;
1083 
1084     // retransmission done
1085     if (publication_model->retransmit_count == 0) {
1086         // wait for next main event if periodic and retransmission complete
1087         if (publication_period_ms != 0){
1088             publication_model->state = MESH_MODEL_PUBLICATION_STATE_W4_PUBLICATION_MS;
1089         } else {
1090             publication_model->state = MESH_MODEL_PUBLICATION_STATE_IDLE;
1091         }
1092         return;
1093     }
1094 
1095     // calc next retransmit time
1096     uint32_t retransmission_period_ms = mesh_model_publication_retransmission_period_ms(publication_model->retransmit) >> publication_model->period_divisor;
1097     uint32_t retransmission_ms = now + retransmission_period_ms;
1098 
1099     // check next publication timeout is before next retransmission
1100     if (publication_period_ms != 0){
1101         if (btstack_time_delta(retransmission_ms, publication_model->next_publication_ms) > 0) return;
1102     }
1103 
1104     // schedule next retransmission
1105     publication_model->next_retransmit_ms = retransmission_ms;
1106     publication_model->state = MESH_MODEL_PUBLICATION_STATE_W4_RETRANSMIT_MS;
1107 }
1108 
1109 static void mesh_model_publication_publish_now_model(mesh_model_t * mesh_model){
1110     mesh_publication_model_t * publication_model = mesh_model->publication_model;
1111     if (publication_model == NULL) return;
1112     if (publication_model->publish_state_fn == NULL) return;
1113     uint16_t dest = publication_model->address;
1114     if (dest == MESH_ADDRESS_UNSASSIGNED) return;
1115     uint16_t appkey_index = publication_model->appkey_index;
1116     mesh_transport_key_t * app_key = mesh_transport_key_get(appkey_index);
1117     if (app_key == NULL) return;
1118 
1119     // compose message
1120     mesh_pdu_t * pdu = (*publication_model->publish_state_fn)(mesh_model);
1121     if (pdu == NULL) return;
1122 
1123     // handle ttl = default
1124     uint8_t ttl = publication_model->ttl;
1125     if (ttl == 0xff){
1126         ttl = mesh_foundation_default_ttl_get();
1127     }
1128 
1129     mesh_upper_transport_setup_access_pdu_header(pdu, app_key->netkey_index, appkey_index, ttl, mesh_access_get_element_address(mesh_model), dest, 0);
1130     mesh_access_send_unacknowledged_pdu(pdu);
1131 }
1132 
1133 static void mesh_model_publication_run(btstack_timer_source_t * ts){
1134 
1135     uint32_t now = btstack_run_loop_get_time_ms();
1136 
1137     // iterate over elements and models and handle time-based transitions
1138     mesh_element_iterator_t element_it;
1139     mesh_element_iterator_init(&element_it);
1140     while (mesh_element_iterator_has_next(&element_it)){
1141         mesh_element_t * element = mesh_element_iterator_next(&element_it);
1142         mesh_model_iterator_t model_it;
1143         mesh_model_iterator_init(&model_it, element);
1144         while (mesh_model_iterator_has_next(&model_it)){
1145             mesh_model_t * mesh_model = mesh_model_iterator_next(&model_it);
1146             mesh_publication_model_t * publication_model = mesh_model->publication_model;
1147             if (publication_model == NULL) continue;
1148 
1149             // check if either timer fired
1150             switch (publication_model->state){
1151                 case MESH_MODEL_PUBLICATION_STATE_W4_PUBLICATION_MS:
1152                     if (btstack_time_delta(publication_model->next_publication_ms, now) > 0) break;
1153                     publication_model->state = MESH_MODEL_PUBLICATION_STATE_PUBLICATION_READY;
1154                     break;
1155                 case MESH_MODEL_PUBLICATION_STATE_W4_RETRANSMIT_MS:
1156                     if (btstack_time_delta(publication_model->next_retransmit_ms, now) > 0) break;
1157                     publication_model->state = MESH_MODEL_PUBLICATION_STATE_RETRANSMIT_READY;
1158                     break;
1159                 default:
1160                     break;
1161             }
1162 
1163             switch (publication_model->state){
1164                 case MESH_MODEL_PUBLICATION_STATE_PUBLICATION_READY:
1165                     // schedule next publication and retransmission
1166                     mesh_model_publication_setup_publication(publication_model, now);
1167                     mesh_model_publication_setup_retransmission(publication_model, now);
1168                     mesh_model_publication_publish_now_model(mesh_model);
1169                     break;
1170                 case MESH_MODEL_PUBLICATION_STATE_RETRANSMIT_READY:
1171                     // schedule next retransmission
1172                     publication_model->retransmit_count--;
1173                     mesh_model_publication_setup_retransmission(publication_model, now);
1174                     mesh_model_publication_publish_now_model(mesh_model);
1175                     break;
1176                 default:
1177                     break;
1178             }
1179         }
1180     }
1181 
1182     int32_t next_timeout_ms = 0;
1183     mesh_element_iterator_init(&element_it);
1184     while (mesh_element_iterator_has_next(&element_it)){
1185         mesh_element_t * element = mesh_element_iterator_next(&element_it);
1186         mesh_model_iterator_t model_it;
1187         mesh_model_iterator_init(&model_it, element);
1188         while (mesh_model_iterator_has_next(&model_it)){
1189             mesh_model_t * mesh_model = mesh_model_iterator_next(&model_it);
1190             mesh_publication_model_t * publication_model = mesh_model->publication_model;
1191             if (publication_model == NULL) continue;
1192 
1193             // schedule next
1194             int32_t timeout_delta_ms;
1195             switch (publication_model->state){
1196                 case MESH_MODEL_PUBLICATION_STATE_W4_PUBLICATION_MS:
1197                     timeout_delta_ms = btstack_time_delta(publication_model->next_publication_ms, now);
1198                     if (next_timeout_ms == 0 || timeout_delta_ms < next_timeout_ms){
1199                         next_timeout_ms = timeout_delta_ms;
1200                     }
1201                     break;
1202                 case MESH_MODEL_PUBLICATION_STATE_W4_RETRANSMIT_MS:
1203                     timeout_delta_ms = btstack_time_delta(publication_model->next_retransmit_ms, now);
1204                     if (next_timeout_ms == 0 || timeout_delta_ms < next_timeout_ms){
1205                         next_timeout_ms = timeout_delta_ms;
1206                     }
1207                     break;
1208                 default:
1209                     break;
1210             }
1211         }
1212     }
1213 
1214     // remove current timer if active
1215     if (ts == NULL){
1216         btstack_run_loop_remove_timer(&mesh_access_publication_timer);
1217 
1218     }
1219 
1220     // new timeout?
1221     if (next_timeout_ms == 0) return;
1222 
1223     // set timer
1224     btstack_run_loop_set_timer(&mesh_access_publication_timer, next_timeout_ms);
1225     btstack_run_loop_set_timer_handler(&mesh_access_publication_timer, mesh_model_publication_run);
1226     btstack_run_loop_add_timer(&mesh_access_publication_timer);
1227 }
1228 
1229 void mesh_model_publication_start(mesh_model_t * mesh_model){
1230     mesh_publication_model_t * publication_model = mesh_model->publication_model;
1231     if (publication_model == NULL) return;
1232 
1233     // publish right away
1234     publication_model->state = MESH_MODEL_PUBLICATION_STATE_PUBLICATION_READY;
1235     mesh_model_publication_run(NULL);
1236 }
1237 
1238 void mesh_model_publication_stop(mesh_model_t * mesh_model){
1239     mesh_publication_model_t * publication_model = mesh_model->publication_model;
1240     if (publication_model == NULL) return;
1241 
1242     // reset state
1243     publication_model->state = MESH_MODEL_PUBLICATION_STATE_IDLE;
1244 }
1245 
1246 void mesh_access_state_changed(mesh_model_t * mesh_model){
1247     mesh_publication_model_t * publication_model = mesh_model->publication_model;
1248     if (publication_model == NULL) return;
1249     publication_model->state = MESH_MODEL_PUBLICATION_STATE_PUBLICATION_READY;
1250     mesh_model_publication_run(NULL);
1251 }
1252 
1253