xref: /btstack/src/mesh/mesh_access.c (revision 56305cc23c9fade178f71a207f2f925d9eb2551d)
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 
57 #define MEST_TRANSACTION_TIMEOUT_MS  6000
58 
59 static void mesh_access_message_process_handler(mesh_pdu_t * pdu);
60 static void mesh_access_secure_network_beacon_handler(uint8_t packet_type, uint16_t channel, uint8_t * packet, uint16_t size);
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 static void mesh_persist_iv_index_and_sequence_number(void);
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 static uint16_t mid_counter;
70 
71 static const btstack_tlv_t * btstack_tlv_singleton_impl;
72 static void *                btstack_tlv_singleton_context;
73 
74 // Transitions
75 static btstack_linked_list_t  transitions;
76 static btstack_timer_source_t transitions_timer;
77 static uint32_t transition_step_min_ms;
78 static uint8_t mesh_transaction_id_counter = 0;
79 
80 static void mesh_access_setup_tlv(void){
81     if (btstack_tlv_singleton_impl) return;
82     btstack_tlv_get_instance(&btstack_tlv_singleton_impl, &btstack_tlv_singleton_context);
83 }
84 
85 void mesh_access_init(void){
86     // register with upper transport
87     mesh_upper_transport_register_access_message_handler(&mesh_access_message_process_handler);
88     mesh_upper_transport_set_higher_layer_handler(&mesh_access_upper_transport_handler);
89 
90     // register for secure network beacons
91     beacon_register_for_secure_network_beacons(&mesh_access_secure_network_beacon_handler);
92 
93     // register for seq number updates
94     mesh_sequence_number_set_update_callback(&mesh_persist_iv_index_and_sequence_number);
95 }
96 
97 void mesh_access_emit_state_update_bool(btstack_packet_handler_t event_handler, uint8_t element_index, uint32_t model_identifier,
98     model_state_id_t state_identifier, model_state_update_reason_t reason, uint8_t value){
99     if (event_handler == NULL) return;
100     uint8_t event[14] = {HCI_EVENT_MESH_META, 12, MESH_SUBEVENT_STATE_UPDATE_BOOL};
101     int pos = 3;
102     event[pos++] = element_index;
103     little_endian_store_32(event, pos, model_identifier);
104     pos += 4;
105     little_endian_store_32(event, pos, (uint32_t)state_identifier);
106     pos += 4;
107     event[pos++] = (uint8_t)reason;
108     event[pos++] = value;
109     (*event_handler)(HCI_EVENT_PACKET, 0, event, sizeof(event));
110 }
111 
112 void mesh_access_emit_state_update_int16(btstack_packet_handler_t event_handler, uint8_t element_index, uint32_t model_identifier,
113     model_state_id_t state_identifier, model_state_update_reason_t reason, int16_t value){
114     if (event_handler == NULL) return;
115     uint8_t event[15] = {HCI_EVENT_MESH_META, 13, MESH_SUBEVENT_STATE_UPDATE_BOOL};
116     int pos = 3;
117     event[pos++] = element_index;
118     little_endian_store_32(event, pos, model_identifier);
119     pos += 4;
120     little_endian_store_32(event, pos, (uint32_t)state_identifier);
121     pos += 4;
122     event[pos++] = (uint8_t)reason;
123     little_endian_store_16(event, pos, (uint16_t) value);
124     pos += 2;
125     (*event_handler)(HCI_EVENT_PACKET, 0, event, sizeof(event));
126 }
127 
128 uint8_t mesh_access_acknowledged_message_retransmissions(void){
129     return 3;
130 }
131 
132 uint32_t mesh_access_acknowledged_message_timeout_ms(void){
133     return 30000;
134 }
135 
136 #define MESH_ACCESS_OPCODE_INVALID 0xFFFFFFFFu
137 
138 void mesh_access_send_unacknowledged_pdu(mesh_pdu_t * pdu){
139     pdu->ack_opcode = MESH_ACCESS_OPCODE_INVALID;;
140     mesh_upper_transport_send_access_pdu(pdu);
141 }
142 
143 void mesh_access_send_acknowledged_pdu(mesh_pdu_t * pdu, uint8_t retransmissions, uint32_t ack_opcode){
144     pdu->retransmit_count = retransmissions;
145     pdu->ack_opcode = ack_opcode;
146 
147     mesh_upper_transport_send_access_pdu(pdu);
148 }
149 
150 #define MESH_SUBEVENT_MESSAGE_NOT_ACKNOWLEDGED                                        0x30
151 
152 static void mesh_access_acknowledged_run(btstack_timer_source_t * ts){
153     UNUSED(ts);
154 
155     uint32_t now = btstack_run_loop_get_time_ms();
156 
157     // handle timeouts
158     btstack_linked_list_iterator_t ack_it;
159     btstack_linked_list_iterator_init(&ack_it, &mesh_access_acknowledged_messages);
160     while (btstack_linked_list_iterator_has_next(&ack_it)){
161         mesh_pdu_t * pdu = (mesh_pdu_t *) btstack_linked_list_iterator_next(&ack_it);
162         if (btstack_time_delta(now, pdu->retransmit_timeout_ms) >= 0) {
163             // remove from list
164             btstack_linked_list_remove(&mesh_access_acknowledged_messages, (btstack_linked_item_t*) pdu);
165             // retransmit or report failure
166             if (pdu->retransmit_count){
167                 pdu->retransmit_count--;
168                 mesh_upper_transport_send_access_pdu(pdu);
169             } else {
170                 // find correct model and emit error
171                 uint16_t src = mesh_pdu_src(pdu);
172                 uint16_t dst = mesh_pdu_dst(pdu);
173                 mesh_element_t * element = mesh_node_element_for_unicast_address(src);
174                 if (element){
175                     // find
176                     mesh_model_iterator_t model_it;
177                     mesh_model_iterator_init(&model_it, element);
178                     while (mesh_model_iterator_has_next(&model_it)){
179                         mesh_model_t * model = mesh_model_iterator_next(&model_it);
180                         // find opcode in table
181                         const mesh_operation_t * operation = mesh_model_lookup_operation_by_opcode(model, pdu->ack_opcode);
182                         if (operation == NULL) continue;
183                         if (model->model_packet_handler == NULL) continue;
184                         // emit event
185                         uint8_t event[13];
186                         event[0] = HCI_EVENT_MESH_META;
187                         event[1] = sizeof(event) - 2;
188                         event[2] = element->element_index;
189                         little_endian_store_32(event, 3, model->model_identifier);
190                         little_endian_store_32(event, 7, pdu->ack_opcode);
191                         little_endian_store_16(event, 11, dst);
192                         (*model->model_packet_handler)(HCI_EVENT_PACKET, 0, event, sizeof(event));
193                     }
194                 }
195 
196                 // free
197                 mesh_upper_transport_pdu_free(pdu);
198             }
199         }
200     }
201 
202     // find earliest timeout and set timer
203     btstack_linked_list_iterator_init(&ack_it, &mesh_access_acknowledged_messages);
204     int32_t next_timeout_ms = 0;
205     while (btstack_linked_list_iterator_has_next(&ack_it)){
206         mesh_pdu_t * pdu = (mesh_pdu_t *) btstack_linked_list_iterator_next(&ack_it);
207         int32_t timeout_delta_ms = btstack_time_delta(pdu->retransmit_timeout_ms, now);
208         if (next_timeout_ms == 0 || timeout_delta_ms < next_timeout_ms){
209             next_timeout_ms = timeout_delta_ms;
210         }
211     }
212 
213     // set timer
214     if (next_timeout_ms == 0) return;
215 
216     btstack_run_loop_set_timer(&mesh_access_acknowledged_timer, next_timeout_ms);
217     btstack_run_loop_set_timer_handler(&mesh_access_acknowledged_timer, mesh_access_acknowledged_run);
218     btstack_run_loop_add_timer(&mesh_access_acknowledged_timer);
219 }
220 
221 static void mesh_access_acknowledged_received(uint16_t rx_src, uint32_t opcode){
222     // check if received src matches our dest
223     // free acknowledged messages if we were waiting for this message
224 
225     btstack_linked_list_iterator_t ack_it;
226     btstack_linked_list_iterator_init(&ack_it, &mesh_access_acknowledged_messages);
227     while (btstack_linked_list_iterator_has_next(&ack_it)){
228         mesh_pdu_t * tx_pdu = (mesh_pdu_t *) btstack_linked_list_iterator_next(&ack_it);
229         uint16_t tx_dest = mesh_pdu_dst(tx_pdu);
230         if (tx_dest != rx_src) continue;
231         if (tx_pdu->ack_opcode != opcode) continue;
232         // got expected response from dest, remove from outgoing messages
233         mesh_upper_transport_pdu_free(tx_pdu);
234         return;
235     }
236 }
237 
238 static void mesh_access_upper_transport_handler(mesh_transport_callback_type_t callback_type, mesh_transport_status_t status, mesh_pdu_t * pdu){
239     switch (callback_type){
240         case MESH_TRANSPORT_PDU_SENT:
241             // unacknowledged -> free
242             if (pdu->ack_opcode == MESH_ACCESS_OPCODE_INVALID){
243                 mesh_upper_transport_pdu_free(pdu);
244                 break;
245             }
246             // setup timeout
247             pdu->retransmit_timeout_ms = btstack_run_loop_get_time_ms() + mesh_access_acknowledged_message_timeout_ms();
248             // add to mesh_access_acknowledged_messages
249             btstack_linked_list_add(&mesh_access_acknowledged_messages, (btstack_linked_item_t *) pdu);
250             // update timer
251             mesh_access_acknowledged_run(NULL);
252             break;
253         default:
254             break;
255     }
256 }
257 
258 // Mesh Model Transitions
259 
260 void mesh_access_transitions_setup_transaction(mesh_transition_t * transition, uint8_t transaction_identifier, uint16_t src_address, uint16_t dst_address){
261     transition->transaction_timestamp_ms = btstack_run_loop_get_time_ms();
262     transition->transaction_identifier = transaction_identifier;
263     transition->src_address = src_address;
264     transition->dst_address = dst_address;
265 }
266 
267 void mesh_access_transitions_abort_transaction(mesh_transition_t * transition){
268     mesh_access_transitions_remove(transition);
269 }
270 
271 
272 static int mesh_access_transitions_transaction_is_expired(mesh_transition_t * transition){
273     return (btstack_run_loop_get_time_ms() - transition->transaction_timestamp_ms) > MEST_TRANSACTION_TIMEOUT_MS;
274 }
275 
276 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){
277     if (transition->src_address != src_address || transition->dst_address != dst_address) return MESH_TRANSACTION_STATUS_DIFFERENT_DST_OR_SRC;
278 
279     if (transition->transaction_identifier == transaction_identifier && !mesh_access_transitions_transaction_is_expired(transition)){
280             return MESH_TRANSACTION_STATUS_RETRANSMISSION;
281     }
282     return MESH_TRANSACTION_STATUS_NEW;
283 }
284 
285 uint8_t mesh_access_transitions_num_steps_from_gdtt(uint8_t time_gdtt){
286     return time_gdtt >> 2;
287 }
288 
289 static uint32_t mesh_access_transitions_step_ms_from_gdtt(uint8_t time_gdtt){
290     mesh_default_transition_step_resolution_t step_resolution = (mesh_default_transition_step_resolution_t) (time_gdtt & 0x03u);
291     switch (step_resolution){
292         case MESH_DEFAULT_TRANSITION_STEP_RESOLUTION_100ms:
293             return 100;
294         case MESH_DEFAULT_TRANSITION_STEP_RESOLUTION_1s:
295             return 1000;
296         case MESH_DEFAULT_TRANSITION_STEP_RESOLUTION_10s:
297             return 10000;
298         case MESH_DEFAULT_TRANSITION_STEP_RESOLUTION_10min:
299             return 600000;
300         default:
301             return 0;
302     }
303 }
304 
305 uint32_t mesh_access_time_gdtt2ms(uint8_t time_gdtt){
306     uint8_t num_steps  = mesh_access_transitions_num_steps_from_gdtt(time_gdtt);
307     if (num_steps > 0x3E) return 0;
308 
309     return mesh_access_transitions_step_ms_from_gdtt(time_gdtt) * num_steps;
310 }
311 
312 static void mesh_access_transitions_timeout_handler(btstack_timer_source_t * timer){
313     btstack_linked_list_iterator_t it;
314     btstack_linked_list_iterator_init(&it, &transitions);
315     while (btstack_linked_list_iterator_has_next(&it)){
316         mesh_transition_t * transition = (mesh_transition_t *)btstack_linked_list_iterator_next(&it);
317         (transition->transition_callback)(transition, TRANSITION_UPDATE, btstack_run_loop_get_time_ms());
318     }
319     if (btstack_linked_list_empty(&transitions)) return;
320 
321     btstack_run_loop_set_timer(timer, transition_step_min_ms);
322     btstack_run_loop_add_timer(timer);
323 }
324 
325 static void mesh_access_transitions_timer_start(void){
326     btstack_run_loop_remove_timer(&transitions_timer);
327     btstack_run_loop_set_timer_handler(&transitions_timer, mesh_access_transitions_timeout_handler);
328     btstack_run_loop_set_timer(&transitions_timer, transition_step_min_ms);
329     btstack_run_loop_add_timer(&transitions_timer);
330 }
331 
332 static void mesh_access_transitions_timer_stop(void){
333     btstack_run_loop_remove_timer(&transitions_timer);
334 }
335 
336 static uint32_t mesh_access_transitions_get_step_min_ms(void){
337     uint32_t min_timeout_ms = 0;
338 
339     btstack_linked_list_iterator_t it;
340     btstack_linked_list_iterator_init(&it, &transitions);
341     while (btstack_linked_list_iterator_has_next(&it)){
342         mesh_transition_t * transition = (mesh_transition_t *)btstack_linked_list_iterator_next(&it);
343         if (min_timeout_ms == 0 || transition->step_duration_ms < min_timeout_ms){
344             min_timeout_ms = transition->step_duration_ms;
345         }
346     }
347     return min_timeout_ms;
348 }
349 
350 void mesh_access_transitions_setup(mesh_transition_t * transition, mesh_model_t * mesh_model,
351     uint8_t transition_time_gdtt, uint8_t delay_gdtt,
352     void (* transition_callback)(struct mesh_transition * transition, transition_event_t event, uint32_t current_timestamp)){
353 
354     //  Only values of 0x00 through 0x3E shall be used to specify the value of the Transition Number of Steps field
355     uint8_t num_steps  = mesh_access_transitions_num_steps_from_gdtt(transition_time_gdtt);
356     if (num_steps > 0x3E) return;
357 
358     transition->state = MESH_TRANSITION_STATE_IDLE;
359     transition->phase_start_ms = 0;
360 
361     transition->mesh_model = mesh_model;
362     transition->transition_callback = transition_callback;
363     transition->step_duration_ms = mesh_access_transitions_step_ms_from_gdtt(transition_time_gdtt);
364     transition->remaining_delay_time_ms = delay_gdtt * 5;
365     transition->remaining_transition_time_ms = num_steps * transition->step_duration_ms;
366 }
367 
368 void mesh_access_transitions_add(mesh_transition_t * transition){
369     if (transition->step_duration_ms == 0) return;
370 
371     if (btstack_linked_list_empty(&transitions) || transition->step_duration_ms < transition_step_min_ms){
372         transition_step_min_ms = transition->step_duration_ms;
373     }
374     mesh_access_transitions_timer_start();
375     btstack_linked_list_add(&transitions, (btstack_linked_item_t *) transition);
376     (transition->transition_callback)(transition, TRANSITION_START, btstack_run_loop_get_time_ms());
377 }
378 
379 void mesh_access_transitions_remove(mesh_transition_t * transition){
380     mesh_access_transitions_setup(transition, NULL, 0, 0, NULL);
381     btstack_linked_list_remove(&transitions, (btstack_linked_item_t *) transition);
382 
383     if (btstack_linked_list_empty(&transitions)){
384         mesh_access_transitions_timer_stop();
385     } else {
386         transition_step_min_ms = mesh_access_transitions_get_step_min_ms();
387     }
388 }
389 
390 uint8_t mesh_access_transactions_get_next_transaction_id(void){
391     mesh_transaction_id_counter++;
392     if (mesh_transaction_id_counter == 0){
393         mesh_transaction_id_counter = 1;
394     }
395     return mesh_transaction_id_counter;
396 }
397 
398 // Mesh Node Element functions
399 uint8_t mesh_access_get_element_index(mesh_model_t * mesh_model){
400     return mesh_model->element->element_index;
401 }
402 
403 uint16_t mesh_access_get_element_address(mesh_model_t * mesh_model){
404     return mesh_node_get_primary_element_address() + mesh_model->element->element_index;
405 }
406 
407 // Model Identifier utilities
408 
409 uint32_t mesh_model_get_model_identifier(uint16_t vendor_id, uint16_t model_id){
410     return (vendor_id << 16) | model_id;
411 }
412 
413 uint32_t mesh_model_get_model_identifier_bluetooth_sig(uint16_t model_id){
414     return (BLUETOOTH_COMPANY_ID_BLUETOOTH_SIG_INC << 16) | model_id;
415 }
416 
417 uint16_t mesh_model_get_model_id(uint32_t model_identifier){
418     return model_identifier & 0xFFFFu;
419 }
420 
421 uint16_t mesh_model_get_vendor_id(uint32_t model_identifier){
422     return model_identifier >> 16;
423 }
424 
425 int mesh_model_is_bluetooth_sig(uint32_t model_identifier){
426     return mesh_model_get_vendor_id(model_identifier) == BLUETOOTH_COMPANY_ID_BLUETOOTH_SIG_INC;
427 }
428 
429 mesh_model_t * mesh_model_get_configuration_server(void){
430     return mesh_model_get_by_identifier(mesh_node_get_primary_element(), mesh_model_get_model_identifier_bluetooth_sig(MESH_SIG_MODEL_ID_CONFIGURATION_SERVER));
431 }
432 
433 void mesh_element_add_model(mesh_element_t * element, mesh_model_t * mesh_model){
434     // reset app keys
435     mesh_model_reset_appkeys(mesh_model);
436 
437     if (mesh_model_is_bluetooth_sig(mesh_model->model_identifier)){
438         element->models_count_sig++;
439     } else {
440         element->models_count_vendor++;
441     }
442     mesh_model->mid = mid_counter++;
443     mesh_model->element = element;
444     btstack_linked_list_add_tail(&element->models, (btstack_linked_item_t *) mesh_model);
445 }
446 
447 void mesh_model_iterator_init(mesh_model_iterator_t * iterator, mesh_element_t * element){
448     btstack_linked_list_iterator_init(&iterator->it, &element->models);
449 }
450 
451 int mesh_model_iterator_has_next(mesh_model_iterator_t * iterator){
452     return btstack_linked_list_iterator_has_next(&iterator->it);
453 }
454 
455 mesh_model_t * mesh_model_iterator_next(mesh_model_iterator_t * iterator){
456     return (mesh_model_t *) btstack_linked_list_iterator_next(&iterator->it);
457 }
458 
459 mesh_model_t * mesh_model_get_by_identifier(mesh_element_t * element, uint32_t model_identifier){
460     mesh_model_iterator_t it;
461     mesh_model_iterator_init(&it, element);
462     while (mesh_model_iterator_has_next(&it)){
463         mesh_model_t * model = mesh_model_iterator_next(&it);
464         if (model->model_identifier != model_identifier) continue;
465         return model;
466     }
467     return NULL;
468 }
469 
470 mesh_model_t * mesh_access_model_for_address_and_model_identifier(uint16_t element_address, uint32_t model_identifier, uint8_t * status){
471     mesh_element_t * element = mesh_node_element_for_unicast_address(element_address);
472     if (element == NULL){
473         *status = MESH_FOUNDATION_STATUS_INVALID_ADDRESS;
474         return NULL;
475     }
476     mesh_model_t * model = mesh_model_get_by_identifier(element, model_identifier);
477     if (model == NULL) {
478         *status = MESH_FOUNDATION_STATUS_INVALID_MODEL;
479     } else {
480         *status = MESH_FOUNDATION_STATUS_SUCCESS;
481     }
482     return model;
483 }
484 
485 uint16_t mesh_pdu_src(mesh_pdu_t * pdu){
486     switch (pdu->pdu_type){
487         case MESH_PDU_TYPE_TRANSPORT:
488             return mesh_transport_src((mesh_transport_pdu_t*) pdu);
489         case MESH_PDU_TYPE_NETWORK:
490             return mesh_network_src((mesh_network_pdu_t *) pdu);
491         default:
492             return MESH_ADDRESS_UNSASSIGNED;
493     }
494 }
495 
496 uint16_t mesh_pdu_dst(mesh_pdu_t * pdu){
497     switch (pdu->pdu_type){
498         case MESH_PDU_TYPE_TRANSPORT:
499             return mesh_transport_dst((mesh_transport_pdu_t*) pdu);
500         case MESH_PDU_TYPE_NETWORK:
501             return mesh_network_dst((mesh_network_pdu_t *) pdu);
502         default:
503             return MESH_ADDRESS_UNSASSIGNED;
504     }
505 }
506 
507 uint16_t mesh_pdu_netkey_index(mesh_pdu_t * pdu){
508     switch (pdu->pdu_type){
509         case MESH_PDU_TYPE_TRANSPORT:
510             return ((mesh_transport_pdu_t*) pdu)->netkey_index;
511         case MESH_PDU_TYPE_NETWORK:
512             return ((mesh_network_pdu_t *) pdu)->netkey_index;
513         default:
514             return 0;
515     }
516 }
517 
518 uint16_t mesh_pdu_appkey_index(mesh_pdu_t * pdu){
519     switch (pdu->pdu_type){
520         case MESH_PDU_TYPE_TRANSPORT:
521             return ((mesh_transport_pdu_t*) pdu)->appkey_index;
522         case MESH_PDU_TYPE_NETWORK:
523             return ((mesh_network_pdu_t *) pdu)->appkey_index;
524         default:
525             return 0;
526     }
527 }
528 
529 uint16_t mesh_pdu_len(mesh_pdu_t * pdu){
530     switch (pdu->pdu_type){
531         case MESH_PDU_TYPE_TRANSPORT:
532             return ((mesh_transport_pdu_t*) pdu)->len;
533         case MESH_PDU_TYPE_NETWORK:
534             return ((mesh_network_pdu_t *) pdu)->len - 10;
535         default:
536             return 0;
537     }
538 }
539 
540 uint8_t * mesh_pdu_data(mesh_pdu_t * pdu){
541     switch (pdu->pdu_type){
542         case MESH_PDU_TYPE_TRANSPORT:
543             return ((mesh_transport_pdu_t*) pdu)->data;
544         case MESH_PDU_TYPE_NETWORK:
545             return &((mesh_network_pdu_t *) pdu)->data[10];
546         default:
547             return NULL;
548     }
549 }
550 
551 // message parser
552 
553 static int mesh_access_get_opcode(uint8_t * buffer, uint16_t buffer_size, uint32_t * opcode, uint16_t * opcode_size){
554     switch (buffer[0] >> 6){
555         case 0:
556         case 1:
557             if (buffer[0] == 0x7f) return 0;
558             *opcode = buffer[0];
559             *opcode_size = 1;
560             return 1;
561         case 2:
562             if (buffer_size < 2) return 0;
563             *opcode = big_endian_read_16(buffer, 0);
564             *opcode_size = 2;
565             return 1;
566         case 3:
567             if (buffer_size < 3) return 0;
568             *opcode = (buffer[0] << 16) | little_endian_read_16(buffer, 1);
569             *opcode_size = 3;
570             return 1;
571         default:
572             return 0;
573     }
574 }
575 
576 static int mesh_access_transport_get_opcode(mesh_transport_pdu_t * transport_pdu, uint32_t * opcode, uint16_t * opcode_size){
577     return mesh_access_get_opcode(transport_pdu->data, transport_pdu->len, opcode, opcode_size);
578 }
579 
580 static int mesh_access_network_get_opcode(mesh_network_pdu_t * network_pdu, uint32_t * opcode, uint16_t * opcode_size){
581     // TransMIC already removed by mesh_upper_transport_validate_unsegmented_message_ccm
582     return mesh_access_get_opcode(&network_pdu->data[10], network_pdu->len - 10, opcode, opcode_size);
583 }
584 
585 int mesh_access_pdu_get_opcode(mesh_pdu_t * pdu, uint32_t * opcode, uint16_t * opcode_size){
586     switch (pdu->pdu_type){
587         case MESH_PDU_TYPE_TRANSPORT:
588             return mesh_access_transport_get_opcode((mesh_transport_pdu_t*) pdu, opcode, opcode_size);
589         case MESH_PDU_TYPE_NETWORK:
590             return mesh_access_network_get_opcode((mesh_network_pdu_t *) pdu, opcode, opcode_size);
591         default:
592             return 0;
593     }
594 }
595 
596 void mesh_access_parser_skip(mesh_access_parser_state_t * state, uint16_t bytes_to_skip){
597     state->data += bytes_to_skip;
598     state->len  -= bytes_to_skip;
599 }
600 
601 int mesh_access_parser_init(mesh_access_parser_state_t * state, mesh_pdu_t * pdu){
602     state->data = mesh_pdu_data(pdu);
603     state->len  = mesh_pdu_len(pdu);
604 
605     uint16_t opcode_size = 0;
606     int ok = mesh_access_get_opcode(state->data, state->len, &state->opcode, &opcode_size);
607     if (ok){
608         mesh_access_parser_skip(state, opcode_size);
609     }
610     return ok;
611 }
612 
613 uint16_t mesh_access_parser_available(mesh_access_parser_state_t * state){
614     return state->len;
615 }
616 
617 uint8_t mesh_access_parser_get_u8(mesh_access_parser_state_t * state){
618     uint8_t value = *state->data;
619     mesh_access_parser_skip(state, 1);
620     return value;
621 }
622 
623 uint16_t mesh_access_parser_get_u16(mesh_access_parser_state_t * state){
624     uint16_t value = little_endian_read_16(state->data, 0);
625     mesh_access_parser_skip(state, 2);
626     return value;
627 }
628 
629 uint32_t mesh_access_parser_get_u24(mesh_access_parser_state_t * state){
630     uint32_t value = little_endian_read_24(state->data, 0);
631     mesh_access_parser_skip(state, 3);
632     return value;
633 }
634 
635 uint32_t mesh_access_parser_get_u32(mesh_access_parser_state_t * state){
636     uint32_t value = little_endian_read_24(state->data, 0);
637     mesh_access_parser_skip(state, 4);
638     return value;
639 }
640 
641 void mesh_access_parser_get_u128(mesh_access_parser_state_t * state, uint8_t * dest){
642     reverse_128( state->data, dest);
643     mesh_access_parser_skip(state, 16);
644 }
645 
646 void mesh_access_parser_get_label_uuid(mesh_access_parser_state_t * state, uint8_t * dest){
647     memcpy( dest, state->data, 16);
648     mesh_access_parser_skip(state, 16);
649 }
650 
651 void mesh_access_parser_get_key(mesh_access_parser_state_t * state, uint8_t * dest){
652     memcpy( dest, state->data, 16);
653     mesh_access_parser_skip(state, 16);
654 }
655 
656 uint32_t mesh_access_parser_get_model_identifier(mesh_access_parser_state_t * parser){
657     if (mesh_access_parser_available(parser) == 4){
658         return mesh_access_parser_get_u32(parser);
659     } else {
660         return (BLUETOOTH_COMPANY_ID_BLUETOOTH_SIG_INC << 16) | mesh_access_parser_get_u16(parser);
661     }
662 }
663 
664 // Mesh Access Message Builder
665 
666 // message builder
667 
668 static int mesh_access_setup_opcode(uint8_t * buffer, uint32_t opcode){
669     if (opcode < 0x100){
670         buffer[0] = opcode;
671         return 1;
672     }
673     if (opcode < 0x10000){
674         big_endian_store_16(buffer, 0, opcode);
675         return 2;
676     }
677     buffer[0] = opcode >> 16;
678     little_endian_store_16(buffer, 1, opcode & 0xffff);
679     return 3;
680 }
681 
682 mesh_transport_pdu_t * mesh_access_transport_init(uint32_t opcode){
683     mesh_transport_pdu_t * pdu = mesh_transport_pdu_get();
684     if (!pdu) return NULL;
685 
686     pdu->len  = mesh_access_setup_opcode(pdu->data, opcode);
687     return pdu;
688 }
689 
690 void mesh_access_transport_add_uint8(mesh_transport_pdu_t * pdu, uint8_t value){
691     pdu->data[pdu->len++] = value;
692 }
693 
694 void mesh_access_transport_add_uint16(mesh_transport_pdu_t * pdu, uint16_t value){
695     little_endian_store_16(pdu->data, pdu->len, value);
696     pdu->len += 2;
697 }
698 
699 void mesh_access_transport_add_uint24(mesh_transport_pdu_t * pdu, uint32_t value){
700     little_endian_store_24(pdu->data, pdu->len, value);
701     pdu->len += 3;
702 }
703 
704 void mesh_access_transport_add_uint32(mesh_transport_pdu_t * pdu, uint32_t value){
705     little_endian_store_32(pdu->data, pdu->len, value);
706     pdu->len += 4;
707 }
708 void mesh_access_transport_add_model_identifier(mesh_transport_pdu_t * pdu, uint32_t model_identifier){
709     if (mesh_model_is_bluetooth_sig(model_identifier)){
710         mesh_access_transport_add_uint16( pdu, mesh_model_get_model_id(model_identifier) );
711     } else {
712         mesh_access_transport_add_uint32( pdu, model_identifier );
713     }
714 }
715 
716 mesh_network_pdu_t * mesh_access_network_init(uint32_t opcode){
717     mesh_network_pdu_t * pdu = mesh_network_pdu_get();
718     if (!pdu) return NULL;
719 
720     pdu->len  = mesh_access_setup_opcode(&pdu->data[10], opcode) + 10;
721     return pdu;
722 }
723 
724 void mesh_access_network_add_uint8(mesh_network_pdu_t * pdu, uint8_t value){
725     pdu->data[pdu->len++] = value;
726 }
727 
728 void mesh_access_network_add_uint16(mesh_network_pdu_t * pdu, uint16_t value){
729     little_endian_store_16(pdu->data, pdu->len, value);
730     pdu->len += 2;
731 }
732 
733 void mesh_access_network_add_uint24(mesh_network_pdu_t * pdu, uint16_t value){
734     little_endian_store_24(pdu->data, pdu->len, value);
735     pdu->len += 3;
736 }
737 
738 void mesh_access_network_add_uint32(mesh_network_pdu_t * pdu, uint16_t value){
739     little_endian_store_32(pdu->data, pdu->len, value);
740     pdu->len += 4;
741 }
742 
743 void mesh_access_network_add_model_identifier(mesh_network_pdu_t * pdu, uint32_t model_identifier){
744     if (mesh_model_is_bluetooth_sig(model_identifier)){
745         mesh_access_network_add_uint16( pdu, mesh_model_get_model_id(model_identifier) );
746     } else {
747         mesh_access_network_add_uint32( pdu, model_identifier );
748     }
749 }
750 
751 // access message template
752 
753 mesh_network_pdu_t * mesh_access_setup_unsegmented_message(const mesh_access_message_t *template, ...){
754     mesh_network_pdu_t * network_pdu = mesh_access_network_init(template->opcode);
755     if (!network_pdu) return NULL;
756 
757     va_list argptr;
758     va_start(argptr, template);
759 
760     // add params
761     const char * format = template->format;
762     uint16_t word;
763     uint32_t longword;
764     while (*format){
765         switch (*format){
766             case '1':
767                 word = va_arg(argptr, int);  // minimal va_arg is int: 2 bytes on 8+16 bit CPUs
768                 mesh_access_network_add_uint8( network_pdu, word);
769                 break;
770             case '2':
771                 word = va_arg(argptr, int);  // minimal va_arg is int: 2 bytes on 8+16 bit CPUs
772                 mesh_access_network_add_uint16( network_pdu, word);
773                 break;
774             case '3':
775                 longword = va_arg(argptr, uint32_t);
776                 mesh_access_network_add_uint24( network_pdu, longword);
777                 break;
778             case '4':
779                 longword = va_arg(argptr, uint32_t);
780                 mesh_access_network_add_uint32( network_pdu, longword);
781                 break;
782             case 'm':
783                 longword = va_arg(argptr, uint32_t);
784                 mesh_access_network_add_model_identifier( network_pdu, longword);
785                 break;
786             default:
787                 log_error("Unsupported mesh message format specifier '%c", *format);
788                 break;
789         }
790         format++;
791     }
792 
793     va_end(argptr);
794 
795     return network_pdu;
796 }
797 
798 mesh_transport_pdu_t * mesh_access_setup_segmented_message(const mesh_access_message_t *template, ...){
799     mesh_transport_pdu_t * transport_pdu = mesh_access_transport_init(template->opcode);
800     if (!transport_pdu) return NULL;
801 
802     va_list argptr;
803     va_start(argptr, template);
804 
805     // add params
806     const char * format = template->format;
807     uint16_t word;
808     uint32_t longword;
809     while (*format){
810         switch (*format++){
811             case '1':
812                 word = va_arg(argptr, int);  // minimal va_arg is int: 2 bytes on 8+16 bit CPUs
813                 mesh_access_transport_add_uint8( transport_pdu, word);
814                 break;
815             case '2':
816                 word = va_arg(argptr, int);  // minimal va_arg is int: 2 bytes on 8+16 bit CPUs
817                 mesh_access_transport_add_uint16( transport_pdu, word);
818                 break;
819             case '3':
820                 longword = va_arg(argptr, uint32_t);
821                 mesh_access_transport_add_uint24( transport_pdu, longword);
822                 break;
823             case '4':
824                 longword = va_arg(argptr, uint32_t);
825                 mesh_access_transport_add_uint32( transport_pdu, longword);
826                 break;
827             case 'm':
828                 longword = va_arg(argptr, uint32_t);
829                 mesh_access_transport_add_model_identifier( transport_pdu, longword);
830                 break;
831             default:
832                 break;
833         }
834     }
835 
836     va_end(argptr);
837 
838     return transport_pdu;
839 }
840 
841 static const mesh_operation_t * mesh_model_lookup_operation_by_opcode(mesh_model_t * model, uint32_t opcode){
842     // find opcode in table
843     const mesh_operation_t * operation = model->operations;
844     if (operation == NULL) return NULL;
845     for ( ; operation->handler != NULL ; operation++){
846         if (operation->opcode != opcode) continue;
847         return operation;
848     }
849     return NULL;
850 }
851 
852 static const mesh_operation_t * mesh_model_lookup_operation(mesh_model_t * model, mesh_pdu_t * pdu){
853 
854     uint32_t opcode = 0;
855     uint16_t opcode_size = 0;
856     int ok = mesh_access_pdu_get_opcode( pdu, &opcode, &opcode_size);
857     if (!ok) return NULL;
858 
859     uint16_t len = mesh_pdu_len(pdu);
860 
861     // find opcode in table
862     const mesh_operation_t * operation = model->operations;
863     if (operation == NULL) return NULL;
864     for ( ; operation->handler != NULL ; operation++){
865         if (operation->opcode != opcode) continue;
866         if ((opcode_size + operation->minimum_length) > len) continue;
867         return operation;
868     }
869     return NULL;
870 }
871 
872 static int mesh_access_validate_appkey_index(mesh_model_t * model, uint16_t appkey_index){
873     // DeviceKey is valid for all models
874     if (appkey_index == MESH_DEVICE_KEY_INDEX) return 1;
875     // check if AppKey that is bound to this particular model
876     return mesh_model_contains_appkey(model, appkey_index);
877 }
878 
879 static void mesh_access_message_process_handler(mesh_pdu_t * pdu){
880     // get opcode and size
881     uint32_t opcode = 0;
882     uint16_t opcode_size = 0;
883 
884 
885     int ok = mesh_access_pdu_get_opcode( pdu, &opcode, &opcode_size);
886     if (!ok) {
887         mesh_access_message_processed(pdu);
888         return;
889     }
890 
891     uint16_t len = mesh_pdu_len(pdu);
892     printf("MESH Access Message, Opcode = %x: ", opcode);
893     printf_hexdump(mesh_pdu_data(pdu), len);
894 
895     uint16_t src = mesh_pdu_src(pdu);
896     uint16_t dst = mesh_pdu_dst(pdu);
897     uint16_t appkey_index = mesh_pdu_appkey_index(pdu);
898     if (mesh_network_address_unicast(dst)){
899         // loookup element by unicast address
900         mesh_element_t * element = mesh_node_element_for_unicast_address(dst);
901         if (element != NULL){
902             // iterate over models, look for operation
903             mesh_model_iterator_t model_it;
904             mesh_model_iterator_init(&model_it, element);
905             while (mesh_model_iterator_has_next(&model_it)){
906                 mesh_model_t * model = mesh_model_iterator_next(&model_it);
907                 // find opcode in table
908                 const mesh_operation_t * operation = mesh_model_lookup_operation(model, pdu);
909                 if (operation == NULL) continue;
910                 if (mesh_access_validate_appkey_index(model, appkey_index) == 0) continue;
911                 mesh_access_acknowledged_received(src, opcode);
912                 operation->handler(model, pdu);
913                 return;
914             }
915         }
916     }
917     else if (mesh_network_address_group(dst)){
918 
919         // handle fixed group address
920         if (dst >= 0xff00){
921             int deliver_to_primary_element = 1;
922             switch (dst){
923                 case MESH_ADDRESS_ALL_PROXIES:
924                     if (mesh_foundation_gatt_proxy_get() == 1){
925                         deliver_to_primary_element = 1;
926                     }
927                     break;
928                 case MESH_ADDRESS_ALL_FRIENDS:
929                     // TODO: not implemented
930                     break;
931                 case MESH_ADDRESS_ALL_RELAYS:
932                     if (mesh_foundation_relay_get() == 1){
933                         deliver_to_primary_element =1;
934                     }
935                     break;
936                 case MESH_ADDRESS_ALL_NODES:
937                     deliver_to_primary_element = 1;
938                     break;
939                 default:
940                     break;
941             }
942             if (deliver_to_primary_element){
943                 mesh_model_iterator_t model_it;
944                 mesh_model_iterator_init(&model_it, mesh_node_get_primary_element());
945                 while (mesh_model_iterator_has_next(&model_it)){
946                     mesh_model_t * model = mesh_model_iterator_next(&model_it);
947                     // find opcode in table
948                     const mesh_operation_t * operation = mesh_model_lookup_operation(model, pdu);
949                     if (operation == NULL) continue;
950                     if (mesh_access_validate_appkey_index(model, appkey_index) == 0) continue;
951                     mesh_access_acknowledged_received(src, opcode);
952                     operation->handler(model, pdu);
953                     return;
954                 }
955             }
956         }
957         else {
958             // iterate over all elements / models, check subscription list
959             mesh_element_iterator_t it;
960             mesh_element_iterator_init(&it);
961             while (mesh_element_iterator_has_next(&it)){
962                 mesh_element_t * element = (mesh_element_t *) mesh_element_iterator_next(&it);
963                 mesh_model_iterator_t model_it;
964                 mesh_model_iterator_init(&model_it, element);
965                 while (mesh_model_iterator_has_next(&model_it)){
966                     mesh_model_t * model = mesh_model_iterator_next(&model_it);
967                     if (mesh_model_contains_subscription(model, dst)){
968                         // find opcode in table
969                         const mesh_operation_t * operation = mesh_model_lookup_operation(model, pdu);
970                         if (operation == NULL) continue;
971                         if (mesh_access_validate_appkey_index(model, appkey_index) == 0) continue;
972                         mesh_access_acknowledged_received(src, opcode);
973                         operation->handler(model, pdu);
974                         return;
975                     }
976                 }
977             }
978         }
979     }
980 
981     // operation not found -> done
982     printf("Message not handled\n");
983     mesh_access_message_processed(pdu);
984 }
985 
986 void mesh_access_message_processed(mesh_pdu_t * pdu){
987     mesh_upper_transport_message_processed_by_higher_layer(pdu);
988 }
989 
990 int mesh_model_contains_subscription(mesh_model_t * mesh_model, uint16_t address){
991     uint16_t i;
992     for (i=0;i<MAX_NR_MESH_SUBSCRIPTION_PER_MODEL;i++){
993         if (mesh_model->subscriptions[i] == address) return 1;
994     }
995     return 0;
996 }
997 
998 static uint32_t mesh_network_key_tag_for_internal_index(uint16_t internal_index){
999     return ((uint32_t) 'M' << 24) | ((uint32_t) 'N' << 16) | ((uint32_t) internal_index);
1000 }
1001 
1002 // Foundation state
1003 
1004 static const uint32_t mesh_foundation_state_tag = ((uint32_t) 'M' << 24) | ((uint32_t) 'F' << 16)  | ((uint32_t) 'N' << 8) | ((uint32_t) 'D' << 8);
1005 
1006 typedef struct {
1007     uint8_t gatt_proxy;
1008     uint8_t beacon;
1009     uint8_t default_ttl;
1010     uint8_t network_transmit;
1011     uint8_t relay;
1012     uint8_t relay_retransmit;
1013     uint8_t friend;
1014 } mesh_persistent_foundation_t;
1015 
1016 void mesh_foundation_state_load(void){
1017     mesh_access_setup_tlv();
1018     mesh_persistent_foundation_t data;
1019 
1020     int app_key_len = btstack_tlv_singleton_impl->get_tag(btstack_tlv_singleton_context, mesh_foundation_state_tag, (uint8_t *) &data, sizeof(data));
1021     if (app_key_len == 0) return;
1022 
1023     mesh_foundation_gatt_proxy_set(data.gatt_proxy);
1024     mesh_foundation_beacon_set(data.gatt_proxy);
1025     mesh_foundation_default_ttl_set(data.default_ttl);
1026     mesh_foundation_friend_set(data.friend);
1027     mesh_foundation_network_transmit_set(data.network_transmit);
1028     mesh_foundation_relay_set(data.relay);
1029     mesh_foundation_relay_retransmit_set(data.relay_retransmit);
1030 }
1031 
1032 void mesh_foundation_state_store(void){
1033     mesh_access_setup_tlv();
1034     mesh_persistent_foundation_t data;
1035     data.gatt_proxy       = mesh_foundation_gatt_proxy_get();
1036     data.gatt_proxy       = mesh_foundation_beacon_get();
1037     data.default_ttl      = mesh_foundation_default_ttl_get();
1038     data.friend           = mesh_foundation_friend_get();
1039     data.network_transmit = mesh_foundation_network_transmit_get();
1040     data.relay            = mesh_foundation_relay_get();
1041     data.relay_retransmit = mesh_foundation_relay_retransmit_get();
1042     btstack_tlv_singleton_impl->store_tag(btstack_tlv_singleton_context, mesh_foundation_state_tag, (uint8_t *) &data, sizeof(data));
1043 }
1044 
1045 // Mesh Network Keys
1046 typedef struct {
1047     uint16_t netkey_index;
1048 
1049     uint8_t  version;
1050 
1051     // net_key from provisioner or Config Model Client
1052     uint8_t net_key[16];
1053 
1054     // derived data
1055 
1056     // k1
1057     uint8_t identity_key[16];
1058     uint8_t beacon_key[16];
1059 
1060     // k3
1061     uint8_t network_id[8];
1062 
1063     // k2
1064     uint8_t nid;
1065     uint8_t encryption_key[16];
1066     uint8_t privacy_key[16];
1067 } mesh_persistent_net_key_t;
1068 
1069 void mesh_store_network_key(mesh_network_key_t * network_key){
1070     mesh_access_setup_tlv();
1071     mesh_persistent_net_key_t data;
1072     printf("Store NetKey: internal index 0x%x, NetKey Index 0x%06x, NID %02x: ", network_key->internal_index, network_key->netkey_index, network_key->nid);
1073     printf_hexdump(network_key->net_key, 16);
1074     uint32_t tag = mesh_network_key_tag_for_internal_index(network_key->internal_index);
1075     data.netkey_index = network_key->netkey_index;
1076     memcpy(data.net_key, network_key->net_key, 16);
1077     memcpy(data.identity_key, network_key->identity_key, 16);
1078     memcpy(data.beacon_key, network_key->beacon_key, 16);
1079     memcpy(data.network_id, network_key->network_id, 8);
1080     data.nid = network_key->nid;
1081     data.version = network_key->version;
1082     memcpy(data.encryption_key, network_key->encryption_key, 16);
1083     memcpy(data.privacy_key, network_key->privacy_key, 16);
1084     btstack_tlv_singleton_impl->store_tag(btstack_tlv_singleton_context, tag, (uint8_t *) &data, sizeof(mesh_persistent_net_key_t));
1085 }
1086 
1087 void mesh_delete_network_key(uint16_t internal_index){
1088     mesh_access_setup_tlv();
1089     uint32_t tag = mesh_network_key_tag_for_internal_index(internal_index);
1090     btstack_tlv_singleton_impl->delete_tag(btstack_tlv_singleton_context, tag);
1091 }
1092 
1093 
1094 void mesh_load_network_keys(void){
1095     mesh_access_setup_tlv();
1096     printf("Load Network Keys\n");
1097     uint16_t internal_index;
1098     for (internal_index = 0; internal_index < MAX_NR_MESH_NETWORK_KEYS; internal_index++){
1099         mesh_persistent_net_key_t data;
1100         uint32_t tag = mesh_network_key_tag_for_internal_index(internal_index);
1101         int netkey_len = btstack_tlv_singleton_impl->get_tag(btstack_tlv_singleton_context, tag, (uint8_t *) &data, sizeof(data));
1102         if (netkey_len != sizeof(mesh_persistent_net_key_t)) continue;
1103 
1104         mesh_network_key_t * network_key = btstack_memory_mesh_network_key_get();
1105         if (network_key == NULL) return;
1106 
1107         network_key->netkey_index = data.netkey_index;
1108         memcpy(network_key->net_key, data.net_key, 16);
1109         memcpy(network_key->identity_key, data.identity_key, 16);
1110         memcpy(network_key->beacon_key, data.beacon_key, 16);
1111         memcpy(network_key->network_id, data.network_id, 8);
1112         network_key->nid = data.nid;
1113         network_key->version = data.version;
1114         memcpy(network_key->encryption_key, data.encryption_key, 16);
1115         memcpy(network_key->privacy_key, data.privacy_key, 16);
1116 
1117 #ifdef ENABLE_GATT_BEARER
1118         // setup advertisement with network id
1119         network_key->advertisement_with_network_id.adv_length = mesh_proxy_setup_advertising_with_network_id(network_key->advertisement_with_network_id.adv_data, network_key->network_id);
1120 #endif
1121 
1122         mesh_network_key_add(network_key);
1123 
1124         mesh_subnet_setup_for_netkey_index(network_key->netkey_index);
1125 
1126         printf("- internal index 0x%x, NetKey Index 0x%06x, NID %02x: ", network_key->internal_index, network_key->netkey_index, network_key->nid);
1127         printf_hexdump(network_key->net_key, 16);
1128     }
1129 }
1130 
1131 void mesh_delete_network_keys(void){
1132     printf("Delete Network Keys\n");
1133 
1134     uint16_t internal_index;
1135     for (internal_index = 0; internal_index < MAX_NR_MESH_NETWORK_KEYS; internal_index++){
1136         mesh_delete_network_key(internal_index);
1137     }
1138 }
1139 
1140 
1141 // Mesh App Keys
1142 
1143 typedef struct {
1144     uint16_t netkey_index;
1145     uint16_t appkey_index;
1146     uint8_t  aid;
1147     uint8_t  version;
1148     uint8_t  key[16];
1149 } mesh_persistent_app_key_t;
1150 
1151 static uint32_t mesh_transport_key_tag_for_internal_index(uint16_t internal_index){
1152     return ((uint32_t) 'M' << 24) | ((uint32_t) 'A' << 16) | ((uint32_t) internal_index);
1153 }
1154 
1155 void mesh_store_app_key(mesh_transport_key_t * app_key){
1156     mesh_access_setup_tlv();
1157 
1158     mesh_persistent_app_key_t data;
1159     printf("Store AppKey: internal index 0x%x, AppKey Index 0x%06x, AID %02x: ", app_key->internal_index, app_key->appkey_index, app_key->aid);
1160     printf_hexdump(app_key->key, 16);
1161     uint32_t tag = mesh_transport_key_tag_for_internal_index(app_key->internal_index);
1162     data.netkey_index = app_key->netkey_index;
1163     data.appkey_index = app_key->appkey_index;
1164     data.aid = app_key->aid;
1165     data.version = app_key->version;
1166     memcpy(data.key, app_key->key, 16);
1167     btstack_tlv_singleton_impl->store_tag(btstack_tlv_singleton_context, tag, (uint8_t *) &data, sizeof(data));
1168 }
1169 
1170 void mesh_delete_app_key(uint16_t internal_index){
1171     mesh_access_setup_tlv();
1172 
1173     uint32_t tag = mesh_transport_key_tag_for_internal_index(internal_index);
1174     btstack_tlv_singleton_impl->delete_tag(btstack_tlv_singleton_context, tag);
1175 }
1176 
1177 void mesh_load_app_keys(void){
1178     mesh_access_setup_tlv();
1179     printf("Load App Keys\n");
1180     uint16_t internal_index;
1181     for (internal_index = 0; internal_index < MAX_NR_MESH_TRANSPORT_KEYS; internal_index++){
1182         mesh_persistent_app_key_t data;
1183         uint32_t tag = mesh_transport_key_tag_for_internal_index(internal_index);
1184         int app_key_len = btstack_tlv_singleton_impl->get_tag(btstack_tlv_singleton_context, tag, (uint8_t *) &data, sizeof(data));
1185         if (app_key_len == 0) continue;
1186 
1187         mesh_transport_key_t * key = btstack_memory_mesh_transport_key_get();
1188         if (key == NULL) return;
1189 
1190         key->internal_index = internal_index;
1191         key->appkey_index = data.appkey_index;
1192         key->netkey_index = data.netkey_index;
1193         key->aid          = data.aid;
1194         key->akf          = 1;
1195         key->version      = data.version;
1196         memcpy(key->key, data.key, 16);
1197         mesh_transport_key_add(key);
1198         printf("- internal index 0x%x, AppKey Index 0x%06x, AID %02x: ", key->internal_index, key->appkey_index, key->aid);
1199         printf_hexdump(key->key, 16);
1200     }
1201 }
1202 
1203 void mesh_delete_app_keys(void){
1204     printf("Delete App Keys\n");
1205 
1206     uint16_t internal_index;
1207     for (internal_index = 0; internal_index < MAX_NR_MESH_TRANSPORT_KEYS; internal_index++){
1208         mesh_delete_app_key(internal_index);
1209     }
1210 }
1211 
1212 
1213 // Model to Appkey List
1214 
1215 static uint32_t mesh_model_tag_for_index(uint16_t internal_model_id){
1216     return ((uint32_t) 'M' << 24) | ((uint32_t) 'B' << 16) | ((uint32_t) internal_model_id);
1217 }
1218 
1219 static void mesh_load_appkey_list(mesh_model_t * model){
1220     mesh_access_setup_tlv();
1221     uint32_t tag = mesh_model_tag_for_index(model->mid);
1222     btstack_tlv_singleton_impl->get_tag(btstack_tlv_singleton_context, tag, (uint8_t *) &model->appkey_indices, sizeof(model->appkey_indices));
1223 }
1224 
1225 static void mesh_store_appkey_list(mesh_model_t * model){
1226     mesh_access_setup_tlv();
1227     uint32_t tag = mesh_model_tag_for_index(model->mid);
1228     btstack_tlv_singleton_impl->store_tag(btstack_tlv_singleton_context, tag, (uint8_t *) &model->appkey_indices, sizeof(model->appkey_indices));
1229 }
1230 
1231 static void mesh_delete_appkey_list(mesh_model_t * model){
1232     mesh_access_setup_tlv();
1233     uint32_t tag = mesh_model_tag_for_index(model->mid);
1234     btstack_tlv_singleton_impl->delete_tag(btstack_tlv_singleton_context, tag);
1235 }
1236 
1237 void mesh_load_appkey_lists(void){
1238     printf("Load Appkey Lists\n");
1239     // iterate over elements and models
1240     mesh_element_iterator_t element_it;
1241     mesh_element_iterator_init(&element_it);
1242     while (mesh_element_iterator_has_next(&element_it)){
1243         mesh_element_t * element = mesh_element_iterator_next(&element_it);
1244         mesh_model_iterator_t model_it;
1245         mesh_model_iterator_init(&model_it, element);
1246         while (mesh_model_iterator_has_next(&model_it)){
1247             mesh_model_t * model = mesh_model_iterator_next(&model_it);
1248             mesh_load_appkey_list(model);
1249         }
1250     }
1251 }
1252 
1253 void mesh_delete_appkey_lists(void){
1254     printf("Delete Appkey Lists\n");
1255     mesh_access_setup_tlv();
1256     // iterate over elements and models
1257     mesh_element_iterator_t element_it;
1258     mesh_element_iterator_init(&element_it);
1259     while (mesh_element_iterator_has_next(&element_it)){
1260         mesh_element_t * element = mesh_element_iterator_next(&element_it);
1261         mesh_model_iterator_t model_it;
1262         mesh_model_iterator_init(&model_it, element);
1263         while (mesh_model_iterator_has_next(&model_it)){
1264             mesh_model_t * model = mesh_model_iterator_next(&model_it);
1265             mesh_delete_appkey_list(model);
1266         }
1267     }
1268 }
1269 
1270 void mesh_model_reset_appkeys(mesh_model_t * mesh_model){
1271     uint16_t i;
1272     for (i=0;i<MAX_NR_MESH_APPKEYS_PER_MODEL;i++){
1273         mesh_model->appkey_indices[i] = MESH_APPKEY_INVALID;
1274     }
1275 }
1276 
1277 uint8_t mesh_model_bind_appkey(mesh_model_t * mesh_model, uint16_t appkey_index){
1278     uint16_t i;
1279     for (i=0;i<MAX_NR_MESH_APPKEYS_PER_MODEL;i++){
1280         if (mesh_model->appkey_indices[i] == appkey_index) return MESH_FOUNDATION_STATUS_SUCCESS;
1281     }
1282     for (i=0;i<MAX_NR_MESH_APPKEYS_PER_MODEL;i++){
1283         if (mesh_model->appkey_indices[i] == MESH_APPKEY_INVALID) {
1284             mesh_model->appkey_indices[i] = appkey_index;
1285             mesh_store_appkey_list(mesh_model);
1286             return MESH_FOUNDATION_STATUS_SUCCESS;
1287         }
1288     }
1289     return MESH_FOUNDATION_STATUS_INSUFFICIENT_RESOURCES;
1290 }
1291 
1292 void mesh_model_unbind_appkey(mesh_model_t * mesh_model, uint16_t appkey_index){
1293     uint16_t i;
1294     for (i=0;i<MAX_NR_MESH_APPKEYS_PER_MODEL;i++){
1295         if (mesh_model->appkey_indices[i] == appkey_index) {
1296             mesh_model->appkey_indices[i] = MESH_APPKEY_INVALID;
1297             mesh_store_appkey_list(mesh_model);
1298         }
1299     }
1300 }
1301 
1302 int mesh_model_contains_appkey(mesh_model_t * mesh_model, uint16_t appkey_index){
1303     uint16_t i;
1304     for (i=0;i<MAX_NR_MESH_APPKEYS_PER_MODEL;i++){
1305         if (mesh_model->appkey_indices[i] == appkey_index) return 1;
1306     }
1307     return 0;
1308 
1309 }
1310 
1311 // Mesh IV Index
1312 static uint32_t mesh_tag_for_iv_index_and_seq_number(void){
1313     return ((uint32_t) 'M' << 24) | ((uint32_t) 'F' << 16) | ((uint32_t) 'I' << 9) | ((uint32_t) 'S');
1314 }
1315 
1316 typedef struct {
1317     uint32_t iv_index;
1318     uint32_t seq_number;
1319 } iv_index_and_sequence_number_t;
1320 
1321 static uint32_t sequence_number_last_stored;
1322 static uint32_t sequence_number_storage_trigger;
1323 
1324 void mesh_store_iv_index_after_provisioning(uint32_t iv_index){
1325     iv_index_and_sequence_number_t data;
1326     mesh_access_setup_tlv();
1327     uint32_t tag = mesh_tag_for_iv_index_and_seq_number();
1328     data.iv_index   = iv_index;
1329     data.seq_number = 0;
1330     btstack_tlv_singleton_impl->store_tag(btstack_tlv_singleton_context, tag, (uint8_t *) &data, sizeof(data));
1331 
1332     sequence_number_last_stored = data.seq_number;
1333     sequence_number_storage_trigger = sequence_number_last_stored + MESH_SEQUENCE_NUMBER_STORAGE_INTERVAL;
1334 }
1335 
1336 void mesh_store_iv_index_and_sequence_number(void){
1337     iv_index_and_sequence_number_t data;
1338     mesh_access_setup_tlv();
1339     uint32_t tag = mesh_tag_for_iv_index_and_seq_number();
1340     data.iv_index   = mesh_get_iv_index();
1341     data.seq_number = mesh_sequence_number_peek();
1342     btstack_tlv_singleton_impl->store_tag(btstack_tlv_singleton_context, tag, (uint8_t *) &data, sizeof(data));
1343 
1344     sequence_number_last_stored = data.seq_number;
1345     sequence_number_storage_trigger = sequence_number_last_stored + MESH_SEQUENCE_NUMBER_STORAGE_INTERVAL;
1346 }
1347 
1348 int mesh_load_iv_index_and_sequence_number(uint32_t * iv_index, uint32_t * sequence_number){
1349     iv_index_and_sequence_number_t data;
1350     mesh_access_setup_tlv();
1351     uint32_t tag = mesh_tag_for_iv_index_and_seq_number();
1352     uint32_t len = btstack_tlv_singleton_impl->get_tag(btstack_tlv_singleton_context, tag, (uint8_t *) &data, sizeof(data));
1353     if (len == sizeof(iv_index_and_sequence_number_t)){
1354         *iv_index = data.iv_index;
1355         *sequence_number = data.seq_number;
1356         return 1;
1357     }
1358     return 0;
1359 }
1360 
1361 // higher layer
1362 static void mesh_persist_iv_index_and_sequence_number(void){
1363     if (mesh_sequence_number_peek() >= sequence_number_storage_trigger){
1364         mesh_store_iv_index_and_sequence_number();
1365     }
1366 }
1367 
1368 
1369 // Mesh Model Publication
1370 static btstack_timer_source_t mesh_access_publication_timer;
1371 
1372 static uint32_t mesh_model_publication_retransmit_count(uint8_t retransmit){
1373     return retransmit & 0x07u;
1374 }
1375 
1376 static uint32_t mesh_model_publication_retransmission_period_ms(uint8_t retransmit){
1377     return ((uint32_t)((retransmit >> 3) + 1)) * 50;
1378 }
1379 
1380 static void mesh_model_publication_setup_publication(mesh_publication_model_t * publication_model, uint32_t now){
1381 
1382     // set retransmit counter
1383     publication_model->retransmit_count = mesh_model_publication_retransmit_count(publication_model->retransmit);
1384 
1385     // schedule next publication or retransmission
1386     uint32_t publication_period_ms = mesh_access_transitions_step_ms_from_gdtt(publication_model->period);
1387 
1388     // set next publication
1389     if (publication_period_ms != 0){
1390         publication_model->next_publication_ms = now + publication_period_ms;
1391         publication_model->state = MESH_MODEL_PUBLICATION_STATE_W4_PUBLICATION_MS;
1392     }
1393 }
1394 
1395 static void mesh_model_publication_setup_retransmission(mesh_publication_model_t * publication_model, uint32_t now){
1396     uint8_t num_retransmits = mesh_model_publication_retransmit_count(publication_model->retransmit);
1397     if (num_retransmits == 0) return;
1398 
1399     // calc next retransmit time
1400     uint32_t retransmission_ms = now + mesh_model_publication_retransmission_period_ms(publication_model->retransmit);
1401 
1402     // ignore if retransmission would be after next publication timeout
1403     if (publication_model->state == MESH_MODEL_PUBLICATION_STATE_W4_PUBLICATION_MS){
1404         if (btstack_time_delta(retransmission_ms, publication_model->next_publication_ms) > 0) return;
1405     }
1406 
1407     // schedule next retransmission
1408     publication_model->next_retransmit_ms = retransmission_ms;
1409     publication_model->state = MESH_MODEL_PUBLICATION_STATE_W4_RETRANSMIT_MS;
1410 }
1411 
1412 static void mesh_model_publication_publish_now_model(mesh_model_t * mesh_model){
1413     mesh_publication_model_t * publication_model = mesh_model->publication_model;
1414     if (publication_model == NULL) return;
1415     if (publication_model->publish_state_fn == NULL) return;
1416     uint16_t dest = publication_model->address;
1417     if (dest == MESH_ADDRESS_UNSASSIGNED) return;
1418     uint16_t appkey_index = publication_model->appkey_index;
1419     mesh_transport_key_t * app_key = mesh_transport_key_get(appkey_index);
1420     if (app_key == NULL) return;
1421 
1422     // compose message
1423     mesh_pdu_t * pdu = (*publication_model->publish_state_fn)(mesh_model);
1424     if (pdu == NULL) return;
1425 
1426     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);
1427     mesh_upper_transport_send_access_pdu(pdu);
1428 }
1429 
1430 static void mesh_model_publication_run(btstack_timer_source_t * ts){
1431     UNUSED(ts);
1432 
1433     uint32_t now = btstack_run_loop_get_time_ms();
1434 
1435     // iterate over elements and models and handle time-based transitions
1436     mesh_element_iterator_t element_it;
1437     mesh_element_iterator_init(&element_it);
1438     while (mesh_element_iterator_has_next(&element_it)){
1439         mesh_element_t * element = mesh_element_iterator_next(&element_it);
1440         mesh_model_iterator_t model_it;
1441         mesh_model_iterator_init(&model_it, element);
1442         while (mesh_model_iterator_has_next(&model_it)){
1443             mesh_model_t * mesh_model = mesh_model_iterator_next(&model_it);
1444             mesh_publication_model_t * publication_model = mesh_model->publication_model;
1445             if (publication_model == NULL) continue;
1446 
1447             // schedule next
1448             switch (publication_model->state){
1449                 case MESH_MODEL_PUBLICATION_STATE_W4_PUBLICATION_MS:
1450                     if (btstack_time_delta(publication_model->next_publication_ms, now) > 0) break;
1451                     // timeout
1452                     publication_model->publish_now = 1;
1453                     // schedule next publication and retransmission
1454                     mesh_model_publication_setup_publication(publication_model, now);
1455                     mesh_model_publication_setup_retransmission(publication_model, now);
1456                     break;
1457                 case MESH_MODEL_PUBLICATION_STATE_W4_RETRANSMIT_MS:
1458                     if (btstack_time_delta(publication_model->next_retransmit_ms, now) > 0) break;
1459                     // timeout
1460                     publication_model->publish_now = 1;
1461                     publication_model->retransmit_count--;
1462                     // schedule next retransmission
1463                     mesh_model_publication_setup_retransmission(publication_model, now);
1464                     break;
1465                 default:
1466                     break;
1467             }
1468 
1469             if (publication_model->publish_now == 0) continue;
1470 
1471             publication_model->publish_now = 0;
1472             mesh_model_publication_publish_now_model(mesh_model);
1473         }
1474     }
1475 
1476     int32_t next_timeout_ms = 0;
1477     mesh_element_iterator_init(&element_it);
1478     while (mesh_element_iterator_has_next(&element_it)){
1479         mesh_element_t * element = mesh_element_iterator_next(&element_it);
1480         mesh_model_iterator_t model_it;
1481         mesh_model_iterator_init(&model_it, element);
1482         while (mesh_model_iterator_has_next(&model_it)){
1483             mesh_model_t * mesh_model = mesh_model_iterator_next(&model_it);
1484             mesh_publication_model_t * publication_model = mesh_model->publication_model;
1485             if (publication_model == NULL) continue;
1486 
1487             // schedule next
1488             int32_t timeout_delta_ms;
1489             switch (publication_model->state){
1490                 case MESH_MODEL_PUBLICATION_STATE_W4_PUBLICATION_MS:
1491                     timeout_delta_ms = btstack_time_delta(publication_model->next_publication_ms, now);
1492                     if (next_timeout_ms == 0 || timeout_delta_ms < next_timeout_ms){
1493                         next_timeout_ms = timeout_delta_ms;
1494                     }
1495                     break;
1496                 case MESH_MODEL_PUBLICATION_STATE_W4_RETRANSMIT_MS:
1497                     timeout_delta_ms = btstack_time_delta(publication_model->next_retransmit_ms, now);
1498                     if (next_timeout_ms == 0 || timeout_delta_ms < next_timeout_ms){
1499                         next_timeout_ms = timeout_delta_ms;
1500                     }
1501                     break;
1502                 default:
1503                     break;
1504             }
1505         }
1506     }
1507 
1508     // set timer
1509     if (next_timeout_ms == 0) return;
1510 
1511     btstack_run_loop_set_timer(&mesh_access_publication_timer, next_timeout_ms);
1512     btstack_run_loop_set_timer_handler(&mesh_access_publication_timer, mesh_model_publication_run);
1513     btstack_run_loop_add_timer(&mesh_access_publication_timer);
1514 }
1515 
1516 void mesh_model_publication_start(mesh_model_t * mesh_model){
1517     mesh_publication_model_t * publication_model = mesh_model->publication_model;
1518     if (publication_model == NULL) return;
1519 
1520     // reset state
1521     publication_model->state = MESH_MODEL_PUBLICATION_STATE_IDLE;
1522 
1523     // publish right away
1524     publication_model->publish_now = 1;
1525 
1526     // setup next publication and retransmission
1527     uint32_t now = btstack_run_loop_get_time_ms();
1528     mesh_model_publication_setup_publication(publication_model, now);
1529     mesh_model_publication_setup_retransmission(publication_model, now);
1530 
1531     mesh_model_publication_run(NULL);
1532 }
1533 
1534 void mesh_model_publication_stop(mesh_model_t * mesh_model){
1535     mesh_publication_model_t * publication_model = mesh_model->publication_model;
1536     if (publication_model == NULL) return;
1537 
1538     // reset state
1539     publication_model->state = MESH_MODEL_PUBLICATION_STATE_IDLE;
1540 }
1541 
1542 void mesh_access_state_changed(mesh_model_t * mesh_model){
1543     mesh_publication_model_t * publication_model = mesh_model->publication_model;
1544     if (publication_model == NULL) return;
1545     publication_model->publish_now = 1;
1546     mesh_model_publication_run(NULL);
1547 }
1548 
1549 void mesh_access_netkey_finalize(mesh_network_key_t * network_key){
1550     mesh_network_key_remove(network_key);
1551     mesh_delete_network_key(network_key->internal_index);
1552     btstack_memory_mesh_network_key_free(network_key);
1553 }
1554 
1555 void mesh_access_appkey_finalize(mesh_transport_key_t * transport_key){
1556     mesh_transport_key_remove(transport_key);
1557     mesh_delete_app_key(transport_key->appkey_index);
1558     btstack_memory_mesh_transport_key_free(transport_key);
1559 }
1560 
1561 void mesh_access_key_refresh_revoke_keys(mesh_subnet_t * subnet){
1562     // delete old netkey index
1563     mesh_access_netkey_finalize(subnet->old_key);
1564     subnet->old_key = subnet->new_key;
1565     subnet->new_key = NULL;
1566 
1567     // delete old appkeys, if any
1568     mesh_transport_key_iterator_t it;
1569     mesh_transport_key_iterator_init(&it, subnet->netkey_index);
1570     while (mesh_transport_key_iterator_has_more(&it)){
1571         mesh_transport_key_t * transport_key = mesh_transport_key_iterator_get_next(&it);
1572         if (transport_key->old_key == 0) continue;
1573         mesh_access_appkey_finalize(transport_key);
1574     }
1575 }
1576 
1577 static void mesh_access_secure_network_beacon_handler(uint8_t packet_type, uint16_t channel, uint8_t * packet, uint16_t size){
1578     UNUSED(channel);
1579     UNUSED(size);
1580 
1581     if (packet_type != MESH_BEACON_PACKET) return;
1582 
1583     // lookup subnet and netkey by network id
1584     uint8_t * beacon_network_id = &packet[2];
1585     mesh_subnet_iterator_t it;
1586     mesh_subnet_iterator_init(&it);
1587     mesh_subnet_t * subnet = NULL;
1588     uint8_t new_key = 0;
1589     while (mesh_subnet_iterator_has_more(&it)){
1590         mesh_subnet_t * item = mesh_subnet_iterator_get_next(&it);
1591         if (memcmp(item->old_key->network_id, beacon_network_id, 8) == 0 ) {
1592             subnet = item;
1593         }
1594         if (item->new_key != NULL && memcmp(item->new_key->network_id, beacon_network_id, 8) == 0 ) {
1595             subnet = item;
1596             new_key = 1;
1597         }
1598         break;
1599     }
1600     if (subnet == NULL) return;
1601 
1602     uint8_t flags = packet[1];
1603 
1604     // Key refresh via secure network beacons that are authenticated with new netkey
1605     if (new_key){
1606         // either first or second phase (in phase 0, new key is not set)
1607         int key_refresh_flag = flags & 1;
1608         if (key_refresh_flag){
1609             //  transition to phase 3 from either phase 1 or 2
1610             switch (subnet->key_refresh){
1611                 case MESH_KEY_REFRESH_FIRST_PHASE:
1612                 case MESH_KEY_REFRESH_SECOND_PHASE:
1613                     mesh_access_key_refresh_revoke_keys(subnet);
1614                     subnet->key_refresh = MESH_KEY_REFRESH_NOT_ACTIVE;
1615                     break;
1616                 default:
1617                     break;
1618             }
1619         } else {
1620             //  transition to phase 2 from either phase 1
1621             switch (subnet->key_refresh){
1622                 case MESH_KEY_REFRESH_FIRST_PHASE:
1623                     // -- update state
1624                     subnet->key_refresh = MESH_KEY_REFRESH_SECOND_PHASE;
1625                     break;
1626                 default:
1627                     break;
1628             }
1629         }
1630     }
1631 
1632     // IV Update
1633 
1634     int     beacon_iv_update_active = flags & 2;
1635     int     local_iv_update_active = mesh_iv_update_active();
1636     uint32_t beacon_iv_index = big_endian_read_32(packet, 10);
1637     uint32_t local_iv_index = mesh_get_iv_index();
1638 
1639     int32_t iv_index_delta = (int32_t)(beacon_iv_index - local_iv_index);
1640 
1641     // "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
1642     //  the last known IV Index + 42, the Secure Network beacon shall be ignored."
1643     if (iv_index_delta < 0 || iv_index_delta > 42){
1644         return;
1645     }
1646 
1647     // "If a node in Normal Operation receives a Secure Network beacon with an IV index equal to the last known IV index+1 and
1648     //  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
1649     //  an IV Index Recovery procedure (Section 3.10.6), or it may ignore the Secure Network beacon. The node makes the choice depending
1650     //  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.""
1651     if (local_iv_update_active == 0 && beacon_iv_update_active == 0 && iv_index_delta == 1){
1652         // instant iv update
1653         mesh_set_iv_index( beacon_iv_index );
1654         // store updated iv index
1655         mesh_store_iv_index_and_sequence_number();
1656         return;
1657     }
1658 
1659     // "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
1660     //  the last known IV Index of the primary subnet, the Secure Network beacon shall be ignored."
1661     int member_of_primary_subnet = mesh_subnet_get_by_netkey_index(0) != NULL;
1662     int beacon_on_secondary_subnet = subnet->netkey_index != 0;
1663     if (member_of_primary_subnet && beacon_on_secondary_subnet && iv_index_delta > 0){
1664         return;
1665     }
1666 
1667     // "If a node in Normal Operation receives a Secure Network beacon with an IV index greater than the last known IV Index + 1..."
1668     // "... it may initiate an IV Index Recovery procedure, see Section 3.10.6."
1669     if (local_iv_update_active == 0 && iv_index_delta > 1){
1670         // "Upon receiving and successfully authenticating a Secure Network beacon for a primary subnet... "
1671         int beacon_on_primary_subnet = subnet->netkey_index == 0;
1672         if (!beacon_on_primary_subnet) return;
1673         // "... whose IV Index is 1 or more higher than the current known IV Index, the node shall "
1674         // " set its current IV Index and its current IV Update procedure state from the values in this Secure Network beacon."
1675         mesh_iv_index_recovered(beacon_iv_update_active, beacon_iv_index);
1676         // store updated iv index if in normal mode
1677         if (beacon_iv_update_active == 0){
1678             mesh_store_iv_index_and_sequence_number();
1679         }
1680         return;
1681     }
1682 
1683     if (local_iv_update_active == 0){
1684         if (beacon_iv_update_active){
1685             mesh_trigger_iv_update();
1686         }
1687     } else {
1688         if (beacon_iv_update_active == 0){
1689             // " At the point of transition, the node shall reset the sequence number to 0x000000."
1690             mesh_sequence_number_set(0);
1691             mesh_iv_update_completed();
1692             // store updated iv index
1693             mesh_store_iv_index_and_sequence_number();
1694         }
1695     }
1696 }
1697