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