xref: /btstack/src/mesh/pb_adv.c (revision 7cdc89a533ca236b2c2564b759993b788bae89d3)
1 /*
2  * Copyright (C) 2014 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__ "pb_adv.c"
39 
40 #include "pb_adv.h"
41 
42 #include <stdint.h>
43 #include <stdio.h>
44 #include <stdlib.h>
45 #include <string.h>
46 
47 #include "btstack_debug.h"
48 #include "btstack_event.h"
49 #include "btstack_util.h"
50 
51 #include "mesh/adv_bearer.h"
52 #include "mesh/beacon.h"
53 #include "mesh/mesh_node.h"
54 #include "mesh/provisioning.h"
55 
56 #define PB_ADV_LINK_OPEN_RETRANSMIT_MS 1000
57 
58 static void pb_adv_run(void);
59 
60 /* taps: 32 31 29 1; characteristic polynomial: x^32 + x^31 + x^29 + x + 1 */
61 #define LFSR(a) ((a >> 1) ^ (uint32_t)((0 - (a & 1u)) & 0xd0000001u))
62 
63 // PB-ADV - Provisioning Bearer using Advertisement Bearer
64 
65 #define MESH_GENERIC_PROVISIONING_LINK_OPEN              0x00
66 #define MESH_GENERIC_PROVISIONING_LINK_ACK               0x01
67 #define MESH_GENERIC_PROVISIONING_LINK_CLOSE             0x02
68 
69 #define MESH_GENERIC_PROVISIONING_TRANSACTION_TIMEOUT_MS 30000
70 
71 #define MESH_PB_ADV_MAX_PDU_SIZE  100
72 #define MESH_PB_ADV_MAX_SEGMENTS    8
73 #define MESH_PB_ADV_START_PAYLOAD  20
74 #define MESH_PB_ADV_CONT_PAYLOAD   23
75 
76 typedef enum mesh_gpcf_format {
77     MESH_GPCF_TRANSACTION_START = 0,
78     MESH_GPCF_TRANSACTION_ACK,
79     MESH_GPCF_TRANSACTION_CONT,
80     MESH_GPCF_PROV_BEARER_CONTROL,
81 } mesh_gpcf_format_t;
82 
83 typedef enum {
84     LINK_STATE_W4_OPEN,
85     LINK_STATE_W2_SEND_ACK,
86     LINK_STATE_W4_ACK,
87     LINK_STATE_OPEN,
88     LINK_STATE_CLOSING,
89 } link_state_t;
90 static link_state_t link_state;
91 
92 #ifdef ENABLE_MESH_PROVISIONER
93 static const uint8_t * pb_adv_peer_device_uuid;
94 #endif
95 
96 static uint8_t  pb_adv_msg_in_buffer[MESH_PB_ADV_MAX_PDU_SIZE];   // TODO: how large are prov messages?
97 
98 // single adv link
99 static uint16_t pb_adv_cid = 1;
100 static uint8_t  pb_adv_provisioner_role;
101 
102 // link state
103 static uint32_t pb_adv_link_id;
104 static uint8_t  pb_adv_link_close_reason;
105 static uint8_t  pb_adv_link_close_countdown;
106 
107 // random delay for outgoing packets
108 static uint32_t pb_adv_lfsr;
109 static uint8_t                pb_adv_random_delay_active;
110 static btstack_timer_source_t pb_adv_random_delay_timer;
111 
112 // incoming message
113 static uint8_t  pb_adv_msg_in_transaction_nr_prev;
114 static uint16_t pb_adv_msg_in_len;   //
115 static uint8_t  pb_adv_msg_in_fcs;
116 static uint8_t  pb_adv_msg_in_last_segment;
117 static uint8_t  pb_adv_msg_in_segments_missing; // bitfield for segmentes 1-n
118 static uint8_t  pb_adv_msg_in_transaction_nr;
119 static uint8_t  pb_adv_msg_in_send_ack;
120 
121 // oputgoing message
122 static uint8_t         pb_adv_msg_out_active;
123 static uint8_t         pb_adv_msg_out_transaction_nr;
124 static uint8_t         pb_adv_msg_out_completed_transaction_nr;
125 static uint16_t        pb_adv_msg_out_len;
126 static uint16_t        pb_adv_msg_out_pos;
127 static uint8_t         pb_adv_msg_out_seg;
128 static uint32_t        pb_adv_msg_out_start;
129 static const uint8_t * pb_adv_msg_out_buffer;
130 
131 static btstack_packet_handler_t pb_adv_packet_handler;
132 
133 // poor man's random number generator
134 static uint32_t pb_adv_random(void){
135     pb_adv_lfsr = LFSR(pb_adv_lfsr);
136     return pb_adv_lfsr;
137 }
138 
139 static void pb_adv_emit_pdu_sent(uint8_t status){
140     uint8_t event[] = { HCI_EVENT_MESH_META, 2, MESH_SUBEVENT_PB_TRANSPORT_PDU_SENT, status};
141     pb_adv_packet_handler(HCI_EVENT_PACKET, 0, event, sizeof(event));
142 }
143 
144 static void pb_adv_emit_link_open(uint8_t status, uint16_t pb_transport_cid){
145     uint8_t event[7] = { HCI_EVENT_MESH_META, 5, MESH_SUBEVENT_PB_TRANSPORT_LINK_OPEN, status};
146     little_endian_store_16(event, 4, pb_transport_cid);
147     event[6] = MESH_PB_TYPE_ADV;
148     pb_adv_packet_handler(HCI_EVENT_PACKET, 0, event, sizeof(event));
149 }
150 
151 static void pb_adv_emit_link_close(uint16_t pb_transport_cid, uint8_t reason){
152     uint8_t event[6] = { HCI_EVENT_MESH_META, 3, MESH_SUBEVENT_PB_TRANSPORT_LINK_CLOSED};
153     little_endian_store_16(event, 3, pb_transport_cid);
154     event[5] = reason;
155     pb_adv_packet_handler(HCI_EVENT_PACKET, 0, event, sizeof(event));
156 }
157 
158 static void pb_adv_handle_bearer_control(uint32_t link_id, uint8_t transaction_nr, const uint8_t * pdu, uint16_t size){
159     UNUSED(transaction_nr);
160     UNUSED(size);
161 
162     uint8_t bearer_opcode = pdu[0] >> 2;
163     uint8_t reason;
164     const uint8_t * own_device_uuid;
165     switch (bearer_opcode){
166         case MESH_GENERIC_PROVISIONING_LINK_OPEN: // Open a session on a bearer with a device
167             // does it match our device_uuid?
168             own_device_uuid = mesh_node_get_device_uuid();
169             if (!own_device_uuid) break;
170             if (memcmp(&pdu[1], own_device_uuid, 16) != 0) break;
171             switch(link_state){
172                 case LINK_STATE_W4_OPEN:
173                     pb_adv_link_id = link_id;
174                     pb_adv_provisioner_role = 0;
175                     pb_adv_msg_in_transaction_nr = 0xff;  // first transaction nr will be 0x00
176                     pb_adv_msg_in_transaction_nr_prev = 0xff;
177                     log_info("link open, id %08x", pb_adv_link_id);
178                     printf("PB-ADV: Link Open %08x\n", pb_adv_link_id);
179                     link_state = LINK_STATE_W2_SEND_ACK;
180                     adv_bearer_request_can_send_now_for_provisioning_pdu();
181                     pb_adv_emit_link_open(0, pb_adv_cid);
182                     break;
183                 case LINK_STATE_OPEN:
184                     if (pb_adv_link_id != link_id) break;
185                     log_info("link open, resend ACK");
186                     link_state = LINK_STATE_W2_SEND_ACK;
187                     adv_bearer_request_can_send_now_for_provisioning_pdu();
188                     break;
189                 default:
190                     break;
191             }
192             break;
193 #ifdef ENABLE_MESH_PROVISIONER
194         case MESH_GENERIC_PROVISIONING_LINK_ACK:   // Acknowledge a session on a bearer
195             if (link_state != LINK_STATE_W4_ACK) break;
196             link_state = LINK_STATE_OPEN;
197             pb_adv_msg_out_transaction_nr = 0;
198             pb_adv_msg_in_transaction_nr = 0x7f;    // first transaction nr will be 0x80
199             pb_adv_msg_in_transaction_nr_prev = 0x7f;
200             btstack_run_loop_remove_timer(&pb_adv_random_delay_timer);
201             log_info("link open, id %08x", pb_adv_link_id);
202             printf("PB-ADV: Link Open %08x\n", pb_adv_link_id);
203             pb_adv_emit_link_open(0, pb_adv_cid);
204             break;
205 #endif
206         case MESH_GENERIC_PROVISIONING_LINK_CLOSE: // Close a session on a bearer
207             // does it match link id
208             if (link_id != pb_adv_link_id) break;
209             reason = pdu[1];
210             link_state = LINK_STATE_W4_OPEN;
211             log_info("link close, reason %x", reason);
212             pb_adv_emit_link_close(pb_adv_cid, reason);
213             break;
214         default:
215             log_info("BearerOpcode %x reserved for future use\n", bearer_opcode);
216             break;
217     }
218 }
219 
220 static void pb_adv_pdu_complete(void){
221 
222     // Verify FCS
223     uint8_t pdu_crc = btstack_crc8_calc((uint8_t*)pb_adv_msg_in_buffer, pb_adv_msg_in_len);
224     if (pdu_crc != pb_adv_msg_in_fcs){
225         printf("Incoming PDU: fcs %02x, calculated %02x -> drop packet\n", pb_adv_msg_in_fcs, btstack_crc8_calc(pb_adv_msg_in_buffer, pb_adv_msg_in_len));
226         return;
227     }
228 
229     printf("PB-ADV: %02x complete\n", pb_adv_msg_in_transaction_nr);
230 
231     // transaction complete
232     pb_adv_msg_in_transaction_nr_prev = pb_adv_msg_in_transaction_nr;
233     if (pb_adv_provisioner_role){
234         pb_adv_msg_in_transaction_nr = 0x7f;    // invalid
235     } else {
236         pb_adv_msg_in_transaction_nr = 0xff;    // invalid
237     }
238 
239     // Ack Transaction
240     pb_adv_msg_in_send_ack = 1;
241     pb_adv_run();
242 
243     // Forward to Provisioning
244     pb_adv_packet_handler(PROVISIONING_DATA_PACKET, 0, pb_adv_msg_in_buffer, pb_adv_msg_in_len);
245 }
246 
247 static void pb_adv_handle_transaction_start(uint8_t transaction_nr, const uint8_t * pdu, uint16_t size){
248 
249     // resend ack if packet from previous transaction received
250     if (transaction_nr != 0xff && transaction_nr == pb_adv_msg_in_transaction_nr_prev){
251         printf("PB_ADV: %02x transaction complete, resending ack \n", transaction_nr);
252         pb_adv_msg_in_send_ack = 1;
253         return;
254     }
255 
256     // new transaction?
257     if (transaction_nr != pb_adv_msg_in_transaction_nr){
258 
259         // check len
260         uint16_t msg_len = big_endian_read_16(pdu, 1);
261         if (msg_len > MESH_PB_ADV_MAX_PDU_SIZE){
262             // abort transaction
263             return;
264         }
265 
266         // check num segments
267         uint8_t last_segment = pdu[0] >> 2;
268         if (last_segment >= MESH_PB_ADV_MAX_SEGMENTS){
269             // abort transaction
270             return;
271         }
272 
273         printf("PB-ADV: %02x started\n", transaction_nr);
274 
275         pb_adv_msg_in_transaction_nr = transaction_nr;
276         pb_adv_msg_in_len            = msg_len;
277         pb_adv_msg_in_fcs            = pdu[3];
278         pb_adv_msg_in_last_segment   = last_segment;
279 
280         // set bits for  segments 1..n (segment 0 already received in this message)
281         pb_adv_msg_in_segments_missing = (1 << last_segment) - 1;
282 
283         // store payload
284         uint16_t payload_len = size - 4;
285         (void)memcpy(pb_adv_msg_in_buffer, &pdu[4], payload_len);
286 
287         // complete?
288         if (pb_adv_msg_in_segments_missing == 0){
289             pb_adv_pdu_complete();
290         }
291     }
292 }
293 
294 static void pb_adv_handle_transaction_cont(uint8_t transaction_nr, const uint8_t * pdu, uint16_t size){
295 
296     // check transaction nr
297     if (transaction_nr != 0xff && transaction_nr == pb_adv_msg_in_transaction_nr_prev){
298         printf("PB_ADV: %02x transaction complete, resending resending ack\n", transaction_nr);
299         pb_adv_msg_in_send_ack = 1;
300         return;
301     }
302 
303     if (transaction_nr != pb_adv_msg_in_transaction_nr){
304         printf("PB-ADV: %02x received msg for transaction nr %x\n", pb_adv_msg_in_transaction_nr, transaction_nr);
305         return;
306     }
307 
308     // validate seg nr
309     uint8_t seg = pdu[0] >> 2;
310     if (seg >= MESH_PB_ADV_MAX_SEGMENTS || seg == 0){
311         return;
312     }
313 
314     // check if segment already received
315     uint8_t seg_mask = 1 << (seg-1);
316     if ((pb_adv_msg_in_segments_missing & seg_mask) == 0){
317         printf("PB-ADV: %02x, segment %u already received\n", transaction_nr, seg);
318         return;
319     }
320     printf("PB-ADV: %02x, segment %u stored\n", transaction_nr, seg);
321 
322     // calculate offset and fragment size
323     uint16_t msg_pos = MESH_PB_ADV_START_PAYLOAD + (seg-1) * MESH_PB_ADV_CONT_PAYLOAD;
324     uint16_t fragment_size = size - 1;
325 
326     // check size if last segment
327     if (seg == pb_adv_msg_in_last_segment && (msg_pos + fragment_size) != pb_adv_msg_in_len){
328         // last segment has invalid size
329         return;
330     }
331 
332     // store segment and mark as received
333     (void)memcpy(&pb_adv_msg_in_buffer[msg_pos], &pdu[1], fragment_size);
334     pb_adv_msg_in_segments_missing &= ~seg_mask;
335 
336      // last segment
337      if (pb_adv_msg_in_segments_missing == 0){
338         pb_adv_pdu_complete();
339     }
340 }
341 
342 static void pb_adv_outgoing_transation_complete(uint8_t status){
343     // stop sending
344     pb_adv_msg_out_active = 0;
345     // emit done
346     pb_adv_emit_pdu_sent(status);
347     // keep track of ack'ed transactions
348     pb_adv_msg_out_completed_transaction_nr = pb_adv_msg_out_transaction_nr;
349     // increment outgoing transaction nr
350     pb_adv_msg_out_transaction_nr++;
351     if (pb_adv_msg_out_transaction_nr == 0x00){
352         // Device role
353         pb_adv_msg_out_transaction_nr = 0x80;
354     }
355     if (pb_adv_msg_out_transaction_nr == 0x80){
356         // Provisioner role
357         pb_adv_msg_out_transaction_nr = 0x00;
358     }
359 }
360 
361 static void pb_adv_handle_transaction_ack(uint8_t transaction_nr, const uint8_t * pdu, uint16_t size){
362     UNUSED(pdu);
363     UNUSED(size);
364     if (transaction_nr == pb_adv_msg_out_transaction_nr){
365         printf("PB-ADV: %02x ACK received\n", transaction_nr);
366         pb_adv_outgoing_transation_complete(ERROR_CODE_SUCCESS);
367     } else if (transaction_nr == pb_adv_msg_out_completed_transaction_nr){
368         // Transaction ack received again
369     } else {
370         printf("PB-ADV: %02x unexpected Transaction ACK %x recevied\n", pb_adv_msg_out_transaction_nr, transaction_nr);
371     }
372 }
373 
374 static int pb_adv_packet_to_send(void){
375     return pb_adv_msg_in_send_ack || pb_adv_msg_out_active || (link_state == LINK_STATE_W4_ACK);
376 }
377 
378 static void pb_adv_timer_handler(btstack_timer_source_t * ts){
379     UNUSED(ts);
380     pb_adv_random_delay_active = 0;
381     if (!pb_adv_packet_to_send()) return;
382     adv_bearer_request_can_send_now_for_provisioning_pdu();
383 }
384 
385 static void pb_adv_run(void){
386     if (!pb_adv_packet_to_send()) return;
387     if (pb_adv_random_delay_active) return;
388 
389     // spec recommends 20-50 ms, we use 20-51 ms
390     pb_adv_random_delay_active = 1;
391     uint16_t random_delay_ms = 20 + (pb_adv_random() & 0x1f);
392     log_info("random delay %u ms", random_delay_ms);
393     btstack_run_loop_set_timer_handler(&pb_adv_random_delay_timer, &pb_adv_timer_handler);
394     btstack_run_loop_set_timer(&pb_adv_random_delay_timer, random_delay_ms);
395     btstack_run_loop_add_timer(&pb_adv_random_delay_timer);
396 }
397 
398 static void pb_adv_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
399     UNUSED(channel);
400 
401     if (packet_type != HCI_EVENT_PACKET) return;
402     const uint8_t * data;
403     uint8_t  length;
404     uint32_t link_id;
405     uint8_t  transaction_nr;
406     uint8_t  generic_provisioning_control;
407     switch(packet[0]){
408         case GAP_EVENT_ADVERTISING_REPORT:
409             // data starts at offset 12
410             data = &packet[12];
411             // PDB ADV PDU
412             length = data[0];
413 
414             // validate length field
415             if ((12 + length) > size) return;
416 
417             link_id = big_endian_read_32(data, 2);
418             transaction_nr = data[6];
419             // generic provision PDU
420             generic_provisioning_control = data[7];
421             mesh_gpcf_format_t generic_provisioning_control_format = (mesh_gpcf_format_t) generic_provisioning_control & 3;
422 
423             // unless, we're waiting for LINK_OPEN, check link_id
424             if (link_state != LINK_STATE_W4_OPEN){
425                 if (link_id != pb_adv_link_id) break;
426             }
427 
428             if (generic_provisioning_control_format == MESH_GPCF_PROV_BEARER_CONTROL){
429                 pb_adv_handle_bearer_control(link_id, transaction_nr, &data[7], length-6);
430                 break;
431             }
432 
433             // verify link id and link state
434             if (link_state != LINK_STATE_OPEN) break;
435 
436             switch (generic_provisioning_control_format){
437                 case MESH_GPCF_TRANSACTION_START:
438                     pb_adv_handle_transaction_start(transaction_nr, &data[7], length-6);
439                     break;
440                 case MESH_GPCF_TRANSACTION_CONT:
441                     pb_adv_handle_transaction_cont(transaction_nr, &data[7], length-6);
442                     break;
443                 case MESH_GPCF_TRANSACTION_ACK:
444                     pb_adv_handle_transaction_ack(transaction_nr, &data[7], length-6);
445                     break;
446                 default:
447                     break;
448             }
449             pb_adv_run();
450             break;
451         case HCI_EVENT_MESH_META:
452             switch(packet[2]){
453                 case MESH_SUBEVENT_CAN_SEND_NOW:
454 #ifdef ENABLE_MESH_PROVISIONER
455                     if (link_state == LINK_STATE_W4_ACK){
456                         // build packet
457                         uint8_t buffer[22];
458                         big_endian_store_32(buffer, 0, pb_adv_link_id);
459                         buffer[4] = 0;            // Transaction ID = 0
460                         buffer[5] = (0 << 2) | 3; // Link Open | Provisioning Bearer Control
461                         (void)memcpy(&buffer[6], pb_adv_peer_device_uuid, 16);
462                         adv_bearer_send_provisioning_pdu(buffer, sizeof(buffer));
463                         log_info("link open %08x", pb_adv_link_id);
464                         printf("PB-ADV: Sending Link Open for device uuid: ");
465                         printf_hexdump(pb_adv_peer_device_uuid, 16);
466                         btstack_run_loop_set_timer_handler(&pb_adv_random_delay_timer, &pb_adv_timer_handler);
467                         btstack_run_loop_set_timer(&pb_adv_random_delay_timer, PB_ADV_LINK_OPEN_RETRANSMIT_MS);
468                         btstack_run_loop_add_timer(&pb_adv_random_delay_timer);
469                         break;
470                     }
471 #endif
472                     if (link_state == LINK_STATE_CLOSING){
473                         log_info("link close %08x", pb_adv_link_id);
474                         printf("PB-ADV: Sending Link Close\n");
475                         // build packet
476                         uint8_t buffer[7];
477                         big_endian_store_32(buffer, 0, pb_adv_link_id);
478                         buffer[4] = 0;            // Transaction ID = 0
479                         buffer[5] = (2 << 2) | 3; // Link Close | Provisioning Bearer Control
480                         buffer[6] = pb_adv_link_close_reason;
481                         adv_bearer_send_provisioning_pdu(buffer, sizeof(buffer));
482                         pb_adv_link_close_countdown--;
483                         if (pb_adv_link_close_countdown) {
484                             adv_bearer_request_can_send_now_for_provisioning_pdu();
485                         } else {
486                             link_state = LINK_STATE_W4_OPEN;
487                         }
488                         break;
489                     }
490                     if (link_state == LINK_STATE_W2_SEND_ACK){
491                         link_state = LINK_STATE_OPEN;
492                         pb_adv_msg_out_transaction_nr = 0x80;
493                         // build packet
494                         uint8_t buffer[6];
495                         big_endian_store_32(buffer, 0, pb_adv_link_id);
496                         buffer[4] = 0;
497                         buffer[5] = (1 << 2) | 3; // Link Ack | Provisioning Bearer Control
498                         adv_bearer_send_provisioning_pdu(buffer, sizeof(buffer));
499                         log_info("link ack %08x", pb_adv_link_id);
500                         printf("PB-ADV: Sending Link Open Ack\n");
501                         break;
502                     }
503                     if (pb_adv_msg_in_send_ack){
504                         pb_adv_msg_in_send_ack = 0;
505                         uint8_t buffer[6];
506                         big_endian_store_32(buffer, 0, pb_adv_link_id);
507                         buffer[4] = pb_adv_msg_in_transaction_nr_prev;
508                         buffer[5] = MESH_GPCF_TRANSACTION_ACK;
509                         adv_bearer_send_provisioning_pdu(buffer, sizeof(buffer));
510                         log_info("transaction ack %08x", pb_adv_link_id);
511                         printf("PB-ADV: %02x sending ACK\n", pb_adv_msg_in_transaction_nr_prev);
512                         pb_adv_run();
513                         break;
514                     }
515                     if (pb_adv_msg_out_active){
516 
517                         // check timeout for outgoing message
518                         // since uint32_t is used and time now must be greater than pb_adv_msg_out_start,
519                         // this claculation is correct even when the run loop time overruns
520                         uint32_t transaction_time_ms = btstack_run_loop_get_time_ms() - pb_adv_msg_out_start;
521                         if (transaction_time_ms >= MESH_GENERIC_PROVISIONING_TRANSACTION_TIMEOUT_MS){
522                             pb_adv_outgoing_transation_complete(ERROR_CODE_CONNECTION_TIMEOUT);
523                             return;
524                         }
525 
526                         uint8_t buffer[29]; // ADV MTU
527                         big_endian_store_32(buffer, 0, pb_adv_link_id);
528                         buffer[4] = pb_adv_msg_out_transaction_nr;
529                         uint16_t bytes_left;
530                         uint16_t pos;
531                         if (pb_adv_msg_out_pos == 0){
532                             // Transaction start
533                             int seg_n = pb_adv_msg_out_len / 24;
534                             pb_adv_msg_out_seg = 0;
535                             buffer[5] = seg_n << 2 | MESH_GPCF_TRANSACTION_START;
536                             big_endian_store_16(buffer, 6, pb_adv_msg_out_len);
537                             buffer[8] = btstack_crc8_calc((uint8_t*)pb_adv_msg_out_buffer, pb_adv_msg_out_len);
538                             pos = 9;
539                             bytes_left = 24 - 4;
540                             printf("PB-ADV: %02x Sending Start: ", pb_adv_msg_out_transaction_nr);
541                         } else {
542                             // Transaction continue
543                             buffer[5] = pb_adv_msg_out_seg << 2 | MESH_GPCF_TRANSACTION_CONT;
544                             pos = 6;
545                             bytes_left = 24 - 1;
546                             printf("PB-ADV: %02x Sending Cont:  ", pb_adv_msg_out_transaction_nr);
547                         }
548                         pb_adv_msg_out_seg++;
549                         uint16_t bytes_to_copy = btstack_min(bytes_left, pb_adv_msg_out_len - pb_adv_msg_out_pos);
550                         (void)memcpy(&buffer[pos],
551                                      &pb_adv_msg_out_buffer[pb_adv_msg_out_pos],
552                                      bytes_to_copy);
553                         pos += bytes_to_copy;
554                         printf("bytes %02u, pos %02u, len %02u: ", bytes_to_copy, pb_adv_msg_out_pos, pb_adv_msg_out_len);
555                         printf_hexdump(buffer, pos);
556                         pb_adv_msg_out_pos += bytes_to_copy;
557 
558                         if (pb_adv_msg_out_pos == pb_adv_msg_out_len){
559                             // done
560                             pb_adv_msg_out_pos = 0;
561                         }
562                         adv_bearer_send_provisioning_pdu(buffer, pos);
563                         pb_adv_run();
564                         break;
565                     }
566                     break;
567                 default:
568                     break;
569             }
570         default:
571             break;
572     }
573 }
574 
575 void pb_adv_init(void){
576     adv_bearer_register_for_provisioning_pdu(&pb_adv_handler);
577     pb_adv_lfsr = 0x12345678;
578     pb_adv_random();
579 }
580 
581 void pb_adv_register_packet_handler(btstack_packet_handler_t packet_handler){
582     pb_adv_packet_handler = packet_handler;
583 }
584 
585 void pb_adv_send_pdu(uint16_t pb_transport_cid, const uint8_t * pdu, uint16_t size){
586     UNUSED(pb_transport_cid);
587     printf("PB-ADV: Send packet ");
588     printf_hexdump(pdu, size);
589     pb_adv_msg_out_buffer = pdu;
590     pb_adv_msg_out_len    = size;
591     pb_adv_msg_out_pos = 0;
592     pb_adv_msg_out_start = btstack_run_loop_get_time_ms();
593     pb_adv_msg_out_active = 1;
594     pb_adv_run();
595 }
596 
597 /**
598  * Close Link
599  * @param pb_transport_cid
600  */
601 void pb_adv_close_link(uint16_t pb_transport_cid, uint8_t reason){
602     switch (link_state){
603         case LINK_STATE_W4_ACK:
604         case LINK_STATE_OPEN:
605         case LINK_STATE_W2_SEND_ACK:
606             pb_adv_emit_link_close(pb_transport_cid, 0);
607             link_state = LINK_STATE_CLOSING;
608             pb_adv_link_close_countdown = 3;
609             pb_adv_link_close_reason = reason;
610             adv_bearer_request_can_send_now_for_provisioning_pdu();
611             break;
612         case LINK_STATE_W4_OPEN:
613         case LINK_STATE_CLOSING:
614             // nothing to do
615             break;
616     }
617 }
618 
619 #ifdef ENABLE_MESH_PROVISIONER
620 uint16_t pb_adv_create_link(const uint8_t * device_uuid){
621     if (link_state != LINK_STATE_W4_OPEN) return 0;
622 
623     pb_adv_peer_device_uuid = device_uuid;
624     pb_adv_provisioner_role = 1;
625 
626     // create new 32-bit link id
627     pb_adv_link_id = pb_adv_random();
628 
629     // after sending OPEN, we wait for an ACK
630     link_state = LINK_STATE_W4_ACK;
631 
632     // request outgoing
633     adv_bearer_request_can_send_now_for_provisioning_pdu();
634 
635     // dummy pb_adv_cid
636     return pb_adv_cid;
637 }
638 #endif
639 
640