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