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