Skip to content

Commit

Permalink
Add timing parameter to CLI tools (#1869)
Browse files Browse the repository at this point in the history
  • Loading branch information
zariiii9003 authored Nov 23, 2024
1 parent 2eb8f53 commit 7ba6ddd
Show file tree
Hide file tree
Showing 3 changed files with 103 additions and 5 deletions.
47 changes: 46 additions & 1 deletion can/logger.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
import can
from can import Bus, BusState, Logger, SizedRotatingLogger
from can.typechecking import TAdditionalCliArgs
from can.util import cast_from_string
from can.util import _dict2timing, cast_from_string

if TYPE_CHECKING:
from can.io import BaseRotatingLogger
Expand Down Expand Up @@ -58,6 +58,19 @@ def _create_base_argument_parser(parser: argparse.ArgumentParser) -> None:
help="Bitrate to use for the data phase in case of CAN-FD.",
)

parser.add_argument(
"--timing",
action=_BitTimingAction,
nargs=argparse.ONE_OR_MORE,
help="Configure bit rate and bit timing. For example, use "
"`--timing f_clock=8_000_000 tseg1=5 tseg2=2 sjw=2 brp=2 nof_samples=1` for classical CAN "
"or `--timing f_clock=80_000_000 nom_tseg1=119 nom_tseg2=40 nom_sjw=40 nom_brp=1 "
"data_tseg1=29 data_tseg2=10 data_sjw=10 data_brp=1` for CAN FD. "
"Check the python-can documentation to verify whether your "
"CAN interface supports the `timing` argument.",
metavar="TIMING_ARG",
)

parser.add_argument(
"extra_args",
nargs=argparse.REMAINDER,
Expand Down Expand Up @@ -109,6 +122,8 @@ def _create_bus(parsed_args: argparse.Namespace, **kwargs: Any) -> can.BusABC:
config["data_bitrate"] = parsed_args.data_bitrate
if getattr(parsed_args, "can_filters", None):
config["can_filters"] = parsed_args.can_filters
if parsed_args.timing:
config["timing"] = parsed_args.timing

return Bus(parsed_args.channel, **config)

Expand Down Expand Up @@ -143,6 +158,36 @@ def __call__(
setattr(namespace, self.dest, can_filters)


class _BitTimingAction(argparse.Action):
def __call__(
self,
parser: argparse.ArgumentParser,
namespace: argparse.Namespace,
values: Union[str, Sequence[Any], None],
option_string: Optional[str] = None,
) -> None:
if not isinstance(values, list):
raise argparse.ArgumentError(None, "Invalid --timing argument")

timing_dict: Dict[str, int] = {}
for arg in values:
try:
key, value_string = arg.split("=")
value = int(value_string)
timing_dict[key] = value
except ValueError:
raise argparse.ArgumentError(
None, f"Invalid timing argument: {arg}"
) from None

if not (timing := _dict2timing(timing_dict)):
err_msg = "Invalid --timing argument. Incomplete parameters."
raise argparse.ArgumentError(None, err_msg)

setattr(namespace, self.dest, timing)
print(timing)


def _parse_additional_config(unknown_args: Sequence[str]) -> TAdditionalCliArgs:
for arg in unknown_args:
if not re.match(r"^--[a-zA-Z][a-zA-Z0-9\-]*=\S*?$", arg):
Expand Down
4 changes: 0 additions & 4 deletions doc/bit_timing.rst
Original file line number Diff line number Diff line change
@@ -1,10 +1,6 @@
Bit Timing Configuration
========================

.. attention::
This feature is experimental. The implementation might change in future
versions.

The CAN protocol, specified in ISO 11898, allows the bitrate, sample point
and number of samples to be optimized for a given application. These
parameters, known as bit timings, can be adjusted to meet the requirements
Expand Down
57 changes: 57 additions & 0 deletions test/test_logger.py
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,63 @@ def test_parse_can_filters_list(self):
)
assert results.can_filters == expected_can_filters

def test_parse_timing(self) -> None:
can20_args = self.baseargs + [
"--timing",
"f_clock=8_000_000",
"tseg1=5",
"tseg2=2",
"sjw=2",
"brp=2",
"nof_samples=1",
"--app-name=CANalyzer",
]
results, additional_config = can.logger._parse_logger_args(can20_args[1:])
assert results.timing == can.BitTiming(
f_clock=8_000_000, brp=2, tseg1=5, tseg2=2, sjw=2, nof_samples=1
)
assert additional_config["app_name"] == "CANalyzer"

canfd_args = self.baseargs + [
"--timing",
"f_clock=80_000_000",
"nom_tseg1=119",
"nom_tseg2=40",
"nom_sjw=40",
"nom_brp=1",
"data_tseg1=29",
"data_tseg2=10",
"data_sjw=10",
"data_brp=1",
"--app-name=CANalyzer",
]
results, additional_config = can.logger._parse_logger_args(canfd_args[1:])
assert results.timing == can.BitTimingFd(
f_clock=80_000_000,
nom_brp=1,
nom_tseg1=119,
nom_tseg2=40,
nom_sjw=40,
data_brp=1,
data_tseg1=29,
data_tseg2=10,
data_sjw=10,
)
assert additional_config["app_name"] == "CANalyzer"

# remove f_clock parameter, parsing should fail
incomplete_args = self.baseargs + [
"--timing",
"tseg1=5",
"tseg2=2",
"sjw=2",
"brp=2",
"nof_samples=1",
"--app-name=CANalyzer",
]
with self.assertRaises(SystemExit):
can.logger._parse_logger_args(incomplete_args[1:])

def test_parse_additional_config(self):
unknown_args = [
"--app-name=CANalyzer",
Expand Down

0 comments on commit 7ba6ddd

Please sign in to comment.