xref: /btstack/src/mesh/pb_adv.c (revision a5a7b6da93a734de273f68a4770fffd1d7ae3888)
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_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, 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 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, 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     pb_adv_random_delay_active = 0;
374     if (!pb_adv_packet_to_send()) return;
375     adv_bearer_request_can_send_now_for_provisioning_pdu();
376 }
377 
378 static void pb_adv_run(void){
379     if (!pb_adv_packet_to_send()) return;
380     if (pb_adv_random_delay_active) return;
381 
382     // spec recommends 20-50 ms, we use 20-51 ms
383     pb_adv_random_delay_active = 1;
384     uint16_t random_delay_ms = 20 + (pb_adv_random() & 0x1f);
385     log_info("random delay %u ms", random_delay_ms);
386     btstack_run_loop_set_timer_handler(&pb_adv_random_delay_timer, &pb_adv_timer_handler);
387     btstack_run_loop_set_timer(&pb_adv_random_delay_timer, random_delay_ms);
388     btstack_run_loop_add_timer(&pb_adv_random_delay_timer);
389 }
390 
391 static void pb_adv_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
392     if (packet_type != HCI_EVENT_PACKET) return;
393     const uint8_t * data;
394     uint8_t  length;
395     uint32_t link_id;
396     uint8_t  transaction_nr;
397     uint8_t  generic_provisioning_control;
398     switch(packet[0]){
399         case GAP_EVENT_ADVERTISING_REPORT:
400 
401             data = gap_event_advertising_report_get_data(packet);
402             // PDB ADV PDU
403             length = data[0];
404             link_id = big_endian_read_32(data, 2);
405             transaction_nr = data[6];
406             // generic provision PDU
407             generic_provisioning_control = data[7];
408             mesh_gpcf_format_t generic_provisioning_control_format = (mesh_gpcf_format_t) generic_provisioning_control & 3;
409 
410             // unless, we're waiting for LINK_OPEN, check link_id
411             if (link_state != LINK_STATE_W4_OPEN){
412                 if (link_id != pb_adv_link_id) break;
413             }
414 
415             if (generic_provisioning_control_format == MESH_GPCF_PROV_BEARER_CONTROL){
416                 pb_adv_handle_bearer_control(link_id, transaction_nr, &data[7], length-6);
417                 break;
418             }
419 
420             // verify link id and link state
421             if (link_state != LINK_STATE_OPEN) break;
422 
423             switch (generic_provisioning_control_format){
424                 case MESH_GPCF_TRANSACTION_START:
425                     pb_adv_handle_transaction_start(transaction_nr, &data[7], length-6);
426                     break;
427                 case MESH_GPCF_TRANSACTION_CONT:
428                     pb_adv_handle_transaction_cont(transaction_nr, &data[7], length-6);
429                     break;
430                 case MESH_GPCF_TRANSACTION_ACK:
431                     pb_adv_handle_transaction_ack(transaction_nr, &data[7], length-6);
432                     break;
433                 default:
434                     break;
435             }
436             pb_adv_run();
437             break;
438         case HCI_EVENT_MESH_META:
439             switch(packet[2]){
440                 case MESH_SUBEVENT_CAN_SEND_NOW:
441                     if (link_state == LINK_STATE_W4_ACK){
442                         // build packet
443                         uint8_t buffer[22];
444                         big_endian_store_32(buffer, 0, pb_adv_link_id);
445                         buffer[4] = 0;            // Transaction ID = 0
446                         buffer[5] = (0 << 2) | 3; // Link Open | Provisioning Bearer Control
447                         memcpy(&buffer[6], pb_adv_peer_device_uuid, 16);
448                         adv_bearer_send_provisioning_pdu(buffer, sizeof(buffer));
449                         log_info("link open %08x", pb_adv_link_id);
450                         printf("PB-ADV: Sending Link Open for device uuid: ");
451                         printf_hexdump(pb_adv_peer_device_uuid, 16);
452                         btstack_run_loop_set_timer_handler(&pb_adv_random_delay_timer, &pb_adv_timer_handler);
453                         btstack_run_loop_set_timer(&pb_adv_random_delay_timer, PB_ADV_LINK_OPEN_RETRANSMIT_MS);
454                         btstack_run_loop_add_timer(&pb_adv_random_delay_timer);
455                         break;
456                     }
457                     if (link_state == LINK_STATE_CLOSING){
458                         log_info("link close %08x", pb_adv_link_id);
459                         printf("PB-ADV: Sending Link Close\n");
460                         // build packet
461                         uint8_t buffer[7];
462                         big_endian_store_32(buffer, 0, pb_adv_link_id);
463                         buffer[4] = 0;            // Transaction ID = 0
464                         buffer[5] = (2 << 2) | 3; // Link Close | Provisioning Bearer Control
465                         buffer[6] = pb_adv_link_close_reason;
466                         adv_bearer_send_provisioning_pdu(buffer, sizeof(buffer));
467                         pb_adv_link_close_countdown--;
468                         if (pb_adv_link_close_countdown) {
469                             adv_bearer_request_can_send_now_for_provisioning_pdu();
470                         } else {
471                             link_state = LINK_STATE_W4_OPEN;
472                         }
473                         break;
474                     }
475                     if (link_state == LINK_STATE_W2_SEND_ACK){
476                         link_state = LINK_STATE_OPEN;
477                         pb_adv_msg_out_transaction_nr = 0x80;
478                         // build packet
479                         uint8_t buffer[6];
480                         big_endian_store_32(buffer, 0, pb_adv_link_id);
481                         buffer[4] = 0;
482                         buffer[5] = (1 << 2) | 3; // Link Ack | Provisioning Bearer Control
483                         adv_bearer_send_provisioning_pdu(buffer, sizeof(buffer));
484                         log_info("link ack %08x", pb_adv_link_id);
485                         printf("PB-ADV: Sending Link Open Ack\n");
486                         break;
487                     }
488                     if (pb_adv_msg_in_send_ack){
489                         pb_adv_msg_in_send_ack = 0;
490                         uint8_t buffer[6];
491                         big_endian_store_32(buffer, 0, pb_adv_link_id);
492                         buffer[4] = pb_adv_msg_in_transaction_nr_prev;
493                         buffer[5] = MESH_GPCF_TRANSACTION_ACK;
494                         adv_bearer_send_provisioning_pdu(buffer, sizeof(buffer));
495                         log_info("transaction ack %08x", pb_adv_link_id);
496                         printf("PB-ADV: %02x sending ACK\n", pb_adv_msg_in_transaction_nr_prev);
497                         pb_adv_run();
498                         break;
499                     }
500                     if (pb_adv_msg_out_active){
501 
502                         // check timeout for outgoing message
503                         // since uint32_t is used and time now must be greater than pb_adv_msg_out_start,
504                         // this claculation is correct even when the run loop time overruns
505                         uint32_t transaction_time_ms = btstack_run_loop_get_time_ms() - pb_adv_msg_out_start;
506                         if (transaction_time_ms >= MESH_GENERIC_PROVISIONING_TRANSACTION_TIMEOUT_MS){
507                             pb_adv_outgoing_transation_complete(ERROR_CODE_CONNECTION_TIMEOUT);
508                             return;
509                         }
510 
511                         uint8_t buffer[29]; // ADV MTU
512                         big_endian_store_32(buffer, 0, pb_adv_link_id);
513                         buffer[4] = pb_adv_msg_out_transaction_nr;
514                         uint16_t bytes_left;
515                         uint16_t pos;
516                         if (pb_adv_msg_out_pos == 0){
517                             // Transaction start
518                             int seg_n = pb_adv_msg_out_len / 24;
519                             pb_adv_msg_out_seg = 0;
520                             buffer[5] = seg_n << 2 | MESH_GPCF_TRANSACTION_START;
521                             big_endian_store_16(buffer, 6, pb_adv_msg_out_len);
522                             buffer[8] = btstack_crc8_calc((uint8_t*)pb_adv_msg_out_buffer, pb_adv_msg_out_len);
523                             pos = 9;
524                             bytes_left = 24 - 4;
525                             printf("PB-ADV: %02x Sending Start: ", pb_adv_msg_out_transaction_nr);
526                         } else {
527                             // Transaction continue
528                             buffer[5] = pb_adv_msg_out_seg << 2 | MESH_GPCF_TRANSACTION_CONT;
529                             pos = 6;
530                             bytes_left = 24 - 1;
531                             printf("PB-ADV: %02x Sending Cont:  ", pb_adv_msg_out_transaction_nr);
532                         }
533                         pb_adv_msg_out_seg++;
534                         uint16_t bytes_to_copy = btstack_min(bytes_left, pb_adv_msg_out_len - pb_adv_msg_out_pos);
535                         memcpy(&buffer[pos], &pb_adv_msg_out_buffer[pb_adv_msg_out_pos], bytes_to_copy);
536                         pos += bytes_to_copy;
537                         printf("bytes %02u, pos %02u, len %02u: ", bytes_to_copy, pb_adv_msg_out_pos, pb_adv_msg_out_len);
538                         printf_hexdump(buffer, pos);
539                         pb_adv_msg_out_pos += bytes_to_copy;
540 
541                         if (pb_adv_msg_out_pos == pb_adv_msg_out_len){
542                             // done
543                             pb_adv_msg_out_pos = 0;
544                         }
545                         adv_bearer_send_provisioning_pdu(buffer, pos);
546                         pb_adv_run();
547                         break;
548                     }
549                     break;
550                 default:
551                     break;
552             }
553         default:
554             break;
555     }
556 }
557 
558 void pb_adv_init(void){
559     adv_bearer_register_for_provisioning_pdu(&pb_adv_handler);
560     pb_adv_lfsr = 0x12345678;
561     pb_adv_random();
562 }
563 
564 void pb_adv_register_packet_handler(btstack_packet_handler_t packet_handler){
565     pb_adv_packet_handler = packet_handler;
566 }
567 
568 void pb_adv_send_pdu(uint16_t pb_adv_cid, const uint8_t * pdu, uint16_t size){
569     UNUSED(pb_adv_cid);
570     printf("PB-ADV: Send packet ");
571     printf_hexdump(pdu, size);
572     pb_adv_msg_out_buffer = pdu;
573     pb_adv_msg_out_len    = size;
574     pb_adv_msg_out_pos = 0;
575     pb_adv_msg_out_start = btstack_run_loop_get_time_ms();
576     pb_adv_msg_out_active = 1;
577     pb_adv_run();
578 }
579 
580 /**
581  * Close Link
582  * @param pb_adv_cid
583  */
584 void pb_adv_close_link(uint16_t pb_adv_cid, uint8_t reason){
585     switch (link_state){
586         case LINK_STATE_W4_ACK:
587         case LINK_STATE_OPEN:
588         case LINK_STATE_W2_SEND_ACK:
589             pb_adv_emit_link_close(pb_adv_cid, 0);
590             link_state = LINK_STATE_CLOSING;
591             pb_adv_link_close_countdown = 3;
592             pb_adv_link_close_reason = reason;
593             adv_bearer_request_can_send_now_for_provisioning_pdu();
594             break;
595         case LINK_STATE_W4_OPEN:
596         case LINK_STATE_CLOSING:
597             // nothing to do
598             break;
599     }
600 }
601 
602 #ifdef ENABLE_MESH_PROVISIONER
603 uint16_t pb_adv_create_link(const uint8_t * device_uuid){
604     if (link_state != LINK_STATE_W4_OPEN) return 0;
605 
606     pb_adv_peer_device_uuid = device_uuid;
607     pb_adv_provisioner_role = 1;
608 
609     // create new 32-bit link id
610     pb_adv_link_id = pb_adv_random();
611 
612     // after sending OPEN, we wait for an ACK
613     link_state = LINK_STATE_W4_ACK;
614 
615     // request outgoing
616     adv_bearer_request_can_send_now_for_provisioning_pdu();
617 
618     // dummy pb_adv_cid
619     return pb_adv_cid;
620 }
621 #endif
622 
623