Skip to content

Commit

Permalink
drv/bluetooth_btstack: use PT for tasks
Browse files Browse the repository at this point in the history
In MicroPython, if a task it canceled, it tries to run the protothread.
In the case of starting broadcasting and observing we weren't actually
creating any protothread so it caused a crash when cancellation tried
to run the thread.
  • Loading branch information
dlech committed May 30, 2023
1 parent ac9b039 commit 1648303
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 3 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@

### Fixed
- Fixed BLE broadcast not working on City hub.
- Fixed crash on BTStack hubs when program stopped during call to `ble.broadcast()`.

[support#402]: https://github.com/pybricks/support/issues/402

Expand Down
26 changes: 23 additions & 3 deletions lib/pbio/drv/bluetooth/bluetooth_btstack.c
Original file line number Diff line number Diff line change
Expand Up @@ -736,10 +736,14 @@ void pbdrv_bluetooth_disconnect_remote(void) {
}
}

void pbdrv_bluetooth_start_broadcasting(pbio_task_t *task, pbdrv_bluetooth_value_t *value) {
static PT_THREAD(start_broadcasting_task(struct pt *pt, pbio_task_t *task)) {
pbdrv_bluetooth_value_t *value = task->context;

PT_BEGIN(pt);

if (value->size > LE_ADVERTISING_DATA_SIZE) {
task->status = PBIO_ERROR_INVALID_ARG;
return;
PT_EXIT(pt);
}

bd_addr_t null_addr = { };
Expand All @@ -758,6 +762,12 @@ void pbdrv_bluetooth_start_broadcasting(pbio_task_t *task, pbdrv_bluetooth_value

// REVISIT: use callback to actually wait for start?
task->status = PBIO_SUCCESS;

PT_END(pt);
}

void pbdrv_bluetooth_start_broadcasting(pbio_task_t *task, pbdrv_bluetooth_value_t *value) {
start_task(task, start_broadcasting_task, value);
}

void pbdrv_bluetooth_stop_broadcasting(void) {
Expand All @@ -767,7 +777,11 @@ void pbdrv_bluetooth_stop_broadcasting(void) {
}
}

void pbdrv_bluetooth_start_observing(pbio_task_t *task, pbdrv_bluetooth_start_observing_callback_t callback) {
static PT_THREAD(start_observing_task(struct pt *pt, pbio_task_t *task)) {
pbdrv_bluetooth_start_observing_callback_t callback = task->context;

PT_BEGIN(pt);

observe_callback = callback;

if (!is_observing) {
Expand All @@ -777,6 +791,12 @@ void pbdrv_bluetooth_start_observing(pbio_task_t *task, pbdrv_bluetooth_start_ob

// REVISIT: use callback to actually wait for start?
task->status = PBIO_SUCCESS;

PT_END(pt);
}

void pbdrv_bluetooth_start_observing(pbio_task_t *task, pbdrv_bluetooth_start_observing_callback_t callback) {
start_task(task, start_observing_task, callback);
}

void pbdrv_bluetooth_stop_observing(void) {
Expand Down

0 comments on commit 1648303

Please sign in to comment.