xref: /btstack/src/mesh/mesh.c (revision a0253209c2d80682c681bcaad7ff6cfb5f4998e4)
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 
51 #include "mesh/adv_bearer.h"
52 #include "mesh/beacon.h"
53 #include "mesh/gatt_bearer.h"
54 #include "mesh/mesh_access.h"
55 #include "mesh/mesh_configuration_server.h"
56 #include "mesh/mesh_foundation.h"
57 #include "mesh/mesh_generic_model.h"
58 #include "mesh/mesh_generic_server.h"
59 #include "mesh/mesh_iv_index_seq_number.h"
60 #include "mesh/mesh_lower_transport.h"
61 #include "mesh/mesh_peer.h"
62 #include "mesh/mesh_proxy.h"
63 #include "mesh/mesh_upper_transport.h"
64 #include "mesh/mesh_virtual_addresses.h"
65 #include "mesh/pb_adv.h"
66 #include "mesh/pb_gatt.h"
67 #include "mesh/provisioning.h"
68 #include "mesh/provisioning_device.h"
69 
70 // Persistent storage structures
71 
72 typedef struct {
73     uint16_t netkey_index;
74 
75     uint8_t  version;
76 
77     // net_key from provisioner or Config Model Client
78     uint8_t net_key[16];
79 
80     // derived data
81 
82     // k1
83     uint8_t identity_key[16];
84     uint8_t beacon_key[16];
85 
86     // k3
87     uint8_t network_id[8];
88 
89     // k2
90     uint8_t nid;
91     uint8_t encryption_key[16];
92     uint8_t privacy_key[16];
93 } mesh_persistent_net_key_t;
94 
95 typedef struct {
96     uint16_t netkey_index;
97     uint16_t appkey_index;
98     uint8_t  aid;
99     uint8_t  version;
100     uint8_t  key[16];
101 } mesh_persistent_app_key_t;
102 
103 typedef struct {
104     uint8_t gatt_proxy;
105     uint8_t beacon;
106     uint8_t default_ttl;
107     uint8_t network_transmit;
108     uint8_t relay;
109     uint8_t relay_retransmit;
110     uint8_t friend;
111 } mesh_persistent_foundation_t;
112 
113 typedef struct {
114     uint32_t iv_index;
115     uint32_t seq_number;
116 } iv_index_and_sequence_number_t;
117 
118 static btstack_packet_handler_t provisioning_device_packet_handler;
119 static btstack_packet_callback_registration_t hci_event_callback_registration;
120 static int provisioned;
121 
122 // Mandatory Confiuration Server
123 static mesh_model_t                 mesh_configuration_server_model;
124 
125 // Mandatory Health Server
126 static mesh_model_t                 mesh_health_server_model;
127 static mesh_configuration_server_model_context_t mesh_configuration_server_model_context;
128 
129 // Random UUID on start
130 static btstack_crypto_random_t mesh_access_crypto_random;
131 static uint8_t random_device_uuid[16];
132 
133 // TLV
134 static const btstack_tlv_t * btstack_tlv_singleton_impl;
135 static void *                btstack_tlv_singleton_context;
136 
137 // IV Index persistence
138 static uint32_t sequence_number_last_stored;
139 static uint32_t sequence_number_storage_trigger;
140 
141 
142 void mesh_access_setup_from_provisioning_data(const mesh_provisioning_data_t * provisioning_data){
143 
144     // set iv_index and iv index update active
145     int iv_index_update_active = (provisioning_data->flags & 2) >> 1;
146     mesh_iv_index_recovered(iv_index_update_active, provisioning_data->iv_index);
147 
148     // set unicast address
149     mesh_node_primary_element_address_set(provisioning_data->unicast_address);
150 
151     // set device_key
152     mesh_transport_set_device_key(provisioning_data->device_key);
153 
154     if (provisioning_data->network_key){
155 
156         // setup primary network with provisioned netkey
157         mesh_network_key_add(provisioning_data->network_key);
158 
159         // setup primary network
160         mesh_subnet_setup_for_netkey_index(provisioning_data->network_key->netkey_index);
161 
162         // start sending Secure Network Beacons
163         mesh_subnet_t * provisioned_subnet = mesh_subnet_get_by_netkey_index(provisioning_data->network_key->netkey_index);
164         beacon_secure_network_start(provisioned_subnet);
165     }
166 
167     // Mesh Proxy
168 #ifdef ENABLE_MESH_PROXY_SERVER
169     // Setup Proxy
170     mesh_proxy_init(provisioning_data->unicast_address);
171     mesh_proxy_start_advertising_with_network_id();
172 #endif
173 }
174 
175 static void mesh_access_setup_unprovisioned_device(void * arg){
176     // set random value
177     if (arg == NULL){
178         mesh_node_set_device_uuid(random_device_uuid);
179     }
180 
181 #ifdef ENABLE_MESH_PB_ADV
182     // PB-ADV
183     beacon_unprovisioned_device_start(mesh_node_get_device_uuid(), 0);
184 #endif
185 #ifdef ENABLE_MESH_PB_GATT
186     mesh_proxy_start_advertising_unprovisioned_device();
187 #endif
188 }
189 
190 void mesh_access_setup_without_provisiong_data(void){
191     const uint8_t * device_uuid = mesh_node_get_device_uuid();
192     if (device_uuid){
193         mesh_access_setup_unprovisioned_device((void *)device_uuid);
194     } else{
195         btstack_crypto_random_generate(&mesh_access_crypto_random, random_device_uuid, 16, &mesh_access_setup_unprovisioned_device, NULL);
196     }
197 }
198 
199 static void mesh_provisioning_message_handler (uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
200     mesh_provisioning_data_t provisioning_data;
201 
202     switch(packet[0]){
203         case HCI_EVENT_MESH_META:
204             switch(packet[2]){
205                 case MESH_SUBEVENT_PB_PROV_COMPLETE:
206                     // get provisioning data
207                     provisioning_device_data_get(&provisioning_data);
208 
209                     // and store in TLV
210                     mesh_node_store_provisioning_data(&provisioning_data);
211 
212                     // setup node after provisioned
213                     mesh_access_setup_from_provisioning_data(&provisioning_data);
214 
215                     // start advertising with node id after provisioning
216                     mesh_proxy_set_advertising_with_node_id(provisioning_data.network_key->netkey_index, MESH_NODE_IDENTITY_STATE_ADVERTISING_RUNNING);
217 
218                     provisioned = 1;
219                     break;
220                 default:
221                     break;
222             }
223             break;
224         default:
225             break;
226     }
227     if (provisioning_device_packet_handler == NULL) return;
228 
229     // forward
230     (*provisioning_device_packet_handler)(packet_type, channel, packet, size);
231 }
232 
233 static void hci_packet_handler (uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
234     UNUSED(channel);
235     UNUSED(size);
236 
237     switch (packet_type) {
238         case HCI_EVENT_PACKET:
239             switch (hci_event_packet_get_type(packet)) {
240                 case BTSTACK_EVENT_STATE:
241                     if (btstack_event_state_get_state(packet) != HCI_STATE_WORKING) break;
242                     // get TLV instance
243                     btstack_tlv_get_instance(&btstack_tlv_singleton_impl, &btstack_tlv_singleton_context);
244 
245                     // startup from provisioning data stored in TLV
246                     provisioned = mesh_node_startup_from_tlv();
247                     break;
248 
249                 case HCI_EVENT_DISCONNECTION_COMPLETE:
250                     // enable PB_GATT
251                     if (provisioned == 0){
252                         mesh_proxy_start_advertising_unprovisioned_device();
253                     } else {
254 #ifdef ENABLE_MESH_PROXY_SERVER
255                         mesh_proxy_start_advertising_with_network_id();
256 #endif
257                     }
258                     break;
259 
260                 case HCI_EVENT_LE_META:
261                     if (hci_event_le_meta_get_subevent_code(packet) !=  HCI_SUBEVENT_LE_CONNECTION_COMPLETE) break;
262                     // disable PB_GATT
263                     mesh_proxy_stop_advertising_unprovisioned_device();
264                     break;
265                 default:
266                     break;
267             }
268             break;
269     }
270 }
271 
272 // Foundation state
273 static const uint32_t mesh_foundation_state_tag = ((uint32_t) 'M' << 24) | ((uint32_t) 'F' << 16)  | ((uint32_t) 'N' << 8) | ((uint32_t) 'D' << 8);
274 
275 void mesh_foundation_state_load(void){
276     mesh_persistent_foundation_t data;
277 
278     int foundation_state_len = btstack_tlv_singleton_impl->get_tag(btstack_tlv_singleton_context, mesh_foundation_state_tag, (uint8_t *) &data, sizeof(data));
279     if (foundation_state_len != sizeof(data)) return;
280 
281     mesh_foundation_gatt_proxy_set(data.gatt_proxy);
282     mesh_foundation_beacon_set(data.gatt_proxy);
283     mesh_foundation_default_ttl_set(data.default_ttl);
284     mesh_foundation_friend_set(data.friend);
285     mesh_foundation_network_transmit_set(data.network_transmit);
286     mesh_foundation_relay_set(data.relay);
287     mesh_foundation_relay_retransmit_set(data.relay_retransmit);
288 }
289 
290 void mesh_foundation_state_store(void){
291     mesh_persistent_foundation_t data;
292     data.gatt_proxy       = mesh_foundation_gatt_proxy_get();
293     data.gatt_proxy       = mesh_foundation_beacon_get();
294     data.default_ttl      = mesh_foundation_default_ttl_get();
295     data.friend           = mesh_foundation_friend_get();
296     data.network_transmit = mesh_foundation_network_transmit_get();
297     data.relay            = mesh_foundation_relay_get();
298     data.relay_retransmit = mesh_foundation_relay_retransmit_get();
299     btstack_tlv_singleton_impl->store_tag(btstack_tlv_singleton_context, mesh_foundation_state_tag, (uint8_t *) &data, sizeof(data));
300 }
301 
302 // Mesh Network Keys
303 static uint32_t mesh_network_key_tag_for_internal_index(uint16_t internal_index){
304     return ((uint32_t) 'M' << 24) | ((uint32_t) 'N' << 16) | ((uint32_t) internal_index);
305 }
306 
307 void mesh_store_network_key(mesh_network_key_t * network_key){
308     mesh_persistent_net_key_t data;
309     printf("Store NetKey: internal index 0x%x, NetKey Index 0x%06x, NID %02x: ", network_key->internal_index, network_key->netkey_index, network_key->nid);
310     printf_hexdump(network_key->net_key, 16);
311     uint32_t tag = mesh_network_key_tag_for_internal_index(network_key->internal_index);
312     data.netkey_index = network_key->netkey_index;
313     memcpy(data.net_key, network_key->net_key, 16);
314     memcpy(data.identity_key, network_key->identity_key, 16);
315     memcpy(data.beacon_key, network_key->beacon_key, 16);
316     memcpy(data.network_id, network_key->network_id, 8);
317     data.nid = network_key->nid;
318     data.version = network_key->version;
319     memcpy(data.encryption_key, network_key->encryption_key, 16);
320     memcpy(data.privacy_key, network_key->privacy_key, 16);
321     btstack_tlv_singleton_impl->store_tag(btstack_tlv_singleton_context, tag, (uint8_t *) &data, sizeof(mesh_persistent_net_key_t));
322 }
323 
324 void mesh_delete_network_key(uint16_t internal_index){
325     uint32_t tag = mesh_network_key_tag_for_internal_index(internal_index);
326     btstack_tlv_singleton_impl->delete_tag(btstack_tlv_singleton_context, tag);
327 }
328 
329 
330 void mesh_load_network_keys(void){
331     printf("Load Network Keys\n");
332     uint16_t internal_index;
333     for (internal_index = 0; internal_index < MAX_NR_MESH_NETWORK_KEYS; internal_index++){
334         mesh_persistent_net_key_t data;
335         uint32_t tag = mesh_network_key_tag_for_internal_index(internal_index);
336         int netkey_len = btstack_tlv_singleton_impl->get_tag(btstack_tlv_singleton_context, tag, (uint8_t *) &data, sizeof(data));
337         if (netkey_len != sizeof(mesh_persistent_net_key_t)) continue;
338 
339         mesh_network_key_t * network_key = btstack_memory_mesh_network_key_get();
340         if (network_key == NULL) return;
341 
342         network_key->netkey_index = data.netkey_index;
343         memcpy(network_key->net_key, data.net_key, 16);
344         memcpy(network_key->identity_key, data.identity_key, 16);
345         memcpy(network_key->beacon_key, data.beacon_key, 16);
346         memcpy(network_key->network_id, data.network_id, 8);
347         network_key->nid = data.nid;
348         network_key->version = data.version;
349         memcpy(network_key->encryption_key, data.encryption_key, 16);
350         memcpy(network_key->privacy_key, data.privacy_key, 16);
351 
352 #ifdef ENABLE_GATT_BEARER
353         // setup advertisement with network id
354         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);
355 #endif
356 
357         mesh_network_key_add(network_key);
358 
359         mesh_subnet_setup_for_netkey_index(network_key->netkey_index);
360 
361         printf("- internal index 0x%x, NetKey Index 0x%06x, NID %02x: ", network_key->internal_index, network_key->netkey_index, network_key->nid);
362         printf_hexdump(network_key->net_key, 16);
363     }
364 }
365 
366 void mesh_delete_network_keys(void){
367     printf("Delete Network Keys\n");
368 
369     uint16_t internal_index;
370     for (internal_index = 0; internal_index < MAX_NR_MESH_NETWORK_KEYS; internal_index++){
371         mesh_delete_network_key(internal_index);
372     }
373 }
374 
375 // Mesh App Keys
376 
377 static uint32_t mesh_transport_key_tag_for_internal_index(uint16_t internal_index){
378     return ((uint32_t) 'M' << 24) | ((uint32_t) 'A' << 16) | ((uint32_t) internal_index);
379 }
380 
381 void mesh_store_app_key(mesh_transport_key_t * app_key){
382     mesh_persistent_app_key_t data;
383     printf("Store AppKey: internal index 0x%x, AppKey Index 0x%06x, AID %02x: ", app_key->internal_index, app_key->appkey_index, app_key->aid);
384     printf_hexdump(app_key->key, 16);
385     uint32_t tag = mesh_transport_key_tag_for_internal_index(app_key->internal_index);
386     data.netkey_index = app_key->netkey_index;
387     data.appkey_index = app_key->appkey_index;
388     data.aid = app_key->aid;
389     data.version = app_key->version;
390     memcpy(data.key, app_key->key, 16);
391     btstack_tlv_singleton_impl->store_tag(btstack_tlv_singleton_context, tag, (uint8_t *) &data, sizeof(data));
392 }
393 
394 void mesh_delete_app_key(uint16_t internal_index){
395     uint32_t tag = mesh_transport_key_tag_for_internal_index(internal_index);
396     btstack_tlv_singleton_impl->delete_tag(btstack_tlv_singleton_context, tag);
397 }
398 
399 void mesh_load_app_keys(void){
400     printf("Load App Keys\n");
401     uint16_t internal_index;
402     for (internal_index = 0; internal_index < MAX_NR_MESH_TRANSPORT_KEYS; internal_index++){
403         mesh_persistent_app_key_t data;
404         uint32_t tag = mesh_transport_key_tag_for_internal_index(internal_index);
405         int app_key_len = btstack_tlv_singleton_impl->get_tag(btstack_tlv_singleton_context, tag, (uint8_t *) &data, sizeof(data));
406         if (app_key_len == 0) continue;
407 
408         mesh_transport_key_t * key = btstack_memory_mesh_transport_key_get();
409         if (key == NULL) return;
410 
411         key->internal_index = internal_index;
412         key->appkey_index = data.appkey_index;
413         key->netkey_index = data.netkey_index;
414         key->aid          = data.aid;
415         key->akf          = 1;
416         key->version      = data.version;
417         memcpy(key->key, data.key, 16);
418         mesh_transport_key_add(key);
419         printf("- internal index 0x%x, AppKey Index 0x%06x, AID %02x: ", key->internal_index, key->appkey_index, key->aid);
420         printf_hexdump(key->key, 16);
421     }
422 }
423 
424 void mesh_delete_app_keys(void){
425     printf("Delete App Keys\n");
426 
427     uint16_t internal_index;
428     for (internal_index = 0; internal_index < MAX_NR_MESH_TRANSPORT_KEYS; internal_index++){
429         mesh_delete_app_key(internal_index);
430     }
431 }
432 
433 
434 // Model to Appkey List
435 
436 static uint32_t mesh_model_tag_for_index(uint16_t internal_model_id){
437     return ((uint32_t) 'M' << 24) | ((uint32_t) 'B' << 16) | ((uint32_t) internal_model_id);
438 }
439 
440 static void mesh_load_appkey_list(mesh_model_t * model){
441     uint32_t tag = mesh_model_tag_for_index(model->mid);
442     btstack_tlv_singleton_impl->get_tag(btstack_tlv_singleton_context, tag, (uint8_t *) &model->appkey_indices, sizeof(model->appkey_indices));
443 }
444 
445 static void mesh_store_appkey_list(mesh_model_t * model){
446     uint32_t tag = mesh_model_tag_for_index(model->mid);
447     btstack_tlv_singleton_impl->store_tag(btstack_tlv_singleton_context, tag, (uint8_t *) &model->appkey_indices, sizeof(model->appkey_indices));
448 }
449 
450 static void mesh_delete_appkey_list(mesh_model_t * model){
451     uint32_t tag = mesh_model_tag_for_index(model->mid);
452     btstack_tlv_singleton_impl->delete_tag(btstack_tlv_singleton_context, tag);
453 }
454 
455 void mesh_load_appkey_lists(void){
456     printf("Load Appkey Lists\n");
457     // iterate over elements and models
458     mesh_element_iterator_t element_it;
459     mesh_element_iterator_init(&element_it);
460     while (mesh_element_iterator_has_next(&element_it)){
461         mesh_element_t * element = mesh_element_iterator_next(&element_it);
462         mesh_model_iterator_t model_it;
463         mesh_model_iterator_init(&model_it, element);
464         while (mesh_model_iterator_has_next(&model_it)){
465             mesh_model_t * model = mesh_model_iterator_next(&model_it);
466             mesh_load_appkey_list(model);
467         }
468     }
469 }
470 
471 void mesh_delete_appkey_lists(void){
472     printf("Delete Appkey Lists\n");
473     // iterate over elements and models
474     mesh_element_iterator_t element_it;
475     mesh_element_iterator_init(&element_it);
476     while (mesh_element_iterator_has_next(&element_it)){
477         mesh_element_t * element = mesh_element_iterator_next(&element_it);
478         mesh_model_iterator_t model_it;
479         mesh_model_iterator_init(&model_it, element);
480         while (mesh_model_iterator_has_next(&model_it)){
481             mesh_model_t * model = mesh_model_iterator_next(&model_it);
482             mesh_delete_appkey_list(model);
483         }
484     }
485 }
486 
487 void mesh_model_reset_appkeys(mesh_model_t * mesh_model){
488     uint16_t i;
489     for (i=0;i<MAX_NR_MESH_APPKEYS_PER_MODEL;i++){
490         mesh_model->appkey_indices[i] = MESH_APPKEY_INVALID;
491     }
492 }
493 
494 uint8_t mesh_model_bind_appkey(mesh_model_t * mesh_model, uint16_t appkey_index){
495     uint16_t i;
496     for (i=0;i<MAX_NR_MESH_APPKEYS_PER_MODEL;i++){
497         if (mesh_model->appkey_indices[i] == appkey_index) return MESH_FOUNDATION_STATUS_SUCCESS;
498     }
499     for (i=0;i<MAX_NR_MESH_APPKEYS_PER_MODEL;i++){
500         if (mesh_model->appkey_indices[i] == MESH_APPKEY_INVALID) {
501             mesh_model->appkey_indices[i] = appkey_index;
502             mesh_store_appkey_list(mesh_model);
503             return MESH_FOUNDATION_STATUS_SUCCESS;
504         }
505     }
506     return MESH_FOUNDATION_STATUS_INSUFFICIENT_RESOURCES;
507 }
508 
509 void mesh_model_unbind_appkey(mesh_model_t * mesh_model, uint16_t appkey_index){
510     uint16_t i;
511     for (i=0;i<MAX_NR_MESH_APPKEYS_PER_MODEL;i++){
512         if (mesh_model->appkey_indices[i] == appkey_index) {
513             mesh_model->appkey_indices[i] = MESH_APPKEY_INVALID;
514             mesh_store_appkey_list(mesh_model);
515         }
516     }
517 }
518 
519 int mesh_model_contains_appkey(mesh_model_t * mesh_model, uint16_t appkey_index){
520     uint16_t i;
521     for (i=0;i<MAX_NR_MESH_APPKEYS_PER_MODEL;i++){
522         if (mesh_model->appkey_indices[i] == appkey_index) return 1;
523     }
524     return 0;
525 }
526 
527 void mesh_access_netkey_finalize(mesh_network_key_t * network_key){
528     mesh_network_key_remove(network_key);
529     mesh_delete_network_key(network_key->internal_index);
530     btstack_memory_mesh_network_key_free(network_key);
531 }
532 
533 void mesh_access_appkey_finalize(mesh_transport_key_t * transport_key){
534     mesh_transport_key_remove(transport_key);
535     mesh_delete_app_key(transport_key->appkey_index);
536     btstack_memory_mesh_transport_key_free(transport_key);
537 }
538 
539 void mesh_access_key_refresh_revoke_keys(mesh_subnet_t * subnet){
540     // delete old netkey index
541     mesh_access_netkey_finalize(subnet->old_key);
542     subnet->old_key = subnet->new_key;
543     subnet->new_key = NULL;
544 
545     // delete old appkeys, if any
546     mesh_transport_key_iterator_t it;
547     mesh_transport_key_iterator_init(&it, subnet->netkey_index);
548     while (mesh_transport_key_iterator_has_more(&it)){
549         mesh_transport_key_t * transport_key = mesh_transport_key_iterator_get_next(&it);
550         if (transport_key->old_key == 0) continue;
551         mesh_access_appkey_finalize(transport_key);
552     }
553 }
554 
555 // Mesh IV Index
556 static uint32_t mesh_tag_for_iv_index_and_seq_number(void){
557     return ((uint32_t) 'M' << 24) | ((uint32_t) 'F' << 16) | ((uint32_t) 'I' << 9) | ((uint32_t) 'S');
558 }
559 
560 void mesh_store_iv_index_after_provisioning(uint32_t iv_index){
561     iv_index_and_sequence_number_t data;
562     uint32_t tag = mesh_tag_for_iv_index_and_seq_number();
563     data.iv_index   = iv_index;
564     data.seq_number = 0;
565     btstack_tlv_singleton_impl->store_tag(btstack_tlv_singleton_context, tag, (uint8_t *) &data, sizeof(data));
566 
567     sequence_number_last_stored = data.seq_number;
568     sequence_number_storage_trigger = sequence_number_last_stored + MESH_SEQUENCE_NUMBER_STORAGE_INTERVAL;
569 }
570 
571 void mesh_store_iv_index_and_sequence_number(void){
572     iv_index_and_sequence_number_t data;
573     uint32_t tag = mesh_tag_for_iv_index_and_seq_number();
574     data.iv_index   = mesh_get_iv_index();
575     data.seq_number = mesh_sequence_number_peek();
576     btstack_tlv_singleton_impl->store_tag(btstack_tlv_singleton_context, tag, (uint8_t *) &data, sizeof(data));
577 
578     sequence_number_last_stored = data.seq_number;
579     sequence_number_storage_trigger = sequence_number_last_stored + MESH_SEQUENCE_NUMBER_STORAGE_INTERVAL;
580 }
581 
582 int mesh_load_iv_index_and_sequence_number(uint32_t * iv_index, uint32_t * sequence_number){
583     iv_index_and_sequence_number_t data;
584     uint32_t tag = mesh_tag_for_iv_index_and_seq_number();
585     uint32_t len = btstack_tlv_singleton_impl->get_tag(btstack_tlv_singleton_context, tag, (uint8_t *) &data, sizeof(data));
586     if (len == sizeof(iv_index_and_sequence_number_t)){
587         *iv_index = data.iv_index;
588         *sequence_number = data.seq_number;
589         return 1;
590     }
591     return 0;
592 }
593 
594 // higher layer
595 static void mesh_persist_iv_index_and_sequence_number(void){
596     if (mesh_sequence_number_peek() >= sequence_number_storage_trigger){
597         mesh_store_iv_index_and_sequence_number();
598     }
599 }
600 
601 
602 static void mesh_node_setup_default_models(void){
603     // configure Config Server
604     mesh_configuration_server_model.model_identifier = mesh_model_get_model_identifier_bluetooth_sig(MESH_SIG_MODEL_ID_CONFIGURATION_SERVER);
605     mesh_configuration_server_model.model_data       = &mesh_configuration_server_model_context;
606     mesh_configuration_server_model.operations       = mesh_configuration_server_get_operations();
607     mesh_element_add_model(mesh_node_get_primary_element(), &mesh_configuration_server_model);
608 
609     // Config Health Server
610     mesh_health_server_model.model_identifier = mesh_model_get_model_identifier_bluetooth_sig(MESH_SIG_MODEL_ID_HEALTH_SERVER);
611     mesh_element_add_model(mesh_node_get_primary_element(), &mesh_health_server_model);
612 }
613 
614 void mesh_init(void){
615 
616     // register for HCI events
617     hci_event_callback_registration.callback = &hci_packet_handler;
618     hci_add_event_handler(&hci_event_callback_registration);
619 
620     // ADV Bearer also used for GATT Proxy Advertisements and PB-GATT
621     adv_bearer_init();
622 
623 #ifdef ENABLE_MESH_GATT_BEARER
624     // Setup GATT bearer
625     gatt_bearer_init();
626 #endif
627 
628 #ifdef ENABLE_MESH_ADV_BEARER
629     // Setup Unprovisioned Device Beacon
630     beacon_init();
631 #endif
632 
633     provisioning_device_init();
634 
635     // Node Configuration
636     mesh_node_init();
637 
638     // Network layer
639     mesh_network_init();
640 
641     // Transport layers (lower + upper))
642     mesh_lower_transport_init();
643     mesh_upper_transport_init();
644 
645     // Access layer
646     mesh_access_init();
647 
648     // Add mandatory models: Config Server and Health Server
649     mesh_node_setup_default_models();
650 
651     // register for seq number updates
652     mesh_sequence_number_set_update_callback(&mesh_persist_iv_index_and_sequence_number);
653 }
654 
655 /**
656  * Register for Mesh Provisioning Device events
657  * @param packet_handler
658  */
659 void mesh_register_provisioning_device_packet_handler(btstack_packet_handler_t packet_handler){
660     provisioning_device_packet_handler = packet_handler;
661     provisioning_device_register_packet_handler(&mesh_provisioning_message_handler);
662 }
663