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