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