xref: /btstack/src/mesh/mesh.c (revision 293fd5fb21e86fbb29e9789cc0a2c06dafbbf1b3)
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.c"
39 
40 #include <string.h>
41 #include <stdio.h>
42 
43 #include "mesh/mesh.h"
44 
45 #include "btstack_util.h"
46 #include "btstack_config.h"
47 #include "btstack_event.h"
48 #include "btstack_tlv.h"
49 #include "btstack_memory.h"
50 #include "btstack_debug.h"
51 
52 #include "mesh/adv_bearer.h"
53 #include "mesh/beacon.h"
54 #include "mesh/gatt_bearer.h"
55 #include "mesh/mesh_access.h"
56 #include "mesh/mesh_configuration_server.h"
57 #include "mesh/mesh_health_server.h"
58 #include "mesh/mesh_foundation.h"
59 #include "mesh/mesh_generic_model.h"
60 #include "mesh/mesh_generic_on_off_server.h"
61 #include "mesh/mesh_iv_index_seq_number.h"
62 #include "mesh/mesh_lower_transport.h"
63 #include "mesh/mesh_peer.h"
64 #include "mesh/mesh_proxy.h"
65 #include "mesh/mesh_upper_transport.h"
66 #include "mesh/mesh_virtual_addresses.h"
67 #include "mesh/pb_adv.h"
68 #include "mesh/pb_gatt.h"
69 #include "mesh/provisioning.h"
70 #include "mesh/provisioning_device.h"
71 
72 static void mesh_node_store_provisioning_data(mesh_provisioning_data_t * provisioning_data);
73 static int mesh_node_startup_from_tlv(void);
74 
75 // Persistent storage structures
76 
77 typedef struct {
78     uint16_t  hash;
79     uint8_t   label_uuid[16];
80 } mesh_persistent_virtual_address_t;
81 
82 typedef struct {
83     uint16_t netkey_index;
84 
85     uint8_t  version;
86 
87     // net_key from provisioner or Config Model Client
88     uint8_t net_key[16];
89 
90     // derived data
91 
92     // k1
93     uint8_t identity_key[16];
94     uint8_t beacon_key[16];
95 
96     // k3
97     uint8_t network_id[8];
98 
99     // k2
100     uint8_t nid;
101     uint8_t encryption_key[16];
102     uint8_t privacy_key[16];
103 } mesh_persistent_net_key_t;
104 
105 typedef struct {
106     uint16_t netkey_index;
107     uint16_t appkey_index;
108     uint8_t  aid;
109     uint8_t  version;
110     uint8_t  key[16];
111 } mesh_persistent_app_key_t;
112 
113 typedef struct {
114     uint8_t gatt_proxy;
115     uint8_t beacon;
116     uint8_t default_ttl;
117     uint8_t network_transmit;
118     uint8_t relay;
119     uint8_t relay_retransmit;
120     uint8_t friend;
121 } mesh_persistent_foundation_t;
122 
123 typedef struct {
124     uint16_t publish_address;
125     uint16_t appkey_index;
126     uint8_t  friendship_credential_flag;
127     uint8_t  publish_period;
128     uint8_t  publish_ttl;
129     uint8_t  publish_retransmit;
130 } mesh_persistent_publication_t;
131 
132 typedef struct {
133     uint32_t iv_index;
134     uint32_t seq_number;
135 } iv_index_and_sequence_number_t;
136 
137 static btstack_packet_handler_t provisioning_device_packet_handler;
138 static btstack_packet_callback_registration_t hci_event_callback_registration;
139 static int provisioned;
140 
141 // Mandatory Confiuration Server
142 static mesh_model_t                 mesh_configuration_server_model;
143 static mesh_configuration_server_model_context_t mesh_configuration_server_model_context;
144 
145 // Mandatory Health Server
146 static mesh_model_t                 mesh_health_server_model;
147 static mesh_health_state_t  mesh_health_server_model_context;
148 
149 // Random UUID on start
150 static btstack_crypto_random_t mesh_access_crypto_random;
151 static uint8_t random_device_uuid[16];
152 
153 // TLV
154 static const btstack_tlv_t * btstack_tlv_singleton_impl;
155 static void *                btstack_tlv_singleton_context;
156 
157 // IV Index persistence
158 static uint32_t sequence_number_last_stored;
159 static uint32_t sequence_number_storage_trigger;
160 
161 // Attention Timer
162 static uint8_t                attention_timer_timeout_s;
163 static btstack_timer_source_t attention_timer_timer;
164 
165 // used to log all keys to packet log for log viewer
166 // mesh-appkey-0xxx: 1234567890abcdef1234567890abcdef
167 static void mesh_log_key(const char * prefix, uint16_t id, const uint8_t * key){
168     char line[60];
169     strcpy(line, prefix);
170     uint16_t pos = strlen(line);
171     if (id != 0xffff){
172         line[pos++] = '-';
173         line[pos++] = '0';
174         line[pos++] = char_for_nibble((id >> 8) & 0x0f);
175         line[pos++] = char_for_nibble((id >> 4) & 0x0f);
176         line[pos++] = char_for_nibble( id       & 0x0f);
177     }
178     line[pos++] = ':';
179     line[pos++] = ' ';
180     uint16_t i;
181     for (i=0;i<16;i++){
182         line[pos++] = char_for_nibble((key[i] >> 4) & 0x0f);
183         line[pos++] = char_for_nibble( key[i]       & 0x0f);
184     }
185     line[pos++] = 0;
186     hci_dump_log(HCI_DUMP_LOG_LEVEL_INFO, "%s", line);
187 }
188 
189 static void mesh_access_setup_from_provisioning_data(const mesh_provisioning_data_t * provisioning_data){
190 
191     // set iv_index and iv index update active
192     int iv_index_update_active = (provisioning_data->flags & 2) >> 1;
193     mesh_iv_index_recovered(iv_index_update_active, provisioning_data->iv_index);
194 
195     // set unicast address
196     mesh_node_primary_element_address_set(provisioning_data->unicast_address);
197 
198     // set device_key
199     mesh_transport_set_device_key(provisioning_data->device_key);
200 
201     if (provisioning_data->network_key){
202 
203         // setup primary network with provisioned netkey
204         mesh_network_key_add(provisioning_data->network_key);
205 
206         // setup primary network
207         mesh_subnet_setup_for_netkey_index(provisioning_data->network_key->netkey_index);
208 
209         // start sending Secure Network Beacons
210         mesh_subnet_t * provisioned_subnet = mesh_subnet_get_by_netkey_index(provisioning_data->network_key->netkey_index);
211         beacon_secure_network_start(provisioned_subnet);
212     }
213 
214     // Mesh Proxy
215 #ifdef ENABLE_MESH_PROXY_SERVER
216     // Setup Proxy
217     mesh_proxy_init(provisioning_data->unicast_address);
218     mesh_proxy_start_advertising_with_network_id();
219 #endif
220 }
221 
222 // Attention Timer state
223 static void mesh_emit_attention_timer_event(uint8_t timer_s){
224     if (!provisioning_device_packet_handler) return;
225     uint8_t event[4] = { HCI_EVENT_MESH_META, 4, MESH_SUBEVENT_ATTENTION_TIMER};
226     event[3] = timer_s;
227     provisioning_device_packet_handler(HCI_EVENT_PACKET, 0, event, sizeof(event));
228 }
229 
230 static void mesh_attention_timer_handler(btstack_timer_source_t * ts){
231     UNUSED(ts);
232     attention_timer_timeout_s--;
233     mesh_emit_attention_timer_event(attention_timer_timeout_s);
234     if (attention_timer_timeout_s == 0) return;
235 
236     btstack_run_loop_set_timer(&attention_timer_timer, 1000);
237     btstack_run_loop_add_timer(&attention_timer_timer);
238 }
239 
240 void mesh_attention_timer_set(uint8_t timer_s){
241     // stop old timer if running
242     if (attention_timer_timeout_s){
243         btstack_run_loop_remove_timer(&attention_timer_timer);
244     }
245 
246     attention_timer_timeout_s = timer_s;
247     mesh_emit_attention_timer_event(attention_timer_timeout_s);
248 
249     if (attention_timer_timeout_s){
250         btstack_run_loop_set_timer_handler(&attention_timer_timer, &mesh_attention_timer_handler);
251         btstack_run_loop_set_timer(&attention_timer_timer, 1000);
252         btstack_run_loop_add_timer(&attention_timer_timer);
253     }
254 }
255 
256 uint8_t mesh_attention_timer_get(void){
257     return attention_timer_timeout_s;
258 }
259 
260 static void mesh_provisioning_message_handler (uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
261     mesh_provisioning_data_t provisioning_data;
262     switch(packet[0]){
263         case HCI_EVENT_MESH_META:
264             switch(packet[2]){
265                 case MESH_SUBEVENT_PB_PROV_ATTENTION_TIMER:
266                     mesh_attention_timer_set(mesh_subevent_pb_prov_attention_timer_get_attention_time(packet));
267                     break;
268                 case MESH_SUBEVENT_PB_PROV_COMPLETE:
269                     // get provisioning data
270                     provisioning_device_data_get(&provisioning_data);
271 
272                     // and store in TLV
273                     mesh_node_store_provisioning_data(&provisioning_data);
274 
275                     // setup node after provisioned
276                     mesh_access_setup_from_provisioning_data(&provisioning_data);
277 
278 #ifdef ENABLE_MESH_PROXY_SERVER
279                     // start advertising with node id after provisioning
280                     mesh_proxy_set_advertising_with_node_id(provisioning_data.network_key->netkey_index, MESH_NODE_IDENTITY_STATE_ADVERTISING_RUNNING);
281 #endif
282 
283                     provisioned = 1;
284                     break;
285                 default:
286                     break;
287             }
288             break;
289         default:
290             break;
291     }
292     if (provisioning_device_packet_handler == NULL) return;
293 
294     // forward
295     (*provisioning_device_packet_handler)(packet_type, channel, packet, size);
296 }
297 
298 static void hci_packet_handler (uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
299     UNUSED(channel);
300     UNUSED(size);
301 
302     switch (packet_type) {
303         case HCI_EVENT_PACKET:
304             switch (hci_event_packet_get_type(packet)) {
305                 case BTSTACK_EVENT_STATE:
306                     if (btstack_event_state_get_state(packet) != HCI_STATE_WORKING) break;
307                     // get TLV instance
308                     btstack_tlv_get_instance(&btstack_tlv_singleton_impl, &btstack_tlv_singleton_context);
309 
310                     // startup from static provisioning data stored in TLV
311                     provisioned = mesh_node_startup_from_tlv();
312                     break;
313 
314 #ifdef ENABLE_MESH_PROXY_SERVER
315                 case HCI_EVENT_DISCONNECTION_COMPLETE:
316                     // enable PB_GATT
317                     if (provisioned == 0){
318                         mesh_proxy_start_advertising_unprovisioned_device();
319                     } else {
320                         mesh_proxy_start_advertising_with_network_id();
321                     }
322                     break;
323 
324                 case HCI_EVENT_LE_META:
325                     if (hci_event_le_meta_get_subevent_code(packet) !=  HCI_SUBEVENT_LE_CONNECTION_COMPLETE) break;
326                     // disable PB_GATT
327                     mesh_proxy_stop_advertising_unprovisioned_device();
328                     break;
329 #endif
330                 default:
331                     break;
332             }
333             break;
334     }
335 }
336 
337 // Foundation state
338 static const uint32_t mesh_foundation_state_tag = ((uint32_t) 'M' << 24) | ((uint32_t) 'F' << 16)  | ((uint32_t) 'N' << 8) | ((uint32_t) 'D' << 8);
339 
340 void mesh_foundation_state_load(void){
341     mesh_persistent_foundation_t data;
342 
343     int foundation_state_len = btstack_tlv_singleton_impl->get_tag(btstack_tlv_singleton_context, mesh_foundation_state_tag, (uint8_t *) &data, sizeof(data));
344     if (foundation_state_len != sizeof(data)) return;
345 
346     mesh_foundation_gatt_proxy_set(data.gatt_proxy);
347     mesh_foundation_beacon_set(data.beacon);
348     mesh_foundation_default_ttl_set(data.default_ttl);
349     mesh_foundation_friend_set(data.friend);
350     mesh_foundation_network_transmit_set(data.network_transmit);
351     mesh_foundation_relay_set(data.relay);
352     mesh_foundation_relay_retransmit_set(data.relay_retransmit);
353 }
354 
355 void mesh_foundation_state_store(void){
356     mesh_persistent_foundation_t data;
357     data.gatt_proxy       = mesh_foundation_gatt_proxy_get();
358     data.beacon           = mesh_foundation_beacon_get();
359     data.default_ttl      = mesh_foundation_default_ttl_get();
360     data.friend           = mesh_foundation_friend_get();
361     data.network_transmit = mesh_foundation_network_transmit_get();
362     data.relay            = mesh_foundation_relay_get();
363     data.relay_retransmit = mesh_foundation_relay_retransmit_get();
364     btstack_tlv_singleton_impl->store_tag(btstack_tlv_singleton_context, mesh_foundation_state_tag, (uint8_t *) &data, sizeof(data));
365 }
366 
367 // Mesh Virtual Address Management
368 static uint32_t mesh_virtual_address_tag_for_pseudo_dst(uint16_t pseudo_dst){
369     return ((uint32_t) 'M' << 24) | ((uint32_t) 'V' << 16) | ((uint32_t) pseudo_dst);
370 }
371 
372 static void mesh_store_virtual_address(uint16_t pseudo_dest, uint16_t hash, const uint8_t * label_uuid){
373     mesh_persistent_virtual_address_t data;
374     uint32_t tag = mesh_virtual_address_tag_for_pseudo_dst(pseudo_dest);
375     data.hash = hash;
376     memcpy(data.label_uuid, label_uuid, 16);
377     btstack_tlv_singleton_impl->store_tag(btstack_tlv_singleton_context, tag, (uint8_t *) &data, sizeof(data));
378 }
379 
380 static void mesh_delete_virtual_address(uint16_t pseudo_dest){
381     uint32_t tag = mesh_virtual_address_tag_for_pseudo_dst(pseudo_dest);
382     btstack_tlv_singleton_impl->delete_tag(btstack_tlv_singleton_context, tag);
383 }
384 
385 void mesh_load_virtual_addresses(void){
386     uint16_t pseudo_dst;
387     for (pseudo_dst = 0x8000; pseudo_dst < (0x8000 + MAX_NR_MESH_VIRTUAL_ADDRESSES); pseudo_dst++){
388         mesh_virtual_address_tag_for_pseudo_dst(pseudo_dst);
389         mesh_persistent_virtual_address_t data;
390         uint32_t tag = mesh_virtual_address_tag_for_pseudo_dst(pseudo_dst);
391         int virtual_address_len = btstack_tlv_singleton_impl->get_tag(btstack_tlv_singleton_context, tag, (uint8_t *) &data, sizeof(data));
392         if (virtual_address_len == 0) continue;
393 
394         mesh_virtual_address_t * virtual_address = btstack_memory_mesh_virtual_address_get();
395         if (virtual_address == NULL) return;
396 
397         virtual_address->pseudo_dst = pseudo_dst;
398         virtual_address->hash = data.hash;
399         memcpy(virtual_address->label_uuid, data.label_uuid, 16);
400         mesh_virtual_address_add(virtual_address);
401     }
402 }
403 
404 void mesh_delete_virtual_addresses(void){
405     uint16_t pseudo_dest;
406     for (pseudo_dest = 0x8000; pseudo_dest < (0x8000 + MAX_NR_MESH_VIRTUAL_ADDRESSES); pseudo_dest++){
407         mesh_delete_virtual_address(pseudo_dest);
408     }
409 }
410 
411 void mesh_virtual_address_decrease_refcount(mesh_virtual_address_t * virtual_address){
412     if (virtual_address == NULL){
413         log_error("virtual_address == NULL");
414     }
415     // decrease refcount
416     virtual_address->ref_count--;
417     // Free virtual address if ref count reaches zero
418     if (virtual_address->ref_count > 0) return;
419     // delete from TLV
420     mesh_delete_virtual_address(virtual_address->pseudo_dst);
421     // remove from list
422     mesh_virtual_address_remove(virtual_address);
423     // free memory
424     btstack_memory_mesh_virtual_address_free(virtual_address);
425 }
426 
427 void mesh_virtual_address_increase_refcount(mesh_virtual_address_t * virtual_address){
428     if (virtual_address == NULL){
429         log_error("virtual_address == NULL");
430     }
431     virtual_address->ref_count++;
432     if (virtual_address->ref_count > 1) return;
433     // store in TLV
434     mesh_store_virtual_address(virtual_address->pseudo_dst, virtual_address->hash, virtual_address->label_uuid);
435 }
436 
437 // Mesh Subscriptions
438 static uint32_t mesh_model_subscription_tag_for_index(uint16_t internal_model_id){
439     return ((uint32_t) 'M' << 24) | ((uint32_t) 'S' << 16) | ((uint32_t) internal_model_id);
440 }
441 
442 static void mesh_model_load_subscriptions(mesh_model_t * mesh_model){
443     uint32_t tag = mesh_model_subscription_tag_for_index(mesh_model->mid);
444     btstack_tlv_singleton_impl->get_tag(btstack_tlv_singleton_context, tag, (uint8_t *) &mesh_model->subscriptions, sizeof(mesh_model->subscriptions));
445     // update ref count
446 
447     // increase ref counts for virtual subscriptions
448     uint16_t i;
449     for (i = 0; i<MAX_NR_MESH_SUBSCRIPTION_PER_MODEL ; i++){
450         uint16_t src = mesh_model->subscriptions[i];
451         if (mesh_network_address_virtual(src)){
452             mesh_virtual_address_t * virtual_address = mesh_virtual_address_for_pseudo_dst(src);
453             mesh_virtual_address_increase_refcount(virtual_address);
454         }
455     }
456 }
457 
458 void mesh_model_store_subscriptions(mesh_model_t * model){
459     uint32_t tag = mesh_model_subscription_tag_for_index(model->mid);
460     btstack_tlv_singleton_impl->store_tag(btstack_tlv_singleton_context, tag, (uint8_t *) &model->subscriptions, sizeof(model->subscriptions));
461 }
462 
463 static void mesh_model_delete_subscriptions(mesh_model_t * model){
464     uint32_t tag = mesh_model_subscription_tag_for_index(model->mid);
465     btstack_tlv_singleton_impl->delete_tag(btstack_tlv_singleton_context, tag);
466 }
467 
468 void mesh_load_subscriptions(void){
469     printf("Load Model Subscription Lists\n");
470     // iterate over elements and models
471     mesh_element_iterator_t element_it;
472     mesh_element_iterator_init(&element_it);
473     while (mesh_element_iterator_has_next(&element_it)){
474         mesh_element_t * element = mesh_element_iterator_next(&element_it);
475         mesh_model_iterator_t model_it;
476         mesh_model_iterator_init(&model_it, element);
477         while (mesh_model_iterator_has_next(&model_it)){
478             mesh_model_t * model = mesh_model_iterator_next(&model_it);
479             mesh_model_load_subscriptions(model);
480         }
481     }
482 }
483 
484 void mesh_delete_subscriptions(void){
485     printf("Delete Model Subscription Lists\n");
486     // iterate over elements and models
487     mesh_element_iterator_t element_it;
488     mesh_element_iterator_init(&element_it);
489     while (mesh_element_iterator_has_next(&element_it)){
490         mesh_element_t * element = mesh_element_iterator_next(&element_it);
491         mesh_model_iterator_t model_it;
492         mesh_model_iterator_init(&model_it, element);
493         while (mesh_model_iterator_has_next(&model_it)){
494             mesh_model_t * model = mesh_model_iterator_next(&model_it);
495             mesh_model_delete_subscriptions(model);
496         }
497     }
498 }
499 
500 // Model Publication
501 
502 static uint32_t mesh_model_publication_tag_for_index(uint16_t internal_model_id){
503     return ((uint32_t) 'M' << 24) | ((uint32_t) 'P' << 16) | ((uint32_t) internal_model_id);
504 }
505 
506 static void mesh_model_load_publication(mesh_model_t * mesh_model){
507     mesh_publication_model_t * publication = mesh_model->publication_model;
508     if (publication == NULL) return;
509 
510     mesh_persistent_publication_t data;
511     uint32_t tag = mesh_model_publication_tag_for_index(mesh_model->mid);
512     btstack_tlv_singleton_impl->get_tag(btstack_tlv_singleton_context, tag, (uint8_t *) &data, sizeof(mesh_persistent_publication_t));
513 
514     publication->address                    = data.publish_address;
515     publication->appkey_index               = data.appkey_index;
516     publication->friendship_credential_flag = data.friendship_credential_flag;
517     publication->ttl                        = data.publish_ttl;
518     publication->period                     = data.publish_period;
519     publication->retransmit                 = data.publish_retransmit;
520 
521     // increase ref counts for current virtual publicataion address
522     uint16_t src = publication->address;
523     if (mesh_network_address_virtual(src)){
524         mesh_virtual_address_t * virtual_address = mesh_virtual_address_for_pseudo_dst(src);
525         if (virtual_address){
526             mesh_virtual_address_increase_refcount(virtual_address);
527         }
528     }
529 
530     mesh_model_publication_start(mesh_model);
531 }
532 
533 void mesh_model_store_publication(mesh_model_t * mesh_model){
534     mesh_publication_model_t * publication = mesh_model->publication_model;
535     if (publication == NULL) return;
536 
537     mesh_persistent_publication_t data;
538     data.publish_address            = publication->address;
539     data.appkey_index               = publication->appkey_index;
540     data.friendship_credential_flag = publication->friendship_credential_flag;
541     data.publish_ttl                = publication->ttl;
542     data.publish_period             = publication->period;
543     data.publish_retransmit         = publication->retransmit;
544     uint32_t tag = mesh_model_publication_tag_for_index(mesh_model->mid);
545     btstack_tlv_singleton_impl->store_tag(btstack_tlv_singleton_context, tag, (uint8_t *) &data, sizeof(mesh_persistent_publication_t));
546 }
547 
548 static void mesh_model_delete_publication(mesh_model_t * mesh_model){
549     if (mesh_model->publication_model == NULL) return;
550     uint32_t tag = mesh_model_publication_tag_for_index(mesh_model->mid);
551     btstack_tlv_singleton_impl->delete_tag(btstack_tlv_singleton_context, tag);
552 }
553 
554 void mesh_load_publications(void){
555     printf("Load Model Publications\n");
556     // iterate over elements and models
557     mesh_element_iterator_t element_it;
558     mesh_element_iterator_init(&element_it);
559     while (mesh_element_iterator_has_next(&element_it)){
560         mesh_element_t * element = mesh_element_iterator_next(&element_it);
561         mesh_model_iterator_t model_it;
562         mesh_model_iterator_init(&model_it, element);
563         while (mesh_model_iterator_has_next(&model_it)){
564             mesh_model_t * model = mesh_model_iterator_next(&model_it);
565             mesh_model_load_publication(model);
566         }
567     }
568 }
569 
570 void mesh_delete_publications(void){
571     printf("Delete Model Publications\n");
572     // iterate over elements and models
573     mesh_element_iterator_t element_it;
574     mesh_element_iterator_init(&element_it);
575     while (mesh_element_iterator_has_next(&element_it)){
576         mesh_element_t * element = mesh_element_iterator_next(&element_it);
577         mesh_model_iterator_t model_it;
578         mesh_model_iterator_init(&model_it, element);
579         while (mesh_model_iterator_has_next(&model_it)){
580             mesh_model_t * model = mesh_model_iterator_next(&model_it);
581             mesh_model_delete_publication(model);
582         }
583     }
584 }
585 
586 // Mesh Network Keys
587 static uint32_t mesh_network_key_tag_for_internal_index(uint16_t internal_index){
588     return ((uint32_t) 'M' << 24) | ((uint32_t) 'N' << 16) | ((uint32_t) internal_index);
589 }
590 
591 void mesh_store_network_key(mesh_network_key_t * network_key){
592     mesh_persistent_net_key_t data;
593     printf("Store NetKey: internal index 0x%x, NetKey Index 0x%06x, NID %02x: ", network_key->internal_index, network_key->netkey_index, network_key->nid);
594     printf_hexdump(network_key->net_key, 16);
595     uint32_t tag = mesh_network_key_tag_for_internal_index(network_key->internal_index);
596     data.netkey_index = network_key->netkey_index;
597     memcpy(data.net_key, network_key->net_key, 16);
598     memcpy(data.identity_key, network_key->identity_key, 16);
599     memcpy(data.beacon_key, network_key->beacon_key, 16);
600     memcpy(data.network_id, network_key->network_id, 8);
601     data.nid = network_key->nid;
602     data.version = network_key->version;
603     memcpy(data.encryption_key, network_key->encryption_key, 16);
604     memcpy(data.privacy_key, network_key->privacy_key, 16);
605     btstack_tlv_singleton_impl->store_tag(btstack_tlv_singleton_context, tag, (uint8_t *) &data, sizeof(mesh_persistent_net_key_t));
606 }
607 
608 void mesh_delete_network_key(uint16_t internal_index){
609     uint32_t tag = mesh_network_key_tag_for_internal_index(internal_index);
610     btstack_tlv_singleton_impl->delete_tag(btstack_tlv_singleton_context, tag);
611 }
612 
613 void mesh_load_network_keys(void){
614     printf("Load Network Keys\n");
615     uint16_t internal_index;
616     for (internal_index = 0; internal_index < MAX_NR_MESH_NETWORK_KEYS; internal_index++){
617         mesh_persistent_net_key_t data;
618         uint32_t tag = mesh_network_key_tag_for_internal_index(internal_index);
619         int netkey_len = btstack_tlv_singleton_impl->get_tag(btstack_tlv_singleton_context, tag, (uint8_t *) &data, sizeof(data));
620         if (netkey_len != sizeof(mesh_persistent_net_key_t)) continue;
621 
622         mesh_network_key_t * network_key = btstack_memory_mesh_network_key_get();
623         if (network_key == NULL) return;
624 
625         network_key->internal_index = internal_index;
626         network_key->netkey_index = data.netkey_index;
627         memcpy(network_key->net_key, data.net_key, 16);
628         memcpy(network_key->identity_key, data.identity_key, 16);
629         memcpy(network_key->beacon_key, data.beacon_key, 16);
630         memcpy(network_key->network_id, data.network_id, 8);
631         network_key->nid = data.nid;
632         network_key->version = data.version;
633         memcpy(network_key->encryption_key, data.encryption_key, 16);
634         memcpy(network_key->privacy_key, data.privacy_key, 16);
635 
636 #ifdef ENABLE_GATT_BEARER
637         // setup advertisement with network id
638         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);
639 #endif
640 
641         mesh_network_key_add(network_key);
642 
643         mesh_subnet_setup_for_netkey_index(network_key->netkey_index);
644 
645         printf("- internal index 0x%x, NetKey Index 0x%06x, NID %02x: ", network_key->internal_index, network_key->netkey_index, network_key->nid);
646         printf_hexdump(network_key->net_key, 16);
647 
648         // dump into packet log
649         mesh_log_key("mesh-netkey",  network_key->netkey_index, network_key->net_key);
650     }
651 }
652 
653 void mesh_delete_network_keys(void){
654     printf("Delete Network Keys\n");
655 
656     uint16_t internal_index;
657     for (internal_index = 0; internal_index < MAX_NR_MESH_NETWORK_KEYS; internal_index++){
658         mesh_delete_network_key(internal_index);
659     }
660 }
661 
662 // Mesh App Keys
663 
664 static uint32_t mesh_transport_key_tag_for_internal_index(uint16_t internal_index){
665     return ((uint32_t) 'M' << 24) | ((uint32_t) 'A' << 16) | ((uint32_t) internal_index);
666 }
667 
668 void mesh_store_app_key(mesh_transport_key_t * app_key){
669     mesh_persistent_app_key_t data;
670     printf("Store AppKey: internal index 0x%x, AppKey Index 0x%06x, AID %02x: ", app_key->internal_index, app_key->appkey_index, app_key->aid);
671     printf_hexdump(app_key->key, 16);
672     uint32_t tag = mesh_transport_key_tag_for_internal_index(app_key->internal_index);
673     data.netkey_index = app_key->netkey_index;
674     data.appkey_index = app_key->appkey_index;
675     data.aid = app_key->aid;
676     data.version = app_key->version;
677     memcpy(data.key, app_key->key, 16);
678     btstack_tlv_singleton_impl->store_tag(btstack_tlv_singleton_context, tag, (uint8_t *) &data, sizeof(data));
679 }
680 
681 void mesh_delete_app_key(uint16_t internal_index){
682     uint32_t tag = mesh_transport_key_tag_for_internal_index(internal_index);
683     btstack_tlv_singleton_impl->delete_tag(btstack_tlv_singleton_context, tag);
684 }
685 
686 void mesh_load_app_keys(void){
687     printf("Load App Keys\n");
688     uint16_t internal_index;
689     for (internal_index = 0; internal_index < MAX_NR_MESH_TRANSPORT_KEYS; internal_index++){
690         mesh_persistent_app_key_t data;
691         uint32_t tag = mesh_transport_key_tag_for_internal_index(internal_index);
692         int app_key_len = btstack_tlv_singleton_impl->get_tag(btstack_tlv_singleton_context, tag, (uint8_t *) &data, sizeof(data));
693         if (app_key_len == 0) continue;
694 
695         mesh_transport_key_t * key = btstack_memory_mesh_transport_key_get();
696         if (key == NULL) return;
697 
698         key->internal_index = internal_index;
699         key->appkey_index = data.appkey_index;
700         key->netkey_index = data.netkey_index;
701         key->aid          = data.aid;
702         key->akf          = 1;
703         key->version      = data.version;
704         memcpy(key->key, data.key, 16);
705         mesh_transport_key_add(key);
706         printf("- internal index 0x%x, AppKey Index 0x%06x, AID %02x: ", key->internal_index, key->appkey_index, key->aid);
707         printf_hexdump(key->key, 16);
708 
709         // dump into packet log
710         mesh_log_key("mesh-appkey",  key->appkey_index, key->key);
711     }
712 }
713 
714 void mesh_delete_app_keys(void){
715     printf("Delete App Keys\n");
716 
717     uint16_t internal_index;
718     for (internal_index = 0; internal_index < MAX_NR_MESH_TRANSPORT_KEYS; internal_index++){
719         mesh_delete_app_key(internal_index);
720     }
721 }
722 
723 
724 // Model to Appkey List
725 
726 static uint32_t mesh_model_tag_for_index(uint16_t internal_model_id){
727     return ((uint32_t) 'M' << 24) | ((uint32_t) 'B' << 16) | ((uint32_t) internal_model_id);
728 }
729 
730 static void mesh_load_appkey_list(mesh_model_t * model){
731     uint32_t tag = mesh_model_tag_for_index(model->mid);
732     btstack_tlv_singleton_impl->get_tag(btstack_tlv_singleton_context, tag, (uint8_t *) &model->appkey_indices, sizeof(model->appkey_indices));
733 }
734 
735 static void mesh_store_appkey_list(mesh_model_t * model){
736     uint32_t tag = mesh_model_tag_for_index(model->mid);
737     btstack_tlv_singleton_impl->store_tag(btstack_tlv_singleton_context, tag, (uint8_t *) &model->appkey_indices, sizeof(model->appkey_indices));
738 }
739 
740 static void mesh_delete_appkey_list(mesh_model_t * model){
741     uint32_t tag = mesh_model_tag_for_index(model->mid);
742     btstack_tlv_singleton_impl->delete_tag(btstack_tlv_singleton_context, tag);
743 }
744 
745 void mesh_load_appkey_lists(void){
746     printf("Load Appkey Lists\n");
747     // iterate over elements and models
748     mesh_element_iterator_t element_it;
749     mesh_element_iterator_init(&element_it);
750     while (mesh_element_iterator_has_next(&element_it)){
751         mesh_element_t * element = mesh_element_iterator_next(&element_it);
752         mesh_model_iterator_t model_it;
753         mesh_model_iterator_init(&model_it, element);
754         while (mesh_model_iterator_has_next(&model_it)){
755             mesh_model_t * model = mesh_model_iterator_next(&model_it);
756             mesh_load_appkey_list(model);
757         }
758     }
759 }
760 
761 void mesh_delete_appkey_lists(void){
762     printf("Delete Appkey Lists\n");
763     // iterate over elements and models
764     mesh_element_iterator_t element_it;
765     mesh_element_iterator_init(&element_it);
766     while (mesh_element_iterator_has_next(&element_it)){
767         mesh_element_t * element = mesh_element_iterator_next(&element_it);
768         mesh_model_iterator_t model_it;
769         mesh_model_iterator_init(&model_it, element);
770         while (mesh_model_iterator_has_next(&model_it)){
771             mesh_model_t * model = mesh_model_iterator_next(&model_it);
772             mesh_delete_appkey_list(model);
773         }
774     }
775 }
776 
777 uint8_t mesh_model_bind_appkey(mesh_model_t * mesh_model, uint16_t appkey_index){
778     uint16_t i;
779     for (i=0;i<MAX_NR_MESH_APPKEYS_PER_MODEL;i++){
780         if (mesh_model->appkey_indices[i] == appkey_index) return MESH_FOUNDATION_STATUS_SUCCESS;
781     }
782     for (i=0;i<MAX_NR_MESH_APPKEYS_PER_MODEL;i++){
783         if (mesh_model->appkey_indices[i] == MESH_APPKEY_INVALID) {
784             mesh_model->appkey_indices[i] = appkey_index;
785             mesh_store_appkey_list(mesh_model);
786             return MESH_FOUNDATION_STATUS_SUCCESS;
787         }
788     }
789     return MESH_FOUNDATION_STATUS_INSUFFICIENT_RESOURCES;
790 }
791 
792 void mesh_model_unbind_appkey(mesh_model_t * mesh_model, uint16_t appkey_index){
793     uint16_t i;
794     for (i=0;i<MAX_NR_MESH_APPKEYS_PER_MODEL;i++){
795         if (mesh_model->appkey_indices[i] == appkey_index) {
796             mesh_model->appkey_indices[i] = MESH_APPKEY_INVALID;
797             mesh_store_appkey_list(mesh_model);
798         }
799     }
800 }
801 
802 int mesh_model_contains_appkey(mesh_model_t * mesh_model, uint16_t appkey_index){
803     uint16_t i;
804     for (i=0;i<MAX_NR_MESH_APPKEYS_PER_MODEL;i++){
805         if (mesh_model->appkey_indices[i] == appkey_index) return 1;
806     }
807     return 0;
808 }
809 
810 void mesh_access_netkey_finalize(mesh_network_key_t * network_key){
811     mesh_network_key_remove(network_key);
812     mesh_delete_network_key(network_key->internal_index);
813     btstack_memory_mesh_network_key_free(network_key);
814 }
815 
816 void mesh_access_appkey_finalize(mesh_transport_key_t * transport_key){
817     mesh_transport_key_remove(transport_key);
818     mesh_delete_app_key(transport_key->appkey_index);
819     btstack_memory_mesh_transport_key_free(transport_key);
820 }
821 
822 void mesh_access_key_refresh_revoke_keys(mesh_subnet_t * subnet){
823     // delete old netkey index
824     mesh_access_netkey_finalize(subnet->old_key);
825     subnet->old_key = subnet->new_key;
826     subnet->new_key = NULL;
827 
828     // delete old appkeys, if any
829     mesh_transport_key_iterator_t it;
830     mesh_transport_key_iterator_init(&it, subnet->netkey_index);
831     while (mesh_transport_key_iterator_has_more(&it)){
832         mesh_transport_key_t * transport_key = mesh_transport_key_iterator_get_next(&it);
833         if (transport_key->old_key == 0) continue;
834         mesh_access_appkey_finalize(transport_key);
835     }
836 }
837 
838 // Mesh IV Index
839 static const uint32_t mesh_tag_for_iv_index_and_seq_number = ((uint32_t) 'M' << 24) | ((uint32_t) 'F' << 16) | ((uint32_t) 'I' << 9) | ((uint32_t) 'S');
840 
841 static int mesh_load_iv_index_and_sequence_number(uint32_t * iv_index, uint32_t * sequence_number){
842     iv_index_and_sequence_number_t data;
843     uint32_t len = btstack_tlv_singleton_impl->get_tag(btstack_tlv_singleton_context, mesh_tag_for_iv_index_and_seq_number, (uint8_t *) &data, sizeof(data));
844     if (len == sizeof(iv_index_and_sequence_number_t)){
845         *iv_index = data.iv_index;
846         *sequence_number = data.seq_number;
847         return 1;
848     }
849     return 0;
850 }
851 
852 static void mesh_store_iv_index_and_sequence_number(uint32_t iv_index, uint32_t sequence_number){
853     iv_index_and_sequence_number_t data;
854     data.iv_index   = iv_index;
855     data.seq_number = sequence_number;
856     btstack_tlv_singleton_impl->store_tag(btstack_tlv_singleton_context, mesh_tag_for_iv_index_and_seq_number, (uint8_t *) &data, sizeof(data));
857 
858     sequence_number_last_stored = data.seq_number;
859     sequence_number_storage_trigger = sequence_number_last_stored + MESH_SEQUENCE_NUMBER_STORAGE_INTERVAL;
860 }
861 
862 static void mesh_persist_iv_index_and_sequence_number(void){
863     mesh_store_iv_index_and_sequence_number(mesh_get_iv_index(), mesh_sequence_number_peek());
864 }
865 
866 
867 // higher layer - only store if sequence number is higher than trigger
868 static void mesh_persist_iv_index_and_sequence_number_if_needed(void){
869     if (mesh_sequence_number_peek() >= sequence_number_storage_trigger){
870         mesh_persist_iv_index_and_sequence_number();
871     }
872 }
873 
874 static void mesh_access_secure_network_beacon_handler(uint8_t packet_type, uint16_t channel, uint8_t * packet, uint16_t size){
875     UNUSED(channel);
876     UNUSED(size);
877 
878     if (packet_type != MESH_BEACON_PACKET) return;
879 
880     // lookup subnet and netkey by network id
881     uint8_t * beacon_network_id = &packet[2];
882     mesh_subnet_iterator_t it;
883     mesh_subnet_iterator_init(&it);
884     mesh_subnet_t * subnet = NULL;
885     uint8_t new_key = 0;
886     while (mesh_subnet_iterator_has_more(&it)){
887         mesh_subnet_t * item = mesh_subnet_iterator_get_next(&it);
888         if (memcmp(item->old_key->network_id, beacon_network_id, 8) == 0 ) {
889             subnet = item;
890         }
891         if (item->new_key != NULL && memcmp(item->new_key->network_id, beacon_network_id, 8) == 0 ) {
892             subnet = item;
893             new_key = 1;
894         }
895         break;
896     }
897     if (subnet == NULL) return;
898 
899     uint8_t flags = packet[1];
900 
901     // Key refresh via secure network beacons that are authenticated with new netkey
902     if (new_key){
903         // either first or second phase (in phase 0, new key is not set)
904         int key_refresh_flag = flags & 1;
905         if (key_refresh_flag){
906             //  transition to phase 3 from either phase 1 or 2
907             switch (subnet->key_refresh){
908                 case MESH_KEY_REFRESH_FIRST_PHASE:
909                 case MESH_KEY_REFRESH_SECOND_PHASE:
910                     mesh_access_key_refresh_revoke_keys(subnet);
911                     subnet->key_refresh = MESH_KEY_REFRESH_NOT_ACTIVE;
912                     break;
913                 default:
914                     break;
915             }
916         } else {
917             //  transition to phase 2 from either phase 1
918             switch (subnet->key_refresh){
919                 case MESH_KEY_REFRESH_FIRST_PHASE:
920                     // -- update state
921                     subnet->key_refresh = MESH_KEY_REFRESH_SECOND_PHASE;
922                     break;
923                 default:
924                     break;
925             }
926         }
927     }
928 
929     // IV Update
930 
931     int     beacon_iv_update_active = flags & 2;
932     int     local_iv_update_active = mesh_iv_update_active();
933     uint32_t beacon_iv_index = big_endian_read_32(packet, 10);
934     uint32_t local_iv_index = mesh_get_iv_index();
935 
936     int32_t iv_index_delta = (int32_t)(beacon_iv_index - local_iv_index);
937 
938     // "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
939     //  the last known IV Index + 42, the Secure Network beacon shall be ignored."
940     if (iv_index_delta < 0 || iv_index_delta > 42){
941         return;
942     }
943 
944     // "If a node in Normal Operation receives a Secure Network beacon with an IV index equal to the last known IV index+1 and
945     //  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
946     //  an IV Index Recovery procedure (Section 3.10.6), or it may ignore the Secure Network beacon. The node makes the choice depending
947     //  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.""
948     if (local_iv_update_active == 0 && beacon_iv_update_active == 0 && iv_index_delta == 1){
949         // instant iv update
950         mesh_set_iv_index( beacon_iv_index );
951         // store updated iv index
952         mesh_persist_iv_index_and_sequence_number();
953         return;
954     }
955 
956     // "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
957     //  the last known IV Index of the primary subnet, the Secure Network beacon shall be ignored."
958     int member_of_primary_subnet = mesh_subnet_get_by_netkey_index(0) != NULL;
959     int beacon_on_secondary_subnet = subnet->netkey_index != 0;
960     if (member_of_primary_subnet && beacon_on_secondary_subnet && iv_index_delta > 0){
961         return;
962     }
963 
964     // "If a node in Normal Operation receives a Secure Network beacon with an IV index greater than the last known IV Index + 1..."
965     // "... it may initiate an IV Index Recovery procedure, see Section 3.10.6."
966     if (local_iv_update_active == 0 && iv_index_delta > 1){
967         // "Upon receiving and successfully authenticating a Secure Network beacon for a primary subnet... "
968         int beacon_on_primary_subnet = subnet->netkey_index == 0;
969         if (!beacon_on_primary_subnet) return;
970         // "... whose IV Index is 1 or more higher than the current known IV Index, the node shall "
971         // " set its current IV Index and its current IV Update procedure state from the values in this Secure Network beacon."
972         mesh_iv_index_recovered(beacon_iv_update_active, beacon_iv_index);
973         // store updated iv index if in normal mode
974         if (beacon_iv_update_active == 0){
975             mesh_persist_iv_index_and_sequence_number();
976         }
977         return;
978     }
979 
980     if (local_iv_update_active == 0){
981         if (beacon_iv_update_active){
982             mesh_trigger_iv_update();
983         }
984     } else {
985         if (beacon_iv_update_active == 0){
986             // " At the point of transition, the node shall reset the sequence number to 0x000000."
987             mesh_sequence_number_set(0);
988             mesh_iv_update_completed();
989             // store updated iv index
990             mesh_persist_iv_index_and_sequence_number();
991         }
992     }
993 }
994 
995 static const uint32_t mesh_tag_for_prov_data = ((uint32_t) 'P' << 24) | ((uint32_t) 'R' << 16) | ((uint32_t) 'O' <<  8) | (uint32_t)'V';
996 
997 void mesh_node_reset(void){
998     // PROV
999     btstack_tlv_singleton_impl->delete_tag(btstack_tlv_singleton_context, mesh_tag_for_prov_data);
1000     // everything else
1001     mesh_delete_network_keys();
1002     mesh_delete_app_keys();
1003     mesh_delete_appkey_lists();
1004     mesh_delete_virtual_addresses();
1005     mesh_delete_subscriptions();
1006     mesh_delete_publications();
1007 }
1008 
1009 typedef struct {
1010     uint16_t unicast_address;
1011     uint8_t  flags;
1012     uint8_t  device_key[16];
1013 
1014 } mesh_persistent_provisioning_data_t;
1015 
1016 static void mesh_node_store_provisioning_data(mesh_provisioning_data_t * provisioning_data){
1017 
1018     // fill persistent prov data
1019     mesh_persistent_provisioning_data_t persistent_provisioning_data;
1020 
1021     persistent_provisioning_data.unicast_address = provisioning_data->unicast_address;
1022     persistent_provisioning_data.flags = provisioning_data->flags;
1023     memcpy(persistent_provisioning_data.device_key, provisioning_data->device_key, 16);
1024 
1025     // store in tlv
1026     btstack_tlv_get_instance(&btstack_tlv_singleton_impl, &btstack_tlv_singleton_context);
1027     btstack_tlv_singleton_impl->store_tag(btstack_tlv_singleton_context, mesh_tag_for_prov_data, (uint8_t *) &persistent_provisioning_data, sizeof(mesh_persistent_provisioning_data_t));
1028 
1029     // store IV Index and sequence number
1030     mesh_store_iv_index_and_sequence_number(provisioning_data->iv_index, 0);
1031 
1032     // store primary network key
1033     mesh_store_network_key(provisioning_data->network_key);
1034 }
1035 
1036 static void mesh_access_setup_unprovisioned_device(const uint8_t * device_uuid){
1037 #ifdef ENABLE_MESH_PB_ADV
1038     // PB-ADV
1039     beacon_unprovisioned_device_start(device_uuid, 0);
1040 #else
1041     UNUSED(device_uuid);;
1042 #endif
1043 #ifdef ENABLE_MESH_PB_GATT
1044     mesh_proxy_start_advertising_unprovisioned_device();
1045 #endif
1046 }
1047 
1048 static void mesh_access_setup_without_provisiong_data_random(void * arg){
1049     UNUSED(arg);
1050     // set random value
1051     mesh_node_set_device_uuid(random_device_uuid);
1052     mesh_access_setup_unprovisioned_device(random_device_uuid);
1053 }
1054 
1055 static void mesh_access_setup_with_provisiong_data_random(void * arg){
1056     UNUSED(arg);
1057     // set random value
1058     mesh_node_set_device_uuid(random_device_uuid);
1059 }
1060 
1061 static int mesh_node_startup_from_tlv(void){
1062 
1063     mesh_persistent_provisioning_data_t persistent_provisioning_data;
1064     btstack_tlv_get_instance(&btstack_tlv_singleton_impl, &btstack_tlv_singleton_context);
1065 
1066     // load provisioning data
1067     uint32_t prov_len = btstack_tlv_singleton_impl->get_tag(btstack_tlv_singleton_context, mesh_tag_for_prov_data, (uint8_t *) &persistent_provisioning_data, sizeof(mesh_persistent_provisioning_data_t));
1068     printf("Provisioning data available: %u\n", prov_len ? 1 : 0);
1069     int prov_data_valid = prov_len == sizeof(mesh_persistent_provisioning_data_t);
1070     if (prov_data_valid){
1071 
1072         // copy into mesh_provisioning_data
1073         mesh_provisioning_data_t provisioning_data;
1074         memcpy(provisioning_data.device_key, persistent_provisioning_data.device_key, 16);
1075         provisioning_data.unicast_address = persistent_provisioning_data.unicast_address;
1076         provisioning_data.flags = persistent_provisioning_data.flags;
1077         provisioning_data.network_key = NULL;
1078 
1079         // dump into packet log
1080         mesh_log_key("mesh-devkey",  0xffff, persistent_provisioning_data.device_key);
1081 
1082         printf("Flags %x, unicast_address %04x\n", persistent_provisioning_data.flags, provisioning_data.unicast_address);
1083 
1084         // load iv index and sequence number
1085         uint32_t iv_index;
1086         uint32_t sequence_number;
1087         int ok = mesh_load_iv_index_and_sequence_number(&iv_index, &sequence_number);
1088         if (ok){
1089             mesh_sequence_number_set(sequence_number);
1090             provisioning_data.iv_index = iv_index;
1091         }
1092 
1093         // dump into packet log
1094         hci_dump_log(HCI_DUMP_LOG_LEVEL_INFO, "mesh-iv-index: %08x",  iv_index);
1095 
1096         // load network keys
1097         mesh_load_network_keys();
1098         // load app keys
1099         mesh_load_app_keys();
1100         // load model to appkey bindings
1101         mesh_load_appkey_lists();
1102         // load virtual addresses
1103         mesh_load_virtual_addresses();
1104         // load model subscriptions
1105         mesh_load_subscriptions();
1106         // load model publications
1107         mesh_load_publications();
1108         // load foundation state
1109         mesh_foundation_state_load();
1110 
1111         mesh_access_setup_from_provisioning_data(&provisioning_data);
1112 
1113         // bump sequence number to account for interval updates
1114         sequence_number = mesh_sequence_number_peek() + MESH_SEQUENCE_NUMBER_STORAGE_INTERVAL;
1115         iv_index = mesh_get_iv_index();
1116         mesh_store_iv_index_and_sequence_number(iv_index, sequence_number);
1117         mesh_sequence_number_set(sequence_number);
1118         log_info("IV Index: %08x, Sequence Number %08x", (int) iv_index, (int) sequence_number);
1119 
1120         printf("IV Index: %08x, Sequence Number %08x\n", (int) iv_index, (int) sequence_number);
1121 
1122 #if defined(ENABLE_MESH_ADV_BEARER) || defined(ENABLE_MESH_PB_ADV)
1123         // start sending Secure Network Beacon
1124         mesh_subnet_t * subnet = mesh_subnet_get_by_netkey_index(0);
1125         if (subnet){
1126             beacon_secure_network_start(subnet);
1127         }
1128 #endif
1129         // create random uuid if not already set
1130         if (mesh_node_get_device_uuid() == NULL){
1131             btstack_crypto_random_generate(&mesh_access_crypto_random, random_device_uuid, 16, &mesh_access_setup_with_provisiong_data_random, NULL);
1132         }
1133 
1134     } else {
1135 
1136         const uint8_t * device_uuid = mesh_node_get_device_uuid();
1137         if (device_uuid){
1138             mesh_access_setup_unprovisioned_device(device_uuid);
1139         } else{
1140             btstack_crypto_random_generate(&mesh_access_crypto_random, random_device_uuid, 16, &mesh_access_setup_without_provisiong_data_random, NULL);
1141         }
1142 
1143     }
1144 
1145     return prov_data_valid;
1146 }
1147 
1148 static void mesh_control_message_handler(mesh_pdu_t * pdu){
1149     // get opcode
1150     uint8_t opcode = mesh_pdu_control_opcode(pdu);
1151     printf("Opcode: 0x%02x\n", opcode);
1152 
1153     uint8_t init_ttl;
1154     uint8_t hops = 0;
1155     uint16_t features = 0;
1156     switch(opcode){
1157         case 0x0a:
1158             // read params
1159             init_ttl = (*mesh_pdu_data(pdu)) & 0x7fu;
1160             features = big_endian_read_16(mesh_pdu_data(pdu), 1);
1161             // calculates hops
1162             hops     = init_ttl - mesh_pdu_ttl(pdu) + 1;
1163             // process heartbeat info
1164             mesh_configuration_server_process_heartbeat(&mesh_configuration_server_model, mesh_pdu_src(pdu), mesh_pdu_dst(pdu), hops, features);
1165             break;
1166         default:
1167             break;
1168     }
1169     mesh_upper_transport_message_processed_by_higher_layer(pdu);
1170 }
1171 
1172 static void mesh_node_setup_default_models(void){
1173     // configure Config Server
1174     mesh_configuration_server_model.model_identifier = mesh_model_get_model_identifier_bluetooth_sig(MESH_SIG_MODEL_ID_CONFIGURATION_SERVER);
1175     mesh_configuration_server_model.model_data       = &mesh_configuration_server_model_context;
1176     mesh_configuration_server_model.operations       = mesh_configuration_server_get_operations();
1177     mesh_element_add_model(mesh_node_get_primary_element(), &mesh_configuration_server_model);
1178 
1179     // Config Health Server
1180     mesh_health_server_model.model_identifier = mesh_model_get_model_identifier_bluetooth_sig(MESH_SIG_MODEL_ID_HEALTH_SERVER);
1181     mesh_health_server_model.model_data       = &mesh_health_server_model_context;
1182     mesh_health_server_model.operations       = mesh_health_server_get_operations();
1183     mesh_element_add_model(mesh_node_get_primary_element(), &mesh_health_server_model);
1184 }
1185 
1186 void mesh_init(void){
1187 
1188     // register for HCI events
1189     hci_event_callback_registration.callback = &hci_packet_handler;
1190     hci_add_event_handler(&hci_event_callback_registration);
1191 
1192     // ADV Bearer also used for GATT Proxy Advertisements and PB-GATT
1193     adv_bearer_init();
1194 
1195 #ifdef ENABLE_MESH_GATT_BEARER
1196     // Setup GATT bearer
1197     gatt_bearer_init();
1198 #endif
1199 
1200 #ifdef ENABLE_MESH_ADV_BEARER
1201     // Setup Unprovisioned Device Beacon
1202     beacon_init();
1203 #endif
1204 
1205     provisioning_device_init();
1206     provisioning_device_register_packet_handler(&mesh_provisioning_message_handler);
1207 
1208     // Node Configuration
1209     mesh_node_init();
1210 
1211     // Network layer
1212     mesh_network_init();
1213 
1214     // Transport layers (lower + upper))
1215     mesh_lower_transport_init();
1216     mesh_upper_transport_init();
1217 
1218     // Access layer
1219     mesh_access_init();
1220 
1221     // Add mandatory models: Config Server and Health Server
1222     mesh_node_setup_default_models();
1223 
1224     // register for secure network beacons
1225     beacon_register_for_secure_network_beacons(&mesh_access_secure_network_beacon_handler);
1226 
1227     // register for seq number updates
1228     mesh_sequence_number_set_update_callback(&mesh_persist_iv_index_and_sequence_number_if_needed);
1229 
1230     // register for control messages
1231     mesh_upper_transport_register_control_message_handler(&mesh_control_message_handler);
1232 }
1233 
1234 /**
1235  * Register for Mesh Provisioning Device events
1236  * @param packet_handler
1237  */
1238 void mesh_register_provisioning_device_packet_handler(btstack_packet_handler_t packet_handler){
1239     provisioning_device_packet_handler = packet_handler;
1240 }
1241