xref: /btstack/src/mesh/mesh_access.c (revision 68d9ac23974385a8674b68f1c8d442b9a23fa7b1)
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_access.c"
39 
40 #include <string.h>
41 #include <stdio.h>
42 #include <stdarg.h>
43 
44 #include "mesh/mesh_access.h"
45 
46 #include "btstack_debug.h"
47 #include "btstack_memory.h"
48 #include "btstack_tlv.h"
49 
50 #include "mesh/beacon.h"
51 #include "mesh/mesh_foundation.h"
52 #include "mesh/mesh_iv_index_seq_number.h"
53 #include "mesh/mesh_node.h"
54 #include "mesh/mesh_proxy.h"
55 #include "mesh/mesh_upper_transport.h"
56 #include "mesh/mesh.h"
57 
58 #define MEST_TRANSACTION_TIMEOUT_MS  6000
59 
60 static void mesh_access_message_process_handler(mesh_pdu_t * pdu);
61 static void mesh_access_secure_network_beacon_handler(uint8_t packet_type, uint16_t channel, uint8_t * packet, uint16_t size);
62 static void mesh_access_upper_transport_handler(mesh_transport_callback_type_t callback_type, mesh_transport_status_t status, mesh_pdu_t * pdu);
63 static const mesh_operation_t * mesh_model_lookup_operation_by_opcode(mesh_model_t * model, uint32_t opcode);
64 static void mesh_persist_iv_index_and_sequence_number(void);
65 
66 // acknowledged messages
67 static btstack_linked_list_t  mesh_access_acknowledged_messages;
68 static btstack_timer_source_t mesh_access_acknowledged_timer;
69 
70 static uint16_t mid_counter;
71 
72 static const btstack_tlv_t * btstack_tlv_singleton_impl;
73 static void *                btstack_tlv_singleton_context;
74 
75 // Transitions
76 static btstack_linked_list_t  transitions;
77 static btstack_timer_source_t transitions_timer;
78 static uint32_t transition_step_min_ms;
79 static uint8_t mesh_transaction_id_counter = 0;
80 
81 static void mesh_access_setup_tlv(void){
82     if (btstack_tlv_singleton_impl) return;
83     btstack_tlv_get_instance(&btstack_tlv_singleton_impl, &btstack_tlv_singleton_context);
84 }
85 
86 void mesh_access_init(void){
87     // register with upper transport
88     mesh_upper_transport_register_access_message_handler(&mesh_access_message_process_handler);
89     mesh_upper_transport_set_higher_layer_handler(&mesh_access_upper_transport_handler);
90 
91     // register for secure network beacons
92     beacon_register_for_secure_network_beacons(&mesh_access_secure_network_beacon_handler);
93 
94     // register for seq number updates
95     mesh_sequence_number_set_update_callback(&mesh_persist_iv_index_and_sequence_number);
96 }
97 
98 void mesh_access_emit_state_update_bool(btstack_packet_handler_t event_handler, uint8_t element_index, uint32_t model_identifier,
99     model_state_id_t state_identifier, model_state_update_reason_t reason, uint8_t value){
100     if (event_handler == NULL) return;
101     uint8_t event[14] = {HCI_EVENT_MESH_META, 12, MESH_SUBEVENT_STATE_UPDATE_BOOL};
102     int pos = 3;
103     event[pos++] = element_index;
104     little_endian_store_32(event, pos, model_identifier);
105     pos += 4;
106     little_endian_store_32(event, pos, (uint32_t)state_identifier);
107     pos += 4;
108     event[pos++] = (uint8_t)reason;
109     event[pos++] = value;
110     (*event_handler)(HCI_EVENT_PACKET, 0, event, sizeof(event));
111 }
112 
113 void mesh_access_emit_state_update_int16(btstack_packet_handler_t event_handler, uint8_t element_index, uint32_t model_identifier,
114     model_state_id_t state_identifier, model_state_update_reason_t reason, int16_t value){
115     if (event_handler == NULL) return;
116     uint8_t event[15] = {HCI_EVENT_MESH_META, 13, MESH_SUBEVENT_STATE_UPDATE_BOOL};
117     int pos = 3;
118     event[pos++] = element_index;
119     little_endian_store_32(event, pos, model_identifier);
120     pos += 4;
121     little_endian_store_32(event, pos, (uint32_t)state_identifier);
122     pos += 4;
123     event[pos++] = (uint8_t)reason;
124     little_endian_store_16(event, pos, (uint16_t) value);
125     pos += 2;
126     (*event_handler)(HCI_EVENT_PACKET, 0, event, sizeof(event));
127 }
128 
129 uint8_t mesh_access_acknowledged_message_retransmissions(void){
130     return 3;
131 }
132 
133 uint32_t mesh_access_acknowledged_message_timeout_ms(void){
134     return 30000;
135 }
136 
137 #define MESH_ACCESS_OPCODE_INVALID 0xFFFFFFFFu
138 
139 void mesh_access_send_unacknowledged_pdu(mesh_pdu_t * pdu){
140     pdu->ack_opcode = MESH_ACCESS_OPCODE_INVALID;;
141     mesh_upper_transport_send_access_pdu(pdu);
142 }
143 
144 void mesh_access_send_acknowledged_pdu(mesh_pdu_t * pdu, uint8_t retransmissions, uint32_t ack_opcode){
145     pdu->retransmit_count = retransmissions;
146     pdu->ack_opcode = ack_opcode;
147 
148     mesh_upper_transport_send_access_pdu(pdu);
149 }
150 
151 #define MESH_SUBEVENT_MESSAGE_NOT_ACKNOWLEDGED                                        0x30
152 
153 static void mesh_access_acknowledged_run(btstack_timer_source_t * ts){
154     UNUSED(ts);
155 
156     uint32_t now = btstack_run_loop_get_time_ms();
157 
158     // handle timeouts
159     btstack_linked_list_iterator_t ack_it;
160     btstack_linked_list_iterator_init(&ack_it, &mesh_access_acknowledged_messages);
161     while (btstack_linked_list_iterator_has_next(&ack_it)){
162         mesh_pdu_t * pdu = (mesh_pdu_t *) btstack_linked_list_iterator_next(&ack_it);
163         if (btstack_time_delta(now, pdu->retransmit_timeout_ms) >= 0) {
164             // remove from list
165             btstack_linked_list_remove(&mesh_access_acknowledged_messages, (btstack_linked_item_t*) pdu);
166             // retransmit or report failure
167             if (pdu->retransmit_count){
168                 pdu->retransmit_count--;
169                 mesh_upper_transport_send_access_pdu(pdu);
170             } else {
171                 // find correct model and emit error
172                 uint16_t src = mesh_pdu_src(pdu);
173                 uint16_t dst = mesh_pdu_dst(pdu);
174                 mesh_element_t * element = mesh_node_element_for_unicast_address(src);
175                 if (element){
176                     // find
177                     mesh_model_iterator_t model_it;
178                     mesh_model_iterator_init(&model_it, element);
179                     while (mesh_model_iterator_has_next(&model_it)){
180                         mesh_model_t * model = mesh_model_iterator_next(&model_it);
181                         // find opcode in table
182                         const mesh_operation_t * operation = mesh_model_lookup_operation_by_opcode(model, pdu->ack_opcode);
183                         if (operation == NULL) continue;
184                         if (model->model_packet_handler == NULL) continue;
185                         // emit event
186                         uint8_t event[13];
187                         event[0] = HCI_EVENT_MESH_META;
188                         event[1] = sizeof(event) - 2;
189                         event[2] = element->element_index;
190                         little_endian_store_32(event, 3, model->model_identifier);
191                         little_endian_store_32(event, 7, pdu->ack_opcode);
192                         little_endian_store_16(event, 11, dst);
193                         (*model->model_packet_handler)(HCI_EVENT_PACKET, 0, event, sizeof(event));
194                     }
195                 }
196 
197                 // free
198                 mesh_upper_transport_pdu_free(pdu);
199             }
200         }
201     }
202 
203     // find earliest timeout and set timer
204     btstack_linked_list_iterator_init(&ack_it, &mesh_access_acknowledged_messages);
205     int32_t next_timeout_ms = 0;
206     while (btstack_linked_list_iterator_has_next(&ack_it)){
207         mesh_pdu_t * pdu = (mesh_pdu_t *) btstack_linked_list_iterator_next(&ack_it);
208         int32_t timeout_delta_ms = btstack_time_delta(pdu->retransmit_timeout_ms, now);
209         if (next_timeout_ms == 0 || timeout_delta_ms < next_timeout_ms){
210             next_timeout_ms = timeout_delta_ms;
211         }
212     }
213 
214     // set timer
215     if (next_timeout_ms == 0) return;
216 
217     btstack_run_loop_set_timer(&mesh_access_acknowledged_timer, next_timeout_ms);
218     btstack_run_loop_set_timer_handler(&mesh_access_acknowledged_timer, mesh_access_acknowledged_run);
219     btstack_run_loop_add_timer(&mesh_access_acknowledged_timer);
220 }
221 
222 static void mesh_access_acknowledged_received(uint16_t rx_src, uint32_t opcode){
223     // check if received src matches our dest
224     // free acknowledged messages if we were waiting for this message
225 
226     btstack_linked_list_iterator_t ack_it;
227     btstack_linked_list_iterator_init(&ack_it, &mesh_access_acknowledged_messages);
228     while (btstack_linked_list_iterator_has_next(&ack_it)){
229         mesh_pdu_t * tx_pdu = (mesh_pdu_t *) btstack_linked_list_iterator_next(&ack_it);
230         uint16_t tx_dest = mesh_pdu_dst(tx_pdu);
231         if (tx_dest != rx_src) continue;
232         if (tx_pdu->ack_opcode != opcode) continue;
233         // got expected response from dest, remove from outgoing messages
234         mesh_upper_transport_pdu_free(tx_pdu);
235         return;
236     }
237 }
238 
239 static void mesh_access_upper_transport_handler(mesh_transport_callback_type_t callback_type, mesh_transport_status_t status, mesh_pdu_t * pdu){
240     switch (callback_type){
241         case MESH_TRANSPORT_PDU_SENT:
242             // unacknowledged -> free
243             if (pdu->ack_opcode == MESH_ACCESS_OPCODE_INVALID){
244                 mesh_upper_transport_pdu_free(pdu);
245                 break;
246             }
247             // setup timeout
248             pdu->retransmit_timeout_ms = btstack_run_loop_get_time_ms() + mesh_access_acknowledged_message_timeout_ms();
249             // add to mesh_access_acknowledged_messages
250             btstack_linked_list_add(&mesh_access_acknowledged_messages, (btstack_linked_item_t *) pdu);
251             // update timer
252             mesh_access_acknowledged_run(NULL);
253             break;
254         default:
255             break;
256     }
257 }
258 
259 // Mesh Model Transitions
260 
261 void mesh_access_transitions_setup_transaction(mesh_transition_t * transition, uint8_t transaction_identifier, uint16_t src_address, uint16_t dst_address){
262     transition->transaction_timestamp_ms = btstack_run_loop_get_time_ms();
263     transition->transaction_identifier = transaction_identifier;
264     transition->src_address = src_address;
265     transition->dst_address = dst_address;
266 }
267 
268 void mesh_access_transitions_abort_transaction(mesh_transition_t * transition){
269     mesh_access_transitions_remove(transition);
270 }
271 
272 
273 static int mesh_access_transitions_transaction_is_expired(mesh_transition_t * transition){
274     return (btstack_run_loop_get_time_ms() - transition->transaction_timestamp_ms) > MEST_TRANSACTION_TIMEOUT_MS;
275 }
276 
277 mesh_transaction_status_t mesh_access_transitions_transaction_status(mesh_transition_t * transition, uint8_t transaction_identifier, uint16_t src_address, uint16_t dst_address){
278     if (transition->src_address != src_address || transition->dst_address != dst_address) return MESH_TRANSACTION_STATUS_DIFFERENT_DST_OR_SRC;
279 
280     if (transition->transaction_identifier == transaction_identifier && !mesh_access_transitions_transaction_is_expired(transition)){
281             return MESH_TRANSACTION_STATUS_RETRANSMISSION;
282     }
283     return MESH_TRANSACTION_STATUS_NEW;
284 }
285 
286 uint8_t mesh_access_transitions_num_steps_from_gdtt(uint8_t time_gdtt){
287     return time_gdtt >> 2;
288 }
289 
290 static uint32_t mesh_access_transitions_step_ms_from_gdtt(uint8_t time_gdtt){
291     mesh_default_transition_step_resolution_t step_resolution = (mesh_default_transition_step_resolution_t) (time_gdtt & 0x03u);
292     switch (step_resolution){
293         case MESH_DEFAULT_TRANSITION_STEP_RESOLUTION_100ms:
294             return 100;
295         case MESH_DEFAULT_TRANSITION_STEP_RESOLUTION_1s:
296             return 1000;
297         case MESH_DEFAULT_TRANSITION_STEP_RESOLUTION_10s:
298             return 10000;
299         case MESH_DEFAULT_TRANSITION_STEP_RESOLUTION_10min:
300             return 600000;
301         default:
302             return 0;
303     }
304 }
305 
306 uint32_t mesh_access_time_gdtt2ms(uint8_t time_gdtt){
307     uint8_t num_steps  = mesh_access_transitions_num_steps_from_gdtt(time_gdtt);
308     if (num_steps > 0x3E) return 0;
309 
310     return mesh_access_transitions_step_ms_from_gdtt(time_gdtt) * num_steps;
311 }
312 
313 static void mesh_access_transitions_timeout_handler(btstack_timer_source_t * timer){
314     btstack_linked_list_iterator_t it;
315     btstack_linked_list_iterator_init(&it, &transitions);
316     while (btstack_linked_list_iterator_has_next(&it)){
317         mesh_transition_t * transition = (mesh_transition_t *)btstack_linked_list_iterator_next(&it);
318         (transition->transition_callback)(transition, TRANSITION_UPDATE, btstack_run_loop_get_time_ms());
319     }
320     if (btstack_linked_list_empty(&transitions)) return;
321 
322     btstack_run_loop_set_timer(timer, transition_step_min_ms);
323     btstack_run_loop_add_timer(timer);
324 }
325 
326 static void mesh_access_transitions_timer_start(void){
327     btstack_run_loop_remove_timer(&transitions_timer);
328     btstack_run_loop_set_timer_handler(&transitions_timer, mesh_access_transitions_timeout_handler);
329     btstack_run_loop_set_timer(&transitions_timer, transition_step_min_ms);
330     btstack_run_loop_add_timer(&transitions_timer);
331 }
332 
333 static void mesh_access_transitions_timer_stop(void){
334     btstack_run_loop_remove_timer(&transitions_timer);
335 }
336 
337 static uint32_t mesh_access_transitions_get_step_min_ms(void){
338     uint32_t min_timeout_ms = 0;
339 
340     btstack_linked_list_iterator_t it;
341     btstack_linked_list_iterator_init(&it, &transitions);
342     while (btstack_linked_list_iterator_has_next(&it)){
343         mesh_transition_t * transition = (mesh_transition_t *)btstack_linked_list_iterator_next(&it);
344         if (min_timeout_ms == 0 || transition->step_duration_ms < min_timeout_ms){
345             min_timeout_ms = transition->step_duration_ms;
346         }
347     }
348     return min_timeout_ms;
349 }
350 
351 void mesh_access_transitions_setup(mesh_transition_t * transition, mesh_model_t * mesh_model,
352     uint8_t transition_time_gdtt, uint8_t delay_gdtt,
353     void (* transition_callback)(struct mesh_transition * transition, transition_event_t event, uint32_t current_timestamp)){
354 
355     //  Only values of 0x00 through 0x3E shall be used to specify the value of the Transition Number of Steps field
356     uint8_t num_steps  = mesh_access_transitions_num_steps_from_gdtt(transition_time_gdtt);
357     if (num_steps > 0x3E) return;
358 
359     transition->state = MESH_TRANSITION_STATE_IDLE;
360     transition->phase_start_ms = 0;
361 
362     transition->mesh_model = mesh_model;
363     transition->transition_callback = transition_callback;
364     transition->step_duration_ms = mesh_access_transitions_step_ms_from_gdtt(transition_time_gdtt);
365     transition->remaining_delay_time_ms = delay_gdtt * 5;
366     transition->remaining_transition_time_ms = num_steps * transition->step_duration_ms;
367 }
368 
369 void mesh_access_transitions_add(mesh_transition_t * transition){
370     if (transition->step_duration_ms == 0) return;
371 
372     if (btstack_linked_list_empty(&transitions) || transition->step_duration_ms < transition_step_min_ms){
373         transition_step_min_ms = transition->step_duration_ms;
374     }
375     mesh_access_transitions_timer_start();
376     btstack_linked_list_add(&transitions, (btstack_linked_item_t *) transition);
377     (transition->transition_callback)(transition, TRANSITION_START, btstack_run_loop_get_time_ms());
378 }
379 
380 void mesh_access_transitions_remove(mesh_transition_t * transition){
381     mesh_access_transitions_setup(transition, NULL, 0, 0, NULL);
382     btstack_linked_list_remove(&transitions, (btstack_linked_item_t *) transition);
383 
384     if (btstack_linked_list_empty(&transitions)){
385         mesh_access_transitions_timer_stop();
386     } else {
387         transition_step_min_ms = mesh_access_transitions_get_step_min_ms();
388     }
389 }
390 
391 uint8_t mesh_access_transactions_get_next_transaction_id(void){
392     mesh_transaction_id_counter++;
393     if (mesh_transaction_id_counter == 0){
394         mesh_transaction_id_counter = 1;
395     }
396     return mesh_transaction_id_counter;
397 }
398 
399 // Mesh Node Element functions
400 uint8_t mesh_access_get_element_index(mesh_model_t * mesh_model){
401     return mesh_model->element->element_index;
402 }
403 
404 uint16_t mesh_access_get_element_address(mesh_model_t * mesh_model){
405     return mesh_node_get_primary_element_address() + mesh_model->element->element_index;
406 }
407 
408 // Model Identifier utilities
409 
410 uint32_t mesh_model_get_model_identifier(uint16_t vendor_id, uint16_t model_id){
411     return (vendor_id << 16) | model_id;
412 }
413 
414 uint32_t mesh_model_get_model_identifier_bluetooth_sig(uint16_t model_id){
415     return (BLUETOOTH_COMPANY_ID_BLUETOOTH_SIG_INC << 16) | model_id;
416 }
417 
418 uint16_t mesh_model_get_model_id(uint32_t model_identifier){
419     return model_identifier & 0xFFFFu;
420 }
421 
422 uint16_t mesh_model_get_vendor_id(uint32_t model_identifier){
423     return model_identifier >> 16;
424 }
425 
426 int mesh_model_is_bluetooth_sig(uint32_t model_identifier){
427     return mesh_model_get_vendor_id(model_identifier) == BLUETOOTH_COMPANY_ID_BLUETOOTH_SIG_INC;
428 }
429 
430 mesh_model_t * mesh_model_get_configuration_server(void){
431     return mesh_model_get_by_identifier(mesh_node_get_primary_element(), mesh_model_get_model_identifier_bluetooth_sig(MESH_SIG_MODEL_ID_CONFIGURATION_SERVER));
432 }
433 
434 void mesh_element_add_model(mesh_element_t * element, mesh_model_t * mesh_model){
435     // reset app keys
436     mesh_model_reset_appkeys(mesh_model);
437 
438     if (mesh_model_is_bluetooth_sig(mesh_model->model_identifier)){
439         element->models_count_sig++;
440     } else {
441         element->models_count_vendor++;
442     }
443     mesh_model->mid = mid_counter++;
444     mesh_model->element = element;
445     btstack_linked_list_add_tail(&element->models, (btstack_linked_item_t *) mesh_model);
446 }
447 
448 void mesh_model_iterator_init(mesh_model_iterator_t * iterator, mesh_element_t * element){
449     btstack_linked_list_iterator_init(&iterator->it, &element->models);
450 }
451 
452 int mesh_model_iterator_has_next(mesh_model_iterator_t * iterator){
453     return btstack_linked_list_iterator_has_next(&iterator->it);
454 }
455 
456 mesh_model_t * mesh_model_iterator_next(mesh_model_iterator_t * iterator){
457     return (mesh_model_t *) btstack_linked_list_iterator_next(&iterator->it);
458 }
459 
460 mesh_model_t * mesh_model_get_by_identifier(mesh_element_t * element, uint32_t model_identifier){
461     mesh_model_iterator_t it;
462     mesh_model_iterator_init(&it, element);
463     while (mesh_model_iterator_has_next(&it)){
464         mesh_model_t * model = mesh_model_iterator_next(&it);
465         if (model->model_identifier != model_identifier) continue;
466         return model;
467     }
468     return NULL;
469 }
470 
471 mesh_model_t * mesh_access_model_for_address_and_model_identifier(uint16_t element_address, uint32_t model_identifier, uint8_t * status){
472     mesh_element_t * element = mesh_node_element_for_unicast_address(element_address);
473     if (element == NULL){
474         *status = MESH_FOUNDATION_STATUS_INVALID_ADDRESS;
475         return NULL;
476     }
477     mesh_model_t * model = mesh_model_get_by_identifier(element, model_identifier);
478     if (model == NULL) {
479         *status = MESH_FOUNDATION_STATUS_INVALID_MODEL;
480     } else {
481         *status = MESH_FOUNDATION_STATUS_SUCCESS;
482     }
483     return model;
484 }
485 
486 uint16_t mesh_pdu_src(mesh_pdu_t * pdu){
487     switch (pdu->pdu_type){
488         case MESH_PDU_TYPE_TRANSPORT:
489             return mesh_transport_src((mesh_transport_pdu_t*) pdu);
490         case MESH_PDU_TYPE_NETWORK:
491             return mesh_network_src((mesh_network_pdu_t *) pdu);
492         default:
493             return MESH_ADDRESS_UNSASSIGNED;
494     }
495 }
496 
497 uint16_t mesh_pdu_dst(mesh_pdu_t * pdu){
498     switch (pdu->pdu_type){
499         case MESH_PDU_TYPE_TRANSPORT:
500             return mesh_transport_dst((mesh_transport_pdu_t*) pdu);
501         case MESH_PDU_TYPE_NETWORK:
502             return mesh_network_dst((mesh_network_pdu_t *) pdu);
503         default:
504             return MESH_ADDRESS_UNSASSIGNED;
505     }
506 }
507 
508 uint16_t mesh_pdu_netkey_index(mesh_pdu_t * pdu){
509     switch (pdu->pdu_type){
510         case MESH_PDU_TYPE_TRANSPORT:
511             return ((mesh_transport_pdu_t*) pdu)->netkey_index;
512         case MESH_PDU_TYPE_NETWORK:
513             return ((mesh_network_pdu_t *) pdu)->netkey_index;
514         default:
515             return 0;
516     }
517 }
518 
519 uint16_t mesh_pdu_appkey_index(mesh_pdu_t * pdu){
520     switch (pdu->pdu_type){
521         case MESH_PDU_TYPE_TRANSPORT:
522             return ((mesh_transport_pdu_t*) pdu)->appkey_index;
523         case MESH_PDU_TYPE_NETWORK:
524             return ((mesh_network_pdu_t *) pdu)->appkey_index;
525         default:
526             return 0;
527     }
528 }
529 
530 uint16_t mesh_pdu_len(mesh_pdu_t * pdu){
531     switch (pdu->pdu_type){
532         case MESH_PDU_TYPE_TRANSPORT:
533             return ((mesh_transport_pdu_t*) pdu)->len;
534         case MESH_PDU_TYPE_NETWORK:
535             return ((mesh_network_pdu_t *) pdu)->len - 10;
536         default:
537             return 0;
538     }
539 }
540 
541 uint8_t * mesh_pdu_data(mesh_pdu_t * pdu){
542     switch (pdu->pdu_type){
543         case MESH_PDU_TYPE_TRANSPORT:
544             return ((mesh_transport_pdu_t*) pdu)->data;
545         case MESH_PDU_TYPE_NETWORK:
546             return &((mesh_network_pdu_t *) pdu)->data[10];
547         default:
548             return NULL;
549     }
550 }
551 
552 // message parser
553 
554 static int mesh_access_get_opcode(uint8_t * buffer, uint16_t buffer_size, uint32_t * opcode, uint16_t * opcode_size){
555     switch (buffer[0] >> 6){
556         case 0:
557         case 1:
558             if (buffer[0] == 0x7f) return 0;
559             *opcode = buffer[0];
560             *opcode_size = 1;
561             return 1;
562         case 2:
563             if (buffer_size < 2) return 0;
564             *opcode = big_endian_read_16(buffer, 0);
565             *opcode_size = 2;
566             return 1;
567         case 3:
568             if (buffer_size < 3) return 0;
569             *opcode = (buffer[0] << 16) | little_endian_read_16(buffer, 1);
570             *opcode_size = 3;
571             return 1;
572         default:
573             return 0;
574     }
575 }
576 
577 static int mesh_access_transport_get_opcode(mesh_transport_pdu_t * transport_pdu, uint32_t * opcode, uint16_t * opcode_size){
578     return mesh_access_get_opcode(transport_pdu->data, transport_pdu->len, opcode, opcode_size);
579 }
580 
581 static int mesh_access_network_get_opcode(mesh_network_pdu_t * network_pdu, uint32_t * opcode, uint16_t * opcode_size){
582     // TransMIC already removed by mesh_upper_transport_validate_unsegmented_message_ccm
583     return mesh_access_get_opcode(&network_pdu->data[10], network_pdu->len - 10, opcode, opcode_size);
584 }
585 
586 int mesh_access_pdu_get_opcode(mesh_pdu_t * pdu, uint32_t * opcode, uint16_t * opcode_size){
587     switch (pdu->pdu_type){
588         case MESH_PDU_TYPE_TRANSPORT:
589             return mesh_access_transport_get_opcode((mesh_transport_pdu_t*) pdu, opcode, opcode_size);
590         case MESH_PDU_TYPE_NETWORK:
591             return mesh_access_network_get_opcode((mesh_network_pdu_t *) pdu, opcode, opcode_size);
592         default:
593             return 0;
594     }
595 }
596 
597 void mesh_access_parser_skip(mesh_access_parser_state_t * state, uint16_t bytes_to_skip){
598     state->data += bytes_to_skip;
599     state->len  -= bytes_to_skip;
600 }
601 
602 int mesh_access_parser_init(mesh_access_parser_state_t * state, mesh_pdu_t * pdu){
603     state->data = mesh_pdu_data(pdu);
604     state->len  = mesh_pdu_len(pdu);
605 
606     uint16_t opcode_size = 0;
607     int ok = mesh_access_get_opcode(state->data, state->len, &state->opcode, &opcode_size);
608     if (ok){
609         mesh_access_parser_skip(state, opcode_size);
610     }
611     return ok;
612 }
613 
614 uint16_t mesh_access_parser_available(mesh_access_parser_state_t * state){
615     return state->len;
616 }
617 
618 uint8_t mesh_access_parser_get_u8(mesh_access_parser_state_t * state){
619     uint8_t value = *state->data;
620     mesh_access_parser_skip(state, 1);
621     return value;
622 }
623 
624 uint16_t mesh_access_parser_get_u16(mesh_access_parser_state_t * state){
625     uint16_t value = little_endian_read_16(state->data, 0);
626     mesh_access_parser_skip(state, 2);
627     return value;
628 }
629 
630 uint32_t mesh_access_parser_get_u24(mesh_access_parser_state_t * state){
631     uint32_t value = little_endian_read_24(state->data, 0);
632     mesh_access_parser_skip(state, 3);
633     return value;
634 }
635 
636 uint32_t mesh_access_parser_get_u32(mesh_access_parser_state_t * state){
637     uint32_t value = little_endian_read_24(state->data, 0);
638     mesh_access_parser_skip(state, 4);
639     return value;
640 }
641 
642 void mesh_access_parser_get_u128(mesh_access_parser_state_t * state, uint8_t * dest){
643     reverse_128( state->data, dest);
644     mesh_access_parser_skip(state, 16);
645 }
646 
647 void mesh_access_parser_get_label_uuid(mesh_access_parser_state_t * state, uint8_t * dest){
648     memcpy( dest, state->data, 16);
649     mesh_access_parser_skip(state, 16);
650 }
651 
652 void mesh_access_parser_get_key(mesh_access_parser_state_t * state, uint8_t * dest){
653     memcpy( dest, state->data, 16);
654     mesh_access_parser_skip(state, 16);
655 }
656 
657 uint32_t mesh_access_parser_get_model_identifier(mesh_access_parser_state_t * parser){
658     if (mesh_access_parser_available(parser) == 4){
659         return mesh_access_parser_get_u32(parser);
660     } else {
661         return (BLUETOOTH_COMPANY_ID_BLUETOOTH_SIG_INC << 16) | mesh_access_parser_get_u16(parser);
662     }
663 }
664 
665 // Mesh Access Message Builder
666 
667 // message builder
668 
669 static int mesh_access_setup_opcode(uint8_t * buffer, uint32_t opcode){
670     if (opcode < 0x100){
671         buffer[0] = opcode;
672         return 1;
673     }
674     if (opcode < 0x10000){
675         big_endian_store_16(buffer, 0, opcode);
676         return 2;
677     }
678     buffer[0] = opcode >> 16;
679     little_endian_store_16(buffer, 1, opcode & 0xffff);
680     return 3;
681 }
682 
683 mesh_transport_pdu_t * mesh_access_transport_init(uint32_t opcode){
684     mesh_transport_pdu_t * pdu = mesh_transport_pdu_get();
685     if (!pdu) return NULL;
686 
687     pdu->len  = mesh_access_setup_opcode(pdu->data, opcode);
688     return pdu;
689 }
690 
691 void mesh_access_transport_add_uint8(mesh_transport_pdu_t * pdu, uint8_t value){
692     pdu->data[pdu->len++] = value;
693 }
694 
695 void mesh_access_transport_add_uint16(mesh_transport_pdu_t * pdu, uint16_t value){
696     little_endian_store_16(pdu->data, pdu->len, value);
697     pdu->len += 2;
698 }
699 
700 void mesh_access_transport_add_uint24(mesh_transport_pdu_t * pdu, uint32_t value){
701     little_endian_store_24(pdu->data, pdu->len, value);
702     pdu->len += 3;
703 }
704 
705 void mesh_access_transport_add_uint32(mesh_transport_pdu_t * pdu, uint32_t value){
706     little_endian_store_32(pdu->data, pdu->len, value);
707     pdu->len += 4;
708 }
709 void mesh_access_transport_add_model_identifier(mesh_transport_pdu_t * pdu, uint32_t model_identifier){
710     if (mesh_model_is_bluetooth_sig(model_identifier)){
711         mesh_access_transport_add_uint16( pdu, mesh_model_get_model_id(model_identifier) );
712     } else {
713         mesh_access_transport_add_uint32( pdu, model_identifier );
714     }
715 }
716 
717 mesh_network_pdu_t * mesh_access_network_init(uint32_t opcode){
718     mesh_network_pdu_t * pdu = mesh_network_pdu_get();
719     if (!pdu) return NULL;
720 
721     pdu->len  = mesh_access_setup_opcode(&pdu->data[10], opcode) + 10;
722     return pdu;
723 }
724 
725 void mesh_access_network_add_uint8(mesh_network_pdu_t * pdu, uint8_t value){
726     pdu->data[pdu->len++] = value;
727 }
728 
729 void mesh_access_network_add_uint16(mesh_network_pdu_t * pdu, uint16_t value){
730     little_endian_store_16(pdu->data, pdu->len, value);
731     pdu->len += 2;
732 }
733 
734 void mesh_access_network_add_uint24(mesh_network_pdu_t * pdu, uint16_t value){
735     little_endian_store_24(pdu->data, pdu->len, value);
736     pdu->len += 3;
737 }
738 
739 void mesh_access_network_add_uint32(mesh_network_pdu_t * pdu, uint16_t value){
740     little_endian_store_32(pdu->data, pdu->len, value);
741     pdu->len += 4;
742 }
743 
744 void mesh_access_network_add_model_identifier(mesh_network_pdu_t * pdu, uint32_t model_identifier){
745     if (mesh_model_is_bluetooth_sig(model_identifier)){
746         mesh_access_network_add_uint16( pdu, mesh_model_get_model_id(model_identifier) );
747     } else {
748         mesh_access_network_add_uint32( pdu, model_identifier );
749     }
750 }
751 
752 // access message template
753 
754 mesh_network_pdu_t * mesh_access_setup_unsegmented_message(const mesh_access_message_t *template, ...){
755     mesh_network_pdu_t * network_pdu = mesh_access_network_init(template->opcode);
756     if (!network_pdu) return NULL;
757 
758     va_list argptr;
759     va_start(argptr, template);
760 
761     // add params
762     const char * format = template->format;
763     uint16_t word;
764     uint32_t longword;
765     while (*format){
766         switch (*format){
767             case '1':
768                 word = va_arg(argptr, int);  // minimal va_arg is int: 2 bytes on 8+16 bit CPUs
769                 mesh_access_network_add_uint8( network_pdu, word);
770                 break;
771             case '2':
772                 word = va_arg(argptr, int);  // minimal va_arg is int: 2 bytes on 8+16 bit CPUs
773                 mesh_access_network_add_uint16( network_pdu, word);
774                 break;
775             case '3':
776                 longword = va_arg(argptr, uint32_t);
777                 mesh_access_network_add_uint24( network_pdu, longword);
778                 break;
779             case '4':
780                 longword = va_arg(argptr, uint32_t);
781                 mesh_access_network_add_uint32( network_pdu, longword);
782                 break;
783             case 'm':
784                 longword = va_arg(argptr, uint32_t);
785                 mesh_access_network_add_model_identifier( network_pdu, longword);
786                 break;
787             default:
788                 log_error("Unsupported mesh message format specifier '%c", *format);
789                 break;
790         }
791         format++;
792     }
793 
794     va_end(argptr);
795 
796     return network_pdu;
797 }
798 
799 mesh_transport_pdu_t * mesh_access_setup_segmented_message(const mesh_access_message_t *template, ...){
800     mesh_transport_pdu_t * transport_pdu = mesh_access_transport_init(template->opcode);
801     if (!transport_pdu) return NULL;
802 
803     va_list argptr;
804     va_start(argptr, template);
805 
806     // add params
807     const char * format = template->format;
808     uint16_t word;
809     uint32_t longword;
810     while (*format){
811         switch (*format++){
812             case '1':
813                 word = va_arg(argptr, int);  // minimal va_arg is int: 2 bytes on 8+16 bit CPUs
814                 mesh_access_transport_add_uint8( transport_pdu, word);
815                 break;
816             case '2':
817                 word = va_arg(argptr, int);  // minimal va_arg is int: 2 bytes on 8+16 bit CPUs
818                 mesh_access_transport_add_uint16( transport_pdu, word);
819                 break;
820             case '3':
821                 longword = va_arg(argptr, uint32_t);
822                 mesh_access_transport_add_uint24( transport_pdu, longword);
823                 break;
824             case '4':
825                 longword = va_arg(argptr, uint32_t);
826                 mesh_access_transport_add_uint32( transport_pdu, longword);
827                 break;
828             case 'm':
829                 longword = va_arg(argptr, uint32_t);
830                 mesh_access_transport_add_model_identifier( transport_pdu, longword);
831                 break;
832             default:
833                 break;
834         }
835     }
836 
837     va_end(argptr);
838 
839     return transport_pdu;
840 }
841 
842 static const mesh_operation_t * mesh_model_lookup_operation_by_opcode(mesh_model_t * model, uint32_t opcode){
843     // find opcode in table
844     const mesh_operation_t * operation = model->operations;
845     if (operation == NULL) return NULL;
846     for ( ; operation->handler != NULL ; operation++){
847         if (operation->opcode != opcode) continue;
848         return operation;
849     }
850     return NULL;
851 }
852 
853 static const mesh_operation_t * mesh_model_lookup_operation(mesh_model_t * model, mesh_pdu_t * pdu){
854 
855     uint32_t opcode = 0;
856     uint16_t opcode_size = 0;
857     int ok = mesh_access_pdu_get_opcode( pdu, &opcode, &opcode_size);
858     if (!ok) return NULL;
859 
860     uint16_t len = mesh_pdu_len(pdu);
861 
862     // find opcode in table
863     const mesh_operation_t * operation = model->operations;
864     if (operation == NULL) return NULL;
865     for ( ; operation->handler != NULL ; operation++){
866         if (operation->opcode != opcode) continue;
867         if ((opcode_size + operation->minimum_length) > len) continue;
868         return operation;
869     }
870     return NULL;
871 }
872 
873 static int mesh_access_validate_appkey_index(mesh_model_t * model, uint16_t appkey_index){
874     // DeviceKey is valid for all models
875     if (appkey_index == MESH_DEVICE_KEY_INDEX) return 1;
876     // check if AppKey that is bound to this particular model
877     return mesh_model_contains_appkey(model, appkey_index);
878 }
879 
880 static void mesh_access_message_process_handler(mesh_pdu_t * pdu){
881     // get opcode and size
882     uint32_t opcode = 0;
883     uint16_t opcode_size = 0;
884 
885 
886     int ok = mesh_access_pdu_get_opcode( pdu, &opcode, &opcode_size);
887     if (!ok) {
888         mesh_access_message_processed(pdu);
889         return;
890     }
891 
892     uint16_t len = mesh_pdu_len(pdu);
893     printf("MESH Access Message, Opcode = %x: ", opcode);
894     printf_hexdump(mesh_pdu_data(pdu), len);
895 
896     uint16_t src = mesh_pdu_src(pdu);
897     uint16_t dst = mesh_pdu_dst(pdu);
898     uint16_t appkey_index = mesh_pdu_appkey_index(pdu);
899     if (mesh_network_address_unicast(dst)){
900         // loookup element by unicast address
901         mesh_element_t * element = mesh_node_element_for_unicast_address(dst);
902         if (element != NULL){
903             // iterate over models, look for operation
904             mesh_model_iterator_t model_it;
905             mesh_model_iterator_init(&model_it, element);
906             while (mesh_model_iterator_has_next(&model_it)){
907                 mesh_model_t * model = mesh_model_iterator_next(&model_it);
908                 // find opcode in table
909                 const mesh_operation_t * operation = mesh_model_lookup_operation(model, pdu);
910                 if (operation == NULL) continue;
911                 if (mesh_access_validate_appkey_index(model, appkey_index) == 0) continue;
912                 mesh_access_acknowledged_received(src, opcode);
913                 operation->handler(model, pdu);
914                 return;
915             }
916         }
917     }
918     else if (mesh_network_address_group(dst)){
919 
920         // handle fixed group address
921         if (dst >= 0xff00){
922             int deliver_to_primary_element = 1;
923             switch (dst){
924                 case MESH_ADDRESS_ALL_PROXIES:
925                     if (mesh_foundation_gatt_proxy_get() == 1){
926                         deliver_to_primary_element = 1;
927                     }
928                     break;
929                 case MESH_ADDRESS_ALL_FRIENDS:
930                     // TODO: not implemented
931                     break;
932                 case MESH_ADDRESS_ALL_RELAYS:
933                     if (mesh_foundation_relay_get() == 1){
934                         deliver_to_primary_element =1;
935                     }
936                     break;
937                 case MESH_ADDRESS_ALL_NODES:
938                     deliver_to_primary_element = 1;
939                     break;
940                 default:
941                     break;
942             }
943             if (deliver_to_primary_element){
944                 mesh_model_iterator_t model_it;
945                 mesh_model_iterator_init(&model_it, mesh_node_get_primary_element());
946                 while (mesh_model_iterator_has_next(&model_it)){
947                     mesh_model_t * model = mesh_model_iterator_next(&model_it);
948                     // find opcode in table
949                     const mesh_operation_t * operation = mesh_model_lookup_operation(model, pdu);
950                     if (operation == NULL) continue;
951                     if (mesh_access_validate_appkey_index(model, appkey_index) == 0) continue;
952                     mesh_access_acknowledged_received(src, opcode);
953                     operation->handler(model, pdu);
954                     return;
955                 }
956             }
957         }
958         else {
959             // iterate over all elements / models, check subscription list
960             mesh_element_iterator_t it;
961             mesh_element_iterator_init(&it);
962             while (mesh_element_iterator_has_next(&it)){
963                 mesh_element_t * element = (mesh_element_t *) mesh_element_iterator_next(&it);
964                 mesh_model_iterator_t model_it;
965                 mesh_model_iterator_init(&model_it, element);
966                 while (mesh_model_iterator_has_next(&model_it)){
967                     mesh_model_t * model = mesh_model_iterator_next(&model_it);
968                     if (mesh_model_contains_subscription(model, dst)){
969                         // find opcode in table
970                         const mesh_operation_t * operation = mesh_model_lookup_operation(model, pdu);
971                         if (operation == NULL) continue;
972                         if (mesh_access_validate_appkey_index(model, appkey_index) == 0) continue;
973                         mesh_access_acknowledged_received(src, opcode);
974                         operation->handler(model, pdu);
975                         return;
976                     }
977                 }
978             }
979         }
980     }
981 
982     // operation not found -> done
983     printf("Message not handled\n");
984     mesh_access_message_processed(pdu);
985 }
986 
987 void mesh_access_message_processed(mesh_pdu_t * pdu){
988     mesh_upper_transport_message_processed_by_higher_layer(pdu);
989 }
990 
991 int mesh_model_contains_subscription(mesh_model_t * mesh_model, uint16_t address){
992     uint16_t i;
993     for (i=0;i<MAX_NR_MESH_SUBSCRIPTION_PER_MODEL;i++){
994         if (mesh_model->subscriptions[i] == address) return 1;
995     }
996     return 0;
997 }
998 
999 // Foundation state
1000 
1001 static const uint32_t mesh_foundation_state_tag = ((uint32_t) 'M' << 24) | ((uint32_t) 'F' << 16)  | ((uint32_t) 'N' << 8) | ((uint32_t) 'D' << 8);
1002 
1003 typedef struct {
1004     uint8_t gatt_proxy;
1005     uint8_t beacon;
1006     uint8_t default_ttl;
1007     uint8_t network_transmit;
1008     uint8_t relay;
1009     uint8_t relay_retransmit;
1010     uint8_t friend;
1011 } mesh_persistent_foundation_t;
1012 
1013 void mesh_foundation_state_load(void){
1014     mesh_access_setup_tlv();
1015     mesh_persistent_foundation_t data;
1016 
1017     int app_key_len = btstack_tlv_singleton_impl->get_tag(btstack_tlv_singleton_context, mesh_foundation_state_tag, (uint8_t *) &data, sizeof(data));
1018     if (app_key_len == 0) return;
1019 
1020     mesh_foundation_gatt_proxy_set(data.gatt_proxy);
1021     mesh_foundation_beacon_set(data.gatt_proxy);
1022     mesh_foundation_default_ttl_set(data.default_ttl);
1023     mesh_foundation_friend_set(data.friend);
1024     mesh_foundation_network_transmit_set(data.network_transmit);
1025     mesh_foundation_relay_set(data.relay);
1026     mesh_foundation_relay_retransmit_set(data.relay_retransmit);
1027 }
1028 
1029 void mesh_foundation_state_store(void){
1030     mesh_access_setup_tlv();
1031     mesh_persistent_foundation_t data;
1032     data.gatt_proxy       = mesh_foundation_gatt_proxy_get();
1033     data.gatt_proxy       = mesh_foundation_beacon_get();
1034     data.default_ttl      = mesh_foundation_default_ttl_get();
1035     data.friend           = mesh_foundation_friend_get();
1036     data.network_transmit = mesh_foundation_network_transmit_get();
1037     data.relay            = mesh_foundation_relay_get();
1038     data.relay_retransmit = mesh_foundation_relay_retransmit_get();
1039     btstack_tlv_singleton_impl->store_tag(btstack_tlv_singleton_context, mesh_foundation_state_tag, (uint8_t *) &data, sizeof(data));
1040 }
1041 
1042 
1043 // Model to Appkey List
1044 
1045 static uint32_t mesh_model_tag_for_index(uint16_t internal_model_id){
1046     return ((uint32_t) 'M' << 24) | ((uint32_t) 'B' << 16) | ((uint32_t) internal_model_id);
1047 }
1048 
1049 static void mesh_load_appkey_list(mesh_model_t * model){
1050     mesh_access_setup_tlv();
1051     uint32_t tag = mesh_model_tag_for_index(model->mid);
1052     btstack_tlv_singleton_impl->get_tag(btstack_tlv_singleton_context, tag, (uint8_t *) &model->appkey_indices, sizeof(model->appkey_indices));
1053 }
1054 
1055 static void mesh_store_appkey_list(mesh_model_t * model){
1056     mesh_access_setup_tlv();
1057     uint32_t tag = mesh_model_tag_for_index(model->mid);
1058     btstack_tlv_singleton_impl->store_tag(btstack_tlv_singleton_context, tag, (uint8_t *) &model->appkey_indices, sizeof(model->appkey_indices));
1059 }
1060 
1061 static void mesh_delete_appkey_list(mesh_model_t * model){
1062     mesh_access_setup_tlv();
1063     uint32_t tag = mesh_model_tag_for_index(model->mid);
1064     btstack_tlv_singleton_impl->delete_tag(btstack_tlv_singleton_context, tag);
1065 }
1066 
1067 void mesh_load_appkey_lists(void){
1068     printf("Load Appkey Lists\n");
1069     // iterate over elements and models
1070     mesh_element_iterator_t element_it;
1071     mesh_element_iterator_init(&element_it);
1072     while (mesh_element_iterator_has_next(&element_it)){
1073         mesh_element_t * element = mesh_element_iterator_next(&element_it);
1074         mesh_model_iterator_t model_it;
1075         mesh_model_iterator_init(&model_it, element);
1076         while (mesh_model_iterator_has_next(&model_it)){
1077             mesh_model_t * model = mesh_model_iterator_next(&model_it);
1078             mesh_load_appkey_list(model);
1079         }
1080     }
1081 }
1082 
1083 void mesh_delete_appkey_lists(void){
1084     printf("Delete Appkey Lists\n");
1085     mesh_access_setup_tlv();
1086     // iterate over elements and models
1087     mesh_element_iterator_t element_it;
1088     mesh_element_iterator_init(&element_it);
1089     while (mesh_element_iterator_has_next(&element_it)){
1090         mesh_element_t * element = mesh_element_iterator_next(&element_it);
1091         mesh_model_iterator_t model_it;
1092         mesh_model_iterator_init(&model_it, element);
1093         while (mesh_model_iterator_has_next(&model_it)){
1094             mesh_model_t * model = mesh_model_iterator_next(&model_it);
1095             mesh_delete_appkey_list(model);
1096         }
1097     }
1098 }
1099 
1100 void mesh_model_reset_appkeys(mesh_model_t * mesh_model){
1101     uint16_t i;
1102     for (i=0;i<MAX_NR_MESH_APPKEYS_PER_MODEL;i++){
1103         mesh_model->appkey_indices[i] = MESH_APPKEY_INVALID;
1104     }
1105 }
1106 
1107 uint8_t mesh_model_bind_appkey(mesh_model_t * mesh_model, uint16_t appkey_index){
1108     uint16_t i;
1109     for (i=0;i<MAX_NR_MESH_APPKEYS_PER_MODEL;i++){
1110         if (mesh_model->appkey_indices[i] == appkey_index) return MESH_FOUNDATION_STATUS_SUCCESS;
1111     }
1112     for (i=0;i<MAX_NR_MESH_APPKEYS_PER_MODEL;i++){
1113         if (mesh_model->appkey_indices[i] == MESH_APPKEY_INVALID) {
1114             mesh_model->appkey_indices[i] = appkey_index;
1115             mesh_store_appkey_list(mesh_model);
1116             return MESH_FOUNDATION_STATUS_SUCCESS;
1117         }
1118     }
1119     return MESH_FOUNDATION_STATUS_INSUFFICIENT_RESOURCES;
1120 }
1121 
1122 void mesh_model_unbind_appkey(mesh_model_t * mesh_model, uint16_t appkey_index){
1123     uint16_t i;
1124     for (i=0;i<MAX_NR_MESH_APPKEYS_PER_MODEL;i++){
1125         if (mesh_model->appkey_indices[i] == appkey_index) {
1126             mesh_model->appkey_indices[i] = MESH_APPKEY_INVALID;
1127             mesh_store_appkey_list(mesh_model);
1128         }
1129     }
1130 }
1131 
1132 int mesh_model_contains_appkey(mesh_model_t * mesh_model, uint16_t appkey_index){
1133     uint16_t i;
1134     for (i=0;i<MAX_NR_MESH_APPKEYS_PER_MODEL;i++){
1135         if (mesh_model->appkey_indices[i] == appkey_index) return 1;
1136     }
1137     return 0;
1138 
1139 }
1140 
1141 // Mesh IV Index
1142 static uint32_t mesh_tag_for_iv_index_and_seq_number(void){
1143     return ((uint32_t) 'M' << 24) | ((uint32_t) 'F' << 16) | ((uint32_t) 'I' << 9) | ((uint32_t) 'S');
1144 }
1145 
1146 typedef struct {
1147     uint32_t iv_index;
1148     uint32_t seq_number;
1149 } iv_index_and_sequence_number_t;
1150 
1151 static uint32_t sequence_number_last_stored;
1152 static uint32_t sequence_number_storage_trigger;
1153 
1154 void mesh_store_iv_index_after_provisioning(uint32_t iv_index){
1155     iv_index_and_sequence_number_t data;
1156     mesh_access_setup_tlv();
1157     uint32_t tag = mesh_tag_for_iv_index_and_seq_number();
1158     data.iv_index   = iv_index;
1159     data.seq_number = 0;
1160     btstack_tlv_singleton_impl->store_tag(btstack_tlv_singleton_context, tag, (uint8_t *) &data, sizeof(data));
1161 
1162     sequence_number_last_stored = data.seq_number;
1163     sequence_number_storage_trigger = sequence_number_last_stored + MESH_SEQUENCE_NUMBER_STORAGE_INTERVAL;
1164 }
1165 
1166 void mesh_store_iv_index_and_sequence_number(void){
1167     iv_index_and_sequence_number_t data;
1168     mesh_access_setup_tlv();
1169     uint32_t tag = mesh_tag_for_iv_index_and_seq_number();
1170     data.iv_index   = mesh_get_iv_index();
1171     data.seq_number = mesh_sequence_number_peek();
1172     btstack_tlv_singleton_impl->store_tag(btstack_tlv_singleton_context, tag, (uint8_t *) &data, sizeof(data));
1173 
1174     sequence_number_last_stored = data.seq_number;
1175     sequence_number_storage_trigger = sequence_number_last_stored + MESH_SEQUENCE_NUMBER_STORAGE_INTERVAL;
1176 }
1177 
1178 int mesh_load_iv_index_and_sequence_number(uint32_t * iv_index, uint32_t * sequence_number){
1179     iv_index_and_sequence_number_t data;
1180     mesh_access_setup_tlv();
1181     uint32_t tag = mesh_tag_for_iv_index_and_seq_number();
1182     uint32_t len = btstack_tlv_singleton_impl->get_tag(btstack_tlv_singleton_context, tag, (uint8_t *) &data, sizeof(data));
1183     if (len == sizeof(iv_index_and_sequence_number_t)){
1184         *iv_index = data.iv_index;
1185         *sequence_number = data.seq_number;
1186         return 1;
1187     }
1188     return 0;
1189 }
1190 
1191 // higher layer
1192 static void mesh_persist_iv_index_and_sequence_number(void){
1193     if (mesh_sequence_number_peek() >= sequence_number_storage_trigger){
1194         mesh_store_iv_index_and_sequence_number();
1195     }
1196 }
1197 
1198 
1199 // Mesh Model Publication
1200 static btstack_timer_source_t mesh_access_publication_timer;
1201 
1202 static uint32_t mesh_model_publication_retransmit_count(uint8_t retransmit){
1203     return retransmit & 0x07u;
1204 }
1205 
1206 static uint32_t mesh_model_publication_retransmission_period_ms(uint8_t retransmit){
1207     return ((uint32_t)((retransmit >> 3) + 1)) * 50;
1208 }
1209 
1210 static void mesh_model_publication_setup_publication(mesh_publication_model_t * publication_model, uint32_t now){
1211 
1212     // set retransmit counter
1213     publication_model->retransmit_count = mesh_model_publication_retransmit_count(publication_model->retransmit);
1214 
1215     // schedule next publication or retransmission
1216     uint32_t publication_period_ms = mesh_access_transitions_step_ms_from_gdtt(publication_model->period);
1217 
1218     // set next publication
1219     if (publication_period_ms != 0){
1220         publication_model->next_publication_ms = now + publication_period_ms;
1221         publication_model->state = MESH_MODEL_PUBLICATION_STATE_W4_PUBLICATION_MS;
1222     }
1223 }
1224 
1225 static void mesh_model_publication_setup_retransmission(mesh_publication_model_t * publication_model, uint32_t now){
1226     uint8_t num_retransmits = mesh_model_publication_retransmit_count(publication_model->retransmit);
1227     if (num_retransmits == 0) return;
1228 
1229     // calc next retransmit time
1230     uint32_t retransmission_ms = now + mesh_model_publication_retransmission_period_ms(publication_model->retransmit);
1231 
1232     // ignore if retransmission would be after next publication timeout
1233     if (publication_model->state == MESH_MODEL_PUBLICATION_STATE_W4_PUBLICATION_MS){
1234         if (btstack_time_delta(retransmission_ms, publication_model->next_publication_ms) > 0) return;
1235     }
1236 
1237     // schedule next retransmission
1238     publication_model->next_retransmit_ms = retransmission_ms;
1239     publication_model->state = MESH_MODEL_PUBLICATION_STATE_W4_RETRANSMIT_MS;
1240 }
1241 
1242 static void mesh_model_publication_publish_now_model(mesh_model_t * mesh_model){
1243     mesh_publication_model_t * publication_model = mesh_model->publication_model;
1244     if (publication_model == NULL) return;
1245     if (publication_model->publish_state_fn == NULL) return;
1246     uint16_t dest = publication_model->address;
1247     if (dest == MESH_ADDRESS_UNSASSIGNED) return;
1248     uint16_t appkey_index = publication_model->appkey_index;
1249     mesh_transport_key_t * app_key = mesh_transport_key_get(appkey_index);
1250     if (app_key == NULL) return;
1251 
1252     // compose message
1253     mesh_pdu_t * pdu = (*publication_model->publish_state_fn)(mesh_model);
1254     if (pdu == NULL) return;
1255 
1256     mesh_upper_transport_setup_access_pdu_header(pdu, app_key->netkey_index, appkey_index, publication_model->ttl, mesh_access_get_element_address(mesh_model), dest, 0);
1257     mesh_upper_transport_send_access_pdu(pdu);
1258 }
1259 
1260 static void mesh_model_publication_run(btstack_timer_source_t * ts){
1261     UNUSED(ts);
1262 
1263     uint32_t now = btstack_run_loop_get_time_ms();
1264 
1265     // iterate over elements and models and handle time-based transitions
1266     mesh_element_iterator_t element_it;
1267     mesh_element_iterator_init(&element_it);
1268     while (mesh_element_iterator_has_next(&element_it)){
1269         mesh_element_t * element = mesh_element_iterator_next(&element_it);
1270         mesh_model_iterator_t model_it;
1271         mesh_model_iterator_init(&model_it, element);
1272         while (mesh_model_iterator_has_next(&model_it)){
1273             mesh_model_t * mesh_model = mesh_model_iterator_next(&model_it);
1274             mesh_publication_model_t * publication_model = mesh_model->publication_model;
1275             if (publication_model == NULL) continue;
1276 
1277             // schedule next
1278             switch (publication_model->state){
1279                 case MESH_MODEL_PUBLICATION_STATE_W4_PUBLICATION_MS:
1280                     if (btstack_time_delta(publication_model->next_publication_ms, now) > 0) break;
1281                     // timeout
1282                     publication_model->publish_now = 1;
1283                     // schedule next publication and retransmission
1284                     mesh_model_publication_setup_publication(publication_model, now);
1285                     mesh_model_publication_setup_retransmission(publication_model, now);
1286                     break;
1287                 case MESH_MODEL_PUBLICATION_STATE_W4_RETRANSMIT_MS:
1288                     if (btstack_time_delta(publication_model->next_retransmit_ms, now) > 0) break;
1289                     // timeout
1290                     publication_model->publish_now = 1;
1291                     publication_model->retransmit_count--;
1292                     // schedule next retransmission
1293                     mesh_model_publication_setup_retransmission(publication_model, now);
1294                     break;
1295                 default:
1296                     break;
1297             }
1298 
1299             if (publication_model->publish_now == 0) continue;
1300 
1301             publication_model->publish_now = 0;
1302             mesh_model_publication_publish_now_model(mesh_model);
1303         }
1304     }
1305 
1306     int32_t next_timeout_ms = 0;
1307     mesh_element_iterator_init(&element_it);
1308     while (mesh_element_iterator_has_next(&element_it)){
1309         mesh_element_t * element = mesh_element_iterator_next(&element_it);
1310         mesh_model_iterator_t model_it;
1311         mesh_model_iterator_init(&model_it, element);
1312         while (mesh_model_iterator_has_next(&model_it)){
1313             mesh_model_t * mesh_model = mesh_model_iterator_next(&model_it);
1314             mesh_publication_model_t * publication_model = mesh_model->publication_model;
1315             if (publication_model == NULL) continue;
1316 
1317             // schedule next
1318             int32_t timeout_delta_ms;
1319             switch (publication_model->state){
1320                 case MESH_MODEL_PUBLICATION_STATE_W4_PUBLICATION_MS:
1321                     timeout_delta_ms = btstack_time_delta(publication_model->next_publication_ms, now);
1322                     if (next_timeout_ms == 0 || timeout_delta_ms < next_timeout_ms){
1323                         next_timeout_ms = timeout_delta_ms;
1324                     }
1325                     break;
1326                 case MESH_MODEL_PUBLICATION_STATE_W4_RETRANSMIT_MS:
1327                     timeout_delta_ms = btstack_time_delta(publication_model->next_retransmit_ms, now);
1328                     if (next_timeout_ms == 0 || timeout_delta_ms < next_timeout_ms){
1329                         next_timeout_ms = timeout_delta_ms;
1330                     }
1331                     break;
1332                 default:
1333                     break;
1334             }
1335         }
1336     }
1337 
1338     // set timer
1339     if (next_timeout_ms == 0) return;
1340 
1341     btstack_run_loop_set_timer(&mesh_access_publication_timer, next_timeout_ms);
1342     btstack_run_loop_set_timer_handler(&mesh_access_publication_timer, mesh_model_publication_run);
1343     btstack_run_loop_add_timer(&mesh_access_publication_timer);
1344 }
1345 
1346 void mesh_model_publication_start(mesh_model_t * mesh_model){
1347     mesh_publication_model_t * publication_model = mesh_model->publication_model;
1348     if (publication_model == NULL) return;
1349 
1350     // reset state
1351     publication_model->state = MESH_MODEL_PUBLICATION_STATE_IDLE;
1352 
1353     // publish right away
1354     publication_model->publish_now = 1;
1355 
1356     // setup next publication and retransmission
1357     uint32_t now = btstack_run_loop_get_time_ms();
1358     mesh_model_publication_setup_publication(publication_model, now);
1359     mesh_model_publication_setup_retransmission(publication_model, now);
1360 
1361     mesh_model_publication_run(NULL);
1362 }
1363 
1364 void mesh_model_publication_stop(mesh_model_t * mesh_model){
1365     mesh_publication_model_t * publication_model = mesh_model->publication_model;
1366     if (publication_model == NULL) return;
1367 
1368     // reset state
1369     publication_model->state = MESH_MODEL_PUBLICATION_STATE_IDLE;
1370 }
1371 
1372 void mesh_access_state_changed(mesh_model_t * mesh_model){
1373     mesh_publication_model_t * publication_model = mesh_model->publication_model;
1374     if (publication_model == NULL) return;
1375     publication_model->publish_now = 1;
1376     mesh_model_publication_run(NULL);
1377 }
1378 
1379 void mesh_access_netkey_finalize(mesh_network_key_t * network_key){
1380     mesh_network_key_remove(network_key);
1381     mesh_delete_network_key(network_key->internal_index);
1382     btstack_memory_mesh_network_key_free(network_key);
1383 }
1384 
1385 void mesh_access_appkey_finalize(mesh_transport_key_t * transport_key){
1386     mesh_transport_key_remove(transport_key);
1387     mesh_delete_app_key(transport_key->appkey_index);
1388     btstack_memory_mesh_transport_key_free(transport_key);
1389 }
1390 
1391 void mesh_access_key_refresh_revoke_keys(mesh_subnet_t * subnet){
1392     // delete old netkey index
1393     mesh_access_netkey_finalize(subnet->old_key);
1394     subnet->old_key = subnet->new_key;
1395     subnet->new_key = NULL;
1396 
1397     // delete old appkeys, if any
1398     mesh_transport_key_iterator_t it;
1399     mesh_transport_key_iterator_init(&it, subnet->netkey_index);
1400     while (mesh_transport_key_iterator_has_more(&it)){
1401         mesh_transport_key_t * transport_key = mesh_transport_key_iterator_get_next(&it);
1402         if (transport_key->old_key == 0) continue;
1403         mesh_access_appkey_finalize(transport_key);
1404     }
1405 }
1406 
1407 static void mesh_access_secure_network_beacon_handler(uint8_t packet_type, uint16_t channel, uint8_t * packet, uint16_t size){
1408     UNUSED(channel);
1409     UNUSED(size);
1410 
1411     if (packet_type != MESH_BEACON_PACKET) return;
1412 
1413     // lookup subnet and netkey by network id
1414     uint8_t * beacon_network_id = &packet[2];
1415     mesh_subnet_iterator_t it;
1416     mesh_subnet_iterator_init(&it);
1417     mesh_subnet_t * subnet = NULL;
1418     uint8_t new_key = 0;
1419     while (mesh_subnet_iterator_has_more(&it)){
1420         mesh_subnet_t * item = mesh_subnet_iterator_get_next(&it);
1421         if (memcmp(item->old_key->network_id, beacon_network_id, 8) == 0 ) {
1422             subnet = item;
1423         }
1424         if (item->new_key != NULL && memcmp(item->new_key->network_id, beacon_network_id, 8) == 0 ) {
1425             subnet = item;
1426             new_key = 1;
1427         }
1428         break;
1429     }
1430     if (subnet == NULL) return;
1431 
1432     uint8_t flags = packet[1];
1433 
1434     // Key refresh via secure network beacons that are authenticated with new netkey
1435     if (new_key){
1436         // either first or second phase (in phase 0, new key is not set)
1437         int key_refresh_flag = flags & 1;
1438         if (key_refresh_flag){
1439             //  transition to phase 3 from either phase 1 or 2
1440             switch (subnet->key_refresh){
1441                 case MESH_KEY_REFRESH_FIRST_PHASE:
1442                 case MESH_KEY_REFRESH_SECOND_PHASE:
1443                     mesh_access_key_refresh_revoke_keys(subnet);
1444                     subnet->key_refresh = MESH_KEY_REFRESH_NOT_ACTIVE;
1445                     break;
1446                 default:
1447                     break;
1448             }
1449         } else {
1450             //  transition to phase 2 from either phase 1
1451             switch (subnet->key_refresh){
1452                 case MESH_KEY_REFRESH_FIRST_PHASE:
1453                     // -- update state
1454                     subnet->key_refresh = MESH_KEY_REFRESH_SECOND_PHASE;
1455                     break;
1456                 default:
1457                     break;
1458             }
1459         }
1460     }
1461 
1462     // IV Update
1463 
1464     int     beacon_iv_update_active = flags & 2;
1465     int     local_iv_update_active = mesh_iv_update_active();
1466     uint32_t beacon_iv_index = big_endian_read_32(packet, 10);
1467     uint32_t local_iv_index = mesh_get_iv_index();
1468 
1469     int32_t iv_index_delta = (int32_t)(beacon_iv_index - local_iv_index);
1470 
1471     // "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
1472     //  the last known IV Index + 42, the Secure Network beacon shall be ignored."
1473     if (iv_index_delta < 0 || iv_index_delta > 42){
1474         return;
1475     }
1476 
1477     // "If a node in Normal Operation receives a Secure Network beacon with an IV index equal to the last known IV index+1 and
1478     //  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
1479     //  an IV Index Recovery procedure (Section 3.10.6), or it may ignore the Secure Network beacon. The node makes the choice depending
1480     //  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.""
1481     if (local_iv_update_active == 0 && beacon_iv_update_active == 0 && iv_index_delta == 1){
1482         // instant iv update
1483         mesh_set_iv_index( beacon_iv_index );
1484         // store updated iv index
1485         mesh_store_iv_index_and_sequence_number();
1486         return;
1487     }
1488 
1489     // "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
1490     //  the last known IV Index of the primary subnet, the Secure Network beacon shall be ignored."
1491     int member_of_primary_subnet = mesh_subnet_get_by_netkey_index(0) != NULL;
1492     int beacon_on_secondary_subnet = subnet->netkey_index != 0;
1493     if (member_of_primary_subnet && beacon_on_secondary_subnet && iv_index_delta > 0){
1494         return;
1495     }
1496 
1497     // "If a node in Normal Operation receives a Secure Network beacon with an IV index greater than the last known IV Index + 1..."
1498     // "... it may initiate an IV Index Recovery procedure, see Section 3.10.6."
1499     if (local_iv_update_active == 0 && iv_index_delta > 1){
1500         // "Upon receiving and successfully authenticating a Secure Network beacon for a primary subnet... "
1501         int beacon_on_primary_subnet = subnet->netkey_index == 0;
1502         if (!beacon_on_primary_subnet) return;
1503         // "... whose IV Index is 1 or more higher than the current known IV Index, the node shall "
1504         // " set its current IV Index and its current IV Update procedure state from the values in this Secure Network beacon."
1505         mesh_iv_index_recovered(beacon_iv_update_active, beacon_iv_index);
1506         // store updated iv index if in normal mode
1507         if (beacon_iv_update_active == 0){
1508             mesh_store_iv_index_and_sequence_number();
1509         }
1510         return;
1511     }
1512 
1513     if (local_iv_update_active == 0){
1514         if (beacon_iv_update_active){
1515             mesh_trigger_iv_update();
1516         }
1517     } else {
1518         if (beacon_iv_update_active == 0){
1519             // " At the point of transition, the node shall reset the sequence number to 0x000000."
1520             mesh_sequence_number_set(0);
1521             mesh_iv_update_completed();
1522             // store updated iv index
1523             mesh_store_iv_index_and_sequence_number();
1524         }
1525     }
1526 }
1527