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