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