|
7 | 7 |
|
8 | 8 | import logging
|
9 | 9 |
|
10 |
| -from typing import Any, BinaryIO, Dict, Union |
| 10 | +from typing import Any, BinaryIO, Dict, Generator, Union |
11 | 11 |
|
12 | 12 | from ..message import Message
|
13 | 13 | from ..typechecking import StringPathLike, Channel
|
14 |
| -from .generic import BinaryIOMessageWriter |
15 |
| -from ..socketcan_common import build_can_frame, CAN_FRAME_HEADER_STRUCT_BE |
| 14 | +from .generic import BinaryIOMessageWriter, BinaryIOMessageReader |
| 15 | +from ..socketcan_common import ( |
| 16 | + build_can_frame, |
| 17 | + parse_can_frame, |
| 18 | + CAN_FRAME_HEADER_STRUCT_BE, |
| 19 | +) |
16 | 20 |
|
17 | 21 | logger = logging.getLogger("can.io.pcapng")
|
18 | 22 |
|
@@ -109,3 +113,56 @@ def on_message_received(self, msg: Message) -> None:
|
109 | 113 | endianness=">", # big
|
110 | 114 | )
|
111 | 115 | )
|
| 116 | + |
| 117 | + |
| 118 | +class PcapngReader(BinaryIOMessageReader): |
| 119 | + """ |
| 120 | + Iterator of CAN messages from a Pcapng File. |
| 121 | + """ |
| 122 | + |
| 123 | + file: BinaryIO |
| 124 | + |
| 125 | + def __init__( |
| 126 | + self, |
| 127 | + file: Union[StringPathLike, BinaryIO], |
| 128 | + **kwargs: Any, |
| 129 | + ) -> None: |
| 130 | + """ |
| 131 | + :param file: a path-like object or as file-like object to read from |
| 132 | + If this is a file-like object, is has to opened in binary |
| 133 | + read mode, not text read mode. |
| 134 | + """ |
| 135 | + |
| 136 | + if pcapng is None: |
| 137 | + raise NotImplementedError( |
| 138 | + "The python-pcapng package was not found. Install python-can with " |
| 139 | + "the optional dependency [pcapng] to use the PcapngReader." |
| 140 | + ) |
| 141 | + |
| 142 | + super().__init__(file, mode="rb") |
| 143 | + self._scanner = pcapng.FileScanner(self.file) |
| 144 | + |
| 145 | + def __iter__(self) -> Generator[Message, None, None]: |
| 146 | + for block in self._scanner: |
| 147 | + if isinstance(block, blocks.EnhancedPacket): |
| 148 | + idn: blocks.InterfaceDescription = block.interface |
| 149 | + # We only care about the CAN packets |
| 150 | + if idn.link_type != LINKTYPE_CAN_SOCKETCAN: |
| 151 | + logger.debug( |
| 152 | + "Skipping non-CAN packet, link type: %s", idn.link_type |
| 153 | + ) |
| 154 | + continue |
| 155 | + |
| 156 | + msg = parse_can_frame( |
| 157 | + block.packet_data, struct=CAN_FRAME_HEADER_STRUCT_BE |
| 158 | + ) |
| 159 | + |
| 160 | + timestamp64 = (block.timestamp_high << 32) + block.timestamp_low |
| 161 | + msg.timestamp = timestamp64 * idn.timestamp_resolution |
| 162 | + |
| 163 | + if "if_name" in idn.options: |
| 164 | + msg.channel = idn.options["if_name"] |
| 165 | + else: |
| 166 | + msg.channel = block.interface_id |
| 167 | + |
| 168 | + yield msg |
0 commit comments