xref: /btstack/src/mesh/mesh_access.c (revision 3c4cc6427fe05577c00b7d2593f58c7abcf9eab7)
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 // acknowledged messages
65 static btstack_linked_list_t  mesh_access_acknowledged_messages;
66 static btstack_timer_source_t mesh_access_acknowledged_timer;
67 
68 // Transitions
69 static btstack_linked_list_t  transitions;
70 static btstack_timer_source_t transitions_timer;
71 static uint32_t transition_step_min_ms;
72 static uint8_t mesh_transaction_id_counter = 0;
73 
74 void mesh_access_init(void){
75     // register with upper transport
76     mesh_upper_transport_register_access_message_handler(&mesh_access_message_process_handler);
77     mesh_upper_transport_set_higher_layer_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 
121 void mesh_access_send_unacknowledged_pdu(mesh_pdu_t * pdu){
122     pdu->ack_opcode = MESH_ACCESS_OPCODE_INVALID;;
123     mesh_upper_transport_send_access_pdu(pdu);
124 }
125 
126 void mesh_access_send_acknowledged_pdu(mesh_pdu_t * pdu, uint8_t retransmissions, uint32_t ack_opcode){
127     pdu->retransmit_count = retransmissions;
128     pdu->ack_opcode = ack_opcode;
129 
130     mesh_upper_transport_send_access_pdu(pdu);
131 }
132 
133 #define MESH_SUBEVENT_MESSAGE_NOT_ACKNOWLEDGED                                        0x30
134 
135 static void mesh_access_acknowledged_run(btstack_timer_source_t * ts){
136     UNUSED(ts);
137 
138     uint32_t now = btstack_run_loop_get_time_ms();
139 
140     // handle timeouts
141     btstack_linked_list_iterator_t ack_it;
142     btstack_linked_list_iterator_init(&ack_it, &mesh_access_acknowledged_messages);
143     while (btstack_linked_list_iterator_has_next(&ack_it)){
144         mesh_pdu_t * pdu = (mesh_pdu_t *) btstack_linked_list_iterator_next(&ack_it);
145         if (btstack_time_delta(now, pdu->retransmit_timeout_ms) >= 0) {
146             // remove from list
147             btstack_linked_list_remove(&mesh_access_acknowledged_messages, (btstack_linked_item_t*) pdu);
148             // retransmit or report failure
149             if (pdu->retransmit_count){
150                 pdu->retransmit_count--;
151                 mesh_upper_transport_send_access_pdu(pdu);
152             } else {
153                 // find correct model and emit error
154                 uint16_t src = mesh_pdu_src(pdu);
155                 uint16_t dst = mesh_pdu_dst(pdu);
156                 mesh_element_t * element = mesh_node_element_for_unicast_address(src);
157                 if (element){
158                     // find
159                     mesh_model_iterator_t model_it;
160                     mesh_model_iterator_init(&model_it, element);
161                     while (mesh_model_iterator_has_next(&model_it)){
162                         mesh_model_t * model = mesh_model_iterator_next(&model_it);
163                         // find opcode in table
164                         const mesh_operation_t * operation = mesh_model_lookup_operation_by_opcode(model, pdu->ack_opcode);
165                         if (operation == NULL) continue;
166                         if (model->model_packet_handler == NULL) continue;
167                         // emit event
168                         uint8_t event[13];
169                         event[0] = HCI_EVENT_MESH_META;
170                         event[1] = sizeof(event) - 2;
171                         event[2] = element->element_index;
172                         little_endian_store_32(event, 3, model->model_identifier);
173                         little_endian_store_32(event, 7, pdu->ack_opcode);
174                         little_endian_store_16(event, 11, dst);
175                         (*model->model_packet_handler)(HCI_EVENT_PACKET, 0, event, sizeof(event));
176                     }
177                 }
178 
179                 // free
180                 mesh_upper_transport_pdu_free(pdu);
181             }
182         }
183     }
184 
185     // find earliest timeout and set timer
186     btstack_linked_list_iterator_init(&ack_it, &mesh_access_acknowledged_messages);
187     int32_t next_timeout_ms = 0;
188     while (btstack_linked_list_iterator_has_next(&ack_it)){
189         mesh_pdu_t * pdu = (mesh_pdu_t *) btstack_linked_list_iterator_next(&ack_it);
190         int32_t timeout_delta_ms = btstack_time_delta(pdu->retransmit_timeout_ms, now);
191         if (next_timeout_ms == 0 || timeout_delta_ms < next_timeout_ms){
192             next_timeout_ms = timeout_delta_ms;
193         }
194     }
195 
196     // set timer
197     if (next_timeout_ms == 0) return;
198 
199     btstack_run_loop_set_timer(&mesh_access_acknowledged_timer, next_timeout_ms);
200     btstack_run_loop_set_timer_handler(&mesh_access_acknowledged_timer, mesh_access_acknowledged_run);
201     btstack_run_loop_add_timer(&mesh_access_acknowledged_timer);
202 }
203 
204 static void mesh_access_acknowledged_received(uint16_t rx_src, uint32_t opcode){
205     // check if received src matches our dest
206     // free acknowledged messages if we were waiting for this message
207 
208     btstack_linked_list_iterator_t ack_it;
209     btstack_linked_list_iterator_init(&ack_it, &mesh_access_acknowledged_messages);
210     while (btstack_linked_list_iterator_has_next(&ack_it)){
211         mesh_pdu_t * tx_pdu = (mesh_pdu_t *) btstack_linked_list_iterator_next(&ack_it);
212         uint16_t tx_dest = mesh_pdu_dst(tx_pdu);
213         if (tx_dest != rx_src) continue;
214         if (tx_pdu->ack_opcode != opcode) continue;
215         // got expected response from dest, remove from outgoing messages
216         mesh_upper_transport_pdu_free(tx_pdu);
217         return;
218     }
219 }
220 
221 static void mesh_access_upper_transport_handler(mesh_transport_callback_type_t callback_type, mesh_transport_status_t status, mesh_pdu_t * pdu){
222     UNUSED(status);
223     switch (callback_type){
224         case MESH_TRANSPORT_PDU_SENT:
225             // unacknowledged -> free
226             if (pdu->ack_opcode == MESH_ACCESS_OPCODE_INVALID){
227                 mesh_upper_transport_pdu_free(pdu);
228                 break;
229             }
230             // setup timeout
231             pdu->retransmit_timeout_ms = btstack_run_loop_get_time_ms() + mesh_access_acknowledged_message_timeout_ms();
232             // add to mesh_access_acknowledged_messages
233             btstack_linked_list_add(&mesh_access_acknowledged_messages, (btstack_linked_item_t *) pdu);
234             // update timer
235             mesh_access_acknowledged_run(NULL);
236             break;
237         default:
238             break;
239     }
240 }
241 
242 // Mesh Model Transitions
243 
244 void mesh_access_transitions_setup_transaction(mesh_transition_t * transition, uint8_t transaction_identifier, uint16_t src_address, uint16_t dst_address){
245     transition->transaction_timestamp_ms = btstack_run_loop_get_time_ms();
246     transition->transaction_identifier = transaction_identifier;
247     transition->src_address = src_address;
248     transition->dst_address = dst_address;
249 }
250 
251 void mesh_access_transitions_abort_transaction(mesh_transition_t * transition){
252     mesh_access_transitions_remove(transition);
253 }
254 
255 
256 static int mesh_access_transitions_transaction_is_expired(mesh_transition_t * transition){
257     return (btstack_run_loop_get_time_ms() - transition->transaction_timestamp_ms) > MEST_TRANSACTION_TIMEOUT_MS;
258 }
259 
260 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){
261     if (transition->src_address != src_address || transition->dst_address != dst_address) return MESH_TRANSACTION_STATUS_DIFFERENT_DST_OR_SRC;
262 
263     if (transition->transaction_identifier == transaction_identifier && !mesh_access_transitions_transaction_is_expired(transition)){
264             return MESH_TRANSACTION_STATUS_RETRANSMISSION;
265     }
266     return MESH_TRANSACTION_STATUS_NEW;
267 }
268 
269 uint8_t mesh_access_transitions_num_steps_from_gdtt(uint8_t time_gdtt){
270     return time_gdtt & 0x3fu;
271 }
272 
273 static uint32_t mesh_access_transitions_step_ms_from_gdtt(uint8_t time_gdtt){
274     mesh_default_transition_step_resolution_t step_resolution = (mesh_default_transition_step_resolution_t) (time_gdtt >> 6);
275     switch (step_resolution){
276         case MESH_DEFAULT_TRANSITION_STEP_RESOLUTION_100ms:
277             return 100;
278         case MESH_DEFAULT_TRANSITION_STEP_RESOLUTION_1s:
279             return 1000;
280         case MESH_DEFAULT_TRANSITION_STEP_RESOLUTION_10s:
281             return 10000;
282         case MESH_DEFAULT_TRANSITION_STEP_RESOLUTION_10min:
283             return 600000;
284         default:
285             return 0;
286     }
287 }
288 
289 uint32_t mesh_access_time_gdtt2ms(uint8_t time_gdtt){
290     uint8_t num_steps  = mesh_access_transitions_num_steps_from_gdtt(time_gdtt);
291     if (num_steps > 0x3E) return 0;
292 
293     return mesh_access_transitions_step_ms_from_gdtt(time_gdtt) * num_steps;
294 }
295 
296 static void mesh_access_transitions_timeout_handler(btstack_timer_source_t * timer){
297     btstack_linked_list_iterator_t it;
298     btstack_linked_list_iterator_init(&it, &transitions);
299     while (btstack_linked_list_iterator_has_next(&it)){
300         mesh_transition_t * transition = (mesh_transition_t *)btstack_linked_list_iterator_next(&it);
301         (transition->transition_callback)(transition, TRANSITION_UPDATE, btstack_run_loop_get_time_ms());
302     }
303     if (btstack_linked_list_empty(&transitions)) return;
304 
305     btstack_run_loop_set_timer(timer, transition_step_min_ms);
306     btstack_run_loop_add_timer(timer);
307 }
308 
309 static void mesh_access_transitions_timer_start(void){
310     btstack_run_loop_remove_timer(&transitions_timer);
311     btstack_run_loop_set_timer_handler(&transitions_timer, mesh_access_transitions_timeout_handler);
312     btstack_run_loop_set_timer(&transitions_timer, transition_step_min_ms);
313     btstack_run_loop_add_timer(&transitions_timer);
314 }
315 
316 static void mesh_access_transitions_timer_stop(void){
317     btstack_run_loop_remove_timer(&transitions_timer);
318 }
319 
320 static uint32_t mesh_access_transitions_get_step_min_ms(void){
321     uint32_t min_timeout_ms = 0;
322 
323     btstack_linked_list_iterator_t it;
324     btstack_linked_list_iterator_init(&it, &transitions);
325     while (btstack_linked_list_iterator_has_next(&it)){
326         mesh_transition_t * transition = (mesh_transition_t *)btstack_linked_list_iterator_next(&it);
327         if (min_timeout_ms == 0 || transition->step_duration_ms < min_timeout_ms){
328             min_timeout_ms = transition->step_duration_ms;
329         }
330     }
331     return min_timeout_ms;
332 }
333 
334 void mesh_access_transitions_setup(mesh_transition_t * transition, mesh_model_t * mesh_model,
335     uint8_t transition_time_gdtt, uint8_t delay_gdtt,
336     void (* transition_callback)(struct mesh_transition * transition, transition_event_t event, uint32_t current_timestamp)){
337 
338     //  Only values of 0x00 through 0x3E shall be used to specify the value of the Transition Number of Steps field
339     uint8_t num_steps  = mesh_access_transitions_num_steps_from_gdtt(transition_time_gdtt);
340     if (num_steps > 0x3E) return;
341 
342     transition->state = MESH_TRANSITION_STATE_IDLE;
343     transition->phase_start_ms = 0;
344 
345     transition->mesh_model = mesh_model;
346     transition->transition_callback = transition_callback;
347     transition->step_duration_ms = mesh_access_transitions_step_ms_from_gdtt(transition_time_gdtt);
348     transition->remaining_delay_time_ms = delay_gdtt * 5;
349     transition->remaining_transition_time_ms = num_steps * transition->step_duration_ms;
350 }
351 
352 void mesh_access_transitions_add(mesh_transition_t * transition){
353     if (transition->step_duration_ms == 0) return;
354 
355     if (btstack_linked_list_empty(&transitions) || transition->step_duration_ms < transition_step_min_ms){
356         transition_step_min_ms = transition->step_duration_ms;
357     }
358     mesh_access_transitions_timer_start();
359     btstack_linked_list_add(&transitions, (btstack_linked_item_t *) transition);
360     (transition->transition_callback)(transition, TRANSITION_START, btstack_run_loop_get_time_ms());
361 }
362 
363 void mesh_access_transitions_remove(mesh_transition_t * transition){
364     mesh_access_transitions_setup(transition, NULL, 0, 0, NULL);
365     btstack_linked_list_remove(&transitions, (btstack_linked_item_t *) transition);
366 
367     if (btstack_linked_list_empty(&transitions)){
368         mesh_access_transitions_timer_stop();
369     } else {
370         transition_step_min_ms = mesh_access_transitions_get_step_min_ms();
371     }
372 }
373 
374 uint8_t mesh_access_transactions_get_next_transaction_id(void){
375     mesh_transaction_id_counter++;
376     if (mesh_transaction_id_counter == 0){
377         mesh_transaction_id_counter = 1;
378     }
379     return mesh_transaction_id_counter;
380 }
381 
382 uint16_t mesh_pdu_ttl(mesh_pdu_t * pdu){
383     switch (pdu->pdu_type){
384         case MESH_PDU_TYPE_TRANSPORT:
385             return mesh_transport_ttl((mesh_transport_pdu_t*) pdu);
386         case MESH_PDU_TYPE_NETWORK:
387             return mesh_network_ttl((mesh_network_pdu_t *) pdu);
388         default:
389             return 0;
390     }
391 }
392 
393 uint16_t mesh_pdu_src(mesh_pdu_t * pdu){
394     switch (pdu->pdu_type){
395         case MESH_PDU_TYPE_TRANSPORT:
396             return mesh_transport_src((mesh_transport_pdu_t*) pdu);
397         case MESH_PDU_TYPE_NETWORK:
398             return mesh_network_src((mesh_network_pdu_t *) pdu);
399         default:
400             return MESH_ADDRESS_UNSASSIGNED;
401     }
402 }
403 
404 uint16_t mesh_pdu_dst(mesh_pdu_t * pdu){
405     switch (pdu->pdu_type){
406         case MESH_PDU_TYPE_TRANSPORT:
407             return mesh_transport_dst((mesh_transport_pdu_t*) pdu);
408         case MESH_PDU_TYPE_NETWORK:
409             return mesh_network_dst((mesh_network_pdu_t *) pdu);
410         default:
411             return MESH_ADDRESS_UNSASSIGNED;
412     }
413 }
414 
415 uint16_t mesh_pdu_netkey_index(mesh_pdu_t * pdu){
416     switch (pdu->pdu_type){
417         case MESH_PDU_TYPE_TRANSPORT:
418             return ((mesh_transport_pdu_t*) pdu)->netkey_index;
419         case MESH_PDU_TYPE_NETWORK:
420             return ((mesh_network_pdu_t *) pdu)->netkey_index;
421         default:
422             return 0;
423     }
424 }
425 
426 uint16_t mesh_pdu_appkey_index(mesh_pdu_t * pdu){
427     switch (pdu->pdu_type){
428         case MESH_PDU_TYPE_TRANSPORT:
429             return ((mesh_transport_pdu_t*) pdu)->appkey_index;
430         case MESH_PDU_TYPE_NETWORK:
431             return ((mesh_network_pdu_t *) pdu)->appkey_index;
432         default:
433             return 0;
434     }
435 }
436 
437 uint16_t mesh_pdu_len(mesh_pdu_t * pdu){
438     switch (pdu->pdu_type){
439         case MESH_PDU_TYPE_TRANSPORT:
440             return ((mesh_transport_pdu_t*) pdu)->len;
441         case MESH_PDU_TYPE_NETWORK:
442             return ((mesh_network_pdu_t *) pdu)->len - 10;
443         default:
444             return 0;
445     }
446 }
447 
448 uint8_t * mesh_pdu_data(mesh_pdu_t * pdu){
449     switch (pdu->pdu_type){
450         case MESH_PDU_TYPE_TRANSPORT:
451             return ((mesh_transport_pdu_t*) pdu)->data;
452         case MESH_PDU_TYPE_NETWORK:
453             return &((mesh_network_pdu_t *) pdu)->data[10];
454         default:
455             return NULL;
456     }
457 }
458 
459 uint8_t mesh_pdu_control_opcode(mesh_pdu_t * pdu){
460     switch (pdu->pdu_type){
461         case MESH_PDU_TYPE_TRANSPORT:
462             return mesh_transport_control_opcode((mesh_transport_pdu_t*) pdu);
463         case MESH_PDU_TYPE_NETWORK:
464             return mesh_network_control_opcode((mesh_network_pdu_t *) pdu);
465         default:
466             return 0xff;
467     }
468 }
469 
470 // message parser
471 
472 static int mesh_access_get_opcode(uint8_t * buffer, uint16_t buffer_size, uint32_t * opcode, uint16_t * opcode_size){
473     switch (buffer[0] >> 6){
474         case 0:
475         case 1:
476             if (buffer[0] == 0x7f) return 0;
477             *opcode = buffer[0];
478             *opcode_size = 1;
479             return 1;
480         case 2:
481             if (buffer_size < 2) return 0;
482             *opcode = big_endian_read_16(buffer, 0);
483             *opcode_size = 2;
484             return 1;
485         case 3:
486             if (buffer_size < 3) return 0;
487             *opcode = (buffer[0] << 16) | little_endian_read_16(buffer, 1);
488             *opcode_size = 3;
489             return 1;
490         default:
491             return 0;
492     }
493 }
494 
495 static int mesh_access_transport_get_opcode(mesh_transport_pdu_t * transport_pdu, uint32_t * opcode, uint16_t * opcode_size){
496     return mesh_access_get_opcode(transport_pdu->data, transport_pdu->len, opcode, opcode_size);
497 }
498 
499 static int mesh_access_network_get_opcode(mesh_network_pdu_t * network_pdu, uint32_t * opcode, uint16_t * opcode_size){
500     // TransMIC already removed by mesh_upper_transport_validate_unsegmented_message_ccm
501     return mesh_access_get_opcode(&network_pdu->data[10], network_pdu->len - 10, opcode, opcode_size);
502 }
503 
504 int mesh_access_pdu_get_opcode(mesh_pdu_t * pdu, uint32_t * opcode, uint16_t * opcode_size){
505     switch (pdu->pdu_type){
506         case MESH_PDU_TYPE_TRANSPORT:
507             return mesh_access_transport_get_opcode((mesh_transport_pdu_t*) pdu, opcode, opcode_size);
508         case MESH_PDU_TYPE_NETWORK:
509             return mesh_access_network_get_opcode((mesh_network_pdu_t *) pdu, opcode, opcode_size);
510         default:
511             return 0;
512     }
513 }
514 
515 void mesh_access_parser_skip(mesh_access_parser_state_t * state, uint16_t bytes_to_skip){
516     state->data += bytes_to_skip;
517     state->len  -= bytes_to_skip;
518 }
519 
520 int mesh_access_parser_init(mesh_access_parser_state_t * state, mesh_pdu_t * pdu){
521     state->data = mesh_pdu_data(pdu);
522     state->len  = mesh_pdu_len(pdu);
523 
524     uint16_t opcode_size = 0;
525     int ok = mesh_access_get_opcode(state->data, state->len, &state->opcode, &opcode_size);
526     if (ok){
527         mesh_access_parser_skip(state, opcode_size);
528     }
529     return ok;
530 }
531 
532 uint16_t mesh_access_parser_available(mesh_access_parser_state_t * state){
533     return state->len;
534 }
535 
536 uint8_t mesh_access_parser_get_u8(mesh_access_parser_state_t * state){
537     uint8_t value = *state->data;
538     mesh_access_parser_skip(state, 1);
539     return value;
540 }
541 
542 uint16_t mesh_access_parser_get_u16(mesh_access_parser_state_t * state){
543     uint16_t value = little_endian_read_16(state->data, 0);
544     mesh_access_parser_skip(state, 2);
545     return value;
546 }
547 
548 uint32_t mesh_access_parser_get_u24(mesh_access_parser_state_t * state){
549     uint32_t value = little_endian_read_24(state->data, 0);
550     mesh_access_parser_skip(state, 3);
551     return value;
552 }
553 
554 uint32_t mesh_access_parser_get_u32(mesh_access_parser_state_t * state){
555     uint32_t value = little_endian_read_24(state->data, 0);
556     mesh_access_parser_skip(state, 4);
557     return value;
558 }
559 
560 void mesh_access_parser_get_u128(mesh_access_parser_state_t * state, uint8_t * dest){
561     reverse_128( state->data, dest);
562     mesh_access_parser_skip(state, 16);
563 }
564 
565 void mesh_access_parser_get_label_uuid(mesh_access_parser_state_t * state, uint8_t * dest){
566     memcpy( dest, state->data, 16);
567     mesh_access_parser_skip(state, 16);
568 }
569 
570 void mesh_access_parser_get_key(mesh_access_parser_state_t * state, uint8_t * dest){
571     memcpy( dest, state->data, 16);
572     mesh_access_parser_skip(state, 16);
573 }
574 
575 uint32_t mesh_access_parser_get_model_identifier(mesh_access_parser_state_t * parser){
576     if (mesh_access_parser_available(parser) == 4){
577         return mesh_access_parser_get_u32(parser);
578     } else {
579         return (BLUETOOTH_COMPANY_ID_BLUETOOTH_SIG_INC << 16) | mesh_access_parser_get_u16(parser);
580     }
581 }
582 
583 // Mesh Access Message Builder
584 
585 // message builder
586 
587 static int mesh_access_setup_opcode(uint8_t * buffer, uint32_t opcode){
588     if (opcode < 0x100){
589         buffer[0] = opcode;
590         return 1;
591     }
592     if (opcode < 0x10000){
593         big_endian_store_16(buffer, 0, opcode);
594         return 2;
595     }
596     buffer[0] = opcode >> 16;
597     little_endian_store_16(buffer, 1, opcode & 0xffff);
598     return 3;
599 }
600 
601 mesh_transport_pdu_t * mesh_access_transport_init(uint32_t opcode){
602     mesh_transport_pdu_t * pdu = mesh_transport_pdu_get();
603     if (!pdu) return NULL;
604 
605     pdu->len  = mesh_access_setup_opcode(pdu->data, opcode);
606     return pdu;
607 }
608 
609 void mesh_access_transport_add_uint8(mesh_transport_pdu_t * pdu, uint8_t value){
610     pdu->data[pdu->len++] = value;
611 }
612 
613 void mesh_access_transport_add_uint16(mesh_transport_pdu_t * pdu, uint16_t value){
614     little_endian_store_16(pdu->data, pdu->len, value);
615     pdu->len += 2;
616 }
617 
618 void mesh_access_transport_add_uint24(mesh_transport_pdu_t * pdu, uint32_t value){
619     little_endian_store_24(pdu->data, pdu->len, value);
620     pdu->len += 3;
621 }
622 
623 void mesh_access_transport_add_uint32(mesh_transport_pdu_t * pdu, uint32_t value){
624     little_endian_store_32(pdu->data, pdu->len, value);
625     pdu->len += 4;
626 }
627 void mesh_access_transport_add_model_identifier(mesh_transport_pdu_t * pdu, uint32_t model_identifier){
628     if (mesh_model_is_bluetooth_sig(model_identifier)){
629         mesh_access_transport_add_uint16( pdu, mesh_model_get_model_id(model_identifier) );
630     } else {
631         mesh_access_transport_add_uint32( pdu, model_identifier );
632     }
633 }
634 
635 mesh_network_pdu_t * mesh_access_network_init(uint32_t opcode){
636     mesh_network_pdu_t * pdu = mesh_network_pdu_get();
637     if (!pdu) return NULL;
638 
639     pdu->len  = mesh_access_setup_opcode(&pdu->data[10], opcode) + 10;
640     return pdu;
641 }
642 
643 void mesh_access_network_add_uint8(mesh_network_pdu_t * pdu, uint8_t value){
644     pdu->data[pdu->len++] = value;
645 }
646 
647 void mesh_access_network_add_uint16(mesh_network_pdu_t * pdu, uint16_t value){
648     little_endian_store_16(pdu->data, pdu->len, value);
649     pdu->len += 2;
650 }
651 
652 void mesh_access_network_add_uint24(mesh_network_pdu_t * pdu, uint16_t value){
653     little_endian_store_24(pdu->data, pdu->len, value);
654     pdu->len += 3;
655 }
656 
657 void mesh_access_network_add_uint32(mesh_network_pdu_t * pdu, uint16_t value){
658     little_endian_store_32(pdu->data, pdu->len, value);
659     pdu->len += 4;
660 }
661 
662 void mesh_access_network_add_model_identifier(mesh_network_pdu_t * pdu, uint32_t model_identifier){
663     if (mesh_model_is_bluetooth_sig(model_identifier)){
664         mesh_access_network_add_uint16( pdu, mesh_model_get_model_id(model_identifier) );
665     } else {
666         mesh_access_network_add_uint32( pdu, model_identifier );
667     }
668 }
669 
670 // access message template
671 
672 mesh_network_pdu_t * mesh_access_setup_unsegmented_message(const mesh_access_message_t *message_template, ...){
673     mesh_network_pdu_t * network_pdu = mesh_access_network_init(message_template->opcode);
674     if (!network_pdu) return NULL;
675 
676     va_list argptr;
677     va_start(argptr, message_template);
678 
679     // add params
680     const char * format = message_template->format;
681     uint16_t word;
682     uint32_t longword;
683     while (*format){
684         switch (*format){
685             case '1':
686                 word = va_arg(argptr, int);  // minimal va_arg is int: 2 bytes on 8+16 bit CPUs
687                 mesh_access_network_add_uint8( network_pdu, word);
688                 break;
689             case '2':
690                 word = va_arg(argptr, int);  // minimal va_arg is int: 2 bytes on 8+16 bit CPUs
691                 mesh_access_network_add_uint16( network_pdu, word);
692                 break;
693             case '3':
694                 longword = va_arg(argptr, uint32_t);
695                 mesh_access_network_add_uint24( network_pdu, longword);
696                 break;
697             case '4':
698                 longword = va_arg(argptr, uint32_t);
699                 mesh_access_network_add_uint32( network_pdu, longword);
700                 break;
701             case 'm':
702                 longword = va_arg(argptr, uint32_t);
703                 mesh_access_network_add_model_identifier( network_pdu, longword);
704                 break;
705             default:
706                 log_error("Unsupported mesh message format specifier '%c", *format);
707                 break;
708         }
709         format++;
710     }
711 
712     va_end(argptr);
713 
714     return network_pdu;
715 }
716 
717 mesh_transport_pdu_t * mesh_access_setup_segmented_message(const mesh_access_message_t *message_template, ...){
718     mesh_transport_pdu_t * transport_pdu = mesh_access_transport_init(message_template->opcode);
719     if (!transport_pdu) return NULL;
720 
721     va_list argptr;
722     va_start(argptr, message_template);
723 
724     // add params
725     const char * format = message_template->format;
726     uint16_t word;
727     uint32_t longword;
728     while (*format){
729         switch (*format++){
730             case '1':
731                 word = va_arg(argptr, int);  // minimal va_arg is int: 2 bytes on 8+16 bit CPUs
732                 mesh_access_transport_add_uint8( transport_pdu, word);
733                 break;
734             case '2':
735                 word = va_arg(argptr, int);  // minimal va_arg is int: 2 bytes on 8+16 bit CPUs
736                 mesh_access_transport_add_uint16( transport_pdu, word);
737                 break;
738             case '3':
739                 longword = va_arg(argptr, uint32_t);
740                 mesh_access_transport_add_uint24( transport_pdu, longword);
741                 break;
742             case '4':
743                 longword = va_arg(argptr, uint32_t);
744                 mesh_access_transport_add_uint32( transport_pdu, longword);
745                 break;
746             case 'm':
747                 longword = va_arg(argptr, uint32_t);
748                 mesh_access_transport_add_model_identifier( transport_pdu, longword);
749                 break;
750             default:
751                 break;
752         }
753     }
754 
755     va_end(argptr);
756 
757     return transport_pdu;
758 }
759 
760 static const mesh_operation_t * mesh_model_lookup_operation_by_opcode(mesh_model_t * model, uint32_t opcode){
761     // find opcode in table
762     const mesh_operation_t * operation = model->operations;
763     if (operation == NULL) return NULL;
764     for ( ; operation->handler != NULL ; operation++){
765         if (operation->opcode != opcode) continue;
766         return operation;
767     }
768     return NULL;
769 }
770 
771 static const mesh_operation_t * mesh_model_lookup_operation(mesh_model_t * model, mesh_pdu_t * pdu){
772 
773     uint32_t opcode = 0;
774     uint16_t opcode_size = 0;
775     int ok = mesh_access_pdu_get_opcode( pdu, &opcode, &opcode_size);
776     if (!ok) return NULL;
777 
778     uint16_t len = mesh_pdu_len(pdu);
779 
780     // find opcode in table
781     const mesh_operation_t * operation = model->operations;
782     if (operation == NULL) return NULL;
783     for ( ; operation->handler != NULL ; operation++){
784         if (operation->opcode != opcode) continue;
785         if ((opcode_size + operation->minimum_length) > len) continue;
786         return operation;
787     }
788     return NULL;
789 }
790 
791 static int mesh_access_validate_appkey_index(mesh_model_t * model, uint16_t appkey_index){
792     // DeviceKey is valid for all models
793     if (appkey_index == MESH_DEVICE_KEY_INDEX) return 1;
794     // check if AppKey that is bound to this particular model
795     return mesh_model_contains_appkey(model, appkey_index);
796 }
797 
798 static void mesh_access_message_process_handler(mesh_pdu_t * pdu){
799     // get opcode and size
800     uint32_t opcode = 0;
801     uint16_t opcode_size = 0;
802 
803 
804     int ok = mesh_access_pdu_get_opcode( pdu, &opcode, &opcode_size);
805     if (!ok) {
806         mesh_access_message_processed(pdu);
807         return;
808     }
809 
810     uint16_t len = mesh_pdu_len(pdu);
811     printf("MESH Access Message, Opcode = %x: ", opcode);
812     printf_hexdump(mesh_pdu_data(pdu), len);
813 
814     uint16_t src = mesh_pdu_src(pdu);
815     uint16_t dst = mesh_pdu_dst(pdu);
816     uint16_t appkey_index = mesh_pdu_appkey_index(pdu);
817     if (mesh_network_address_unicast(dst)){
818         // loookup element by unicast address
819         mesh_element_t * element = mesh_node_element_for_unicast_address(dst);
820         if (element != NULL){
821             // iterate over models, look for operation
822             mesh_model_iterator_t model_it;
823             mesh_model_iterator_init(&model_it, element);
824             while (mesh_model_iterator_has_next(&model_it)){
825                 mesh_model_t * model = mesh_model_iterator_next(&model_it);
826                 // find opcode in table
827                 const mesh_operation_t * operation = mesh_model_lookup_operation(model, pdu);
828                 if (operation == NULL) continue;
829                 if (mesh_access_validate_appkey_index(model, appkey_index) == 0) continue;
830                 mesh_access_acknowledged_received(src, opcode);
831                 operation->handler(model, pdu);
832                 return;
833             }
834         }
835     }
836     else if (mesh_network_address_group(dst)){
837 
838         // handle fixed group address
839         if (dst >= 0xff00){
840             int deliver_to_primary_element = 1;
841             switch (dst){
842                 case MESH_ADDRESS_ALL_PROXIES:
843                     if (mesh_foundation_gatt_proxy_get() == 1){
844                         deliver_to_primary_element = 1;
845                     }
846                     break;
847                 case MESH_ADDRESS_ALL_FRIENDS:
848                     // TODO: not implemented
849                     break;
850                 case MESH_ADDRESS_ALL_RELAYS:
851                     if (mesh_foundation_relay_get() == 1){
852                         deliver_to_primary_element =1;
853                     }
854                     break;
855                 case MESH_ADDRESS_ALL_NODES:
856                     deliver_to_primary_element = 1;
857                     break;
858                 default:
859                     break;
860             }
861             if (deliver_to_primary_element){
862                 mesh_model_iterator_t model_it;
863                 mesh_model_iterator_init(&model_it, mesh_node_get_primary_element());
864                 while (mesh_model_iterator_has_next(&model_it)){
865                     mesh_model_t * model = mesh_model_iterator_next(&model_it);
866                     // find opcode in table
867                     const mesh_operation_t * operation = mesh_model_lookup_operation(model, pdu);
868                     if (operation == NULL) continue;
869                     if (mesh_access_validate_appkey_index(model, appkey_index) == 0) continue;
870                     mesh_access_acknowledged_received(src, opcode);
871                     operation->handler(model, pdu);
872                     return;
873                 }
874             }
875         }
876         else {
877             // iterate over all elements / models, check subscription list
878             mesh_element_iterator_t it;
879             mesh_element_iterator_init(&it);
880             while (mesh_element_iterator_has_next(&it)){
881                 mesh_element_t * element = (mesh_element_t *) mesh_element_iterator_next(&it);
882                 mesh_model_iterator_t model_it;
883                 mesh_model_iterator_init(&model_it, element);
884                 while (mesh_model_iterator_has_next(&model_it)){
885                     mesh_model_t * model = mesh_model_iterator_next(&model_it);
886                     if (mesh_model_contains_subscription(model, dst)){
887                         // find opcode in table
888                         const mesh_operation_t * operation = mesh_model_lookup_operation(model, pdu);
889                         if (operation == NULL) continue;
890                         if (mesh_access_validate_appkey_index(model, appkey_index) == 0) continue;
891                         mesh_access_acknowledged_received(src, opcode);
892                         operation->handler(model, pdu);
893                         return;
894                     }
895                 }
896             }
897         }
898     }
899 
900     // operation not found -> done
901     printf("Message not handled\n");
902     mesh_access_message_processed(pdu);
903 }
904 
905 void mesh_access_message_processed(mesh_pdu_t * pdu){
906     mesh_upper_transport_message_processed_by_higher_layer(pdu);
907 }
908 
909 // Mesh Model Publication
910 static btstack_timer_source_t mesh_access_publication_timer;
911 
912 static uint32_t mesh_model_publication_retransmit_count(uint8_t retransmit){
913     return retransmit & 0x07u;
914 }
915 
916 static uint32_t mesh_model_publication_retransmission_period_ms(uint8_t retransmit){
917     return ((uint32_t)((retransmit >> 3) + 1)) * 50;
918 }
919 
920 static void mesh_model_publication_setup_publication(mesh_publication_model_t * publication_model, uint32_t now){
921 
922     // set retransmit counter
923     publication_model->retransmit_count = mesh_model_publication_retransmit_count(publication_model->retransmit);
924 
925     // schedule next publication or retransmission
926     uint32_t publication_period_ms = mesh_access_time_gdtt2ms(publication_model->period);
927 
928     // set next publication
929     if (publication_period_ms != 0){
930         publication_model->next_publication_ms = now + publication_period_ms;
931         publication_model->state = MESH_MODEL_PUBLICATION_STATE_W4_PUBLICATION_MS;
932     } else {
933         publication_model->state = MESH_MODEL_PUBLICATION_STATE_IDLE;
934     }
935 }
936 
937 // assumes retransmit_count is valid
938 static void mesh_model_publication_setup_retransmission(mesh_publication_model_t * publication_model, uint32_t now){
939     uint32_t publication_period_ms = mesh_access_time_gdtt2ms(publication_model->period);
940 
941     // retransmission done
942     if (publication_model->retransmit_count == 0) {
943         // wait for next main event if periodic and retransmission complete
944         if (publication_period_ms != 0){
945             publication_model->state = MESH_MODEL_PUBLICATION_STATE_W4_PUBLICATION_MS;
946         } else {
947             publication_model->state = MESH_MODEL_PUBLICATION_STATE_IDLE;
948         }
949         return;
950     }
951 
952     // calc next retransmit time
953     uint32_t retransmission_ms = now + mesh_model_publication_retransmission_period_ms(publication_model->retransmit);
954 
955     // check next publication timeout is before next retransmission
956     if (publication_period_ms != 0){
957         if (btstack_time_delta(retransmission_ms, publication_model->next_publication_ms) > 0) return;
958     }
959 
960     // schedule next retransmission
961     publication_model->next_retransmit_ms = retransmission_ms;
962     publication_model->state = MESH_MODEL_PUBLICATION_STATE_W4_RETRANSMIT_MS;
963 }
964 
965 static void mesh_model_publication_publish_now_model(mesh_model_t * mesh_model){
966     mesh_publication_model_t * publication_model = mesh_model->publication_model;
967     if (publication_model == NULL) return;
968     if (publication_model->publish_state_fn == NULL) return;
969     uint16_t dest = publication_model->address;
970     if (dest == MESH_ADDRESS_UNSASSIGNED) return;
971     uint16_t appkey_index = publication_model->appkey_index;
972     mesh_transport_key_t * app_key = mesh_transport_key_get(appkey_index);
973     if (app_key == NULL) return;
974 
975     // compose message
976     mesh_pdu_t * pdu = (*publication_model->publish_state_fn)(mesh_model);
977     if (pdu == NULL) return;
978 
979     mesh_upper_transport_setup_access_pdu_header(pdu, app_key->netkey_index, appkey_index, publication_model->ttl, mesh_access_get_element_address(mesh_model), dest, 0);
980     mesh_upper_transport_send_access_pdu(pdu);
981 }
982 
983 static void mesh_model_publication_run(btstack_timer_source_t * ts){
984 
985     uint32_t now = btstack_run_loop_get_time_ms();
986 
987     // iterate over elements and models and handle time-based transitions
988     mesh_element_iterator_t element_it;
989     mesh_element_iterator_init(&element_it);
990     while (mesh_element_iterator_has_next(&element_it)){
991         mesh_element_t * element = mesh_element_iterator_next(&element_it);
992         mesh_model_iterator_t model_it;
993         mesh_model_iterator_init(&model_it, element);
994         while (mesh_model_iterator_has_next(&model_it)){
995             mesh_model_t * mesh_model = mesh_model_iterator_next(&model_it);
996             mesh_publication_model_t * publication_model = mesh_model->publication_model;
997             if (publication_model == NULL) continue;
998 
999             // check if either timer fired
1000             switch (publication_model->state){
1001                 case MESH_MODEL_PUBLICATION_STATE_W4_PUBLICATION_MS:
1002                     if (btstack_time_delta(publication_model->next_publication_ms, now) > 0) break;
1003                     publication_model->state = MESH_MODEL_PUBLICATION_STATE_PUBLICATION_READY;
1004                     break;
1005                 case MESH_MODEL_PUBLICATION_STATE_W4_RETRANSMIT_MS:
1006                     if (btstack_time_delta(publication_model->next_retransmit_ms, now) > 0) break;
1007                     publication_model->state = MESH_MODEL_PUBLICATION_STATE_RETRANSMIT_READY;
1008                     break;
1009                 default:
1010                     break;
1011             }
1012 
1013             switch (publication_model->state){
1014                 case MESH_MODEL_PUBLICATION_STATE_PUBLICATION_READY:
1015                     // schedule next publication and retransmission
1016                     mesh_model_publication_setup_publication(publication_model, now);
1017                     mesh_model_publication_setup_retransmission(publication_model, now);
1018                     mesh_model_publication_publish_now_model(mesh_model);
1019                     break;
1020                 case MESH_MODEL_PUBLICATION_STATE_RETRANSMIT_READY:
1021                     // schedule next retransmission
1022                     publication_model->retransmit_count--;
1023                     mesh_model_publication_setup_retransmission(publication_model, now);
1024                     mesh_model_publication_publish_now_model(mesh_model);
1025                     break;
1026                 default:
1027                     break;
1028             }
1029         }
1030     }
1031 
1032     int32_t next_timeout_ms = 0;
1033     mesh_element_iterator_init(&element_it);
1034     while (mesh_element_iterator_has_next(&element_it)){
1035         mesh_element_t * element = mesh_element_iterator_next(&element_it);
1036         mesh_model_iterator_t model_it;
1037         mesh_model_iterator_init(&model_it, element);
1038         while (mesh_model_iterator_has_next(&model_it)){
1039             mesh_model_t * mesh_model = mesh_model_iterator_next(&model_it);
1040             mesh_publication_model_t * publication_model = mesh_model->publication_model;
1041             if (publication_model == NULL) continue;
1042 
1043             // schedule next
1044             int32_t timeout_delta_ms;
1045             switch (publication_model->state){
1046                 case MESH_MODEL_PUBLICATION_STATE_W4_PUBLICATION_MS:
1047                     timeout_delta_ms = btstack_time_delta(publication_model->next_publication_ms, now);
1048                     if (next_timeout_ms == 0 || timeout_delta_ms < next_timeout_ms){
1049                         next_timeout_ms = timeout_delta_ms;
1050                     }
1051                     break;
1052                 case MESH_MODEL_PUBLICATION_STATE_W4_RETRANSMIT_MS:
1053                     timeout_delta_ms = btstack_time_delta(publication_model->next_retransmit_ms, now);
1054                     if (next_timeout_ms == 0 || timeout_delta_ms < next_timeout_ms){
1055                         next_timeout_ms = timeout_delta_ms;
1056                     }
1057                     break;
1058                 default:
1059                     break;
1060             }
1061         }
1062     }
1063 
1064     // remove current timer if active
1065     if (ts == NULL){
1066         btstack_run_loop_remove_timer(&mesh_access_publication_timer);
1067 
1068     }
1069 
1070     // new timeout?
1071     if (next_timeout_ms == 0) return;
1072 
1073     // set timer
1074     btstack_run_loop_set_timer(&mesh_access_publication_timer, next_timeout_ms);
1075     btstack_run_loop_set_timer_handler(&mesh_access_publication_timer, mesh_model_publication_run);
1076     btstack_run_loop_add_timer(&mesh_access_publication_timer);
1077 }
1078 
1079 void mesh_model_publication_start(mesh_model_t * mesh_model){
1080     mesh_publication_model_t * publication_model = mesh_model->publication_model;
1081     if (publication_model == NULL) return;
1082 
1083     // publish right away
1084     publication_model->state = MESH_MODEL_PUBLICATION_STATE_PUBLICATION_READY;
1085     mesh_model_publication_run(NULL);
1086 }
1087 
1088 void mesh_model_publication_stop(mesh_model_t * mesh_model){
1089     mesh_publication_model_t * publication_model = mesh_model->publication_model;
1090     if (publication_model == NULL) return;
1091 
1092     // reset state
1093     publication_model->state = MESH_MODEL_PUBLICATION_STATE_IDLE;
1094 }
1095 
1096 void mesh_access_state_changed(mesh_model_t * mesh_model){
1097     mesh_publication_model_t * publication_model = mesh_model->publication_model;
1098     if (publication_model == NULL) return;
1099     publication_model->state = MESH_MODEL_PUBLICATION_STATE_PUBLICATION_READY;
1100     mesh_model_publication_run(NULL);
1101 }
1102 
1103