Exemplo n.º 1
0
def test_can_fd():
    timing = can.BitTiming(f_clock=80000000,
                           bitrate=500000,
                           tseg1=119,
                           tseg2=40,
                           sjw=40)
    assert timing.f_clock == 80000000
    assert timing.bitrate == 500000
    assert timing.brp == 1
    assert timing.nbt == 160
    assert timing.tseg1 == 119
    assert timing.tseg2 == 40
    assert timing.sjw == 40
    assert timing.sample_point == 75

    timing = can.BitTiming(f_clock=80000000,
                           bitrate=2000000,
                           tseg1=29,
                           tseg2=10,
                           sjw=10)
    assert timing.f_clock == 80000000
    assert timing.bitrate == 2000000
    assert timing.brp == 1
    assert timing.nbt == 40
    assert timing.tseg1 == 29
    assert timing.tseg2 == 10
    assert timing.sjw == 10
    assert timing.sample_point == 75
Exemplo n.º 2
0
def test_sja1000():
    """Test some values obtained using other bit timing calculators."""
    timing = can.BitTiming(f_clock=8000000,
                           bitrate=125000,
                           tseg1=11,
                           tseg2=4,
                           sjw=2,
                           nof_samples=3)
    assert timing.f_clock == 8000000
    assert timing.bitrate == 125000
    assert timing.brp == 4
    assert timing.nbt == 16
    assert timing.tseg1 == 11
    assert timing.tseg2 == 4
    assert timing.sjw == 2
    assert timing.nof_samples == 3
    assert timing.sample_point == 75
    assert timing.btr0 == 0x43
    assert timing.btr1 == 0xBA

    timing = can.BitTiming(f_clock=8000000,
                           bitrate=500000,
                           tseg1=13,
                           tseg2=2,
                           sjw=1)
    assert timing.f_clock == 8000000
    assert timing.bitrate == 500000
    assert timing.brp == 1
    assert timing.nbt == 16
    assert timing.tseg1 == 13
    assert timing.tseg2 == 2
    assert timing.sjw == 1
    assert timing.nof_samples == 1
    assert timing.sample_point == 87.5
    assert timing.btr0 == 0x00
    assert timing.btr1 == 0x1C

    timing = can.BitTiming(f_clock=8000000,
                           bitrate=1000000,
                           tseg1=5,
                           tseg2=2,
                           sjw=1)
    assert timing.f_clock == 8000000
    assert timing.bitrate == 1000000
    assert timing.brp == 1
    assert timing.nbt == 8
    assert timing.tseg1 == 5
    assert timing.tseg2 == 2
    assert timing.sjw == 1
    assert timing.nof_samples == 1
    assert timing.sample_point == 75
    assert timing.btr0 == 0x00
    assert timing.btr1 == 0x14
Exemplo n.º 3
0
def test_string_representation():
    timing = can.BitTiming(f_clock=8000000,
                           bitrate=1000000,
                           tseg1=5,
                           tseg2=2,
                           sjw=1)
    assert (
        str(timing) ==
        "1000000 bits/s, sample point: 75.00%, BRP: 1, TSEG1: 5, TSEG2: 2, SJW: 1, BTR: 0014h"
    )
Exemplo n.º 4
0
def test_from_btr():
    timing = can.BitTiming(f_clock=8000000, btr0=0x00, btr1=0x14)
    assert timing.bitrate == 1000000
    assert timing.brp == 1
    assert timing.nbt == 8
    assert timing.tseg1 == 5
    assert timing.tseg2 == 2
    assert timing.sjw == 1
    assert timing.sample_point == 75
    assert timing.btr0 == 0x00
    assert timing.btr1 == 0x14
Exemplo n.º 5
0
    def test_bus_creation_bittiming(self):
        cantact.MockInterface.set_bitrate.reset_mock()

        bt = can.BitTiming(tseg1=13, tseg2=2, brp=6, sjw=1)
        bus = can.Bus(channel=0,
                      bustype="cantact",
                      bit_timing=bt,
                      _testing=True)
        self.assertIsInstance(bus, cantact.CantactBus)
        cantact.MockInterface.set_bitrate.assert_not_called()
        cantact.MockInterface.set_bit_timing.assert_called()
        cantact.MockInterface.set_enabled.assert_called()
        cantact.MockInterface.set_monitor.assert_called()
        cantact.MockInterface.start.assert_called()
