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