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