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