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