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