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