Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .vscode/launch.json
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@
"request": "launch",
"program": "${workspaceFolder}/bricks/virtualhub/build-debug/firmware.elf",
"args": [
"${workspaceFolder}/tests/virtualhub/motor/car.py",
"${workspaceFolder}/tests/virtualhub/basics/hello.py",
],
"stopAtEntry": false,
"cwd": "${workspaceFolder}",
Expand Down
2 changes: 2 additions & 0 deletions bricks/_common/sources.mk
Original file line number Diff line number Diff line change
Expand Up @@ -188,9 +188,11 @@ PBIO_SRC_C = $(addprefix lib/pbio/,\
drv/uart/uart_stm32f0.c \
drv/uart/uart_stm32f4_ll_irq.c \
drv/uart/uart_stm32l4_ll_dma.c \
drv/usb/usb.c \
drv/usb/usb_common_desc.c \
drv/usb/usb_ev3.c \
drv/usb/usb_nxt.c \
drv/usb/usb_simulation.c \
drv/usb/usb_stm32.c \
drv/watchdog/watchdog_ev3.c \
drv/watchdog/watchdog_stm32.c \
Expand Down
227 changes: 227 additions & 0 deletions lib/pbio/drv/usb/usb.c
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It doesn't look like there is anything hardware-specific here, it would make more sense to me to have this new layer be pbsys instead of pbdrv. (Kind of like BlueZ manages the Bluetooth stack on Linux at the OS level doing most of it in userspace and only calls into the kernel to actually poke the hardware).

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, the same probably goes for the newly structured Bluetooth drivers. It could benefit from some renaming too to make it a bit more consistent with its USB counterpart.

Copy link
Member Author

@laurensvalk laurensvalk Nov 7, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Going to leave this for a future update since pbsys starts a bit later. We should be fine but it means that the receive handlers get set up slightly later, so deserves a closer look.

Original file line number Diff line number Diff line change
@@ -0,0 +1,227 @@
// SPDX-License-Identifier: MIT
// Copyright (c) 2025 The Pybricks Authors

#include <pbdrv/config.h>

#if PBDRV_CONFIG_USB

#include <errno.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#include "usb.h"

#include <pbdrv/config.h>
#include <pbdrv/usb.h>

#include <pbio/error.h>
#include <pbio/os.h>
#include <pbio/protocol.h>

#include <lwrb/lwrb.h>

/**
* Host is subscribed to our outgoing event messages.
*/
static bool pbdrv_usb_events_subscribed;

bool pbdrv_usb_connection_is_active(void) {
return pbdrv_usb_events_subscribed && pbdrv_usb_is_ready();
}

/**
* Pybricks system command handler.
*/
static pbdrv_usb_receive_handler_t pbdrv_usb_receive_handler;

void pbdrv_usb_set_receive_handler(pbdrv_usb_receive_handler_t handler) {
pbdrv_usb_receive_handler = handler;
}

/**
* Buffer scheduled status.
*/
static uint8_t status_data[PBIO_PYBRICKS_EVENT_STATUS_REPORT_SIZE];
static bool status_data_pending;

void pbdrv_usb_schedule_status_update(const uint8_t *status_msg) {
// Ignore if message identical to last.
if (!memcmp(status_data, status_msg, sizeof(status_data))) {
return;
}

// Schedule to send whenever the Bluetooth process gets round to it.
memcpy(status_data, status_msg, sizeof(status_data));
status_data_pending = true;
pbio_os_request_poll();
}

/**
* Buffer for scheduled stdout.
*/
static lwrb_t stdout_ring_buf;

pbio_error_t pbdrv_usb_stdout_tx(const uint8_t *data, uint32_t *size) {

if (!pbdrv_usb_connection_is_active()) {
return PBIO_ERROR_INVALID_OP;
}

// Buffer data to send it more efficiently even if the caller is only
// writing one byte at a time.
if ((*size = lwrb_write(&stdout_ring_buf, data, *size)) == 0) {
return PBIO_ERROR_AGAIN;
}

// Poke the process to start tx soon-ish. This way, we can accumulate
// data bytes before actually transmitting.
pbio_os_request_poll();

return PBIO_SUCCESS;
}

uint32_t pbdrv_usb_stdout_tx_available(void) {
if (!pbdrv_usb_connection_is_active()) {
return UINT32_MAX;
}
return lwrb_get_free(&stdout_ring_buf);
}

bool pbdrv_usb_stdout_tx_is_idle(void) {
if (!pbdrv_usb_connection_is_active()) {
return true;
}
return lwrb_get_full(&stdout_ring_buf) == 0;
}

static bool respond_soon;
static pbio_pybricks_error_t respond_result;

/**
* Non-blocking poll handler to process pending incoming messages.
*/
static void pbdrv_usb_handle_data_in(void) {

// Ignore incoming data if we haven't sent our previous response yet.
if (respond_soon) {
return;
}

static uint8_t data_in[PBDRV_CONFIG_USB_MAX_PACKET_SIZE];
uint32_t size = pbdrv_usb_get_data_in(data_in);

// Expecting at least EP_MSG and payload.
if (size < 2) {
return;
}

switch (data_in[0]) {
case PBIO_PYBRICKS_OUT_EP_MSG_SUBSCRIBE:
pbdrv_usb_events_subscribed = data_in[1];
respond_result = PBIO_PYBRICKS_ERROR_OK;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Having global variables without a namespace prefix really throws me off. It makes it looks like this value is assigned but never used. You have go read the entire function up to this point to see that it isn't a local variable, whereas if we follow the convention of namespace prefix on all global variable, it is instantly obvious what is going on.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Happy to change, but FWIW we've been using prefixes consistently for global public variables shared across files, but less so for static variables within files. I find it helpful to tell these apart.

respond_soon = true;

// Schedule sending current status immediately after subscribing.
status_data_pending = true;
break;
case PBIO_PYBRICKS_OUT_EP_MSG_COMMAND:
if (pbdrv_usb_receive_handler) {
respond_result = pbdrv_usb_receive_handler(data_in + 1, size - 1);
respond_soon = true;
}
break;
}
}

static void pbdrv_usb_reset_state(void) {
pbdrv_usb_events_subscribed = false;
respond_soon = false;
status_data_pending = false;
lwrb_reset(&stdout_ring_buf);
}

static pbio_os_process_t pbdrv_usb_process;

static pbio_error_t pbdrv_usb_process_thread(pbio_os_state_t *state, void *context) {

static pbio_os_state_t sub;

static uint8_t *out_data;
static uint32_t out_size;

pbio_error_t err;

// Runs every time. If there is no connection, there just won't be data.
pbdrv_usb_handle_data_in();

PBIO_OS_ASYNC_BEGIN(state);

for (;;) {

// Run charger detection: wait for USB to become physically plugged in.
PBIO_OS_AWAIT(state, &sub, err = pbdrv_usb_wait_for_charger(&sub));

while (pbdrv_usb_process.request != PBIO_OS_PROCESS_REQUEST_TYPE_CANCEL && pbdrv_usb_is_ready()) {

// Find out what we should send, if anything, priotizing response, then
// status, then stdout, then other events.
if (respond_soon) {
// Pack the response to the most recent message.
pbdrv_usb_tx_get_buf(PBIO_PYBRICKS_IN_EP_MSG_RESPONSE, &out_data);
pbio_set_uint32_le(&out_data[1], respond_result);
out_size = sizeof(uint32_t) + 1;
respond_soon = false;
} else if (pbdrv_usb_connection_is_active() && status_data_pending) {
// Send out status if pending (already includes event code).
pbdrv_usb_tx_get_buf(PBIO_PYBRICKS_IN_EP_MSG_EVENT, &out_data);
memcpy(&out_data[1], status_data, PBIO_PYBRICKS_EVENT_STATUS_REPORT_SIZE);
out_size = PBIO_PYBRICKS_USB_MESSAGE_SIZE(PBIO_PYBRICKS_EVENT_STATUS_REPORT_SIZE);
status_data_pending = false;
} else if (pbdrv_usb_connection_is_active() && lwrb_get_full(&stdout_ring_buf) != 0) {
// Send out stdout if anything is buffered.
uint32_t max_size = pbdrv_usb_tx_get_buf(PBIO_PYBRICKS_IN_EP_MSG_EVENT, &out_data);
out_data[1] = PBIO_PYBRICKS_EVENT_WRITE_STDOUT;
out_size = lwrb_read(&stdout_ring_buf, &out_data[2], max_size - 2) + 2;
}

// If there was anything to send, send it.
if (out_size) {
PBIO_OS_AWAIT(state, &sub, err = pbdrv_usb_tx(&sub, out_data, out_size));
out_size = 0;
if (err != PBIO_SUCCESS) {
pbdrv_usb_reset_state();
PBIO_OS_AWAIT(state, &sub, pbdrv_usb_tx_reset(&sub));
}
} else {
// Otherwise yield once before going and check again.
PBIO_OS_AWAIT_ONCE(state);
}
}

PBIO_OS_AWAIT_WHILE(state, pbdrv_usb_is_ready());
pbdrv_usb_reset_state();
pbdrv_usb_tx_reset(&sub);
}

// Unreachable. On cancellation, the charger detection step in the above
// loop keeps running. It will just skip the data handler.
PBIO_OS_ASYNC_END(PBIO_ERROR_FAILED);
}

void pbdrv_usb_init(void) {
pbdrv_usb_init_device();

static uint8_t stdout_buf[PBDRV_CONFIG_USB_MAX_PACKET_SIZE * 2];
lwrb_init(&stdout_ring_buf, stdout_buf, PBIO_ARRAY_SIZE(stdout_buf));

pbio_os_process_start(&pbdrv_usb_process, pbdrv_usb_process_thread, NULL);
}

void pbdrv_usb_deinit(void) {
pbdrv_usb_deinit_device();
pbio_os_process_make_request(&pbdrv_usb_process, PBIO_OS_PROCESS_REQUEST_TYPE_CANCEL);
}

#endif // PBDRV_CONFIG_USB
118 changes: 116 additions & 2 deletions lib/pbio/drv/usb/usb.h
Original file line number Diff line number Diff line change
Expand Up @@ -10,20 +10,134 @@

#if PBDRV_CONFIG_USB

#include <pbio/error.h>
#include <pbio/os.h>
#include <pbio/protocol.h>

#include <stdint.h>

#define PBDRV_USB_TRANSMIT_TIMEOUT (50)

/**
* Initializes the USB driver on boot.
*/
void pbdrv_usb_init(void);

/**
* Platform specific device initialization.
*/
void pbdrv_usb_init_device(void);

/**
* De-initializes the USB driver for data transfers on soft-poweroff. Keeps charging if supported.
*/
void pbdrv_usb_deinit(void);

/**
* Platform specific device deinitialization.
*/
void pbdrv_usb_deinit_device(void);

/**
* Gets most recent incoming message and copies it to provided buffer.
*
* The message is then cleared and the driver prepares to read a new message.
*
* @param [in] data Buffer to copy the message to.
* @return Number of bytes copied. Zero means nothing was available.
*/
uint32_t pbdrv_usb_get_data_in(uint8_t *data);

/**
* Gets the buffer to match the given endpoint mesage type.
*
* @param [in] message_type The message type to find the buffer for
* @param [out] buf The corresponding buffer to write data to before sending.
* @return Maximum size to write.
*/
uint32_t pbdrv_usb_tx_get_buf(pbio_pybricks_usb_in_ep_msg_t message_type, uint8_t **buf);

/**
* Sends and awaits message from hub to host via the Pybricks USB interface OUT endpoint.
*
* Driver-specific implementation. Must return within ::PBDRV_USB_TRANSMIT_TIMEOUT.
*
* The USB process ensures that only one call is made at once.
*
* @param [in] state Protothread state.
* @param [in] data Data to send.
* @param [in] size Data size.
* @return ::PBIO_SUCCESS on completion.
* ::PBIO_ERROR_INVALID_OP if there is no connection.
* ::PBIO_ERROR_AGAIN while awaiting.
* ::PBIO_ERROR_BUSY if this operation is already ongoing.
* ::PBIO_ERROR_INVALID_ARG if @p size is too large.
* ::PBIO_ERROR_TIMEDOUT if the operation was started but could not complete.
*/
pbio_error_t pbdrv_usb_tx(pbio_os_state_t *state, const uint8_t *data, uint32_t size);

/**
* Resets the driver transmission state.
*
* @param [in] state Protothread state.
* @return ::PBIO_SUCCESS on completion.
* ::PBIO_ERROR_AGAIN while awaiting.
*/
pbio_error_t pbdrv_usb_tx_reset(pbio_os_state_t *state);

/**
* Waits for USB to be plugged in and detects what charger type is connected.
*
* @param [in] state Protothread state.
* @return ::PBIO_SUCCESS on completion.
* ::PBIO_ERROR_AGAIN while awaiting.
* ::PBIO_ERROR_NOT_SUPPORTED if platform has no charger.
*/
pbio_error_t pbdrv_usb_wait_for_charger(pbio_os_state_t *state);

/**
* Tests if USB is ready for communication.
*/
bool pbdrv_usb_is_ready(void);

#else // PBDRV_CONFIG_USB

#define pbdrv_usb_init()
#define pbdrv_usb_deinit()
static inline void pbdrv_usb_init(void) {
}

static inline void pbdrv_usb_deinit(void) {
}

static inline void pbdrv_usb_init_device(void) {
}

static inline void pbdrv_usb_deinit_device(void) {
}

static inline pbio_error_t pbdrv_usb_tx(pbio_os_state_t *state, const uint8_t *data, size_t size) {
return PBIO_ERROR_NOT_IMPLEMENTED;
}

static inline uint32_t pbdrv_usb_get_data_in(uint8_t *data) {
return 0;
}

static inline pbio_error_t pbdrv_usb_tx_reset(pbio_os_state_t *state) {
return PBIO_ERROR_NOT_IMPLEMENTED;
}

static inline pbio_error_t pbdrv_usb_wait_for_charger(pbio_os_state_t *state) {
return PBIO_ERROR_NOT_IMPLEMENTED;
}

static inline bool pbdrv_usb_is_ready(void) {
return false;
}

static inline uint32_t pbdrv_usb_tx_get_buf(pbio_pybricks_usb_in_ep_msg_t message_type, uint8_t **buf) {
return 0;
}


#endif // PBDRV_CONFIG_USB

Expand Down
Loading