xref: /btstack/src/mesh/mesh_access.c (revision a0253209c2d80682c681bcaad7ff6cfb5f4998e4)
1 /*
2  * Copyright (C) 2019 BlueKitchen GmbH
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  *
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. Neither the name of the copyright holders nor the names of
14  *    contributors may be used to endorse or promote products derived
15  *    from this software without specific prior written permission.
16  * 4. Any redistribution, use, or modification is done solely for
17  *    personal benefit and not for any commercial purpose or for
18  *    monetary gain.
19  *
20  * THIS SOFTWARE IS PROVIDED BY BLUEKITCHEN GMBH AND CONTRIBUTORS
21  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
23  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL MATTHIAS
24  * RINGWALD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
25  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
26  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
27  * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
28  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
29  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
30  * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  *
33  * Please inquire about commercial licensing options at
34  * [email protected]
35  *
36  */
37 
38 #define __BTSTACK_FILE__ "mesh_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 
65 // acknowledged messages
66 static btstack_linked_list_t  mesh_access_acknowledged_messages;
67 static btstack_timer_source_t mesh_access_acknowledged_timer;
68 
69 static uint16_t mid_counter;
70 
71 // Transitions
72 static btstack_linked_list_t  transitions;
73 static btstack_timer_source_t transitions_timer;
74 static uint32_t transition_step_min_ms;
75 static uint8_t mesh_transaction_id_counter = 0;
76 
77 void mesh_access_init(void){
78     // register with upper transport
79     mesh_upper_transport_register_access_message_handler(&mesh_access_message_process_handler);
80     mesh_upper_transport_set_higher_layer_handler(&mesh_access_upper_transport_handler);
81 
82     // register for secure network beacons
83     beacon_register_for_secure_network_beacons(&mesh_access_secure_network_beacon_handler);
84 }
85 
86 void mesh_access_emit_state_update_bool(btstack_packet_handler_t event_handler, uint8_t element_index, uint32_t model_identifier,
87     model_state_id_t state_identifier, model_state_update_reason_t reason, uint8_t value){
88     if (event_handler == NULL) return;
89     uint8_t event[14] = {HCI_EVENT_MESH_META, 12, MESH_SUBEVENT_STATE_UPDATE_BOOL};
90     int pos = 3;
91     event[pos++] = element_index;
92     little_endian_store_32(event, pos, model_identifier);
93     pos += 4;
94     little_endian_store_32(event, pos, (uint32_t)state_identifier);
95     pos += 4;
96     event[pos++] = (uint8_t)reason;
97     event[pos++] = value;
98     (*event_handler)(HCI_EVENT_PACKET, 0, event, sizeof(event));
99 }
100 
101 void mesh_access_emit_state_update_int16(btstack_packet_handler_t event_handler, uint8_t element_index, uint32_t model_identifier,
102     model_state_id_t state_identifier, model_state_update_reason_t reason, int16_t value){
103     if (event_handler == NULL) return;
104     uint8_t event[15] = {HCI_EVENT_MESH_META, 13, MESH_SUBEVENT_STATE_UPDATE_BOOL};
105     int pos = 3;
106     event[pos++] = element_index;
107     little_endian_store_32(event, pos, model_identifier);
108     pos += 4;
109     little_endian_store_32(event, pos, (uint32_t)state_identifier);
110     pos += 4;
111     event[pos++] = (uint8_t)reason;
112     little_endian_store_16(event, pos, (uint16_t) value);
113     pos += 2;
114     (*event_handler)(HCI_EVENT_PACKET, 0, event, sizeof(event));
115 }
116 
117 uint8_t mesh_access_acknowledged_message_retransmissions(void){
118     return 3;
119 }
120 
121 uint32_t mesh_access_acknowledged_message_timeout_ms(void){
122     return 30000;
123 }
124 
125 #define MESH_ACCESS_OPCODE_INVALID 0xFFFFFFFFu
126 
127 void mesh_access_send_unacknowledged_pdu(mesh_pdu_t * pdu){
128     pdu->ack_opcode = MESH_ACCESS_OPCODE_INVALID;;
129     mesh_upper_transport_send_access_pdu(pdu);
130 }
131 
132 void mesh_access_send_acknowledged_pdu(mesh_pdu_t * pdu, uint8_t retransmissions, uint32_t ack_opcode){
133     pdu->retransmit_count = retransmissions;
134     pdu->ack_opcode = ack_opcode;
135 
136     mesh_upper_transport_send_access_pdu(pdu);
137 }
138 
139 #define MESH_SUBEVENT_MESSAGE_NOT_ACKNOWLEDGED                                        0x30
140 
141 static void mesh_access_acknowledged_run(btstack_timer_source_t * ts){
142     UNUSED(ts);
143 
144     uint32_t now = btstack_run_loop_get_time_ms();
145 
146     // handle timeouts
147     btstack_linked_list_iterator_t ack_it;
148     btstack_linked_list_iterator_init(&ack_it, &mesh_access_acknowledged_messages);
149     while (btstack_linked_list_iterator_has_next(&ack_it)){
150         mesh_pdu_t * pdu = (mesh_pdu_t *) btstack_linked_list_iterator_next(&ack_it);
151         if (btstack_time_delta(now, pdu->retransmit_timeout_ms) >= 0) {
152             // remove from list
153             btstack_linked_list_remove(&mesh_access_acknowledged_messages, (btstack_linked_item_t*) pdu);
154             // retransmit or report failure
155             if (pdu->retransmit_count){
156                 pdu->retransmit_count--;
157                 mesh_upper_transport_send_access_pdu(pdu);
158             } else {
159                 // find correct model and emit error
160                 uint16_t src = mesh_pdu_src(pdu);
161                 uint16_t dst = mesh_pdu_dst(pdu);
162                 mesh_element_t * element = mesh_node_element_for_unicast_address(src);
163                 if (element){
164                     // find
165                     mesh_model_iterator_t model_it;
166                     mesh_model_iterator_init(&model_it, element);
167                     while (mesh_model_iterator_has_next(&model_it)){
168                         mesh_model_t * model = mesh_model_iterator_next(&model_it);
169                         // find opcode in table
170                         const mesh_operation_t * operation = mesh_model_lookup_operation_by_opcode(model, pdu->ack_opcode);
171                         if (operation == NULL) continue;
172                         if (model->model_packet_handler == NULL) continue;
173                         // emit event
174                         uint8_t event[13];
175                         event[0] = HCI_EVENT_MESH_META;
176                         event[1] = sizeof(event) - 2;
177                         event[2] = element->element_index;
178                         little_endian_store_32(event, 3, model->model_identifier);
179                         little_endian_store_32(event, 7, pdu->ack_opcode);
180                         little_endian_store_16(event, 11, dst);
181                         (*model->model_packet_handler)(HCI_EVENT_PACKET, 0, event, sizeof(event));
182                     }
183                 }
184 
185                 // free
186                 mesh_upper_transport_pdu_free(pdu);
187             }
188         }
189     }
190 
191     // find earliest timeout and set timer
192     btstack_linked_list_iterator_init(&ack_it, &mesh_access_acknowledged_messages);
193     int32_t next_timeout_ms = 0;
194     while (btstack_linked_list_iterator_has_next(&ack_it)){
195         mesh_pdu_t * pdu = (mesh_pdu_t *) btstack_linked_list_iterator_next(&ack_it);
196         int32_t timeout_delta_ms = btstack_time_delta(pdu->retransmit_timeout_ms, now);
197         if (next_timeout_ms == 0 || timeout_delta_ms < next_timeout_ms){
198             next_timeout_ms = timeout_delta_ms;
199         }
200     }
201 
202     // set timer
203     if (next_timeout_ms == 0) return;
204 
205     btstack_run_loop_set_timer(&mesh_access_acknowledged_timer, next_timeout_ms);
206     btstack_run_loop_set_timer_handler(&mesh_access_acknowledged_timer, mesh_access_acknowledged_run);
207     btstack_run_loop_add_timer(&mesh_access_acknowledged_timer);
208 }
209 
210 static void mesh_access_acknowledged_received(uint16_t rx_src, uint32_t opcode){
211     // check if received src matches our dest
212     // free acknowledged messages if we were waiting for this message
213 
214     btstack_linked_list_iterator_t ack_it;
215     btstack_linked_list_iterator_init(&ack_it, &mesh_access_acknowledged_messages);
216     while (btstack_linked_list_iterator_has_next(&ack_it)){
217         mesh_pdu_t * tx_pdu = (mesh_pdu_t *) btstack_linked_list_iterator_next(&ack_it);
218         uint16_t tx_dest = mesh_pdu_dst(tx_pdu);
219         if (tx_dest != rx_src) continue;
220         if (tx_pdu->ack_opcode != opcode) continue;
221         // got expected response from dest, remove from outgoing messages
222         mesh_upper_transport_pdu_free(tx_pdu);
223         return;
224     }
225 }
226 
227 static void mesh_access_upper_transport_handler(mesh_transport_callback_type_t callback_type, mesh_transport_status_t status, mesh_pdu_t * pdu){
228     switch (callback_type){
229         case MESH_TRANSPORT_PDU_SENT:
230             // unacknowledged -> free
231             if (pdu->ack_opcode == MESH_ACCESS_OPCODE_INVALID){
232                 mesh_upper_transport_pdu_free(pdu);
233                 break;
234             }
235             // setup timeout
236             pdu->retransmit_timeout_ms = btstack_run_loop_get_time_ms() + mesh_access_acknowledged_message_timeout_ms();
237             // add to mesh_access_acknowledged_messages
238             btstack_linked_list_add(&mesh_access_acknowledged_messages, (btstack_linked_item_t *) pdu);
239             // update timer
240             mesh_access_acknowledged_run(NULL);
241             break;
242         default:
243             break;
244     }
245 }
246 
247 // Mesh Model Transitions
248 
249 void mesh_access_transitions_setup_transaction(mesh_transition_t * transition, uint8_t transaction_identifier, uint16_t src_address, uint16_t dst_address){
250     transition->transaction_timestamp_ms = btstack_run_loop_get_time_ms();
251     transition->transaction_identifier = transaction_identifier;
252     transition->src_address = src_address;
253     transition->dst_address = dst_address;
254 }
255 
256 void mesh_access_transitions_abort_transaction(mesh_transition_t * transition){
257     mesh_access_transitions_remove(transition);
258 }
259 
260 
261 static int mesh_access_transitions_transaction_is_expired(mesh_transition_t * transition){
262     return (btstack_run_loop_get_time_ms() - transition->transaction_timestamp_ms) > MEST_TRANSACTION_TIMEOUT_MS;
263 }
264 
265 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){
266     if (transition->src_address != src_address || transition->dst_address != dst_address) return MESH_TRANSACTION_STATUS_DIFFERENT_DST_OR_SRC;
267 
268     if (transition->transaction_identifier == transaction_identifier && !mesh_access_transitions_transaction_is_expired(transition)){
269             return MESH_TRANSACTION_STATUS_RETRANSMISSION;
270     }
271     return MESH_TRANSACTION_STATUS_NEW;
272 }
273 
274 uint8_t mesh_access_transitions_num_steps_from_gdtt(uint8_t time_gdtt){
275     return time_gdtt >> 2;
276 }
277 
278 static uint32_t mesh_access_transitions_step_ms_from_gdtt(uint8_t time_gdtt){
279     mesh_default_transition_step_resolution_t step_resolution = (mesh_default_transition_step_resolution_t) (time_gdtt & 0x03u);
280     switch (step_resolution){
281         case MESH_DEFAULT_TRANSITION_STEP_RESOLUTION_100ms:
282             return 100;
283         case MESH_DEFAULT_TRANSITION_STEP_RESOLUTION_1s:
284             return 1000;
285         case MESH_DEFAULT_TRANSITION_STEP_RESOLUTION_10s:
286             return 10000;
287         case MESH_DEFAULT_TRANSITION_STEP_RESOLUTION_10min:
288             return 600000;
289         default:
290             return 0;
291     }
292 }
293 
294 uint32_t mesh_access_time_gdtt2ms(uint8_t time_gdtt){
295     uint8_t num_steps  = mesh_access_transitions_num_steps_from_gdtt(time_gdtt);
296     if (num_steps > 0x3E) return 0;
297 
298     return mesh_access_transitions_step_ms_from_gdtt(time_gdtt) * num_steps;
299 }
300 
301 static void mesh_access_transitions_timeout_handler(btstack_timer_source_t * timer){
302     btstack_linked_list_iterator_t it;
303     btstack_linked_list_iterator_init(&it, &transitions);
304     while (btstack_linked_list_iterator_has_next(&it)){
305         mesh_transition_t * transition = (mesh_transition_t *)btstack_linked_list_iterator_next(&it);
306         (transition->transition_callback)(transition, TRANSITION_UPDATE, btstack_run_loop_get_time_ms());
307     }
308     if (btstack_linked_list_empty(&transitions)) return;
309 
310     btstack_run_loop_set_timer(timer, transition_step_min_ms);
311     btstack_run_loop_add_timer(timer);
312 }
313 
314 static void mesh_access_transitions_timer_start(void){
315     btstack_run_loop_remove_timer(&transitions_timer);
316     btstack_run_loop_set_timer_handler(&transitions_timer, mesh_access_transitions_timeout_handler);
317     btstack_run_loop_set_timer(&transitions_timer, transition_step_min_ms);
318     btstack_run_loop_add_timer(&transitions_timer);
319 }
320 
321 static void mesh_access_transitions_timer_stop(void){
322     btstack_run_loop_remove_timer(&transitions_timer);
323 }
324 
325 static uint32_t mesh_access_transitions_get_step_min_ms(void){
326     uint32_t min_timeout_ms = 0;
327 
328     btstack_linked_list_iterator_t it;
329     btstack_linked_list_iterator_init(&it, &transitions);
330     while (btstack_linked_list_iterator_has_next(&it)){
331         mesh_transition_t * transition = (mesh_transition_t *)btstack_linked_list_iterator_next(&it);
332         if (min_timeout_ms == 0 || transition->step_duration_ms < min_timeout_ms){
333             min_timeout_ms = transition->step_duration_ms;
334         }
335     }
336     return min_timeout_ms;
337 }
338 
339 void mesh_access_transitions_setup(mesh_transition_t * transition, mesh_model_t * mesh_model,
340     uint8_t transition_time_gdtt, uint8_t delay_gdtt,
341     void (* transition_callback)(struct mesh_transition * transition, transition_event_t event, uint32_t current_timestamp)){
342 
343     //  Only values of 0x00 through 0x3E shall be used to specify the value of the Transition Number of Steps field
344     uint8_t num_steps  = mesh_access_transitions_num_steps_from_gdtt(transition_time_gdtt);
345     if (num_steps > 0x3E) return;
346 
347     transition->state = MESH_TRANSITION_STATE_IDLE;
348     transition->phase_start_ms = 0;
349 
350     transition->mesh_model = mesh_model;
351     transition->transition_callback = transition_callback;
352     transition->step_duration_ms = mesh_access_transitions_step_ms_from_gdtt(transition_time_gdtt);
353     transition->remaining_delay_time_ms = delay_gdtt * 5;
354     transition->remaining_transition_time_ms = num_steps * transition->step_duration_ms;
355 }
356 
357 void mesh_access_transitions_add(mesh_transition_t * transition){
358     if (transition->step_duration_ms == 0) return;
359 
360     if (btstack_linked_list_empty(&transitions) || transition->step_duration_ms < transition_step_min_ms){
361         transition_step_min_ms = transition->step_duration_ms;
362     }
363     mesh_access_transitions_timer_start();
364     btstack_linked_list_add(&transitions, (btstack_linked_item_t *) transition);
365     (transition->transition_callback)(transition, TRANSITION_START, btstack_run_loop_get_time_ms());
366 }
367 
368 void mesh_access_transitions_remove(mesh_transition_t * transition){
369     mesh_access_transitions_setup(transition, NULL, 0, 0, NULL);
370     btstack_linked_list_remove(&transitions, (btstack_linked_item_t *) transition);
371 
372     if (btstack_linked_list_empty(&transitions)){
373         mesh_access_transitions_timer_stop();
374     } else {
375         transition_step_min_ms = mesh_access_transitions_get_step_min_ms();
376     }
377 }
378 
379 uint8_t mesh_access_transactions_get_next_transaction_id(void){
380     mesh_transaction_id_counter++;
381     if (mesh_transaction_id_counter == 0){
382         mesh_transaction_id_counter = 1;
383     }
384     return mesh_transaction_id_counter;
385 }
386 
387 // Mesh Node Element functions
388 uint8_t mesh_access_get_element_index(mesh_model_t * mesh_model){
389     return mesh_model->element->element_index;
390 }
391 
392 uint16_t mesh_access_get_element_address(mesh_model_t * mesh_model){
393     return mesh_node_get_primary_element_address() + mesh_model->element->element_index;
394 }
395 
396 // Model Identifier utilities
397 
398 uint32_t mesh_model_get_model_identifier(uint16_t vendor_id, uint16_t model_id){
399     return (vendor_id << 16) | model_id;
400 }
401 
402 uint32_t mesh_model_get_model_identifier_bluetooth_sig(uint16_t model_id){
403     return (BLUETOOTH_COMPANY_ID_BLUETOOTH_SIG_INC << 16) | model_id;
404 }
405 
406 uint16_t mesh_model_get_model_id(uint32_t model_identifier){
407     return model_identifier & 0xFFFFu;
408 }
409 
410 uint16_t mesh_model_get_vendor_id(uint32_t model_identifier){
411     return model_identifier >> 16;
412 }
413 
414 int mesh_model_is_bluetooth_sig(uint32_t model_identifier){
415     return mesh_model_get_vendor_id(model_identifier) == BLUETOOTH_COMPANY_ID_BLUETOOTH_SIG_INC;
416 }
417 
418 mesh_model_t * mesh_model_get_configuration_server(void){
419     return mesh_model_get_by_identifier(mesh_node_get_primary_element(), mesh_model_get_model_identifier_bluetooth_sig(MESH_SIG_MODEL_ID_CONFIGURATION_SERVER));
420 }
421 
422 void mesh_element_add_model(mesh_element_t * element, mesh_model_t * mesh_model){
423     // reset app keys
424     mesh_model_reset_appkeys(mesh_model);
425 
426     if (mesh_model_is_bluetooth_sig(mesh_model->model_identifier)){
427         element->models_count_sig++;
428     } else {
429         element->models_count_vendor++;
430     }
431     mesh_model->mid = mid_counter++;
432     mesh_model->element = element;
433     btstack_linked_list_add_tail(&element->models, (btstack_linked_item_t *) mesh_model);
434 }
435 
436 void mesh_model_iterator_init(mesh_model_iterator_t * iterator, mesh_element_t * element){
437     btstack_linked_list_iterator_init(&iterator->it, &element->models);
438 }
439 
440 int mesh_model_iterator_has_next(mesh_model_iterator_t * iterator){
441     return btstack_linked_list_iterator_has_next(&iterator->it);
442 }
443 
444 mesh_model_t * mesh_model_iterator_next(mesh_model_iterator_t * iterator){
445     return (mesh_model_t *) btstack_linked_list_iterator_next(&iterator->it);
446 }
447 
448 mesh_model_t * mesh_model_get_by_identifier(mesh_element_t * element, uint32_t model_identifier){
449     mesh_model_iterator_t it;
450     mesh_model_iterator_init(&it, element);
451     while (mesh_model_iterator_has_next(&it)){
452         mesh_model_t * model = mesh_model_iterator_next(&it);
453         if (model->model_identifier != model_identifier) continue;
454         return model;
455     }
456     return NULL;
457 }
458 
459 mesh_model_t * mesh_access_model_for_address_and_model_identifier(uint16_t element_address, uint32_t model_identifier, uint8_t * status){
460     mesh_element_t * element = mesh_node_element_for_unicast_address(element_address);
461     if (element == NULL){
462         *status = MESH_FOUNDATION_STATUS_INVALID_ADDRESS;
463         return NULL;
464     }
465     mesh_model_t * model = mesh_model_get_by_identifier(element, model_identifier);
466     if (model == NULL) {
467         *status = MESH_FOUNDATION_STATUS_INVALID_MODEL;
468     } else {
469         *status = MESH_FOUNDATION_STATUS_SUCCESS;
470     }
471     return model;
472 }
473 
474 uint16_t mesh_pdu_src(mesh_pdu_t * pdu){
475     switch (pdu->pdu_type){
476         case MESH_PDU_TYPE_TRANSPORT:
477             return mesh_transport_src((mesh_transport_pdu_t*) pdu);
478         case MESH_PDU_TYPE_NETWORK:
479             return mesh_network_src((mesh_network_pdu_t *) pdu);
480         default:
481             return MESH_ADDRESS_UNSASSIGNED;
482     }
483 }
484 
485 uint16_t mesh_pdu_dst(mesh_pdu_t * pdu){
486     switch (pdu->pdu_type){
487         case MESH_PDU_TYPE_TRANSPORT:
488             return mesh_transport_dst((mesh_transport_pdu_t*) pdu);
489         case MESH_PDU_TYPE_NETWORK:
490             return mesh_network_dst((mesh_network_pdu_t *) pdu);
491         default:
492             return MESH_ADDRESS_UNSASSIGNED;
493     }
494 }
495 
496 uint16_t mesh_pdu_netkey_index(mesh_pdu_t * pdu){
497     switch (pdu->pdu_type){
498         case MESH_PDU_TYPE_TRANSPORT:
499             return ((mesh_transport_pdu_t*) pdu)->netkey_index;
500         case MESH_PDU_TYPE_NETWORK:
501             return ((mesh_network_pdu_t *) pdu)->netkey_index;
502         default:
503             return 0;
504     }
505 }
506 
507 uint16_t mesh_pdu_appkey_index(mesh_pdu_t * pdu){
508     switch (pdu->pdu_type){
509         case MESH_PDU_TYPE_TRANSPORT:
510             return ((mesh_transport_pdu_t*) pdu)->appkey_index;
511         case MESH_PDU_TYPE_NETWORK:
512             return ((mesh_network_pdu_t *) pdu)->appkey_index;
513         default:
514             return 0;
515     }
516 }
517 
518 uint16_t mesh_pdu_len(mesh_pdu_t * pdu){
519     switch (pdu->pdu_type){
520         case MESH_PDU_TYPE_TRANSPORT:
521             return ((mesh_transport_pdu_t*) pdu)->len;
522         case MESH_PDU_TYPE_NETWORK:
523             return ((mesh_network_pdu_t *) pdu)->len - 10;
524         default:
525             return 0;
526     }
527 }
528 
529 uint8_t * mesh_pdu_data(mesh_pdu_t * pdu){
530     switch (pdu->pdu_type){
531         case MESH_PDU_TYPE_TRANSPORT:
532             return ((mesh_transport_pdu_t*) pdu)->data;
533         case MESH_PDU_TYPE_NETWORK:
534             return &((mesh_network_pdu_t *) pdu)->data[10];
535         default:
536             return NULL;
537     }
538 }
539 
540 // message parser
541 
542 static int mesh_access_get_opcode(uint8_t * buffer, uint16_t buffer_size, uint32_t * opcode, uint16_t * opcode_size){
543     switch (buffer[0] >> 6){
544         case 0:
545         case 1:
546             if (buffer[0] == 0x7f) return 0;
547             *opcode = buffer[0];
548             *opcode_size = 1;
549             return 1;
550         case 2:
551             if (buffer_size < 2) return 0;
552             *opcode = big_endian_read_16(buffer, 0);
553             *opcode_size = 2;
554             return 1;
555         case 3:
556             if (buffer_size < 3) return 0;
557             *opcode = (buffer[0] << 16) | little_endian_read_16(buffer, 1);
558             *opcode_size = 3;
559             return 1;
560         default:
561             return 0;
562     }
563 }
564 
565 static int mesh_access_transport_get_opcode(mesh_transport_pdu_t * transport_pdu, uint32_t * opcode, uint16_t * opcode_size){
566     return mesh_access_get_opcode(transport_pdu->data, transport_pdu->len, opcode, opcode_size);
567 }
568 
569 static int mesh_access_network_get_opcode(mesh_network_pdu_t * network_pdu, uint32_t * opcode, uint16_t * opcode_size){
570     // TransMIC already removed by mesh_upper_transport_validate_unsegmented_message_ccm
571     return mesh_access_get_opcode(&network_pdu->data[10], network_pdu->len - 10, opcode, opcode_size);
572 }
573 
574 int mesh_access_pdu_get_opcode(mesh_pdu_t * pdu, uint32_t * opcode, uint16_t * opcode_size){
575     switch (pdu->pdu_type){
576         case MESH_PDU_TYPE_TRANSPORT:
577             return mesh_access_transport_get_opcode((mesh_transport_pdu_t*) pdu, opcode, opcode_size);
578         case MESH_PDU_TYPE_NETWORK:
579             return mesh_access_network_get_opcode((mesh_network_pdu_t *) pdu, opcode, opcode_size);
580         default:
581             return 0;
582     }
583 }
584 
585 void mesh_access_parser_skip(mesh_access_parser_state_t * state, uint16_t bytes_to_skip){
586     state->data += bytes_to_skip;
587     state->len  -= bytes_to_skip;
588 }
589 
590 int mesh_access_parser_init(mesh_access_parser_state_t * state, mesh_pdu_t * pdu){
591     state->data = mesh_pdu_data(pdu);
592     state->len  = mesh_pdu_len(pdu);
593 
594     uint16_t opcode_size = 0;
595     int ok = mesh_access_get_opcode(state->data, state->len, &state->opcode, &opcode_size);
596     if (ok){
597         mesh_access_parser_skip(state, opcode_size);
598     }
599     return ok;
600 }
601 
602 uint16_t mesh_access_parser_available(mesh_access_parser_state_t * state){
603     return state->len;
604 }
605 
606 uint8_t mesh_access_parser_get_u8(mesh_access_parser_state_t * state){
607     uint8_t value = *state->data;
608     mesh_access_parser_skip(state, 1);
609     return value;
610 }
611 
612 uint16_t mesh_access_parser_get_u16(mesh_access_parser_state_t * state){
613     uint16_t value = little_endian_read_16(state->data, 0);
614     mesh_access_parser_skip(state, 2);
615     return value;
616 }
617 
618 uint32_t mesh_access_parser_get_u24(mesh_access_parser_state_t * state){
619     uint32_t value = little_endian_read_24(state->data, 0);
620     mesh_access_parser_skip(state, 3);
621     return value;
622 }
623 
624 uint32_t mesh_access_parser_get_u32(mesh_access_parser_state_t * state){
625     uint32_t value = little_endian_read_24(state->data, 0);
626     mesh_access_parser_skip(state, 4);
627     return value;
628 }
629 
630 void mesh_access_parser_get_u128(mesh_access_parser_state_t * state, uint8_t * dest){
631     reverse_128( state->data, dest);
632     mesh_access_parser_skip(state, 16);
633 }
634 
635 void mesh_access_parser_get_label_uuid(mesh_access_parser_state_t * state, uint8_t * dest){
636     memcpy( dest, state->data, 16);
637     mesh_access_parser_skip(state, 16);
638 }
639 
640 void mesh_access_parser_get_key(mesh_access_parser_state_t * state, uint8_t * dest){
641     memcpy( dest, state->data, 16);
642     mesh_access_parser_skip(state, 16);
643 }
644 
645 uint32_t mesh_access_parser_get_model_identifier(mesh_access_parser_state_t * parser){
646     if (mesh_access_parser_available(parser) == 4){
647         return mesh_access_parser_get_u32(parser);
648     } else {
649         return (BLUETOOTH_COMPANY_ID_BLUETOOTH_SIG_INC << 16) | mesh_access_parser_get_u16(parser);
650     }
651 }
652 
653 // Mesh Access Message Builder
654 
655 // message builder
656 
657 static int mesh_access_setup_opcode(uint8_t * buffer, uint32_t opcode){
658     if (opcode < 0x100){
659         buffer[0] = opcode;
660         return 1;
661     }
662     if (opcode < 0x10000){
663         big_endian_store_16(buffer, 0, opcode);
664         return 2;
665     }
666     buffer[0] = opcode >> 16;
667     little_endian_store_16(buffer, 1, opcode & 0xffff);
668     return 3;
669 }
670 
671 mesh_transport_pdu_t * mesh_access_transport_init(uint32_t opcode){
672     mesh_transport_pdu_t * pdu = mesh_transport_pdu_get();
673     if (!pdu) return NULL;
674 
675     pdu->len  = mesh_access_setup_opcode(pdu->data, opcode);
676     return pdu;
677 }
678 
679 void mesh_access_transport_add_uint8(mesh_transport_pdu_t * pdu, uint8_t value){
680     pdu->data[pdu->len++] = value;
681 }
682 
683 void mesh_access_transport_add_uint16(mesh_transport_pdu_t * pdu, uint16_t value){
684     little_endian_store_16(pdu->data, pdu->len, value);
685     pdu->len += 2;
686 }
687 
688 void mesh_access_transport_add_uint24(mesh_transport_pdu_t * pdu, uint32_t value){
689     little_endian_store_24(pdu->data, pdu->len, value);
690     pdu->len += 3;
691 }
692 
693 void mesh_access_transport_add_uint32(mesh_transport_pdu_t * pdu, uint32_t value){
694     little_endian_store_32(pdu->data, pdu->len, value);
695     pdu->len += 4;
696 }
697 void mesh_access_transport_add_model_identifier(mesh_transport_pdu_t * pdu, uint32_t model_identifier){
698     if (mesh_model_is_bluetooth_sig(model_identifier)){
699         mesh_access_transport_add_uint16( pdu, mesh_model_get_model_id(model_identifier) );
700     } else {
701         mesh_access_transport_add_uint32( pdu, model_identifier );
702     }
703 }
704 
705 mesh_network_pdu_t * mesh_access_network_init(uint32_t opcode){
706     mesh_network_pdu_t * pdu = mesh_network_pdu_get();
707     if (!pdu) return NULL;
708 
709     pdu->len  = mesh_access_setup_opcode(&pdu->data[10], opcode) + 10;
710     return pdu;
711 }
712 
713 void mesh_access_network_add_uint8(mesh_network_pdu_t * pdu, uint8_t value){
714     pdu->data[pdu->len++] = value;
715 }
716 
717 void mesh_access_network_add_uint16(mesh_network_pdu_t * pdu, uint16_t value){
718     little_endian_store_16(pdu->data, pdu->len, value);
719     pdu->len += 2;
720 }
721 
722 void mesh_access_network_add_uint24(mesh_network_pdu_t * pdu, uint16_t value){
723     little_endian_store_24(pdu->data, pdu->len, value);
724     pdu->len += 3;
725 }
726 
727 void mesh_access_network_add_uint32(mesh_network_pdu_t * pdu, uint16_t value){
728     little_endian_store_32(pdu->data, pdu->len, value);
729     pdu->len += 4;
730 }
731 
732 void mesh_access_network_add_model_identifier(mesh_network_pdu_t * pdu, uint32_t model_identifier){
733     if (mesh_model_is_bluetooth_sig(model_identifier)){
734         mesh_access_network_add_uint16( pdu, mesh_model_get_model_id(model_identifier) );
735     } else {
736         mesh_access_network_add_uint32( pdu, model_identifier );
737     }
738 }
739 
740 // access message template
741 
742 mesh_network_pdu_t * mesh_access_setup_unsegmented_message(const mesh_access_message_t *template, ...){
743     mesh_network_pdu_t * network_pdu = mesh_access_network_init(template->opcode);
744     if (!network_pdu) return NULL;
745 
746     va_list argptr;
747     va_start(argptr, template);
748 
749     // add params
750     const char * format = template->format;
751     uint16_t word;
752     uint32_t longword;
753     while (*format){
754         switch (*format){
755             case '1':
756                 word = va_arg(argptr, int);  // minimal va_arg is int: 2 bytes on 8+16 bit CPUs
757                 mesh_access_network_add_uint8( network_pdu, word);
758                 break;
759             case '2':
760                 word = va_arg(argptr, int);  // minimal va_arg is int: 2 bytes on 8+16 bit CPUs
761                 mesh_access_network_add_uint16( network_pdu, word);
762                 break;
763             case '3':
764                 longword = va_arg(argptr, uint32_t);
765                 mesh_access_network_add_uint24( network_pdu, longword);
766                 break;
767             case '4':
768                 longword = va_arg(argptr, uint32_t);
769                 mesh_access_network_add_uint32( network_pdu, longword);
770                 break;
771             case 'm':
772                 longword = va_arg(argptr, uint32_t);
773                 mesh_access_network_add_model_identifier( network_pdu, longword);
774                 break;
775             default:
776                 log_error("Unsupported mesh message format specifier '%c", *format);
777                 break;
778         }
779         format++;
780     }
781 
782     va_end(argptr);
783 
784     return network_pdu;
785 }
786 
787 mesh_transport_pdu_t * mesh_access_setup_segmented_message(const mesh_access_message_t *template, ...){
788     mesh_transport_pdu_t * transport_pdu = mesh_access_transport_init(template->opcode);
789     if (!transport_pdu) return NULL;
790 
791     va_list argptr;
792     va_start(argptr, template);
793 
794     // add params
795     const char * format = template->format;
796     uint16_t word;
797     uint32_t longword;
798     while (*format){
799         switch (*format++){
800             case '1':
801                 word = va_arg(argptr, int);  // minimal va_arg is int: 2 bytes on 8+16 bit CPUs
802                 mesh_access_transport_add_uint8( transport_pdu, word);
803                 break;
804             case '2':
805                 word = va_arg(argptr, int);  // minimal va_arg is int: 2 bytes on 8+16 bit CPUs
806                 mesh_access_transport_add_uint16( transport_pdu, word);
807                 break;
808             case '3':
809                 longword = va_arg(argptr, uint32_t);
810                 mesh_access_transport_add_uint24( transport_pdu, longword);
811                 break;
812             case '4':
813                 longword = va_arg(argptr, uint32_t);
814                 mesh_access_transport_add_uint32( transport_pdu, longword);
815                 break;
816             case 'm':
817                 longword = va_arg(argptr, uint32_t);
818                 mesh_access_transport_add_model_identifier( transport_pdu, longword);
819                 break;
820             default:
821                 break;
822         }
823     }
824 
825     va_end(argptr);
826 
827     return transport_pdu;
828 }
829 
830 static const mesh_operation_t * mesh_model_lookup_operation_by_opcode(mesh_model_t * model, uint32_t opcode){
831     // find opcode in table
832     const mesh_operation_t * operation = model->operations;
833     if (operation == NULL) return NULL;
834     for ( ; operation->handler != NULL ; operation++){
835         if (operation->opcode != opcode) continue;
836         return operation;
837     }
838     return NULL;
839 }
840 
841 static const mesh_operation_t * mesh_model_lookup_operation(mesh_model_t * model, mesh_pdu_t * pdu){
842 
843     uint32_t opcode = 0;
844     uint16_t opcode_size = 0;
845     int ok = mesh_access_pdu_get_opcode( pdu, &opcode, &opcode_size);
846     if (!ok) return NULL;
847 
848     uint16_t len = mesh_pdu_len(pdu);
849 
850     // find opcode in table
851     const mesh_operation_t * operation = model->operations;
852     if (operation == NULL) return NULL;
853     for ( ; operation->handler != NULL ; operation++){
854         if (operation->opcode != opcode) continue;
855         if ((opcode_size + operation->minimum_length) > len) continue;
856         return operation;
857     }
858     return NULL;
859 }
860 
861 static int mesh_access_validate_appkey_index(mesh_model_t * model, uint16_t appkey_index){
862     // DeviceKey is valid for all models
863     if (appkey_index == MESH_DEVICE_KEY_INDEX) return 1;
864     // check if AppKey that is bound to this particular model
865     return mesh_model_contains_appkey(model, appkey_index);
866 }
867 
868 static void mesh_access_message_process_handler(mesh_pdu_t * pdu){
869     // get opcode and size
870     uint32_t opcode = 0;
871     uint16_t opcode_size = 0;
872 
873 
874     int ok = mesh_access_pdu_get_opcode( pdu, &opcode, &opcode_size);
875     if (!ok) {
876         mesh_access_message_processed(pdu);
877         return;
878     }
879 
880     uint16_t len = mesh_pdu_len(pdu);
881     printf("MESH Access Message, Opcode = %x: ", opcode);
882     printf_hexdump(mesh_pdu_data(pdu), len);
883 
884     uint16_t src = mesh_pdu_src(pdu);
885     uint16_t dst = mesh_pdu_dst(pdu);
886     uint16_t appkey_index = mesh_pdu_appkey_index(pdu);
887     if (mesh_network_address_unicast(dst)){
888         // loookup element by unicast address
889         mesh_element_t * element = mesh_node_element_for_unicast_address(dst);
890         if (element != NULL){
891             // iterate over models, look for operation
892             mesh_model_iterator_t model_it;
893             mesh_model_iterator_init(&model_it, element);
894             while (mesh_model_iterator_has_next(&model_it)){
895                 mesh_model_t * model = mesh_model_iterator_next(&model_it);
896                 // find opcode in table
897                 const mesh_operation_t * operation = mesh_model_lookup_operation(model, pdu);
898                 if (operation == NULL) continue;
899                 if (mesh_access_validate_appkey_index(model, appkey_index) == 0) continue;
900                 mesh_access_acknowledged_received(src, opcode);
901                 operation->handler(model, pdu);
902                 return;
903             }
904         }
905     }
906     else if (mesh_network_address_group(dst)){
907 
908         // handle fixed group address
909         if (dst >= 0xff00){
910             int deliver_to_primary_element = 1;
911             switch (dst){
912                 case MESH_ADDRESS_ALL_PROXIES:
913                     if (mesh_foundation_gatt_proxy_get() == 1){
914                         deliver_to_primary_element = 1;
915                     }
916                     break;
917                 case MESH_ADDRESS_ALL_FRIENDS:
918                     // TODO: not implemented
919                     break;
920                 case MESH_ADDRESS_ALL_RELAYS:
921                     if (mesh_foundation_relay_get() == 1){
922                         deliver_to_primary_element =1;
923                     }
924                     break;
925                 case MESH_ADDRESS_ALL_NODES:
926                     deliver_to_primary_element = 1;
927                     break;
928                 default:
929                     break;
930             }
931             if (deliver_to_primary_element){
932                 mesh_model_iterator_t model_it;
933                 mesh_model_iterator_init(&model_it, mesh_node_get_primary_element());
934                 while (mesh_model_iterator_has_next(&model_it)){
935                     mesh_model_t * model = mesh_model_iterator_next(&model_it);
936                     // find opcode in table
937                     const mesh_operation_t * operation = mesh_model_lookup_operation(model, pdu);
938                     if (operation == NULL) continue;
939                     if (mesh_access_validate_appkey_index(model, appkey_index) == 0) continue;
940                     mesh_access_acknowledged_received(src, opcode);
941                     operation->handler(model, pdu);
942                     return;
943                 }
944             }
945         }
946         else {
947             // iterate over all elements / models, check subscription list
948             mesh_element_iterator_t it;
949             mesh_element_iterator_init(&it);
950             while (mesh_element_iterator_has_next(&it)){
951                 mesh_element_t * element = (mesh_element_t *) mesh_element_iterator_next(&it);
952                 mesh_model_iterator_t model_it;
953                 mesh_model_iterator_init(&model_it, element);
954                 while (mesh_model_iterator_has_next(&model_it)){
955                     mesh_model_t * model = mesh_model_iterator_next(&model_it);
956                     if (mesh_model_contains_subscription(model, dst)){
957                         // find opcode in table
958                         const mesh_operation_t * operation = mesh_model_lookup_operation(model, pdu);
959                         if (operation == NULL) continue;
960                         if (mesh_access_validate_appkey_index(model, appkey_index) == 0) continue;
961                         mesh_access_acknowledged_received(src, opcode);
962                         operation->handler(model, pdu);
963                         return;
964                     }
965                 }
966             }
967         }
968     }
969 
970     // operation not found -> done
971     printf("Message not handled\n");
972     mesh_access_message_processed(pdu);
973 }
974 
975 void mesh_access_message_processed(mesh_pdu_t * pdu){
976     mesh_upper_transport_message_processed_by_higher_layer(pdu);
977 }
978 
979 int mesh_model_contains_subscription(mesh_model_t * mesh_model, uint16_t address){
980     uint16_t i;
981     for (i=0;i<MAX_NR_MESH_SUBSCRIPTION_PER_MODEL;i++){
982         if (mesh_model->subscriptions[i] == address) return 1;
983     }
984     return 0;
985 }
986 
987 // Mesh Model Publication
988 static btstack_timer_source_t mesh_access_publication_timer;
989 
990 static uint32_t mesh_model_publication_retransmit_count(uint8_t retransmit){
991     return retransmit & 0x07u;
992 }
993 
994 static uint32_t mesh_model_publication_retransmission_period_ms(uint8_t retransmit){
995     return ((uint32_t)((retransmit >> 3) + 1)) * 50;
996 }
997 
998 static void mesh_model_publication_setup_publication(mesh_publication_model_t * publication_model, uint32_t now){
999 
1000     // set retransmit counter
1001     publication_model->retransmit_count = mesh_model_publication_retransmit_count(publication_model->retransmit);
1002 
1003     // schedule next publication or retransmission
1004     uint32_t publication_period_ms = mesh_access_transitions_step_ms_from_gdtt(publication_model->period);
1005 
1006     // set next publication
1007     if (publication_period_ms != 0){
1008         publication_model->next_publication_ms = now + publication_period_ms;
1009         publication_model->state = MESH_MODEL_PUBLICATION_STATE_W4_PUBLICATION_MS;
1010     }
1011 }
1012 
1013 static void mesh_model_publication_setup_retransmission(mesh_publication_model_t * publication_model, uint32_t now){
1014     uint8_t num_retransmits = mesh_model_publication_retransmit_count(publication_model->retransmit);
1015     if (num_retransmits == 0) return;
1016 
1017     // calc next retransmit time
1018     uint32_t retransmission_ms = now + mesh_model_publication_retransmission_period_ms(publication_model->retransmit);
1019 
1020     // ignore if retransmission would be after next publication timeout
1021     if (publication_model->state == MESH_MODEL_PUBLICATION_STATE_W4_PUBLICATION_MS){
1022         if (btstack_time_delta(retransmission_ms, publication_model->next_publication_ms) > 0) return;
1023     }
1024 
1025     // schedule next retransmission
1026     publication_model->next_retransmit_ms = retransmission_ms;
1027     publication_model->state = MESH_MODEL_PUBLICATION_STATE_W4_RETRANSMIT_MS;
1028 }
1029 
1030 static void mesh_model_publication_publish_now_model(mesh_model_t * mesh_model){
1031     mesh_publication_model_t * publication_model = mesh_model->publication_model;
1032     if (publication_model == NULL) return;
1033     if (publication_model->publish_state_fn == NULL) return;
1034     uint16_t dest = publication_model->address;
1035     if (dest == MESH_ADDRESS_UNSASSIGNED) return;
1036     uint16_t appkey_index = publication_model->appkey_index;
1037     mesh_transport_key_t * app_key = mesh_transport_key_get(appkey_index);
1038     if (app_key == NULL) return;
1039 
1040     // compose message
1041     mesh_pdu_t * pdu = (*publication_model->publish_state_fn)(mesh_model);
1042     if (pdu == NULL) return;
1043 
1044     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);
1045     mesh_upper_transport_send_access_pdu(pdu);
1046 }
1047 
1048 static void mesh_model_publication_run(btstack_timer_source_t * ts){
1049     UNUSED(ts);
1050 
1051     uint32_t now = btstack_run_loop_get_time_ms();
1052 
1053     // iterate over elements and models and handle time-based transitions
1054     mesh_element_iterator_t element_it;
1055     mesh_element_iterator_init(&element_it);
1056     while (mesh_element_iterator_has_next(&element_it)){
1057         mesh_element_t * element = mesh_element_iterator_next(&element_it);
1058         mesh_model_iterator_t model_it;
1059         mesh_model_iterator_init(&model_it, element);
1060         while (mesh_model_iterator_has_next(&model_it)){
1061             mesh_model_t * mesh_model = mesh_model_iterator_next(&model_it);
1062             mesh_publication_model_t * publication_model = mesh_model->publication_model;
1063             if (publication_model == NULL) continue;
1064 
1065             // schedule next
1066             switch (publication_model->state){
1067                 case MESH_MODEL_PUBLICATION_STATE_W4_PUBLICATION_MS:
1068                     if (btstack_time_delta(publication_model->next_publication_ms, now) > 0) break;
1069                     // timeout
1070                     publication_model->publish_now = 1;
1071                     // schedule next publication and retransmission
1072                     mesh_model_publication_setup_publication(publication_model, now);
1073                     mesh_model_publication_setup_retransmission(publication_model, now);
1074                     break;
1075                 case MESH_MODEL_PUBLICATION_STATE_W4_RETRANSMIT_MS:
1076                     if (btstack_time_delta(publication_model->next_retransmit_ms, now) > 0) break;
1077                     // timeout
1078                     publication_model->publish_now = 1;
1079                     publication_model->retransmit_count--;
1080                     // schedule next retransmission
1081                     mesh_model_publication_setup_retransmission(publication_model, now);
1082                     break;
1083                 default:
1084                     break;
1085             }
1086 
1087             if (publication_model->publish_now == 0) continue;
1088 
1089             publication_model->publish_now = 0;
1090             mesh_model_publication_publish_now_model(mesh_model);
1091         }
1092     }
1093 
1094     int32_t next_timeout_ms = 0;
1095     mesh_element_iterator_init(&element_it);
1096     while (mesh_element_iterator_has_next(&element_it)){
1097         mesh_element_t * element = mesh_element_iterator_next(&element_it);
1098         mesh_model_iterator_t model_it;
1099         mesh_model_iterator_init(&model_it, element);
1100         while (mesh_model_iterator_has_next(&model_it)){
1101             mesh_model_t * mesh_model = mesh_model_iterator_next(&model_it);
1102             mesh_publication_model_t * publication_model = mesh_model->publication_model;
1103             if (publication_model == NULL) continue;
1104 
1105             // schedule next
1106             int32_t timeout_delta_ms;
1107             switch (publication_model->state){
1108                 case MESH_MODEL_PUBLICATION_STATE_W4_PUBLICATION_MS:
1109                     timeout_delta_ms = btstack_time_delta(publication_model->next_publication_ms, now);
1110                     if (next_timeout_ms == 0 || timeout_delta_ms < next_timeout_ms){
1111                         next_timeout_ms = timeout_delta_ms;
1112                     }
1113                     break;
1114                 case MESH_MODEL_PUBLICATION_STATE_W4_RETRANSMIT_MS:
1115                     timeout_delta_ms = btstack_time_delta(publication_model->next_retransmit_ms, now);
1116                     if (next_timeout_ms == 0 || timeout_delta_ms < next_timeout_ms){
1117                         next_timeout_ms = timeout_delta_ms;
1118                     }
1119                     break;
1120                 default:
1121                     break;
1122             }
1123         }
1124     }
1125 
1126     // set timer
1127     if (next_timeout_ms == 0) return;
1128 
1129     btstack_run_loop_set_timer(&mesh_access_publication_timer, next_timeout_ms);
1130     btstack_run_loop_set_timer_handler(&mesh_access_publication_timer, mesh_model_publication_run);
1131     btstack_run_loop_add_timer(&mesh_access_publication_timer);
1132 }
1133 
1134 void mesh_model_publication_start(mesh_model_t * mesh_model){
1135     mesh_publication_model_t * publication_model = mesh_model->publication_model;
1136     if (publication_model == NULL) return;
1137 
1138     // reset state
1139     publication_model->state = MESH_MODEL_PUBLICATION_STATE_IDLE;
1140 
1141     // publish right away
1142     publication_model->publish_now = 1;
1143 
1144     // setup next publication and retransmission
1145     uint32_t now = btstack_run_loop_get_time_ms();
1146     mesh_model_publication_setup_publication(publication_model, now);
1147     mesh_model_publication_setup_retransmission(publication_model, now);
1148 
1149     mesh_model_publication_run(NULL);
1150 }
1151 
1152 void mesh_model_publication_stop(mesh_model_t * mesh_model){
1153     mesh_publication_model_t * publication_model = mesh_model->publication_model;
1154     if (publication_model == NULL) return;
1155 
1156     // reset state
1157     publication_model->state = MESH_MODEL_PUBLICATION_STATE_IDLE;
1158 }
1159 
1160 void mesh_access_state_changed(mesh_model_t * mesh_model){
1161     mesh_publication_model_t * publication_model = mesh_model->publication_model;
1162     if (publication_model == NULL) return;
1163     publication_model->publish_now = 1;
1164     mesh_model_publication_run(NULL);
1165 }
1166 
1167 static void mesh_access_secure_network_beacon_handler(uint8_t packet_type, uint16_t channel, uint8_t * packet, uint16_t size){
1168     UNUSED(channel);
1169     UNUSED(size);
1170 
1171     if (packet_type != MESH_BEACON_PACKET) return;
1172 
1173     // lookup subnet and netkey by network id
1174     uint8_t * beacon_network_id = &packet[2];
1175     mesh_subnet_iterator_t it;
1176     mesh_subnet_iterator_init(&it);
1177     mesh_subnet_t * subnet = NULL;
1178     uint8_t new_key = 0;
1179     while (mesh_subnet_iterator_has_more(&it)){
1180         mesh_subnet_t * item = mesh_subnet_iterator_get_next(&it);
1181         if (memcmp(item->old_key->network_id, beacon_network_id, 8) == 0 ) {
1182             subnet = item;
1183         }
1184         if (item->new_key != NULL && memcmp(item->new_key->network_id, beacon_network_id, 8) == 0 ) {
1185             subnet = item;
1186             new_key = 1;
1187         }
1188         break;
1189     }
1190     if (subnet == NULL) return;
1191 
1192     uint8_t flags = packet[1];
1193 
1194     // Key refresh via secure network beacons that are authenticated with new netkey
1195     if (new_key){
1196         // either first or second phase (in phase 0, new key is not set)
1197         int key_refresh_flag = flags & 1;
1198         if (key_refresh_flag){
1199             //  transition to phase 3 from either phase 1 or 2
1200             switch (subnet->key_refresh){
1201                 case MESH_KEY_REFRESH_FIRST_PHASE:
1202                 case MESH_KEY_REFRESH_SECOND_PHASE:
1203                     mesh_access_key_refresh_revoke_keys(subnet);
1204                     subnet->key_refresh = MESH_KEY_REFRESH_NOT_ACTIVE;
1205                     break;
1206                 default:
1207                     break;
1208             }
1209         } else {
1210             //  transition to phase 2 from either phase 1
1211             switch (subnet->key_refresh){
1212                 case MESH_KEY_REFRESH_FIRST_PHASE:
1213                     // -- update state
1214                     subnet->key_refresh = MESH_KEY_REFRESH_SECOND_PHASE;
1215                     break;
1216                 default:
1217                     break;
1218             }
1219         }
1220     }
1221 
1222     // IV Update
1223 
1224     int     beacon_iv_update_active = flags & 2;
1225     int     local_iv_update_active = mesh_iv_update_active();
1226     uint32_t beacon_iv_index = big_endian_read_32(packet, 10);
1227     uint32_t local_iv_index = mesh_get_iv_index();
1228 
1229     int32_t iv_index_delta = (int32_t)(beacon_iv_index - local_iv_index);
1230 
1231     // "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
1232     //  the last known IV Index + 42, the Secure Network beacon shall be ignored."
1233     if (iv_index_delta < 0 || iv_index_delta > 42){
1234         return;
1235     }
1236 
1237     // "If a node in Normal Operation receives a Secure Network beacon with an IV index equal to the last known IV index+1 and
1238     //  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
1239     //  an IV Index Recovery procedure (Section 3.10.6), or it may ignore the Secure Network beacon. The node makes the choice depending
1240     //  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.""
1241     if (local_iv_update_active == 0 && beacon_iv_update_active == 0 && iv_index_delta == 1){
1242         // instant iv update
1243         mesh_set_iv_index( beacon_iv_index );
1244         // store updated iv index
1245         mesh_store_iv_index_and_sequence_number();
1246         return;
1247     }
1248 
1249     // "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
1250     //  the last known IV Index of the primary subnet, the Secure Network beacon shall be ignored."
1251     int member_of_primary_subnet = mesh_subnet_get_by_netkey_index(0) != NULL;
1252     int beacon_on_secondary_subnet = subnet->netkey_index != 0;
1253     if (member_of_primary_subnet && beacon_on_secondary_subnet && iv_index_delta > 0){
1254         return;
1255     }
1256 
1257     // "If a node in Normal Operation receives a Secure Network beacon with an IV index greater than the last known IV Index + 1..."
1258     // "... it may initiate an IV Index Recovery procedure, see Section 3.10.6."
1259     if (local_iv_update_active == 0 && iv_index_delta > 1){
1260         // "Upon receiving and successfully authenticating a Secure Network beacon for a primary subnet... "
1261         int beacon_on_primary_subnet = subnet->netkey_index == 0;
1262         if (!beacon_on_primary_subnet) return;
1263         // "... whose IV Index is 1 or more higher than the current known IV Index, the node shall "
1264         // " set its current IV Index and its current IV Update procedure state from the values in this Secure Network beacon."
1265         mesh_iv_index_recovered(beacon_iv_update_active, beacon_iv_index);
1266         // store updated iv index if in normal mode
1267         if (beacon_iv_update_active == 0){
1268             mesh_store_iv_index_and_sequence_number();
1269         }
1270         return;
1271     }
1272 
1273     if (local_iv_update_active == 0){
1274         if (beacon_iv_update_active){
1275             mesh_trigger_iv_update();
1276         }
1277     } else {
1278         if (beacon_iv_update_active == 0){
1279             // " At the point of transition, the node shall reset the sequence number to 0x000000."
1280             mesh_sequence_number_set(0);
1281             mesh_iv_update_completed();
1282             // store updated iv index
1283             mesh_store_iv_index_and_sequence_number();
1284         }
1285     }
1286 }
1287