Skip to content
Open
Show file tree
Hide file tree
Changes from all 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
11 changes: 8 additions & 3 deletions subsys/usb/device_next/class/gs_usb.c
Original file line number Diff line number Diff line change
Expand Up @@ -1311,6 +1311,12 @@ static void gs_usb_can_tx_callback(const struct device *can_dev, int error, void
uint8_t *tail;

if (error != 0) {
if (!channel->started) {
/* Aborted by a channel reset, which released the host TX contexts */
net_buf_unref(buf);
return;
}

/* There is currently no way to report a dropped frame to the host driver */
LOG_ERR("failed to send CAN frame (err %d)", error);
}
Expand Down Expand Up @@ -1434,9 +1440,8 @@ static void gs_usb_tx_thread(void *p1, void *p2, void *p3)

err = can_send(channel->dev, &frame, K_FOREVER, gs_usb_can_tx_callback, buf);
if (err != 0) {
/* There is no way to report a dropped frame to the host driver */
LOG_ERR("failed to enqueue CAN frame for TX (err %d)", err);
net_buf_unref(buf);
/* Complete the frame through the TX callback for it to be echoed */
gs_usb_can_tx_callback(channel->dev, err, buf);
}
}
}
Expand Down
4 changes: 3 additions & 1 deletion tests/subsys/usb/gs_usb/host/pytest/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,4 +78,6 @@ def fixture_gs_usb(request, usb_vid: int, usb_pid: int, usb_sn: str) -> GsUSB:
logger.info('Waiting %d seconds for USB enumeration...', delay)
time.sleep(delay)

return GsUSB(usb_vid, usb_pid, usb_sn)
dev = GsUSB(usb_vid, usb_pid, usb_sn)
yield dev
dev.close()
118 changes: 117 additions & 1 deletion tests/subsys/usb/gs_usb/host/pytest/gs_usb.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,10 @@

logger = logging.getLogger(__name__)

def timeout_ms(timeout: float) -> int:
"""Return a timeout in milliseconds for PyUSB, where 0 means no timeout."""
return max(1, round(timeout * 1000))

class GsUSBDeviceNotFound(Exception):
"""
Geschwister Schneider USB/CAN device not found.
Expand Down Expand Up @@ -122,6 +126,34 @@ class GsUSBCANChannelFlag(IntFlag):
# CAN channel uses bus error reporting (unsupported, always enabled).
BERR_REPORTING = 2**12

class GsUSBCANIDFlag(IntFlag):
"""
Geschwister Schneider USB/CAN protocol CAN ID flags.
"""
# CAN controller is in bus off state (error frames only).
ERR_BUSOFF = 2**6
# CAN controller restarted (error frames only).
ERR_RESTARTED = 2**8
# CAN frame is an error frame.
ERR = 2**29
# CAN frame is a Remote Transmission Request (RTR) frame.
RTR = 2**30
# CAN frame uses extended (29-bit) CAN ID.
IDE = 2**31

class GsUSBCANFlag(IntFlag):
"""
Geschwister Schneider USB/CAN protocol host frame flags.
"""
# RX overflow occurred.
OVERFLOW = 2**0
# CAN frame is in CAN FD frame format.
FD = 2**1
# CAN frame uses CAN FD Baud Rate Switch (BRS).
BRS = 2**2
# CAN frame has the CAN FD Error State Indicator (ESI) set.
ESI = 2**3

class GsUSBCANChannelState(IntEnum):
"""
Geschwister Schneider USB/CAN protocol CAN channel state.
Expand Down Expand Up @@ -257,6 +289,41 @@ class GsUSBDeviceState:
# CAN channel TX bus error count.
txerr: int

@dataclass
class GsUSBHostFrame:
"""
Geschwister Schneider USB/CAN protocol host frame (without timestamp).
"""
# Echo ID (ECHO_ID_RX for frames received from the CAN bus).
echo_id: int
# CAN ID including flags.
can_id: int
# CAN frame Data Length Code (DLC).
can_dlc: int
# CAN channel.
channel: int
# Host frame flags.
flags: GsUSBCANFlag
# CAN frame payload, padded to 8 (CAN classic) or 64 (CAN FD) bytes when packed.
data: bytes = b''

ECHO_ID_RX = 0xffffffff
HEADER = struct.Struct('<IIBBBx')

