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