xref: /btstack/src/mesh/mesh.c (revision 04a8a7d7e355cbae54a0864463d9191a9b13afae)
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                     // 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) continue;
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->internal_index = internal_index;
572         network_key->netkey_index = data.netkey_index;
573         memcpy(network_key->net_key, data.net_key, 16);
574         memcpy(network_key->identity_key, data.identity_key, 16);
575         memcpy(network_key->beacon_key, data.beacon_key, 16);
576         memcpy(network_key->network_id, data.network_id, 8);
577         network_key->nid = data.nid;
578         network_key->version = data.version;
579         memcpy(network_key->encryption_key, data.encryption_key, 16);
580         memcpy(network_key->privacy_key, data.privacy_key, 16);
581 
582 #ifdef ENABLE_GATT_BEARER
583         // setup advertisement with network id
584         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);
585 #endif
586 
587         mesh_network_key_add(network_key);
588 
589         mesh_subnet_setup_for_netkey_index(network_key->netkey_index);
590 
591         printf("- internal index 0x%x, NetKey Index 0x%06x, NID %02x: ", network_key->internal_index, network_key->netkey_index, network_key->nid);
592         printf_hexdump(network_key->net_key, 16);
593     }
594 }
595 
596 void mesh_delete_network_keys(void){
597     printf("Delete Network Keys\n");
598 
599     uint16_t internal_index;
600     for (internal_index = 0; internal_index < MAX_NR_MESH_NETWORK_KEYS; internal_index++){
601         mesh_delete_network_key(internal_index);
602     }
603 }
604 
605 // Mesh App Keys
606 
607 static uint32_t mesh_transport_key_tag_for_internal_index(uint16_t internal_index){
608     return ((uint32_t) 'M' << 24) | ((uint32_t) 'A' << 16) | ((uint32_t) internal_index);
609 }
610 
611 void mesh_store_app_key(mesh_transport_key_t * app_key){
612     mesh_persistent_app_key_t data;
613     printf("Store AppKey: internal index 0x%x, AppKey Index 0x%06x, AID %02x: ", app_key->internal_index, app_key->appkey_index, app_key->aid);
614     printf_hexdump(app_key->key, 16);
615     uint32_t tag = mesh_transport_key_tag_for_internal_index(app_key->internal_index);
616     data.netkey_index = app_key->netkey_index;
617     data.appkey_index = app_key->appkey_index;
618     data.aid = app_key->aid;
619     data.version = app_key->version;
620     memcpy(data.key, app_key->key, 16);
621     btstack_tlv_singleton_impl->store_tag(btstack_tlv_singleton_context, tag, (uint8_t *) &data, sizeof(data));
622 }
623 
624 void mesh_delete_app_key(uint16_t internal_index){
625     uint32_t tag = mesh_transport_key_tag_for_internal_index(internal_index);
626     btstack_tlv_singleton_impl->delete_tag(btstack_tlv_singleton_context, tag);
627 }
628 
629 void mesh_load_app_keys(void){
630     printf("Load App Keys\n");
631     uint16_t internal_index;
632     for (internal_index = 0; internal_index < MAX_NR_MESH_TRANSPORT_KEYS; internal_index++){
633         mesh_persistent_app_key_t data;
634         uint32_t tag = mesh_transport_key_tag_for_internal_index(internal_index);
635         int app_key_len = btstack_tlv_singleton_impl->get_tag(btstack_tlv_singleton_context, tag, (uint8_t *) &data, sizeof(data));
636         if (app_key_len == 0) continue;
637 
638         mesh_transport_key_t * key = btstack_memory_mesh_transport_key_get();
639         if (key == NULL) return;
640 
641         key->internal_index = internal_index;
642         key->appkey_index = data.appkey_index;
643         key->netkey_index = data.netkey_index;
644         key->aid          = data.aid;
645         key->akf          = 1;
646         key->version      = data.version;
647         memcpy(key->key, data.key, 16);
648         mesh_transport_key_add(key);
649         printf("- internal index 0x%x, AppKey Index 0x%06x, AID %02x: ", key->internal_index, key->appkey_index, key->aid);
650         printf_hexdump(key->key, 16);
651     }
652 }
653 
654 void mesh_delete_app_keys(void){
655     printf("Delete App Keys\n");
656 
657     uint16_t internal_index;
658     for (internal_index = 0; internal_index < MAX_NR_MESH_TRANSPORT_KEYS; internal_index++){
659         mesh_delete_app_key(internal_index);
660     }
661 }
662 
663 
664 // Model to Appkey List
665 
666 static uint32_t mesh_model_tag_for_index(uint16_t internal_model_id){
667     return ((uint32_t) 'M' << 24) | ((uint32_t) 'B' << 16) | ((uint32_t) internal_model_id);
668 }
669 
670 static void mesh_load_appkey_list(mesh_model_t * model){
671     uint32_t tag = mesh_model_tag_for_index(model->mid);
672     btstack_tlv_singleton_impl->get_tag(btstack_tlv_singleton_context, tag, (uint8_t *) &model->appkey_indices, sizeof(model->appkey_indices));
673 }
674 
675 static void mesh_store_appkey_list(mesh_model_t * model){
676     uint32_t tag = mesh_model_tag_for_index(model->mid);
677     btstack_tlv_singleton_impl->store_tag(btstack_tlv_singleton_context, tag, (uint8_t *) &model->appkey_indices, sizeof(model->appkey_indices));
678 }
679 
680 static void mesh_delete_appkey_list(mesh_model_t * model){
681     uint32_t tag = mesh_model_tag_for_index(model->mid);
682     btstack_tlv_singleton_impl->delete_tag(btstack_tlv_singleton_context, tag);
683 }
684 
685 void mesh_load_appkey_lists(void){
686     printf("Load Appkey Lists\n");
687     // iterate over elements and models
688     mesh_element_iterator_t element_it;
689     mesh_element_iterator_init(&element_it);
690     while (mesh_element_iterator_has_next(&element_it)){
691         mesh_element_t * element = mesh_element_iterator_next(&element_it);
692         mesh_model_iterator_t model_it;
693         mesh_model_iterator_init(&model_it, element);
694         while (mesh_model_iterator_has_next(&model_it)){
695             mesh_model_t * model = mesh_model_iterator_next(&model_it);
696             mesh_load_appkey_list(model);
697         }
698     }
699 }
700 
701 void mesh_delete_appkey_lists(void){
702     printf("Delete Appkey Lists\n");
703     // iterate over elements and models
704     mesh_element_iterator_t element_it;
705     mesh_element_iterator_init(&element_it);
706     while (mesh_element_iterator_has_next(&element_it)){
707         mesh_element_t * element = mesh_element_iterator_next(&element_it);
708         mesh_model_iterator_t model_it;
709         mesh_model_iterator_init(&model_it, element);
710         while (mesh_model_iterator_has_next(&model_it)){
711             mesh_model_t * model = mesh_model_iterator_next(&model_it);
712             mesh_delete_appkey_list(model);
713         }
714     }
715 }
716 
717 uint8_t mesh_model_bind_appkey(mesh_model_t * mesh_model, uint16_t appkey_index){
718     uint16_t i;
719     for (i=0;i<MAX_NR_MESH_APPKEYS_PER_MODEL;i++){
720         if (mesh_model->appkey_indices[i] == appkey_index) return MESH_FOUNDATION_STATUS_SUCCESS;
721     }
722     for (i=0;i<MAX_NR_MESH_APPKEYS_PER_MODEL;i++){
723         if (mesh_model->appkey_indices[i] == MESH_APPKEY_INVALID) {
724             mesh_model->appkey_indices[i] = appkey_index;
725             mesh_store_appkey_list(mesh_model);
726             return MESH_FOUNDATION_STATUS_SUCCESS;
727         }
728     }
729     return MESH_FOUNDATION_STATUS_INSUFFICIENT_RESOURCES;
730 }
731 
732 void mesh_model_unbind_appkey(mesh_model_t * mesh_model, uint16_t appkey_index){
733     uint16_t i;
734     for (i=0;i<MAX_NR_MESH_APPKEYS_PER_MODEL;i++){
735         if (mesh_model->appkey_indices[i] == appkey_index) {
736             mesh_model->appkey_indices[i] = MESH_APPKEY_INVALID;
737             mesh_store_appkey_list(mesh_model);
738         }
739     }
740 }
741 
742 int mesh_model_contains_appkey(mesh_model_t * mesh_model, uint16_t appkey_index){
743     uint16_t i;
744     for (i=0;i<MAX_NR_MESH_APPKEYS_PER_MODEL;i++){
745         if (mesh_model->appkey_indices[i] == appkey_index) return 1;
746     }
747     return 0;
748 }
749 
750 void mesh_access_netkey_finalize(mesh_network_key_t * network_key){
751     mesh_network_key_remove(network_key);
752     mesh_delete_network_key(network_key->internal_index);
753     btstack_memory_mesh_network_key_free(network_key);
754 }
755 
756 void mesh_access_appkey_finalize(mesh_transport_key_t * transport_key){
757     mesh_transport_key_remove(transport_key);
758     mesh_delete_app_key(transport_key->appkey_index);
759     btstack_memory_mesh_transport_key_free(transport_key);
760 }
761 
762 void mesh_access_key_refresh_revoke_keys(mesh_subnet_t * subnet){
763     // delete old netkey index
764     mesh_access_netkey_finalize(subnet->old_key);
765     subnet->old_key = subnet->new_key;
766     subnet->new_key = NULL;
767 
768     // delete old appkeys, if any
769     mesh_transport_key_iterator_t it;
770     mesh_transport_key_iterator_init(&it, subnet->netkey_index);
771     while (mesh_transport_key_iterator_has_more(&it)){
772         mesh_transport_key_t * transport_key = mesh_transport_key_iterator_get_next(&it);
773         if (transport_key->old_key == 0) continue;
774         mesh_access_appkey_finalize(transport_key);
775     }
776 }
777 
778 // Mesh IV Index
779 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');
780 
781 static int mesh_load_iv_index_and_sequence_number(uint32_t * iv_index, uint32_t * sequence_number){
782     iv_index_and_sequence_number_t data;
783     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));
784     if (len == sizeof(iv_index_and_sequence_number_t)){
785         *iv_index = data.iv_index;
786         *sequence_number = data.seq_number;
787         return 1;
788     }
789     return 0;
790 }
791 
792 static void mesh_store_iv_index_and_sequence_number(uint32_t iv_index, uint32_t sequence_number){
793     iv_index_and_sequence_number_t data;
794     data.iv_index   = iv_index;
795     data.seq_number = sequence_number;
796     btstack_tlv_singleton_impl->store_tag(btstack_tlv_singleton_context, mesh_tag_for_iv_index_and_seq_number, (uint8_t *) &data, sizeof(data));
797 
798     sequence_number_last_stored = data.seq_number;
799     sequence_number_storage_trigger = sequence_number_last_stored + MESH_SEQUENCE_NUMBER_STORAGE_INTERVAL;
800 }
801 
802 static void mesh_persist_iv_index_and_sequence_number(void){
803     mesh_store_iv_index_and_sequence_number(mesh_get_iv_index(), mesh_sequence_number_peek());
804 }
805 
806 
807 // higher layer - only store if sequence number is higher than trigger
808 static void mesh_persist_iv_index_and_sequence_number_if_needed(void){
809     if (mesh_sequence_number_peek() >= sequence_number_storage_trigger){
810         mesh_persist_iv_index_and_sequence_number();
811     }
812 }
813 
814 static void mesh_access_secure_network_beacon_handler(uint8_t packet_type, uint16_t channel, uint8_t * packet, uint16_t size){
815     UNUSED(channel);
816     UNUSED(size);
817 
818     if (packet_type != MESH_BEACON_PACKET) return;
819 
820     // lookup subnet and netkey by network id
821     uint8_t * beacon_network_id = &packet[2];
822     mesh_subnet_iterator_t it;
823     mesh_subnet_iterator_init(&it);
824     mesh_subnet_t * subnet = NULL;
825     uint8_t new_key = 0;
826     while (mesh_subnet_iterator_has_more(&it)){
827         mesh_subnet_t * item = mesh_subnet_iterator_get_next(&it);
828         if (memcmp(item->old_key->network_id, beacon_network_id, 8) == 0 ) {
829             subnet = item;
830         }
831         if (item->new_key != NULL && memcmp(item->new_key->network_id, beacon_network_id, 8) == 0 ) {
832             subnet = item;
833             new_key = 1;
834         }
835         break;
836     }
837     if (subnet == NULL) return;
838 
839     uint8_t flags = packet[1];
840 
841     // Key refresh via secure network beacons that are authenticated with new netkey
842     if (new_key){
843         // either first or second phase (in phase 0, new key is not set)
844         int key_refresh_flag = flags & 1;
845         if (key_refresh_flag){
846             //  transition to phase 3 from either phase 1 or 2
847             switch (subnet->key_refresh){
848                 case MESH_KEY_REFRESH_FIRST_PHASE:
849                 case MESH_KEY_REFRESH_SECOND_PHASE:
850                     mesh_access_key_refresh_revoke_keys(subnet);
851                     subnet->key_refresh = MESH_KEY_REFRESH_NOT_ACTIVE;
852                     break;
853                 default:
854                     break;
855             }
856         } else {
857             //  transition to phase 2 from either phase 1
858             switch (subnet->key_refresh){
859                 case MESH_KEY_REFRESH_FIRST_PHASE:
860                     // -- update state
861                     subnet->key_refresh = MESH_KEY_REFRESH_SECOND_PHASE;
862                     break;
863                 default:
864                     break;
865             }
866         }
867     }
868 
869     // IV Update
870 
871     int     beacon_iv_update_active = flags & 2;
872     int     local_iv_update_active = mesh_iv_update_active();
873     uint32_t beacon_iv_index = big_endian_read_32(packet, 10);
874     uint32_t local_iv_index = mesh_get_iv_index();
875 
876     int32_t iv_index_delta = (int32_t)(beacon_iv_index - local_iv_index);
877 
878     // "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
879     //  the last known IV Index + 42, the Secure Network beacon shall be ignored."
880     if (iv_index_delta < 0 || iv_index_delta > 42){
881         return;
882     }
883 
884     // "If a node in Normal Operation receives a Secure Network beacon with an IV index equal to the last known IV index+1 and
885     //  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
886     //  an IV Index Recovery procedure (Section 3.10.6), or it may ignore the Secure Network beacon. The node makes the choice depending
887     //  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.""
888     if (local_iv_update_active == 0 && beacon_iv_update_active == 0 && iv_index_delta == 1){
889         // instant iv update
890         mesh_set_iv_index( beacon_iv_index );
891         // store updated iv index
892         mesh_persist_iv_index_and_sequence_number();
893         return;
894     }
895 
896     // "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
897     //  the last known IV Index of the primary subnet, the Secure Network beacon shall be ignored."
898     int member_of_primary_subnet = mesh_subnet_get_by_netkey_index(0) != NULL;
899     int beacon_on_secondary_subnet = subnet->netkey_index != 0;
900     if (member_of_primary_subnet && beacon_on_secondary_subnet && iv_index_delta > 0){
901         return;
902     }
903 
904     // "If a node in Normal Operation receives a Secure Network beacon with an IV index greater than the last known IV Index + 1..."
905     // "... it may initiate an IV Index Recovery procedure, see Section 3.10.6."
906     if (local_iv_update_active == 0 && iv_index_delta > 1){
907         // "Upon receiving and successfully authenticating a Secure Network beacon for a primary subnet... "
908         int beacon_on_primary_subnet = subnet->netkey_index == 0;
909         if (!beacon_on_primary_subnet) return;
910         // "... whose IV Index is 1 or more higher than the current known IV Index, the node shall "
911         // " set its current IV Index and its current IV Update procedure state from the values in this Secure Network beacon."
912         mesh_iv_index_recovered(beacon_iv_update_active, beacon_iv_index);
913         // store updated iv index if in normal mode
914         if (beacon_iv_update_active == 0){
915             mesh_persist_iv_index_and_sequence_number();
916         }
917         return;
918     }
919 
920     if (local_iv_update_active == 0){
921         if (beacon_iv_update_active){
922             mesh_trigger_iv_update();
923         }
924     } else {
925         if (beacon_iv_update_active == 0){
926             // " At the point of transition, the node shall reset the sequence number to 0x000000."
927             mesh_sequence_number_set(0);
928             mesh_iv_update_completed();
929             // store updated iv index
930             mesh_persist_iv_index_and_sequence_number();
931         }
932     }
933 }
934 
935 static const uint32_t mesh_tag_for_prov_data = ((uint32_t) 'P' << 24) | ((uint32_t) 'R' << 16) | ((uint32_t) 'O' <<  8) | (uint32_t)'V';
936 
937 void mesh_node_reset(void){
938     // PROV
939     btstack_tlv_singleton_impl->delete_tag(btstack_tlv_singleton_context, mesh_tag_for_prov_data);
940     // everything else
941     mesh_delete_network_keys();
942     mesh_delete_app_keys();
943     mesh_delete_appkey_lists();
944     mesh_delete_virtual_addresses();
945     mesh_delete_subscriptions();
946     mesh_delete_publications();
947 }
948 
949 typedef struct {
950     uint16_t unicast_address;
951     uint8_t  flags;
952     uint8_t  device_key[16];
953 
954 } mesh_persistent_provisioning_data_t;
955 
956 static void mesh_node_store_provisioning_data(mesh_provisioning_data_t * provisioning_data){
957 
958     // fill persistent prov data
959     mesh_persistent_provisioning_data_t persistent_provisioning_data;
960 
961     persistent_provisioning_data.unicast_address = provisioning_data->unicast_address;
962     persistent_provisioning_data.flags = provisioning_data->flags;
963     memcpy(persistent_provisioning_data.device_key, provisioning_data->device_key, 16);
964 
965     // store in tlv
966     btstack_tlv_get_instance(&btstack_tlv_singleton_impl, &btstack_tlv_singleton_context);
967     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));
968 
969     // store IV Index and sequence number
970     mesh_store_iv_index_and_sequence_number(provisioning_data->iv_index, 0);
971 
972     // store primary network key
973     mesh_store_network_key(provisioning_data->network_key);
974 }
975 
976 static void mesh_access_setup_unprovisioned_device(const uint8_t * device_uuid){
977 #ifdef ENABLE_MESH_PB_ADV
978     // PB-ADV
979     beacon_unprovisioned_device_start(device_uuid, 0);
980 #else
981     UNUSED(device_uuid);;
982 #endif
983 #ifdef ENABLE_MESH_PB_GATT
984     mesh_proxy_start_advertising_unprovisioned_device();
985 #endif
986 }
987 
988 static void mesh_access_setup_without_provisiong_data_random(void * arg){
989     UNUSED(arg);
990     // set random value
991     mesh_node_set_device_uuid(random_device_uuid);
992     mesh_access_setup_unprovisioned_device(random_device_uuid);
993 }
994 
995 static void mesh_access_setup_with_provisiong_data_random(void * arg){
996     UNUSED(arg);
997     // set random value
998     mesh_node_set_device_uuid(random_device_uuid);
999 }
1000 
1001 static int mesh_node_startup_from_tlv(void){
1002 
1003     mesh_persistent_provisioning_data_t persistent_provisioning_data;
1004     btstack_tlv_get_instance(&btstack_tlv_singleton_impl, &btstack_tlv_singleton_context);
1005 
1006     // load provisioning data
1007     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));
1008     printf("Provisioning data available: %u\n", prov_len ? 1 : 0);
1009     int prov_data_valid = prov_len == sizeof(mesh_persistent_provisioning_data_t);
1010     if (prov_data_valid){
1011 
1012         // copy into mesh_provisioning_data
1013         mesh_provisioning_data_t provisioning_data;
1014         memcpy(provisioning_data.device_key, persistent_provisioning_data.device_key, 16);
1015         provisioning_data.unicast_address = persistent_provisioning_data.unicast_address;
1016         provisioning_data.flags = persistent_provisioning_data.flags;
1017         provisioning_data.network_key = NULL;
1018 
1019         printf("Flags %x, unicast_address %04x\n", persistent_provisioning_data.flags, provisioning_data.unicast_address);
1020 
1021         // load iv index and sequence number
1022         uint32_t iv_index;
1023         uint32_t sequence_number;
1024         int ok = mesh_load_iv_index_and_sequence_number(&iv_index, &sequence_number);
1025         if (ok){
1026             mesh_sequence_number_set(sequence_number);
1027             provisioning_data.iv_index = iv_index;
1028         }
1029 
1030         // load network keys
1031         mesh_load_network_keys();
1032         // load app keys
1033         mesh_load_app_keys();
1034         // load model to appkey bindings
1035         mesh_load_appkey_lists();
1036         // load virtual addresses
1037         mesh_load_virtual_addresses();
1038         // load model subscriptions
1039         mesh_load_subscriptions();
1040         // load model publications
1041         mesh_load_publications();
1042         // load foundation state
1043         mesh_foundation_state_load();
1044 
1045         mesh_access_setup_from_provisioning_data(&provisioning_data);
1046 
1047         // bump sequence number to account for interval updates
1048         sequence_number = mesh_sequence_number_peek() + MESH_SEQUENCE_NUMBER_STORAGE_INTERVAL;
1049         iv_index = mesh_get_iv_index();
1050         mesh_store_iv_index_and_sequence_number(iv_index, sequence_number);
1051         mesh_sequence_number_set(sequence_number);
1052         log_info("IV Index: %08x, Sequence Number %08x", (int) iv_index, (int) sequence_number);
1053 
1054         printf("IV Index: %08x, Sequence Number %08x\n", (int) iv_index, (int) sequence_number);
1055 
1056 #if defined(ENABLE_MESH_ADV_BEARER) || defined(ENABLE_MESH_PB_ADV)
1057         // start sending Secure Network Beacon
1058         mesh_subnet_t * subnet = mesh_subnet_get_by_netkey_index(0);
1059         if (subnet){
1060             beacon_secure_network_start(subnet);
1061         }
1062 #endif
1063         // create random uuid if not already set
1064         if (mesh_node_get_device_uuid() == NULL){
1065             btstack_crypto_random_generate(&mesh_access_crypto_random, random_device_uuid, 16, &mesh_access_setup_with_provisiong_data_random, NULL);
1066         }
1067 
1068     } else {
1069 
1070         const uint8_t * device_uuid = mesh_node_get_device_uuid();
1071         if (device_uuid){
1072             mesh_access_setup_unprovisioned_device(device_uuid);
1073         } else{
1074             btstack_crypto_random_generate(&mesh_access_crypto_random, random_device_uuid, 16, &mesh_access_setup_without_provisiong_data_random, NULL);
1075         }
1076 
1077     }
1078 
1079     return prov_data_valid;
1080 }
1081 
1082 
1083 static void mesh_node_setup_default_models(void){
1084     // configure Config Server
1085     mesh_configuration_server_model.model_identifier = mesh_model_get_model_identifier_bluetooth_sig(MESH_SIG_MODEL_ID_CONFIGURATION_SERVER);
1086     mesh_configuration_server_model.model_data       = &mesh_configuration_server_model_context;
1087     mesh_configuration_server_model.operations       = mesh_configuration_server_get_operations();
1088     mesh_element_add_model(mesh_node_get_primary_element(), &mesh_configuration_server_model);
1089 
1090     // Config Health Server
1091     mesh_health_server_model.model_identifier = mesh_model_get_model_identifier_bluetooth_sig(MESH_SIG_MODEL_ID_HEALTH_SERVER);
1092     mesh_element_add_model(mesh_node_get_primary_element(), &mesh_health_server_model);
1093 }
1094 
1095 void mesh_init(void){
1096 
1097     // register for HCI events
1098     hci_event_callback_registration.callback = &hci_packet_handler;
1099     hci_add_event_handler(&hci_event_callback_registration);
1100 
1101     // ADV Bearer also used for GATT Proxy Advertisements and PB-GATT
1102     adv_bearer_init();
1103 
1104 #ifdef ENABLE_MESH_GATT_BEARER
1105     // Setup GATT bearer
1106     gatt_bearer_init();
1107 #endif
1108 
1109 #ifdef ENABLE_MESH_ADV_BEARER
1110     // Setup Unprovisioned Device Beacon
1111     beacon_init();
1112 #endif
1113 
1114     provisioning_device_init();
1115     provisioning_device_register_packet_handler(&mesh_provisioning_message_handler);
1116 
1117     // Node Configuration
1118     mesh_node_init();
1119 
1120     // Network layer
1121     mesh_network_init();
1122 
1123     // Transport layers (lower + upper))
1124     mesh_lower_transport_init();
1125     mesh_upper_transport_init();
1126 
1127     // Access layer
1128     mesh_access_init();
1129 
1130     // Add mandatory models: Config Server and Health Server
1131     mesh_node_setup_default_models();
1132 
1133     // register for secure network beacons
1134     beacon_register_for_secure_network_beacons(&mesh_access_secure_network_beacon_handler);
1135 
1136     // register for seq number updates
1137     mesh_sequence_number_set_update_callback(&mesh_persist_iv_index_and_sequence_number_if_needed);
1138 }
1139 
1140 /**
1141  * Register for Mesh Provisioning Device events
1142  * @param packet_handler
1143  */
1144 void mesh_register_provisioning_device_packet_handler(btstack_packet_handler_t packet_handler){
1145     provisioning_device_packet_handler = packet_handler;
1146 }
1147