xref: /btstack/src/mesh/mesh_access.c (revision e9292fe87e3930bfc41dd2eb6d5180253be2d0b9)
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 uint8_t mesh_pdu_control_opcode(mesh_pdu_t * pdu){
449     switch (pdu->pdu_type){
450         case MESH_PDU_TYPE_TRANSPORT:
451             return mesh_transport_control_opcode((mesh_transport_pdu_t*) pdu);
452         case MESH_PDU_TYPE_NETWORK:
453             return mesh_network_control_opcode((mesh_network_pdu_t *) pdu);
454         default:
455             return 0xff;
456     }
457 }
458 
459 // message parser
460 
461 static int mesh_access_get_opcode(uint8_t * buffer, uint16_t buffer_size, uint32_t * opcode, uint16_t * opcode_size){
462     switch (buffer[0] >> 6){
463         case 0:
464         case 1:
465             if (buffer[0] == 0x7f) return 0;
466             *opcode = buffer[0];
467             *opcode_size = 1;
468             return 1;
469         case 2:
470             if (buffer_size < 2) return 0;
471             *opcode = big_endian_read_16(buffer, 0);
472             *opcode_size = 2;
473             return 1;
474         case 3:
475             if (buffer_size < 3) return 0;
476             *opcode = (buffer[0] << 16) | little_endian_read_16(buffer, 1);
477             *opcode_size = 3;
478             return 1;
479         default:
480             return 0;
481     }
482 }
483 
484 static int mesh_access_transport_get_opcode(mesh_transport_pdu_t * transport_pdu, uint32_t * opcode, uint16_t * opcode_size){
485     return mesh_access_get_opcode(transport_pdu->data, transport_pdu->len, opcode, opcode_size);
486 }
487 
488 static int mesh_access_network_get_opcode(mesh_network_pdu_t * network_pdu, uint32_t * opcode, uint16_t * opcode_size){
489     // TransMIC already removed by mesh_upper_transport_validate_unsegmented_message_ccm
490     return mesh_access_get_opcode(&network_pdu->data[10], network_pdu->len - 10, opcode, opcode_size);
491 }
492 
493 int mesh_access_pdu_get_opcode(mesh_pdu_t * pdu, uint32_t * opcode, uint16_t * opcode_size){
494     switch (pdu->pdu_type){
495         case MESH_PDU_TYPE_TRANSPORT:
496             return mesh_access_transport_get_opcode((mesh_transport_pdu_t*) pdu, opcode, opcode_size);
497         case MESH_PDU_TYPE_NETWORK:
498             return mesh_access_network_get_opcode((mesh_network_pdu_t *) pdu, opcode, opcode_size);
499         default:
500             return 0;
501     }
502 }
503 
504 void mesh_access_parser_skip(mesh_access_parser_state_t * state, uint16_t bytes_to_skip){
505     state->data += bytes_to_skip;
506     state->len  -= bytes_to_skip;
507 }
508 
509 int mesh_access_parser_init(mesh_access_parser_state_t * state, mesh_pdu_t * pdu){
510     state->data = mesh_pdu_data(pdu);
511     state->len  = mesh_pdu_len(pdu);
512 
513     uint16_t opcode_size = 0;
514     int ok = mesh_access_get_opcode(state->data, state->len, &state->opcode, &opcode_size);
515     if (ok){
516         mesh_access_parser_skip(state, opcode_size);
517     }
518     return ok;
519 }
520 
521 uint16_t mesh_access_parser_available(mesh_access_parser_state_t * state){
522     return state->len;
523 }
524 
525 uint8_t mesh_access_parser_get_u8(mesh_access_parser_state_t * state){
526     uint8_t value = *state->data;
527     mesh_access_parser_skip(state, 1);
528     return value;
529 }
530 
531 uint16_t mesh_access_parser_get_u16(mesh_access_parser_state_t * state){
532     uint16_t value = little_endian_read_16(state->data, 0);
533     mesh_access_parser_skip(state, 2);
534     return value;
535 }
536 
537 uint32_t mesh_access_parser_get_u24(mesh_access_parser_state_t * state){
538     uint32_t value = little_endian_read_24(state->data, 0);
539     mesh_access_parser_skip(state, 3);
540     return value;
541 }
542 
543 uint32_t mesh_access_parser_get_u32(mesh_access_parser_state_t * state){
544     uint32_t value = little_endian_read_24(state->data, 0);
545     mesh_access_parser_skip(state, 4);
546     return value;
547 }
548 
549 void mesh_access_parser_get_u128(mesh_access_parser_state_t * state, uint8_t * dest){
550     reverse_128( state->data, dest);
551     mesh_access_parser_skip(state, 16);
552 }
553 
554 void mesh_access_parser_get_label_uuid(mesh_access_parser_state_t * state, uint8_t * dest){
555     memcpy( dest, state->data, 16);
556     mesh_access_parser_skip(state, 16);
557 }
558 
559 void mesh_access_parser_get_key(mesh_access_parser_state_t * state, uint8_t * dest){
560     memcpy( dest, state->data, 16);
561     mesh_access_parser_skip(state, 16);
562 }
563 
564 uint32_t mesh_access_parser_get_model_identifier(mesh_access_parser_state_t * parser){
565     if (mesh_access_parser_available(parser) == 4){
566         return mesh_access_parser_get_u32(parser);
567     } else {
568         return (BLUETOOTH_COMPANY_ID_BLUETOOTH_SIG_INC << 16) | mesh_access_parser_get_u16(parser);
569     }
570 }
571 
572 // Mesh Access Message Builder
573 
574 // message builder
575 
576 static int mesh_access_setup_opcode(uint8_t * buffer, uint32_t opcode){
577     if (opcode < 0x100){
578         buffer[0] = opcode;
579         return 1;
580     }
581     if (opcode < 0x10000){
582         big_endian_store_16(buffer, 0, opcode);
583         return 2;
584     }
585     buffer[0] = opcode >> 16;
586     little_endian_store_16(buffer, 1, opcode & 0xffff);
587     return 3;
588 }
589 
590 mesh_transport_pdu_t * mesh_access_transport_init(uint32_t opcode){
591     mesh_transport_pdu_t * pdu = mesh_transport_pdu_get();
592     if (!pdu) return NULL;
593 
594     pdu->len  = mesh_access_setup_opcode(pdu->data, opcode);
595     return pdu;
596 }
597 
598 void mesh_access_transport_add_uint8(mesh_transport_pdu_t * pdu, uint8_t value){
599     pdu->data[pdu->len++] = value;
600 }
601 
602 void mesh_access_transport_add_uint16(mesh_transport_pdu_t * pdu, uint16_t value){
603     little_endian_store_16(pdu->data, pdu->len, value);
604     pdu->len += 2;
605 }
606 
607 void mesh_access_transport_add_uint24(mesh_transport_pdu_t * pdu, uint32_t value){
608     little_endian_store_24(pdu->data, pdu->len, value);
609     pdu->len += 3;
610 }
611 
612 void mesh_access_transport_add_uint32(mesh_transport_pdu_t * pdu, uint32_t value){
613     little_endian_store_32(pdu->data, pdu->len, value);
614     pdu->len += 4;
615 }
616 void mesh_access_transport_add_model_identifier(mesh_transport_pdu_t * pdu, uint32_t model_identifier){
617     if (mesh_model_is_bluetooth_sig(model_identifier)){
618         mesh_access_transport_add_uint16( pdu, mesh_model_get_model_id(model_identifier) );
619     } else {
620         mesh_access_transport_add_uint32( pdu, model_identifier );
621     }
622 }
623 
624 mesh_network_pdu_t * mesh_access_network_init(uint32_t opcode){
625     mesh_network_pdu_t * pdu = mesh_network_pdu_get();
626     if (!pdu) return NULL;
627 
628     pdu->len  = mesh_access_setup_opcode(&pdu->data[10], opcode) + 10;
629     return pdu;
630 }
631 
632 void mesh_access_network_add_uint8(mesh_network_pdu_t * pdu, uint8_t value){
633     pdu->data[pdu->len++] = value;
634 }
635 
636 void mesh_access_network_add_uint16(mesh_network_pdu_t * pdu, uint16_t value){
637     little_endian_store_16(pdu->data, pdu->len, value);
638     pdu->len += 2;
639 }
640 
641 void mesh_access_network_add_uint24(mesh_network_pdu_t * pdu, uint16_t value){
642     little_endian_store_24(pdu->data, pdu->len, value);
643     pdu->len += 3;
644 }
645 
646 void mesh_access_network_add_uint32(mesh_network_pdu_t * pdu, uint16_t value){
647     little_endian_store_32(pdu->data, pdu->len, value);
648     pdu->len += 4;
649 }
650 
651 void mesh_access_network_add_model_identifier(mesh_network_pdu_t * pdu, uint32_t model_identifier){
652     if (mesh_model_is_bluetooth_sig(model_identifier)){
653         mesh_access_network_add_uint16( pdu, mesh_model_get_model_id(model_identifier) );
654     } else {
655         mesh_access_network_add_uint32( pdu, model_identifier );
656     }
657 }
658 
659 // access message template
660 
661 mesh_network_pdu_t * mesh_access_setup_unsegmented_message(const mesh_access_message_t *template, ...){
662     mesh_network_pdu_t * network_pdu = mesh_access_network_init(template->opcode);
663     if (!network_pdu) return NULL;
664 
665     va_list argptr;
666     va_start(argptr, template);
667 
668     // add params
669     const char * format = template->format;
670     uint16_t word;
671     uint32_t longword;
672     while (*format){
673         switch (*format){
674             case '1':
675                 word = va_arg(argptr, int);  // minimal va_arg is int: 2 bytes on 8+16 bit CPUs
676                 mesh_access_network_add_uint8( network_pdu, word);
677                 break;
678             case '2':
679                 word = va_arg(argptr, int);  // minimal va_arg is int: 2 bytes on 8+16 bit CPUs
680                 mesh_access_network_add_uint16( network_pdu, word);
681                 break;
682             case '3':
683                 longword = va_arg(argptr, uint32_t);
684                 mesh_access_network_add_uint24( network_pdu, longword);
685                 break;
686             case '4':
687                 longword = va_arg(argptr, uint32_t);
688                 mesh_access_network_add_uint32( network_pdu, longword);
689                 break;
690             case 'm':
691                 longword = va_arg(argptr, uint32_t);
692                 mesh_access_network_add_model_identifier( network_pdu, longword);
693                 break;
694             default:
695                 log_error("Unsupported mesh message format specifier '%c", *format);
696                 break;
697         }
698         format++;
699     }
700 
701     va_end(argptr);
702 
703     return network_pdu;
704 }
705 
706 mesh_transport_pdu_t * mesh_access_setup_segmented_message(const mesh_access_message_t *template, ...){
707     mesh_transport_pdu_t * transport_pdu = mesh_access_transport_init(template->opcode);
708     if (!transport_pdu) return NULL;
709 
710     va_list argptr;
711     va_start(argptr, template);
712 
713     // add params
714     const char * format = template->format;
715     uint16_t word;
716     uint32_t longword;
717     while (*format){
718         switch (*format++){
719             case '1':
720                 word = va_arg(argptr, int);  // minimal va_arg is int: 2 bytes on 8+16 bit CPUs
721                 mesh_access_transport_add_uint8( transport_pdu, word);
722                 break;
723             case '2':
724                 word = va_arg(argptr, int);  // minimal va_arg is int: 2 bytes on 8+16 bit CPUs
725                 mesh_access_transport_add_uint16( transport_pdu, word);
726                 break;
727             case '3':
728                 longword = va_arg(argptr, uint32_t);
729                 mesh_access_transport_add_uint24( transport_pdu, longword);
730                 break;
731             case '4':
732                 longword = va_arg(argptr, uint32_t);
733                 mesh_access_transport_add_uint32( transport_pdu, longword);
734                 break;
735             case 'm':
736                 longword = va_arg(argptr, uint32_t);
737                 mesh_access_transport_add_model_identifier( transport_pdu, longword);
738                 break;
739             default:
740                 break;
741         }
742     }
743 
744     va_end(argptr);
745 
746     return transport_pdu;
747 }
748 
749 static const mesh_operation_t * mesh_model_lookup_operation_by_opcode(mesh_model_t * model, uint32_t opcode){
750     // find opcode in table
751     const mesh_operation_t * operation = model->operations;
752     if (operation == NULL) return NULL;
753     for ( ; operation->handler != NULL ; operation++){
754         if (operation->opcode != opcode) continue;
755         return operation;
756     }
757     return NULL;
758 }
759 
760 static const mesh_operation_t * mesh_model_lookup_operation(mesh_model_t * model, mesh_pdu_t * pdu){
761 
762     uint32_t opcode = 0;
763     uint16_t opcode_size = 0;
764     int ok = mesh_access_pdu_get_opcode( pdu, &opcode, &opcode_size);
765     if (!ok) return NULL;
766 
767     uint16_t len = mesh_pdu_len(pdu);
768 
769     // find opcode in table
770     const mesh_operation_t * operation = model->operations;
771     if (operation == NULL) return NULL;
772     for ( ; operation->handler != NULL ; operation++){
773         if (operation->opcode != opcode) continue;
774         if ((opcode_size + operation->minimum_length) > len) continue;
775         return operation;
776     }
777     return NULL;
778 }
779 
780 static int mesh_access_validate_appkey_index(mesh_model_t * model, uint16_t appkey_index){
781     // DeviceKey is valid for all models
782     if (appkey_index == MESH_DEVICE_KEY_INDEX) return 1;
783     // check if AppKey that is bound to this particular model
784     return mesh_model_contains_appkey(model, appkey_index);
785 }
786 
787 static void mesh_access_message_process_handler(mesh_pdu_t * pdu){
788     // get opcode and size
789     uint32_t opcode = 0;
790     uint16_t opcode_size = 0;
791 
792 
793     int ok = mesh_access_pdu_get_opcode( pdu, &opcode, &opcode_size);
794     if (!ok) {
795         mesh_access_message_processed(pdu);
796         return;
797     }
798 
799     uint16_t len = mesh_pdu_len(pdu);
800     printf("MESH Access Message, Opcode = %x: ", opcode);
801     printf_hexdump(mesh_pdu_data(pdu), len);
802 
803     uint16_t src = mesh_pdu_src(pdu);
804     uint16_t dst = mesh_pdu_dst(pdu);
805     uint16_t appkey_index = mesh_pdu_appkey_index(pdu);
806     if (mesh_network_address_unicast(dst)){
807         // loookup element by unicast address
808         mesh_element_t * element = mesh_node_element_for_unicast_address(dst);
809         if (element != NULL){
810             // iterate over models, look for operation
811             mesh_model_iterator_t model_it;
812             mesh_model_iterator_init(&model_it, element);
813             while (mesh_model_iterator_has_next(&model_it)){
814                 mesh_model_t * model = mesh_model_iterator_next(&model_it);
815                 // find opcode in table
816                 const mesh_operation_t * operation = mesh_model_lookup_operation(model, pdu);
817                 if (operation == NULL) continue;
818                 if (mesh_access_validate_appkey_index(model, appkey_index) == 0) continue;
819                 mesh_access_acknowledged_received(src, opcode);
820                 operation->handler(model, pdu);
821                 return;
822             }
823         }
824     }
825     else if (mesh_network_address_group(dst)){
826 
827         // handle fixed group address
828         if (dst >= 0xff00){
829             int deliver_to_primary_element = 1;
830             switch (dst){
831                 case MESH_ADDRESS_ALL_PROXIES:
832                     if (mesh_foundation_gatt_proxy_get() == 1){
833                         deliver_to_primary_element = 1;
834                     }
835                     break;
836                 case MESH_ADDRESS_ALL_FRIENDS:
837                     // TODO: not implemented
838                     break;
839                 case MESH_ADDRESS_ALL_RELAYS:
840                     if (mesh_foundation_relay_get() == 1){
841                         deliver_to_primary_element =1;
842                     }
843                     break;
844                 case MESH_ADDRESS_ALL_NODES:
845                     deliver_to_primary_element = 1;
846                     break;
847                 default:
848                     break;
849             }
850             if (deliver_to_primary_element){
851                 mesh_model_iterator_t model_it;
852                 mesh_model_iterator_init(&model_it, mesh_node_get_primary_element());
853                 while (mesh_model_iterator_has_next(&model_it)){
854                     mesh_model_t * model = mesh_model_iterator_next(&model_it);
855                     // find opcode in table
856                     const mesh_operation_t * operation = mesh_model_lookup_operation(model, pdu);
857                     if (operation == NULL) continue;
858                     if (mesh_access_validate_appkey_index(model, appkey_index) == 0) continue;
859                     mesh_access_acknowledged_received(src, opcode);
860                     operation->handler(model, pdu);
861                     return;
862                 }
863             }
864         }
865         else {
866             // iterate over all elements / models, check subscription list
867             mesh_element_iterator_t it;
868             mesh_element_iterator_init(&it);
869             while (mesh_element_iterator_has_next(&it)){
870                 mesh_element_t * element = (mesh_element_t *) mesh_element_iterator_next(&it);
871                 mesh_model_iterator_t model_it;
872                 mesh_model_iterator_init(&model_it, element);
873                 while (mesh_model_iterator_has_next(&model_it)){
874                     mesh_model_t * model = mesh_model_iterator_next(&model_it);
875                     if (mesh_model_contains_subscription(model, dst)){
876                         // find opcode in table
877                         const mesh_operation_t * operation = mesh_model_lookup_operation(model, pdu);
878                         if (operation == NULL) continue;
879                         if (mesh_access_validate_appkey_index(model, appkey_index) == 0) continue;
880                         mesh_access_acknowledged_received(src, opcode);
881                         operation->handler(model, pdu);
882                         return;
883                     }
884                 }
885             }
886         }
887     }
888 
889     // operation not found -> done
890     printf("Message not handled\n");
891     mesh_access_message_processed(pdu);
892 }
893 
894 void mesh_access_message_processed(mesh_pdu_t * pdu){
895     mesh_upper_transport_message_processed_by_higher_layer(pdu);
896 }
897 
898 // Mesh Model Publication
899 static btstack_timer_source_t mesh_access_publication_timer;
900 
901 static uint32_t mesh_model_publication_retransmit_count(uint8_t retransmit){
902     return retransmit & 0x07u;
903 }
904 
905 static uint32_t mesh_model_publication_retransmission_period_ms(uint8_t retransmit){
906     return ((uint32_t)((retransmit >> 3) + 1)) * 50;
907 }
908 
909 static void mesh_model_publication_setup_publication(mesh_publication_model_t * publication_model, uint32_t now){
910 
911     // set retransmit counter
912     publication_model->retransmit_count = mesh_model_publication_retransmit_count(publication_model->retransmit);
913 
914     // schedule next publication or retransmission
915     uint32_t publication_period_ms = mesh_access_transitions_step_ms_from_gdtt(publication_model->period);
916 
917     // set next publication
918     if (publication_period_ms != 0){
919         publication_model->next_publication_ms = now + publication_period_ms;
920         publication_model->state = MESH_MODEL_PUBLICATION_STATE_W4_PUBLICATION_MS;
921     }
922 }
923 
924 static void mesh_model_publication_setup_retransmission(mesh_publication_model_t * publication_model, uint32_t now){
925     uint8_t num_retransmits = mesh_model_publication_retransmit_count(publication_model->retransmit);
926     if (num_retransmits == 0) return;
927 
928     // calc next retransmit time
929     uint32_t retransmission_ms = now + mesh_model_publication_retransmission_period_ms(publication_model->retransmit);
930 
931     // ignore if retransmission would be after next publication timeout
932     if (publication_model->state == MESH_MODEL_PUBLICATION_STATE_W4_PUBLICATION_MS){
933         if (btstack_time_delta(retransmission_ms, publication_model->next_publication_ms) > 0) return;
934     }
935 
936     // schedule next retransmission
937     publication_model->next_retransmit_ms = retransmission_ms;
938     publication_model->state = MESH_MODEL_PUBLICATION_STATE_W4_RETRANSMIT_MS;
939 }
940 
941 static void mesh_model_publication_publish_now_model(mesh_model_t * mesh_model){
942     mesh_publication_model_t * publication_model = mesh_model->publication_model;
943     if (publication_model == NULL) return;
944     if (publication_model->publish_state_fn == NULL) return;
945     uint16_t dest = publication_model->address;
946     if (dest == MESH_ADDRESS_UNSASSIGNED) return;
947     uint16_t appkey_index = publication_model->appkey_index;
948     mesh_transport_key_t * app_key = mesh_transport_key_get(appkey_index);
949     if (app_key == NULL) return;
950 
951     // compose message
952     mesh_pdu_t * pdu = (*publication_model->publish_state_fn)(mesh_model);
953     if (pdu == NULL) return;
954 
955     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);
956     mesh_upper_transport_send_access_pdu(pdu);
957 }
958 
959 static void mesh_model_publication_run(btstack_timer_source_t * ts){
960     UNUSED(ts);
961 
962     uint32_t now = btstack_run_loop_get_time_ms();
963 
964     // iterate over elements and models and handle time-based transitions
965     mesh_element_iterator_t element_it;
966     mesh_element_iterator_init(&element_it);
967     while (mesh_element_iterator_has_next(&element_it)){
968         mesh_element_t * element = mesh_element_iterator_next(&element_it);
969         mesh_model_iterator_t model_it;
970         mesh_model_iterator_init(&model_it, element);
971         while (mesh_model_iterator_has_next(&model_it)){
972             mesh_model_t * mesh_model = mesh_model_iterator_next(&model_it);
973             mesh_publication_model_t * publication_model = mesh_model->publication_model;
974             if (publication_model == NULL) continue;
975 
976             // schedule next
977             switch (publication_model->state){
978                 case MESH_MODEL_PUBLICATION_STATE_W4_PUBLICATION_MS:
979                     if (btstack_time_delta(publication_model->next_publication_ms, now) > 0) break;
980                     // timeout
981                     publication_model->publish_now = 1;
982                     // schedule next publication and retransmission
983                     mesh_model_publication_setup_publication(publication_model, now);
984                     mesh_model_publication_setup_retransmission(publication_model, now);
985                     break;
986                 case MESH_MODEL_PUBLICATION_STATE_W4_RETRANSMIT_MS:
987                     if (btstack_time_delta(publication_model->next_retransmit_ms, now) > 0) break;
988                     // timeout
989                     publication_model->publish_now = 1;
990                     publication_model->retransmit_count--;
991                     // schedule next retransmission
992                     mesh_model_publication_setup_retransmission(publication_model, now);
993                     break;
994                 default:
995                     break;
996             }
997 
998             if (publication_model->publish_now == 0) continue;
999 
1000             publication_model->publish_now = 0;
1001             mesh_model_publication_publish_now_model(mesh_model);
1002         }
1003     }
1004 
1005     int32_t next_timeout_ms = 0;
1006     mesh_element_iterator_init(&element_it);
1007     while (mesh_element_iterator_has_next(&element_it)){
1008         mesh_element_t * element = mesh_element_iterator_next(&element_it);
1009         mesh_model_iterator_t model_it;
1010         mesh_model_iterator_init(&model_it, element);
1011         while (mesh_model_iterator_has_next(&model_it)){
1012             mesh_model_t * mesh_model = mesh_model_iterator_next(&model_it);
1013             mesh_publication_model_t * publication_model = mesh_model->publication_model;
1014             if (publication_model == NULL) continue;
1015 
1016             // schedule next
1017             int32_t timeout_delta_ms;
1018             switch (publication_model->state){
1019                 case MESH_MODEL_PUBLICATION_STATE_W4_PUBLICATION_MS:
1020                     timeout_delta_ms = btstack_time_delta(publication_model->next_publication_ms, now);
1021                     if (next_timeout_ms == 0 || timeout_delta_ms < next_timeout_ms){
1022                         next_timeout_ms = timeout_delta_ms;
1023                     }
1024                     break;
1025                 case MESH_MODEL_PUBLICATION_STATE_W4_RETRANSMIT_MS:
1026                     timeout_delta_ms = btstack_time_delta(publication_model->next_retransmit_ms, now);
1027                     if (next_timeout_ms == 0 || timeout_delta_ms < next_timeout_ms){
1028                         next_timeout_ms = timeout_delta_ms;
1029                     }
1030                     break;
1031                 default:
1032                     break;
1033             }
1034         }
1035     }
1036 
1037     // set timer
1038     if (next_timeout_ms == 0) return;
1039 
1040     btstack_run_loop_set_timer(&mesh_access_publication_timer, next_timeout_ms);
1041     btstack_run_loop_set_timer_handler(&mesh_access_publication_timer, mesh_model_publication_run);
1042     btstack_run_loop_add_timer(&mesh_access_publication_timer);
1043 }
1044 
1045 void mesh_model_publication_start(mesh_model_t * mesh_model){
1046     mesh_publication_model_t * publication_model = mesh_model->publication_model;
1047     if (publication_model == NULL) return;
1048 
1049     // reset state
1050     publication_model->state = MESH_MODEL_PUBLICATION_STATE_IDLE;
1051 
1052     // publish right away
1053     publication_model->publish_now = 1;
1054 
1055     // setup next publication and retransmission
1056     uint32_t now = btstack_run_loop_get_time_ms();
1057     mesh_model_publication_setup_publication(publication_model, now);
1058     mesh_model_publication_setup_retransmission(publication_model, now);
1059 
1060     mesh_model_publication_run(NULL);
1061 }
1062 
1063 void mesh_model_publication_stop(mesh_model_t * mesh_model){
1064     mesh_publication_model_t * publication_model = mesh_model->publication_model;
1065     if (publication_model == NULL) return;
1066 
1067     // reset state
1068     publication_model->state = MESH_MODEL_PUBLICATION_STATE_IDLE;
1069 }
1070 
1071 void mesh_access_state_changed(mesh_model_t * mesh_model){
1072     mesh_publication_model_t * publication_model = mesh_model->publication_model;
1073     if (publication_model == NULL) return;
1074     publication_model->publish_now = 1;
1075     mesh_model_publication_run(NULL);
1076 }
1077 
1078