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