Skip to content

Commit 8a7a737

Browse files
hakanjanssonnashif
authored andcommitted
samples: bluetooth: Fix PAwR null dereference on disconnection
If an involuntary disconnection happened it could set default_conn to NULL while it was still being used in the main while loop. Signed-off-by: Hakan Jansson <[email protected]>
1 parent 53b9113 commit 8a7a737

File tree

1 file changed

+20
-5
lines changed
  • samples/bluetooth/periodic_adv_rsp/src

1 file changed

+20
-5
lines changed

samples/bluetooth/periodic_adv_rsp/src/main.c

Lines changed: 20 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,13 @@ static K_SEM_DEFINE(sem_discovered, 0, 1);
2020
static K_SEM_DEFINE(sem_written, 0, 1);
2121
static K_SEM_DEFINE(sem_disconnected, 0, 1);
2222

23+
struct k_poll_event events[] = {
24+
K_POLL_EVENT_STATIC_INITIALIZER(K_POLL_TYPE_SEM_AVAILABLE, K_POLL_MODE_NOTIFY_ONLY,
25+
&sem_connected, 0),
26+
K_POLL_EVENT_STATIC_INITIALIZER(K_POLL_TYPE_SEM_AVAILABLE, K_POLL_MODE_NOTIFY_ONLY,
27+
&sem_disconnected, 0),
28+
};
29+
2330
static struct bt_uuid_128 pawr_char_uuid =
2431
BT_UUID_INIT_128(BT_UUID_128_ENCODE(0x12345678, 0x1234, 0x5678, 0x1234, 0x56789abcdef1));
2532
static uint16_t pawr_attr_handle;
@@ -116,9 +123,6 @@ void disconnected_cb(struct bt_conn *conn, uint8_t reason)
116123
{
117124
printk("Disconnected, reason 0x%02X %s\n", reason, bt_hci_err_to_str(reason));
118125

119-
bt_conn_unref(default_conn);
120-
default_conn = NULL;
121-
122126
k_sem_give(&sem_disconnected);
123127
}
124128

@@ -303,7 +307,14 @@ int main(void)
303307

304308
printk("Scanning successfully started\n");
305309

306-
k_sem_take(&sem_connected, K_FOREVER);
310+
/* Wait for either remote info available or involuntary disconnect */
311+
k_poll(events, ARRAY_SIZE(events), K_FOREVER);
312+
err = k_sem_take(&sem_connected, K_NO_WAIT);
313+
if (err) {
314+
printk("Disconnected before remote info available\n");
315+
316+
goto disconnected;
317+
}
307318

308319
err = bt_le_per_adv_set_info_transfer(pawr_adv, default_conn, 0);
309320
if (err) {
@@ -373,11 +384,15 @@ int main(void)
373384
k_sleep(K_MSEC(per_adv_params.interval_max * 2));
374385

375386
err = bt_conn_disconnect(default_conn, BT_HCI_ERR_REMOTE_USER_TERM_CONN);
376-
if (err) {
387+
if (err != 0 && err != -ENOTCONN) {
377388
return 0;
378389
}
379390

391+
disconnected:
380392
k_sem_take(&sem_disconnected, K_FOREVER);
393+
394+
bt_conn_unref(default_conn);
395+
default_conn = NULL;
381396
}
382397

383398
printk("Maximum numnber of syncs onboarded\n");

0 commit comments

Comments
 (0)