Skip to content
Merged
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
31 changes: 22 additions & 9 deletions can/io/mf4.py
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,7 @@ def __init__(
file: StringPathLike | BinaryIO,
database: StringPathLike | None = None,
compression_level: int = 2,
channel: int = 1,
**kwargs: Any,
) -> None:
"""
Expand All @@ -123,6 +124,9 @@ def __init__(
* 0 - no compression
* 1 - deflate (slower, but produces smaller files)
* 2 - transposition + deflate (slowest, but produces the smallest files)
:param channel:
default 1-based bus channel to log as when a message has no channel set
(default 1)
"""
asammdf = _import_asammdf("MF4Writer")
source_information = import_module("asammdf.blocks.v4_blocks").SourceInformation
Expand All @@ -134,6 +138,7 @@ def __init__(
)

super().__init__(file, mode="w+b")
self.channel = channel
now = datetime.now(tz=UTC)
self._mdf = cast("MDF4", asammdf.MDF(version="4.10"))
self._mdf.header.start_time = now
Expand Down Expand Up @@ -207,6 +212,11 @@ def stop(self) -> None:

def on_message_received(self, msg: Message) -> None:
channel = channel2int(msg.channel)
if channel is None:
channel = self.channel
else:
# Many interfaces start channel numbering at 0 which is invalid
channel += 1

timestamp = msg.timestamp
if timestamp is None:
Expand All @@ -217,8 +227,7 @@ def on_message_received(self, msg: Message) -> None:
timestamp -= self._start_time

if msg.is_remote_frame:
if channel is not None:
self._rtr_buffer["CAN_RemoteFrame.BusChannel"] = channel
self._rtr_buffer["CAN_RemoteFrame.BusChannel"] = channel

self._rtr_buffer["CAN_RemoteFrame.ID"] = msg.arbitration_id
self._rtr_buffer["CAN_RemoteFrame.IDE"] = int(msg.is_extended_id)
Expand All @@ -229,8 +238,7 @@ def on_message_received(self, msg: Message) -> None:
self._mdf.extend(2, sigs)

elif msg.is_error_frame:
if channel is not None:
self._err_buffer["CAN_ErrorFrame.BusChannel"] = channel
self._err_buffer["CAN_ErrorFrame.BusChannel"] = channel

self._err_buffer["CAN_ErrorFrame.ID"] = msg.arbitration_id
self._err_buffer["CAN_ErrorFrame.IDE"] = int(msg.is_extended_id)
Expand All @@ -254,8 +262,7 @@ def on_message_received(self, msg: Message) -> None:
self._mdf.extend(1, sigs)

else:
if channel is not None:
self._std_buffer["CAN_DataFrame.BusChannel"] = channel
self._std_buffer["CAN_DataFrame.BusChannel"] = channel

self._std_buffer["CAN_DataFrame.ID"] = msg.arbitration_id
self._std_buffer["CAN_DataFrame.IDE"] = int(msg.is_extended_id)
Expand Down Expand Up @@ -362,7 +369,9 @@ def __iter__(self) -> Generator[Message, None, None]:
}

if "CAN_DataFrame.BusChannel" in names:
kv["channel"] = int(data["CAN_DataFrame.BusChannel"][i])
bus_channel = int(data["CAN_DataFrame.BusChannel"][i])
if bus_channel > 0:
kv["channel"] = bus_channel - 1
if "CAN_DataFrame.Dir" in names:
if data["CAN_DataFrame.Dir"][i].dtype.kind == "S":
kv["is_rx"] = data["CAN_DataFrame.Dir"][i] == b"Rx"
Expand Down Expand Up @@ -400,7 +409,9 @@ def __iter__(self) -> Generator[Message, None, None]:
}

if "CAN_ErrorFrame.BusChannel" in names:
kv["channel"] = int(data["CAN_ErrorFrame.BusChannel"][i])
bus_channel = int(data["CAN_ErrorFrame.BusChannel"][i])
if bus_channel > 0:
kv["channel"] = bus_channel - 1
if "CAN_ErrorFrame.Dir" in names:
if data["CAN_ErrorFrame.Dir"][i].dtype.kind == "S":
kv["is_rx"] = data["CAN_ErrorFrame.Dir"][i] == b"Rx"
Expand Down Expand Up @@ -458,7 +469,9 @@ def __iter__(self) -> Generator[Message, None, None]:
}

