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