Exemplo n.º 6
0
def _create_bus_config(config: Dict[str, Any]) -> typechecking.BusConfig:
    """Validates some config values, performs compatibility mappings and creates specific
    structures (e.g. for bit timings).

    :param config: The raw config as specified by the user
    :return: A config that can be used by a :class:`~can.BusABC`
    :raises NotImplementedError: if the ``interface`` is unknown
    """
    # substitute None for all values not found
    for key in REQUIRED_KEYS:
        if key not in config:
            config[key] = None

    if config["interface"] not in VALID_INTERFACES:
        raise CanInterfaceNotImplementedError(
            f'Unknown interface type "{config["interface"]}"'
        )

    if "bitrate" in config:
        config["bitrate"] = int(config["bitrate"])
    if "fd" in config:
        config["fd"] = config["fd"] not in ("0", "False", "false", False)
    if "data_bitrate" in config:
        config["data_bitrate"] = int(config["data_bitrate"])

    # Create bit timing configuration if given
    timing_conf = {}
    for key in (
        "f_clock",
        "brp",
        "tseg1",
        "tseg2",
        "sjw",
        "nof_samples",
        "btr0",
        "btr1",
    ):
        if key in config:
            timing_conf[key] = int(str(config[key]), base=0)
            del config[key]
    if timing_conf:
        timing_conf["bitrate"] = config["bitrate"]
        config["timing"] = can.BitTiming(**timing_conf)

    return cast(typechecking.BusConfig, config)
Exemplo n.º 7
0
def load_config(
    path: Optional[typechecking.AcceptedIOType] = None,
    config=None,
    context: Optional[str] = None,
) -> typechecking.BusConfig:
    """
    Returns a dict with configuration details which is loaded from (in this order):

    - config
    - can.rc
    - Environment variables CAN_INTERFACE, CAN_CHANNEL, CAN_BITRATE
    - Config files ``/etc/can.conf`` or ``~/.can`` or ``~/.canrc``
      where the latter may add or replace values of the former.

    Interface can be any of the strings from ``can.VALID_INTERFACES`` for example:
    kvaser, socketcan, pcan, usb2can, ixxat, nican, virtual.

    .. note::

            The key ``bustype`` is copied to ``interface`` if that one is missing
            and does never appear in the result.

    :param path:
        Optional path to config file.

    :param config:
        A dict which may set the 'interface', and/or the 'channel', or neither.
        It may set other values that are passed through.

    :param context:
        Extra 'context' pass to config sources. This can be use to section
        other than 'default' in the configuration file.

    :return:
        A config dictionary that should contain 'interface' & 'channel'::

            {
                'interface': 'python-can backend interface to use',
                'channel': 'default channel to use',
                # possibly more
            }

        Note ``None`` will be used if all the options are exhausted without
        finding a value.

        All unused values are passed from ``config`` over to this.

    :raises:
        NotImplementedError if the ``interface`` isn't recognized
    """

    # start with an empty dict to apply filtering to all sources
    given_config = config or {}
    config = {}

    # use the given dict for default values
    config_sources = [
        given_config,
        can.rc,
        lambda _context: load_environment_config(  # pylint: disable=unnecessary-lambda
            _context),
        lambda _context: load_environment_config(),
        lambda _context: load_file_config(path, _context),
        lambda _context: load_file_config(path),
    ]

    # Slightly complex here to only search for the file config if required
    for cfg in config_sources:
        if callable(cfg):
            cfg = cfg(context)
        # remove legacy operator (and copy to interface if not already present)
        if "bustype" in cfg:
            if "interface" not in cfg or not cfg["interface"]:
                cfg["interface"] = cfg["bustype"]
            del cfg["bustype"]
        # copy all new parameters
        for key in cfg:
            if key not in config:
                config[key] = cfg[key]

    # substitute None for all values not found
    for key in REQUIRED_KEYS:
        if key not in config:
            config[key] = None

    if config["interface"] not in VALID_INTERFACES:
        raise NotImplementedError("Invalid CAN Bus Type - {}".format(
            config["interface"]))

    if "bitrate" in config:
        config["bitrate"] = int(config["bitrate"])
    if "fd" in config:
        config["fd"] = config["fd"] not in ("0", "False", "false")
    if "data_bitrate" in config:
        config["data_bitrate"] = int(config["data_bitrate"])

    # Create bit timing configuration if given
    timing_conf = {}
    for key in (
            "f_clock",
            "brp",
            "tseg1",
            "tseg2",
            "sjw",
            "nof_samples",
            "btr0",
            "btr1",
    ):
        if key in config:
            timing_conf[key] = int(config[key], base=0)
            del config[key]
    if timing_conf:
        timing_conf["bitrate"] = config.get("bitrate")
        config["timing"] = can.BitTiming(**timing_conf)

    can.log.debug("can config: {}".format(config))
    return config