if "CAN_RemoteFrame.BusChannel" in names:
kv["channel"] = int(data["CAN_RemoteFrame.BusChannel"][i])
bus_channel = int(data["CAN_RemoteFrame.BusChannel"][i])
if bus_channel > 0:
kv["channel"] = bus_channel - 1
if "CAN_RemoteFrame.Dir" in names:
if data["CAN_RemoteFrame.Dir"][i].dtype.kind == "S":
kv["is_rx"] = data["CAN_RemoteFrame.Dir"][i] == b"Rx"
Expand Down
3 changes: 3 additions & 0 deletions doc/changelog.d/2164.added.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
Added a ``channel`` parameter to :class:`~can.MF4Writer` to specify the default
1-based ``BusChannel`` value used when a logged :class:`~can.Message` has no
channel set (defaults to ``1``).
8 changes: 8 additions & 0 deletions doc/changelog.d/2164.fixed.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
Fixed :class:`~can.MF4Reader` and :class:`~can.MF4Writer` to convert between
1-based ASAM MDF4 ``BusChannel`` numbers and 0-based :attr:`can.Message.channel`
values, matching :class:`~can.ASCReader`/:class:`~can.ASCWriter` and
:class:`~can.BLFReader`/:class:`~can.BLFWriter` so ``can_logconvert`` preserves
bus numbers when converting from ``.mf4`` to ``.trc``, ``.asc``, or ``.blf``.
Note that ``.mf4`` files written by earlier :class:`~can.MF4Writer` versions
contain 0-based ``BusChannel`` values and will now be read back with channel
numbers shifted down by one (``0`` becomes ``None``, ``1`` becomes ``0``).
83 changes: 82 additions & 1 deletion test/logformats_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -1617,14 +1617,95 @@ def test_error_frame_payload(self, name, storage, payload, length, fd):
self.assertEqual(msg.dlc, length)
self.assertEqual(msg.timestamp, start.timestamp() + 1.5 + index)
self.assertEqual(msg.arbitration_id, 0x12345)
self.assertEqual(msg.channel, 2)
self.assertEqual(msg.channel, 1)
self.assertTrue(msg.is_error_frame)
self.assertTrue(msg.is_extended_id)
self.assertFalse(msg.is_rx)
self.assertEqual(msg.is_fd, fd)
self.assertEqual(msg.bitrate_switch, fd)
self.assertEqual(msg.error_state_indicator, fd)

def test_bus_channel_one_based_conversion(self):
from asammdf.blocks.v4_blocks import SourceInformation
from asammdf.blocks.v4_constants import FLAG_CG_BUS_EVENT

path = Path(self.test_file_name).with_suffix(".mf4")
self.addCleanup(path.unlink, missing_ok=True)

std_samples = mf4.np.zeros(3, dtype=mf4.STD_DTYPE)
std_samples["CAN_DataFrame.BusChannel"] = [1, 2, 0]
std_samples["CAN_DataFrame.ID"] = [0x100, 0x110, 0x120]
std_samples["CAN_DataFrame.DLC"] = 2
std_samples["CAN_DataFrame.DataLength"] = 2
std_samples["CAN_DataFrame.DataBytes"][:, :2] = [0x50, 0x5A]

rtr_samples = mf4.np.zeros(1, dtype=mf4.RTR_DTYPE)
rtr_samples["CAN_RemoteFrame.BusChannel"] = [2]
rtr_samples["CAN_RemoteFrame.ID"] = [0x200]
rtr_samples["CAN_RemoteFrame.DLC"] = [4]

start = datetime(2024, 1, 1, tzinfo=timezone.utc)
source = SourceInformation(
source_type=asammdf.Source.SOURCE_BUS,
bus_type=asammdf.Source.BUS_TYPE_CAN,
)
with asammdf.MDF(version="4.10") as mdf:
mdf.header.start_time = start
mdf.append(
asammdf.Signal(
name="CAN_DataFrame",
samples=std_samples,
timestamps=mf4.np.array([0.0, 0.25, 0.5]),
source=source,
)
)
mdf.append(
asammdf.Signal(
name="CAN_RemoteFrame",
samples=rtr_samples,
timestamps=mf4.np.array([0.75]),
source=source,
)
)
for group in mdf.groups:
group.channel_group.flags |= FLAG_CG_BUS_EVENT
mdf.save(path, overwrite=True)

with can.MF4Reader(path) as reader:
messages = list(reader)

self.assertEqual([msg.channel for msg in messages], [0, 1, None, 1])

def test_writer_writes_one_based_bus_channel(self):
path = Path(self.test_file_name).with_suffix(".mf4")
self.addCleanup(path.unlink, missing_ok=True)

messages = [
can.Message(timestamp=1.0, arbitration_id=0x100, data=b"\x01", channel=0),
can.Message(timestamp=2.0, arbitration_id=0x101, data=b"\x02", channel=1),
can.Message(
timestamp=3.0, arbitration_id=0x102, data=b"\x03", channel="can2"
),
can.Message(timestamp=4.0, arbitration_id=0x103, data=b"\x04"),
can.Message(timestamp=5.0, is_error_frame=True, channel=1),
can.Message(
timestamp=6.0, arbitration_id=0x200, is_remote_frame=True, channel=2
),
]

with can.MF4Writer(path) as writer:
for msg in messages:
writer(msg)

with asammdf.MDF(path) as mdf:
self.assertEqual(
mdf.get("CAN_DataFrame.BusChannel").samples.tolist(), [1, 2, 3, 1]
)
self.assertEqual(mdf.get("CAN_ErrorFrame.BusChannel").samples.tolist(), [2])
self.assertEqual(
mdf.get("CAN_RemoteFrame.BusChannel").samples.tolist(), [3]
)

def _setup_instance(self):
super()._setup_instance_helper(
can.MF4Writer,
Expand Down
Loading