xref: /btstack/src/mesh/mesh_access.c (revision 6e7785c71c373163bf88f2745fe7af620f8dd2f8)
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 #include "mesh_upper_transport.h"
58 
59 #define MEST_TRANSACTION_TIMEOUT_MS  6000
60 
61 static void mesh_access_message_process_handler(mesh_pdu_t * pdu);
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 // receive
66 static uint16_t mesh_access_received_pdu_refcount;
67 
68 // acknowledged messages
69 static btstack_linked_list_t  mesh_access_acknowledged_messages;
70 static btstack_timer_source_t mesh_access_acknowledged_timer;
71 static int                    mesh_access_acknowledged_timer_active;
72 
73 // Transitions
74 static uint8_t mesh_transaction_id_counter = 0;
75 
76 void mesh_access_init(void){
77     // register with upper transport
78     mesh_upper_transport_register_access_message_handler(&mesh_access_upper_transport_handler);
79 }
80 
81 void mesh_access_emit_state_update_bool(btstack_packet_handler_t event_handler, uint8_t element_index, uint32_t model_identifier,
82     model_state_id_t state_identifier, model_state_update_reason_t reason, uint8_t value){
83     if (event_handler == NULL) return;
84     uint8_t event[14] = {HCI_EVENT_MESH_META, 12, MESH_SUBEVENT_STATE_UPDATE_BOOL};
85     int pos = 3;
86     event[pos++] = element_index;
87     little_endian_store_32(event, pos, model_identifier);
88     pos += 4;
89     little_endian_store_32(event, pos, (uint32_t)state_identifier);
90     pos += 4;
91     event[pos++] = (uint8_t)reason;
92     event[pos++] = value;
93     (*event_handler)(HCI_EVENT_PACKET, 0, event, sizeof(event));
94 }
95 
96 void mesh_access_emit_state_update_int16(btstack_packet_handler_t event_handler, uint8_t element_index, uint32_t model_identifier,
97     model_state_id_t state_identifier, model_state_update_reason_t reason, int16_t value){
98     if (event_handler == NULL) return;
99     uint8_t event[15] = {HCI_EVENT_MESH_META, 13, MESH_SUBEVENT_STATE_UPDATE_BOOL};
100     int pos = 3;
101     event[pos++] = element_index;
102     little_endian_store_32(event, pos, model_identifier);
103     pos += 4;
104     little_endian_store_32(event, pos, (uint32_t)state_identifier);
105     pos += 4;
106     event[pos++] = (uint8_t)reason;
107     little_endian_store_16(event, pos, (uint16_t) value);
108     pos += 2;
109     (*event_handler)(HCI_EVENT_PACKET, 0, event, sizeof(event));
110 }
111 
112 uint8_t mesh_access_acknowledged_message_retransmissions(void){
113     return 3;
114 }
115 
116 uint32_t mesh_access_acknowledged_message_timeout_ms(void){
117     return 30000;
118 }
119 
120 #define MESH_ACCESS_OPCODE_INVALID 0xFFFFFFFFu
121 #define MESH_ACCESS_OPCODE_NOT_SET 0xFFFFFFFEu
122 
123 void mesh_access_send_unacknowledged_pdu(mesh_pdu_t * pdu){
124     ((mesh_upper_transport_pdu_t *) pdu)->ack_opcode = MESH_ACCESS_OPCODE_INVALID;
125     mesh_upper_transport_send_access_pdu(pdu);
126 }
127 
128 void mesh_access_send_acknowledged_pdu(mesh_pdu_t * pdu, uint8_t retransmissions, uint32_t ack_opcode){
129     ((mesh_upper_transport_pdu_t *) pdu)->retransmit_count = retransmissions;
130     ((mesh_upper_transport_pdu_t *) pdu)->ack_opcode = ack_opcode;
131 
132     mesh_upper_transport_send_access_pdu(pdu);
133 }
134 
135 #define MESH_SUBEVENT_MESSAGE_NOT_ACKNOWLEDGED                                        0x30
136 
137 static void mesh_access_acknowledged_run(btstack_timer_source_t * ts){
138     UNUSED(ts);
139 
140     uint32_t now = btstack_run_loop_get_time_ms();
141 
142     // handle timeouts
143     btstack_linked_list_iterator_t ack_it;
144     btstack_linked_list_iterator_init(&ack_it, &mesh_access_acknowledged_messages);
145     while (btstack_linked_list_iterator_has_next(&ack_it)){
146         mesh_pdu_t * pdu = (mesh_pdu_t *) btstack_linked_list_iterator_next(&ack_it);
147         uint32_t retransmit_timeout_ms = ((mesh_upper_transport_pdu_t *) pdu)->retransmit_timeout_ms;
148         if (btstack_time_delta(now, retransmit_timeout_ms) >= 0) {
149             // remove from list
150             btstack_linked_list_remove(&mesh_access_acknowledged_messages, (btstack_linked_item_t*) pdu);
151             // retransmit or report failure
152             uint8_t retransmit_count = ((mesh_upper_transport_pdu_t *) pdu)->retransmit_count;
153             if (retransmit_count){
154                 ((mesh_upper_transport_pdu_t *) pdu)->retransmit_count = retransmit_count - 1;
155                 mesh_upper_transport_send_access_pdu(pdu);
156             } else {
157                 // find correct model and emit error
158                 uint16_t src = mesh_pdu_src(pdu);
159                 uint16_t dst = mesh_pdu_dst(pdu);
160                 mesh_element_t * element = mesh_node_element_for_unicast_address(src);
161                 if (element){
162                     // find
163                     mesh_model_iterator_t model_it;
164                     mesh_model_iterator_init(&model_it, element);
165                     while (mesh_model_iterator_has_next(&model_it)){
166                         mesh_model_t * model = mesh_model_iterator_next(&model_it);
167                         // find opcode in table
168                         uint32_t ack_opcode = ((mesh_upper_transport_pdu_t *) pdu)->ack_opcode;
169                         const mesh_operation_t * operation = mesh_model_lookup_operation_by_opcode(model, ack_opcode);
170                         if (operation == NULL) continue;
171                         if (model->model_packet_handler == NULL) continue;
172                         // emit event
173                         uint8_t event[13];
174                         event[0] = HCI_EVENT_MESH_META;
175                         event[1] = sizeof(event) - 2;
176                         event[2] = element->element_index;
177                         little_endian_store_32(event, 3, model->model_identifier);
178                         little_endian_store_32(event, 7, ack_opcode);
179                         little_endian_store_16(event, 11, dst);
180                         (*model->model_packet_handler)(HCI_EVENT_PACKET, 0, event, sizeof(event));
181                     }
182                 }
183 
184                 // free
185                 mesh_upper_transport_pdu_free(pdu);
186             }
187         }
188     }
189 
190     if (mesh_access_acknowledged_timer_active) return;
191 
192     // find earliest timeout and set timer
193     btstack_linked_list_iterator_init(&ack_it, &mesh_access_acknowledged_messages);
194     int32_t next_timeout_ms = 0;
195     while (btstack_linked_list_iterator_has_next(&ack_it)){
196         mesh_pdu_t * pdu = (mesh_pdu_t *) btstack_linked_list_iterator_next(&ack_it);
197         uint32_t retransmit_timeout_ms = ((mesh_upper_transport_pdu_t *) pdu)->retransmit_timeout_ms;
198         int32_t timeout_delta_ms = btstack_time_delta(retransmit_timeout_ms, now);
199         if (next_timeout_ms == 0 || timeout_delta_ms < next_timeout_ms){
200             next_timeout_ms = timeout_delta_ms;
201         }
202     }
203 
204     // set timer
205     if (next_timeout_ms == 0) return;
206 
207     btstack_run_loop_set_timer(&mesh_access_acknowledged_timer, next_timeout_ms);
208     btstack_run_loop_set_timer_handler(&mesh_access_acknowledged_timer, mesh_access_acknowledged_run);
209     btstack_run_loop_add_timer(&mesh_access_acknowledged_timer);
210     mesh_access_acknowledged_timer_active = 1;
211 }
212 
213 static void mesh_access_acknowledged_received(uint16_t rx_src, uint32_t opcode){
214     // check if received src matches our dest
215     // free acknowledged messages if we were waiting for this message
216 
217     btstack_linked_list_iterator_t ack_it;
218     btstack_linked_list_iterator_init(&ack_it, &mesh_access_acknowledged_messages);
219     while (btstack_linked_list_iterator_has_next(&ack_it)){
220         mesh_pdu_t * tx_pdu = (mesh_pdu_t *) btstack_linked_list_iterator_next(&ack_it);
221         uint16_t tx_dest = mesh_pdu_dst(tx_pdu);
222         if (tx_dest != rx_src) continue;
223         if (((mesh_upper_transport_pdu_t *) tx_pdu)->ack_opcode != opcode) continue;
224         // got expected response from dest, remove from outgoing messages
225         mesh_upper_transport_pdu_free(tx_pdu);
226         return;
227     }
228 }
229 
230 static void mesh_access_upper_transport_handler(mesh_transport_callback_type_t callback_type, mesh_transport_status_t status, mesh_pdu_t * pdu){
231     UNUSED(status);
232     switch (callback_type){
233         case MESH_TRANSPORT_PDU_RECEIVED:
234             mesh_access_message_process_handler(pdu);
235             break;
236         case MESH_TRANSPORT_PDU_SENT:
237             // unacknowledged -> free
238         {
239             if (((mesh_upper_transport_pdu_t *) pdu)->ack_opcode == MESH_ACCESS_OPCODE_INVALID){
240                 mesh_upper_transport_pdu_free(pdu);
241                 break;
242             }
243         }
244             // setup timeout
245             uint32_t retransmitTimeoutMs =
246                     btstack_run_loop_get_time_ms() + mesh_access_acknowledged_message_timeout_ms();
247             ((mesh_upper_transport_pdu_t *) pdu)->retransmit_timeout_ms = retransmitTimeoutMs;
248             // add to mesh_access_acknowledged_messages
249             btstack_linked_list_add(&mesh_access_acknowledged_messages, (btstack_linked_item_t *) pdu);
250             // update timer
251             mesh_access_acknowledged_run(NULL);
252             break;
253         default:
254             break;
255     }
256 }
257 
258 // Mesh Model Transitions
259 
260 uint32_t mesh_access_time_gdtt2ms(uint8_t time_gdtt){
261     uint8_t num_steps  = mesh_access_transitions_num_steps_from_gdtt(time_gdtt);
262     if (num_steps > 0x3E) return 0;
263 
264     return mesh_access_transitions_step_ms_from_gdtt(time_gdtt) * num_steps;
265 }
266 
267 uint8_t mesh_access_transitions_num_steps_from_gdtt(uint8_t time_gdtt){
268     return time_gdtt & 0x3fu;
269 }
270 
271 uint32_t mesh_access_transitions_step_ms_from_gdtt(uint8_t time_gdtt){
272     mesh_default_transition_step_resolution_t step_resolution = (mesh_default_transition_step_resolution_t) (time_gdtt >> 6);
273     switch (step_resolution){
274         case MESH_DEFAULT_TRANSITION_STEP_RESOLUTION_100ms:
275             return 100;
276         case MESH_DEFAULT_TRANSITION_STEP_RESOLUTION_1s:
277             return 1000;
278         case MESH_DEFAULT_TRANSITION_STEP_RESOLUTION_10s:
279             return 10000;
280         case MESH_DEFAULT_TRANSITION_STEP_RESOLUTION_10min:
281             return 600000;
282         default:
283             return 0;
284     }
285 }
286 
287 uint8_t mesh_access_transactions_get_next_transaction_id(void){
288     mesh_transaction_id_counter++;
289     if (mesh_transaction_id_counter == 0){
290         mesh_transaction_id_counter = 1;
291     }
292     return mesh_transaction_id_counter;
293 }
294 
295 static int mesh_access_transitions_transaction_is_expired(mesh_transition_t * transition){
296     return (btstack_run_loop_get_time_ms() - transition->transaction_timestamp_ms) > MEST_TRANSACTION_TIMEOUT_MS;
297 }
298 
299 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){
300     if (transition->src_address != src_address || transition->dst_address != dst_address) return MESH_TRANSACTION_STATUS_DIFFERENT_DST_OR_SRC;
301 
302     if (transition->transaction_identifier == transaction_identifier && !mesh_access_transitions_transaction_is_expired(transition)){
303             return MESH_TRANSACTION_STATUS_RETRANSMISSION;
304     }
305     return MESH_TRANSACTION_STATUS_NEW;
306 }
307 
308 void mesh_access_transitions_init_transaction(mesh_transition_t * transition, uint8_t transaction_identifier, uint16_t src_address, uint16_t dst_address){
309     transition->transaction_timestamp_ms = btstack_run_loop_get_time_ms();
310     transition->transaction_identifier = transaction_identifier;
311     transition->src_address = src_address;
312     transition->dst_address = dst_address;
313 }
314 
315 static void mesh_server_transition_timeout(btstack_timer_source_t * ts){
316     mesh_transition_t * base_transition = (mesh_transition_t*) btstack_run_loop_get_timer_context(ts);
317     switch (base_transition->state){
318         case MESH_TRANSITION_STATE_DELAYED:
319             base_transition->state = MESH_TRANSITION_STATE_ACTIVE;
320             (*base_transition->transition_callback)(base_transition, MODEL_STATE_UPDATE_REASON_TRANSITION_START);
321             if (base_transition->num_steps > 0){
322                 btstack_run_loop_set_timer(&base_transition->timer, base_transition->step_duration_ms);
323                 btstack_run_loop_add_timer(&base_transition->timer);
324                 return;
325             }
326             base_transition->state = MESH_TRANSITION_STATE_IDLE;
327             (*base_transition->transition_callback)(base_transition, MODEL_STATE_UPDATE_REASON_TRANSITION_END);
328             break;
329         case MESH_TRANSITION_STATE_ACTIVE:
330             if (base_transition->num_steps < MESH_TRANSITION_NUM_STEPS_INFINITE){
331                 base_transition->num_steps--;
332             }
333             (*base_transition->transition_callback)(base_transition, MODEL_STATE_UPDATE_REASON_TRANSITION_ACTIVE);
334             if (base_transition->num_steps > 0){
335                 btstack_run_loop_set_timer(&base_transition->timer, base_transition->step_duration_ms);
336                 btstack_run_loop_add_timer(&base_transition->timer);
337                 return;
338             }
339             base_transition->state = MESH_TRANSITION_STATE_IDLE;
340             (*base_transition->transition_callback)(base_transition, MODEL_STATE_UPDATE_REASON_TRANSITION_END);
341             break;
342         default:
343             break;
344     }
345 }
346 
347 void mesh_access_transition_setup(mesh_model_t *mesh_model, mesh_transition_t * base_transition, uint8_t transition_time_gdtt, uint8_t delay_time_gdtt, void (*transition_callback)(mesh_transition_t * base_transition, model_state_update_reason_t event)){
348 
349     base_transition->mesh_model          = mesh_model;
350     base_transition->num_steps           = mesh_access_transitions_num_steps_from_gdtt(transition_time_gdtt);
351     base_transition->step_resolution     = (mesh_default_transition_step_resolution_t) (transition_time_gdtt >> 6);
352     base_transition->step_duration_ms    = mesh_access_transitions_step_ms_from_gdtt(transition_time_gdtt);
353     base_transition->transition_callback = transition_callback;
354 
355     btstack_run_loop_set_timer_context(&base_transition->timer, base_transition);
356     btstack_run_loop_set_timer_handler(&base_transition->timer, &mesh_server_transition_timeout);
357 
358     // delayed
359     if (delay_time_gdtt > 0){
360         base_transition->state = MESH_TRANSITION_STATE_DELAYED;
361         btstack_run_loop_set_timer(&base_transition->timer, delay_time_gdtt * 5);
362         btstack_run_loop_add_timer(&base_transition->timer);
363         return;
364     }
365 
366     // started
367     if (base_transition->num_steps > 0){
368         base_transition->state = MESH_TRANSITION_STATE_ACTIVE;
369         btstack_run_loop_set_timer(&base_transition->timer, base_transition->step_duration_ms);
370         btstack_run_loop_add_timer(&base_transition->timer);
371         return;
372     }
373 
374     // instanteneous update
375     base_transition->state = MESH_TRANSITION_STATE_IDLE;
376     (*transition_callback)(base_transition, MODEL_STATE_UPDATE_REASON_SET);
377     return;
378 }
379 
380 void mesh_access_transitions_abort_transaction(mesh_transition_t * base_transition){
381     btstack_run_loop_add_timer(&base_transition->timer);
382 }
383 
384 static uint16_t mesh_access_src(mesh_access_pdu_t * access_pdu){
385     return access_pdu->src;
386 }
387 
388 uint16_t mesh_pdu_ctl(mesh_pdu_t * pdu){
389     switch (pdu->pdu_type){
390         case MESH_PDU_TYPE_NETWORK:
391             return mesh_network_control((mesh_network_pdu_t *) pdu);
392         default:
393             btstack_assert(false);
394             return 0;
395     }
396 }
397 
398 uint16_t mesh_pdu_ttl(mesh_pdu_t * pdu){
399     switch (pdu->pdu_type){
400         case MESH_PDU_TYPE_NETWORK:
401             return mesh_network_ttl((mesh_network_pdu_t *) pdu);
402         default:
403             btstack_assert(false);
404             return 0;
405     }
406 }
407 
408 uint16_t mesh_pdu_src(mesh_pdu_t * pdu){
409     switch (pdu->pdu_type){
410         case MESH_PDU_TYPE_ACCESS:
411             return mesh_access_src((mesh_access_pdu_t *) pdu);
412         case MESH_PDU_TYPE_NETWORK:
413             return mesh_network_src((mesh_network_pdu_t *) pdu);
414         default:
415             btstack_assert(false);
416             return MESH_ADDRESS_UNSASSIGNED;
417     }
418 }
419 
420 uint16_t mesh_pdu_dst(mesh_pdu_t * pdu){
421     switch (pdu->pdu_type){
422         case MESH_PDU_TYPE_ACCESS: {
423             return ((mesh_access_pdu_t *) pdu)->dst;
424         }
425         case MESH_PDU_TYPE_NETWORK:
426             return mesh_network_dst((mesh_network_pdu_t *) pdu);
427         case MESH_PDU_TYPE_UPPER_UNSEGMENTED_ACCESS:
428             return ((mesh_upper_transport_pdu_t *) pdu)->dst;
429         default:
430             btstack_assert(false);
431             return MESH_ADDRESS_UNSASSIGNED;
432     }
433 }
434 
435 uint16_t mesh_pdu_netkey_index(mesh_pdu_t * pdu){
436     switch (pdu->pdu_type){
437         case MESH_PDU_TYPE_ACCESS:
438             return ((mesh_access_pdu_t*) pdu)->netkey_index;
439         case MESH_PDU_TYPE_NETWORK:
440             return ((mesh_network_pdu_t *) pdu)->netkey_index;
441         default:
442             btstack_assert(false);
443             return 0;
444     }
445 }
446 
447 uint16_t mesh_pdu_appkey_index(mesh_pdu_t * pdu){
448     switch (pdu->pdu_type){
449         case MESH_PDU_TYPE_ACCESS:
450             return ((mesh_access_pdu_t*) pdu)->appkey_index;
451         default:
452             btstack_assert(false);
453             return 0;
454     }
455 }
456 
457 uint16_t mesh_pdu_len(mesh_pdu_t * pdu){
458     switch (pdu->pdu_type){
459         case MESH_PDU_TYPE_ACCESS:
460             return ((mesh_access_pdu_t*) pdu)->len;
461         case MESH_PDU_TYPE_NETWORK:
462             return ((mesh_network_pdu_t *) pdu)->len - 10;
463         default:
464             btstack_assert(false);
465             return 0;
466     }
467 }
468 
469 uint8_t * mesh_pdu_data(mesh_pdu_t * pdu){
470     switch (pdu->pdu_type){
471         case MESH_PDU_TYPE_ACCESS:
472             return ((mesh_access_pdu_t*) pdu)->data;
473         case MESH_PDU_TYPE_NETWORK:
474             return &((mesh_network_pdu_t *) pdu)->data[10];
475         default:
476             btstack_assert(false);
477             return NULL;
478     }
479 }
480 
481 uint8_t mesh_pdu_control_opcode(mesh_pdu_t * pdu){
482     switch (pdu->pdu_type){
483         case MESH_PDU_TYPE_NETWORK:
484             return mesh_network_control_opcode((mesh_network_pdu_t *) pdu);
485         default:
486             btstack_assert(false);
487             return 0xff;
488     }
489 }
490 
491 // message parser
492 
493 static int mesh_access_get_opcode(uint8_t * buffer, uint16_t buffer_size, uint32_t * opcode, uint16_t * opcode_size){
494     switch (buffer[0] >> 6){
495         case 0:
496         case 1:
497             if (buffer[0] == 0x7f) return 0;
498             *opcode = buffer[0];
499             *opcode_size = 1;
500             return 1;
501         case 2:
502             if (buffer_size < 2) return 0;
503             *opcode = big_endian_read_16(buffer, 0);
504             *opcode_size = 2;
505             return 1;
506         case 3:
507             if (buffer_size < 3) return 0;
508             *opcode = (buffer[0] << 16) | little_endian_read_16(buffer, 1);
509             *opcode_size = 3;
510             return 1;
511         default:
512             return 0;
513     }
514 }
515 
516 int mesh_access_pdu_get_opcode(mesh_pdu_t * pdu, uint32_t * opcode, uint16_t * opcode_size){
517     btstack_assert(pdu->pdu_type == MESH_PDU_TYPE_ACCESS);
518     return mesh_access_get_opcode(((mesh_access_pdu_t *) pdu)->data, ((mesh_access_pdu_t *) pdu)->len, opcode,
519                                   opcode_size);
520 }
521 
522 void mesh_access_parser_skip(mesh_access_parser_state_t * state, uint16_t bytes_to_skip){
523     state->data += bytes_to_skip;
524     state->len  -= bytes_to_skip;
525 }
526 
527 int mesh_access_parser_init(mesh_access_parser_state_t * state, mesh_pdu_t * pdu){
528     btstack_assert(pdu->pdu_type == MESH_PDU_TYPE_ACCESS);
529     state->data = mesh_pdu_data(pdu);
530     state->len  = mesh_pdu_len(pdu);
531 
532     uint16_t opcode_size = 0;
533     int ok = mesh_access_get_opcode(state->data, state->len, &state->opcode, &opcode_size);
534     if (ok){
535         mesh_access_parser_skip(state, opcode_size);
536     }
537     return ok;
538 }
539 
540 uint16_t mesh_access_parser_available(mesh_access_parser_state_t * state){
541     return state->len;
542 }
543 
544 uint8_t mesh_access_parser_get_uint8(mesh_access_parser_state_t * state){
545     uint8_t value = *state->data;
546     mesh_access_parser_skip(state, 1);
547     return value;
548 }
549 
550 uint16_t mesh_access_parser_get_uint16(mesh_access_parser_state_t * state){
551     uint16_t value = little_endian_read_16(state->data, 0);
552     mesh_access_parser_skip(state, 2);
553     return value;
554 }
555 
556 uint32_t mesh_access_parser_get_uint24(mesh_access_parser_state_t * state){
557     uint32_t value = little_endian_read_24(state->data, 0);
558     mesh_access_parser_skip(state, 3);
559     return value;
560 }
561 
562 uint32_t mesh_access_parser_get_uint32(mesh_access_parser_state_t * state){
563     uint32_t value = little_endian_read_32(state->data, 0);
564     mesh_access_parser_skip(state, 4);
565     return value;
566 }
567 
568 void mesh_access_parser_get_uint128(mesh_access_parser_state_t * state, uint8_t * dest){
569     reverse_128( state->data, dest);
570     mesh_access_parser_skip(state, 16);
571 }
572 
573 void mesh_access_parser_get_label_uuid(mesh_access_parser_state_t * state, uint8_t * dest){
574     (void)memcpy(dest, state->data, 16);
575     mesh_access_parser_skip(state, 16);
576 }
577 
578 void mesh_access_parser_get_key(mesh_access_parser_state_t * state, uint8_t * dest){
579     (void)memcpy(dest, state->data, 16);
580     mesh_access_parser_skip(state, 16);
581 }
582 
583 uint32_t mesh_access_parser_get_model_identifier(mesh_access_parser_state_t * parser){
584     uint16_t vendor_id = BLUETOOTH_COMPANY_ID_BLUETOOTH_SIG_INC;
585     if (mesh_access_parser_available(parser) == 4){
586         vendor_id = mesh_access_parser_get_uint16(parser);
587     }
588     uint16_t model_id = mesh_access_parser_get_uint16(parser);
589     return mesh_model_get_model_identifier(vendor_id, model_id);
590 }
591 
592 uint32_t mesh_access_parser_get_sig_model_identifier(mesh_access_parser_state_t * parser){
593     uint16_t model_id = mesh_access_parser_get_uint16(parser);
594     return mesh_model_get_model_identifier(BLUETOOTH_COMPANY_ID_BLUETOOTH_SIG_INC, model_id);
595 }
596 
597 uint32_t mesh_access_parser_get_vendor_model_identifier(mesh_access_parser_state_t * parser){
598     uint16_t vendor_id = mesh_access_parser_get_uint16(parser);
599     uint16_t model_id  = mesh_access_parser_get_uint16(parser);
600     return mesh_model_get_model_identifier(vendor_id, model_id);
601 }
602 
603 // Mesh Access Message Builder
604 
605 // message builder
606 
607 static int mesh_access_setup_opcode(uint8_t * buffer, uint32_t opcode){
608     if (opcode < 0x100){
609         buffer[0] = opcode;
610         return 1;
611     }
612     if (opcode < 0x10000){
613         big_endian_store_16(buffer, 0, opcode);
614         return 2;
615     }
616     buffer[0] = opcode >> 16;
617     little_endian_store_16(buffer, 1, opcode & 0xffff);
618     return 3;
619 }
620 
621 // mesh_message_t builder
622 
623 void mesh_access_message_init(mesh_upper_transport_builder_t * builder, uint32_t opcode) {
624     mesh_upper_transport_message_init(builder, MESH_PDU_TYPE_UPPER_UNSEGMENTED_ACCESS);
625 
626     // add opcode
627     uint8_t opcode_buffer[3];
628     uint8_t opcode_len = mesh_access_setup_opcode(opcode_buffer, opcode);
629     mesh_access_message_add_data(builder, opcode_buffer, opcode_len);
630 }
631 
632 void mesh_access_message_add_data(mesh_upper_transport_builder_t * pdu, const uint8_t * data, uint16_t data_len){
633     mesh_upper_transport_message_add_data(pdu, data, data_len);
634 }
635 
636 void mesh_access_message_add_uint8(mesh_upper_transport_builder_t * builder, uint8_t value){
637     mesh_upper_transport_message_add_uint8(builder, value);
638 }
639 
640 void mesh_access_message_add_uint16(mesh_upper_transport_builder_t * builder, uint16_t value){
641     mesh_upper_transport_message_add_uint16(builder, value);
642 }
643 
644 void mesh_access_message_add_uint24(mesh_upper_transport_builder_t * builder, uint16_t value){
645     mesh_upper_transport_message_add_uint24(builder, value);
646 }
647 
648 void mesh_access_message_add_uint32(mesh_upper_transport_builder_t * builder, uint16_t value){
649     mesh_upper_transport_message_add_uint32(builder, value);
650 }
651 
652 void mesh_access_message_add_model_identifier(mesh_upper_transport_builder_t * builder, uint32_t model_identifier){
653     if (mesh_model_is_bluetooth_sig(model_identifier)){
654         return mesh_access_message_add_uint16(builder, mesh_model_get_model_id(model_identifier) );
655     } else {
656         return mesh_access_message_add_uint32(builder, model_identifier );
657     }
658 }
659 
660 mesh_upper_transport_pdu_t * mesh_access_message_finalize(mesh_upper_transport_builder_t * builder){
661     mesh_upper_transport_pdu_t * upper_pdu = mesh_upper_transport_message_finalize(builder);
662     if (upper_pdu == NULL) return NULL;
663 
664     // upgrade to segmented if needed
665     if (upper_pdu->pdu_header.pdu_type == MESH_PDU_TYPE_UPPER_UNSEGMENTED_ACCESS) {
666         if (((upper_pdu->flags & MESH_TRANSPORT_FLAG_TRANSMIC_64) != 0) || (upper_pdu->len > 11)){
667             upper_pdu->pdu_header.pdu_type = MESH_PDU_TYPE_UPPER_SEGMENTED_ACCESS;
668         }
669     }
670     return upper_pdu;
671 }
672 
673 // access message template
674 mesh_upper_transport_pdu_t * mesh_access_setup_message(const mesh_access_message_t *message_template, ...){
675 
676     mesh_upper_transport_builder_t builder;
677     mesh_access_message_init(&builder, message_template->opcode);
678 
679     va_list argptr;
680     va_start(argptr, message_template);
681 
682     // add params
683     const char * format = message_template->format;
684     uint16_t word;
685     uint32_t longword;
686     while (*format){
687         switch (*format){
688             case '1':
689                 word = va_arg(argptr, int);  // minimal va_arg is int: 2 bytes on 8+16 bit CPUs
690                 mesh_access_message_add_uint8(&builder, word);
691                 break;
692             case '2':
693                 word = va_arg(argptr, int);  // minimal va_arg is int: 2 bytes on 8+16 bit CPUs
694                 mesh_access_message_add_uint16(&builder, word);
695                 break;
696             case '3':
697                 longword = va_arg(argptr, uint32_t);
698                 mesh_access_message_add_uint24(&builder, longword);
699                 break;
700             case '4':
701                 longword = va_arg(argptr, uint32_t);
702                 mesh_access_message_add_uint32(&builder, longword);
703                 break;
704             case 'm':
705                 longword = va_arg(argptr, uint32_t);
706                 mesh_access_message_add_model_identifier(&builder, longword);
707                 break;
708             default:
709                 btstack_assert(false);
710                 break;
711         }
712         format++;
713     }
714 
715     va_end(argptr);
716 
717     return mesh_access_message_finalize(&builder);
718 }
719 
720 static const mesh_operation_t * mesh_model_lookup_operation_by_opcode(mesh_model_t * model, uint32_t opcode){
721     // find opcode in table
722     const mesh_operation_t * operation = model->operations;
723     if (operation == NULL) return NULL;
724     for ( ; operation->handler != NULL ; operation++){
725         if (operation->opcode != opcode) continue;
726         return operation;
727     }
728     return NULL;
729 }
730 
731 static const mesh_operation_t * mesh_model_lookup_operation(mesh_model_t * model, mesh_pdu_t * pdu){
732 
733     uint32_t opcode = 0;
734     uint16_t opcode_size = 0;
735     int ok = mesh_access_pdu_get_opcode( pdu, &opcode, &opcode_size);
736     if (!ok) return NULL;
737 
738     uint16_t len = mesh_pdu_len(pdu);
739 
740     // find opcode in table
741     const mesh_operation_t * operation = model->operations;
742     if (operation == NULL) return NULL;
743     for ( ; operation->handler != NULL ; operation++){
744         if (operation->opcode != opcode) continue;
745         if ((opcode_size + operation->minimum_length) > len) continue;
746         return operation;
747     }
748     return NULL;
749 }
750 
751 static int mesh_access_validate_appkey_index(mesh_model_t * model, uint16_t appkey_index){
752     // DeviceKey is valid for all models
753     if (appkey_index == MESH_DEVICE_KEY_INDEX) return 1;
754     // check if AppKey that is bound to this particular model
755     return mesh_model_contains_appkey(model, appkey_index);
756 }
757 
758 // decrease use count and report as free if done
759 void mesh_access_message_processed(mesh_pdu_t * pdu){
760     if (mesh_access_received_pdu_refcount > 0){
761         mesh_access_received_pdu_refcount--;
762     }
763     if (mesh_access_received_pdu_refcount == 0){
764         mesh_upper_transport_message_processed_by_higher_layer(pdu);
765     }
766 }
767 
768 static void mesh_access_message_process_handler(mesh_pdu_t * pdu){
769 
770     // init use count
771     mesh_access_received_pdu_refcount = 1;
772 
773     // get opcode and size
774     uint32_t opcode = 0;
775     uint16_t opcode_size = 0;
776 
777     int ok = mesh_access_pdu_get_opcode( pdu, &opcode, &opcode_size);
778     if (!ok) {
779         mesh_access_message_processed(pdu);
780         return;
781     }
782 
783     uint16_t len = mesh_pdu_len(pdu);
784     printf("MESH Access Message, Opcode = %x: ", opcode);
785     printf_hexdump(mesh_pdu_data(pdu), len);
786 
787     uint16_t src = mesh_pdu_src(pdu);
788     uint16_t dst = mesh_pdu_dst(pdu);
789     uint16_t appkey_index = mesh_pdu_appkey_index(pdu);
790     if (mesh_network_address_unicast(dst)){
791         // loookup element by unicast address
792         mesh_element_t * element = mesh_node_element_for_unicast_address(dst);
793         if (element != NULL){
794             // iterate over models, look for operation
795             mesh_model_iterator_t model_it;
796             mesh_model_iterator_init(&model_it, element);
797             while (mesh_model_iterator_has_next(&model_it)){
798                 mesh_model_t * model = mesh_model_iterator_next(&model_it);
799                 // find opcode in table
800                 const mesh_operation_t * operation = mesh_model_lookup_operation(model, pdu);
801                 if (operation == NULL) continue;
802                 if (mesh_access_validate_appkey_index(model, appkey_index) == 0) continue;
803                 mesh_access_acknowledged_received(src, opcode);
804                 mesh_access_received_pdu_refcount++;
805                 operation->handler(model, pdu);
806             }
807         }
808     }
809     else if (mesh_network_address_group(dst)){
810 
811         // handle fixed group address
812         if (dst >= 0xff00){
813             int deliver_to_primary_element = 1;
814             switch (dst){
815                 case MESH_ADDRESS_ALL_PROXIES:
816                     if (mesh_foundation_gatt_proxy_get() == 1){
817                         deliver_to_primary_element = 1;
818                     }
819                     break;
820                 case MESH_ADDRESS_ALL_FRIENDS:
821                     // TODO: not implemented
822                     break;
823                 case MESH_ADDRESS_ALL_RELAYS:
824                     if (mesh_foundation_relay_get() == 1){
825                         deliver_to_primary_element = 1;
826                     }
827                     break;
828                 case MESH_ADDRESS_ALL_NODES:
829                     deliver_to_primary_element = 1;
830                     break;
831                 default:
832                     break;
833             }
834             if (deliver_to_primary_element){
835                 mesh_model_iterator_t model_it;
836                 mesh_model_iterator_init(&model_it, mesh_node_get_primary_element());
837                 while (mesh_model_iterator_has_next(&model_it)){
838                     mesh_model_t * model = mesh_model_iterator_next(&model_it);
839                     // find opcode in table
840                     const mesh_operation_t * operation = mesh_model_lookup_operation(model, pdu);
841                     if (operation == NULL) continue;
842                     if (mesh_access_validate_appkey_index(model, appkey_index) == 0) continue;
843                     mesh_access_acknowledged_received(src, opcode);
844                     mesh_access_received_pdu_refcount++;
845                     operation->handler(model, pdu);
846                 }
847             }
848         }
849         else {
850             // iterate over all elements / models, check subscription list
851             mesh_element_iterator_t it;
852             mesh_element_iterator_init(&it);
853             while (mesh_element_iterator_has_next(&it)){
854                 mesh_element_t * element = (mesh_element_t *) mesh_element_iterator_next(&it);
855                 mesh_model_iterator_t model_it;
856                 mesh_model_iterator_init(&model_it, element);
857                 while (mesh_model_iterator_has_next(&model_it)){
858                     mesh_model_t * model = mesh_model_iterator_next(&model_it);
859                     if (mesh_model_contains_subscription(model, dst)){
860                         // find opcode in table
861                         const mesh_operation_t * operation = mesh_model_lookup_operation(model, pdu);
862                         if (operation == NULL) continue;
863                         if (mesh_access_validate_appkey_index(model, appkey_index) == 0) continue;
864                         mesh_access_acknowledged_received(src, opcode);
865                         mesh_access_received_pdu_refcount++;
866                         operation->handler(model, pdu);
867                     }
868                 }
869             }
870         }
871     }
872 
873     // we're done
874     mesh_access_message_processed(pdu);
875 }
876 
877 // Mesh Model Publication
878 static btstack_timer_source_t mesh_access_publication_timer;
879 
880 static uint32_t mesh_model_publication_retransmit_count(uint8_t retransmit){
881     return retransmit & 0x07u;
882 }
883 
884 static uint32_t mesh_model_publication_retransmission_period_ms(uint8_t retransmit){
885     return ((uint32_t)((retransmit >> 3) + 1)) * 50;
886 }
887 
888 static void mesh_model_publication_setup_publication(mesh_publication_model_t * publication_model, uint32_t now){
889 
890     // set retransmit counter
891     publication_model->retransmit_count = mesh_model_publication_retransmit_count(publication_model->retransmit);
892 
893     // schedule next publication or retransmission
894     uint32_t publication_period_ms = mesh_access_time_gdtt2ms(publication_model->period) >> publication_model->period_divisor;
895 
896     // set next publication
897     if (publication_period_ms != 0){
898         publication_model->next_publication_ms = now + publication_period_ms;
899         publication_model->state = MESH_MODEL_PUBLICATION_STATE_W4_PUBLICATION_MS;
900     } else {
901         publication_model->state = MESH_MODEL_PUBLICATION_STATE_IDLE;
902     }
903 }
904 
905 // assumes retransmit_count is valid
906 static void mesh_model_publication_setup_retransmission(mesh_publication_model_t * publication_model, uint32_t now){
907     uint32_t publication_period_ms = mesh_access_time_gdtt2ms(publication_model->period) >> publication_model->period_divisor;
908 
909     // retransmission done
910     if (publication_model->retransmit_count == 0) {
911         // wait for next main event if periodic and retransmission complete
912         if (publication_period_ms != 0){
913             publication_model->state = MESH_MODEL_PUBLICATION_STATE_W4_PUBLICATION_MS;
914         } else {
915             publication_model->state = MESH_MODEL_PUBLICATION_STATE_IDLE;
916         }
917         return;
918     }
919 
920     // calc next retransmit time
921     uint32_t retransmission_period_ms = mesh_model_publication_retransmission_period_ms(publication_model->retransmit) >> publication_model->period_divisor;
922     uint32_t retransmission_ms = now + retransmission_period_ms;
923 
924     // check next publication timeout is before next retransmission
925     if (publication_period_ms != 0){
926         if (btstack_time_delta(retransmission_ms, publication_model->next_publication_ms) > 0) return;
927     }
928 
929     // schedule next retransmission
930     publication_model->next_retransmit_ms = retransmission_ms;
931     publication_model->state = MESH_MODEL_PUBLICATION_STATE_W4_RETRANSMIT_MS;
932 }
933 
934 static void mesh_model_publication_publish_now_model(mesh_model_t * mesh_model){
935     mesh_publication_model_t * publication_model = mesh_model->publication_model;
936     if (publication_model == NULL) return;
937     if (publication_model->publish_state_fn == NULL) return;
938     uint16_t dest = publication_model->address;
939     if (dest == MESH_ADDRESS_UNSASSIGNED) return;
940     uint16_t appkey_index = publication_model->appkey_index;
941     mesh_transport_key_t * app_key = mesh_transport_key_get(appkey_index);
942     if (app_key == NULL) return;
943 
944     // compose message
945     mesh_pdu_t * pdu = (*publication_model->publish_state_fn)(mesh_model);
946     if (pdu == NULL) return;
947 
948     // handle ttl = default
949     uint8_t ttl = publication_model->ttl;
950     if (ttl == 0xff){
951         ttl = mesh_foundation_default_ttl_get();
952     }
953 
954     mesh_upper_transport_setup_access_pdu_header(pdu, app_key->netkey_index, appkey_index, ttl, mesh_access_get_element_address(mesh_model), dest, 0);
955     mesh_access_send_unacknowledged_pdu(pdu);
956 }
957 
958 static void mesh_model_trigger_publication(mesh_model_t * mesh_model){
959     // queue publication
960     mesh_publication_model_t * publication_model = mesh_model->publication_model;
961     publication_model->send_request.context = mesh_model;
962     publication_model->send_request.callback = &mesh_model_publication_publish_now_model;
963     mesh_upper_transport_request_to_send(&publication_model->send_request);
964 }
965 
966 static void mesh_model_publication_run(btstack_timer_source_t * ts){
967 
968     uint32_t now = btstack_run_loop_get_time_ms();
969 
970     // iterate over elements and models and handle time-based transitions
971     mesh_element_iterator_t element_it;
972     mesh_element_iterator_init(&element_it);
973     while (mesh_element_iterator_has_next(&element_it)){
974         mesh_element_t * element = mesh_element_iterator_next(&element_it);
975         mesh_model_iterator_t model_it;
976         mesh_model_iterator_init(&model_it, element);
977         while (mesh_model_iterator_has_next(&model_it)){
978             mesh_model_t * mesh_model = mesh_model_iterator_next(&model_it);
979             mesh_publication_model_t * publication_model = mesh_model->publication_model;
980             if (publication_model == NULL) continue;
981 
982             // check if either timer fired
983             switch (publication_model->state){
984                 case MESH_MODEL_PUBLICATION_STATE_W4_PUBLICATION_MS:
985                     if (btstack_time_delta(publication_model->next_publication_ms, now) > 0) break;
986                     publication_model->state = MESH_MODEL_PUBLICATION_STATE_PUBLICATION_READY;
987                     break;
988                 case MESH_MODEL_PUBLICATION_STATE_W4_RETRANSMIT_MS:
989                     if (btstack_time_delta(publication_model->next_retransmit_ms, now) > 0) break;
990                     publication_model->state = MESH_MODEL_PUBLICATION_STATE_RETRANSMIT_READY;
991                     break;
992                 default:
993                     break;
994             }
995 
996             switch (publication_model->state){
997                 case MESH_MODEL_PUBLICATION_STATE_PUBLICATION_READY:
998                     // schedule next publication and retransmission
999                     mesh_model_publication_setup_publication(publication_model, now);
1000                     mesh_model_publication_setup_retransmission(publication_model, now);
1001                     mesh_model_trigger_publication(mesh_model);
1002                     break;
1003                 case MESH_MODEL_PUBLICATION_STATE_RETRANSMIT_READY:
1004                     // schedule next retransmission
1005                     publication_model->retransmit_count--;
1006                     mesh_model_publication_setup_retransmission(publication_model, now);
1007                     mesh_model_trigger_publication(mesh_model);
1008                     break;
1009                 default:
1010                     break;
1011             }
1012         }
1013     }
1014 
1015     int32_t next_timeout_ms = 0;
1016     mesh_element_iterator_init(&element_it);
1017     while (mesh_element_iterator_has_next(&element_it)){
1018         mesh_element_t * element = mesh_element_iterator_next(&element_it);
1019         mesh_model_iterator_t model_it;
1020         mesh_model_iterator_init(&model_it, element);
1021         while (mesh_model_iterator_has_next(&model_it)){
1022             mesh_model_t * mesh_model = mesh_model_iterator_next(&model_it);
1023             mesh_publication_model_t * publication_model = mesh_model->publication_model;
1024             if (publication_model == NULL) continue;
1025 
1026             // schedule next
1027             int32_t timeout_delta_ms;
1028             switch (publication_model->state){
1029                 case MESH_MODEL_PUBLICATION_STATE_W4_PUBLICATION_MS:
1030                     timeout_delta_ms = btstack_time_delta(publication_model->next_publication_ms, now);
1031                     if (next_timeout_ms == 0 || timeout_delta_ms < next_timeout_ms){
1032                         next_timeout_ms = timeout_delta_ms;
1033                     }
1034                     break;
1035                 case MESH_MODEL_PUBLICATION_STATE_W4_RETRANSMIT_MS:
1036                     timeout_delta_ms = btstack_time_delta(publication_model->next_retransmit_ms, now);
1037                     if (next_timeout_ms == 0 || timeout_delta_ms < next_timeout_ms){
1038                         next_timeout_ms = timeout_delta_ms;
1039                     }
1040                     break;
1041                 default:
1042                     break;
1043             }
1044         }
1045     }
1046 
1047     // remove current timer if active
1048     if (ts == NULL){
1049         btstack_run_loop_remove_timer(&mesh_access_publication_timer);
1050 
1051     }
1052 
1053     // new timeout?
1054     if (next_timeout_ms == 0) return;
1055 
1056     // set timer
1057     btstack_run_loop_set_timer(&mesh_access_publication_timer, next_timeout_ms);
1058     btstack_run_loop_set_timer_handler(&mesh_access_publication_timer, mesh_model_publication_run);
1059     btstack_run_loop_add_timer(&mesh_access_publication_timer);
1060 }
1061 
1062 void mesh_model_publication_start(mesh_model_t * mesh_model){
1063     mesh_publication_model_t * publication_model = mesh_model->publication_model;
1064     if (publication_model == NULL) return;
1065 
1066     // publish right away
1067     publication_model->state = MESH_MODEL_PUBLICATION_STATE_PUBLICATION_READY;
1068     mesh_model_publication_run(NULL);
1069 }
1070 
1071 void mesh_model_publication_stop(mesh_model_t * mesh_model){
1072     mesh_publication_model_t * publication_model = mesh_model->publication_model;
1073     if (publication_model == NULL) return;
1074 
1075     // reset state
1076     publication_model->state = MESH_MODEL_PUBLICATION_STATE_IDLE;
1077 }
1078 
1079 void mesh_access_state_changed(mesh_model_t * mesh_model){
1080     mesh_publication_model_t * publication_model = mesh_model->publication_model;
1081     if (publication_model == NULL) return;
1082     publication_model->state = MESH_MODEL_PUBLICATION_STATE_PUBLICATION_READY;
1083     mesh_model_publication_run(NULL);
1084 }
1085 
1086