def pack(self) -> bytes:
"""Return the host frame in USB wire format."""
size = 64 if self.flags & GsUSBCANFlag.FD else 8
return self.HEADER.pack(self.echo_id, self.can_id, self.can_dlc, self.channel,
self.flags) + self.data.ljust(size, b'\0')

@classmethod
def unpack(cls, raw: bytes) -> 'GsUSBHostFrame':
"""Return the host frame contained in a USB transfer."""
echo_id, can_id, can_dlc, channel, flags = cls.HEADER.unpack_from(raw)
size = 64 if flags & GsUSBCANFlag.FD else 8
data = bytes(raw[cls.HEADER.size:cls.HEADER.size + size])
return cls(echo_id, can_id, can_dlc, channel, GsUSBCANFlag(flags), data)

class GsUSB():
"""
Utility class implementing the gs_usb protocol.
Expand All @@ -278,9 +345,26 @@ def __init__(self, usb_vid: int, usb_pid: int, usb_sn: str) -> None:
logger.error('USB device %04x:%04x S/N %s not found', usb_vid, usb_pid, usb_sn)
raise GsUSBDeviceNotFound

device.set_configuration()
# Setting the active configuration again resets the data toggles of the host, but not
# those of a Zephyr device, after which the first bulk packets would be dropped
try:
configured = device.get_active_configuration().bConfigurationValue == 1
except usb.core.USBError:
configured = False

if not configured:
device.set_configuration(1)

self.device = device

intf = device.get_active_configuration()[(0, 0)]
self.ep_in = usb.util.find_descriptor(
intf, custom_match=lambda e: usb.util.endpoint_direction(e.bEndpointAddress) ==
usb.util.ENDPOINT_IN)
self.ep_out = usb.util.find_descriptor(
intf, custom_match=lambda e: usb.util.endpoint_direction(e.bEndpointAddress) ==
usb.util.ENDPOINT_OUT)

rtype = usb.util.build_request_type(usb.util.CTRL_OUT,
usb.util.CTRL_TYPE_VENDOR,
usb.util.CTRL_RECIPIENT_INTERFACE)
Expand All @@ -291,6 +375,10 @@ def __init__(self, usb_vid: int, usb_pid: int, usb_sn: str) -> None:
data_or_wLength = data)
assert length == len(data)

def close(self) -> None:
"""Release the USB device, allowing another instance to use it."""
usb.util.dispose_resources(self.device)

def bittiming(self, ch: int, bittiming: GsUSBDeviceBittiming) -> None:
"""Send a bittiming request."""
rtype = usb.util.build_request_type(usb.util.CTRL_OUT,
Expand Down Expand Up @@ -412,3 +500,31 @@ def get_state(self, ch: int) -> GsUSBDeviceState:
wValue = ch, data_or_wLength = struct.calcsize('<3I'))

return GsUSBDeviceState(*struct.unpack('<3I', data))

def write(self, data: bytes, timeout: float) -> None:
"""Write raw data to the bulk OUT endpoint, raising usb.core.USBTimeoutError on timeout."""
length = self.ep_out.write(data, timeout=timeout_ms(timeout))
assert length == len(data)

def send(self, frame: GsUSBHostFrame, timeout: float) -> None:
"""Send a host frame to the device."""
self.write(frame.pack(), timeout)

def receive(self, timeout: float) -> GsUSBHostFrame | None:
"""Receive a host frame from the device, return None on timeout."""
try:
# Read a multiple of the packet size so the host never sees a babble error
raw = self.ep_in.read(4 * self.ep_in.wMaxPacketSize, timeout=timeout_ms(timeout))
except usb.core.USBTimeoutError:
return None

return GsUSBHostFrame.unpack(raw)

def receive_all(self, timeout: float) -> list[GsUSBHostFrame]:
"""Receive host frames until none arrives within the timeout."""
frames = []

while (frame := self.receive(timeout)) is not None:
frames.append(frame)

return frames
96 changes: 96 additions & 0 deletions tests/subsys/usb/gs_usb/host/pytest/test_gs_usb_tx_errors.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
# SPDX-FileCopyrightText: Copyright (c) 2026 Base Power Company
#
# SPDX-License-Identifier: Apache-2.0

"""
Test suite for gs_usb host frames that fail to send.
"""

import logging
import pytest

from gs_usb import GsUSBCANChannelFlag, GsUSBCANChannelMode, GsUSBCANFlag, GsUSBCANIDFlag, \
GsUSBDeviceMode, GsUSBHostFrame

logger = logging.getLogger(__name__)

TIMEOUT = 1.0
IDLE = 0.2

FAKE_CHANNEL = 0

# Sending a frame with this CAN ID makes a fake CAN controller go bus-off (see src/main.c)
CAN_ID_BUS_OFF = 0x7ff
# A frame with this CAN ID stays pending on a fake CAN controller until it is stopped
CAN_ID_PENDING = 0x7fe

def tx_frame(echo_id: int, can_id: int) -> GsUSBHostFrame:
"""Return a CAN classic host frame for the fake CAN channel."""
return GsUSBHostFrame(echo_id, can_id, 2, FAKE_CHANNEL, GsUSBCANFlag(0), bytes([echo_id, 0xa5]))

@pytest.mark.usefixtures('dev')
class TestGsUsbTxErrors():
"""
Class for testing gs_usb host frames that fail to send.
"""

def test_echo_on_tx_failure(self, dev) -> None:
"""Test that every host frame is echoed, even if it could not be sent"""
dev.receive_all(IDLE)
dev.mode(FAKE_CHANNEL, GsUSBDeviceMode(GsUSBCANChannelMode.START,
GsUSBCANChannelFlag.NORMAL))
try:
dev.send(tx_frame(0, 0x123), TIMEOUT)
# Fails in the TX callback, and takes the controller bus-off
dev.send(tx_frame(1, CAN_ID_BUS_OFF), TIMEOUT)
# Fail in can_send() while bus-off
for echo_id in range(2, 6):
dev.send(tx_frame(echo_id, 0x123), TIMEOUT)

frames = dev.receive_all(IDLE)
finally:
dev.mode(FAKE_CHANNEL, GsUSBDeviceMode(GsUSBCANChannelMode.RESET,
GsUSBCANChannelFlag.NORMAL))

logger.debug('frames = %s', frames)
echoes = [f.echo_id for f in frames if f.echo_id != GsUSBHostFrame.ECHO_ID_RX]
assert echoes == list(range(6))

bus_off = [f for f in frames if f.echo_id == GsUSBHostFrame.ECHO_ID_RX and
f.can_id & GsUSBCANIDFlag.ERR and f.can_id & GsUSBCANIDFlag.ERR_BUSOFF]
assert len(bus_off) == 1

# Starting the channel again recovers the controller from bus-off
dev.mode(FAKE_CHANNEL, GsUSBDeviceMode(GsUSBCANChannelMode.START,
GsUSBCANChannelFlag.NORMAL))
try:
dev.send(tx_frame(6, 0x123), TIMEOUT)
frames = dev.receive_all(IDLE)
finally:
dev.mode(FAKE_CHANNEL, GsUSBDeviceMode(GsUSBCANChannelMode.RESET,
GsUSBCANChannelFlag.NORMAL))

assert [f.echo_id for f in frames] == [6]

def test_no_echo_after_reset(self, dev) -> None:
"""Test that frames aborted by a channel reset are not echoed"""
dev.receive_all(IDLE)
dev.mode(FAKE_CHANNEL, GsUSBDeviceMode(GsUSBCANChannelMode.START,
GsUSBCANChannelFlag.NORMAL))
dev.send(tx_frame(0, CAN_ID_PENDING), TIMEOUT)
assert not dev.receive_all(IDLE)

# The host releases its TX contexts when resetting the channel, and may reuse the
# echo ID of an aborted frame right after starting it again
dev.mode(FAKE_CHANNEL, GsUSBDeviceMode(GsUSBCANChannelMode.RESET,
GsUSBCANChannelFlag.NORMAL))
dev.mode(FAKE_CHANNEL, GsUSBDeviceMode(GsUSBCANChannelMode.START,
GsUSBCANChannelFlag.NORMAL))
try:
dev.send(tx_frame(1, 0x123), TIMEOUT)
frames = dev.receive_all(IDLE)
finally:
dev.mode(FAKE_CHANNEL, GsUSBDeviceMode(GsUSBCANChannelMode.RESET,
GsUSBCANChannelFlag.NORMAL))

assert [f.echo_id for f in frames] == [1]
Loading
Loading