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