python-can-csscan-txt 2026.11.20__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,149 @@
1
+ """Read TXT log files from the CSS Electronics CLX000 (CL1000/CL2000/CL3000) through python-can."""
2
+
3
+ import calendar
4
+ import io
5
+ import logging
6
+ import os
7
+ from collections.abc import Generator
8
+ from typing import Any, TextIO
9
+
10
+ from can import Message
11
+ from can.io.generic import TextIOMessageReader
12
+ from can.typechecking import StringPathLike
13
+
14
+ __all__ = ["LogFile"]
15
+
16
+ logger = logging.getLogger(__name__)
17
+
18
+ _COLUMNS = {"Timestamp", "Lost", "Type", "ID", "Length", "Data"}
19
+
20
+ # Seconds after which the timestamp wraps around, for time formats 0 (kkk), 1 (sskkk), 2 (mmsskkk) and 3 (hhmmsskkk).
21
+ # Format 4 (DDhhmmsskkk) wraps every month and format 5 (MMDDhhmmsskkk) every year. Format 6 holds the full date.
22
+ _WRAP_SECONDS = {0: 1, 1: 60, 2: 60 * 60, 3: 24 * 60 * 60}
23
+
24
+
25
+ class LogFile(TextIOMessageReader):
26
+ """Iterate over the CAN messages of a CLX000 TXT log file.
27
+
28
+ :param file: Path to a log file, or an open file.
29
+ :param kwargs: Ignored. Accepted for compatibility with ``can.LogReader``.
30
+ """
31
+
32
+ def __init__(self, file: StringPathLike | TextIO | io.BufferedIOBase, **kwargs: Any) -> None:
33
+ if isinstance(file, (io.RawIOBase, io.BufferedIOBase)):
34
+ file = io.TextIOWrapper(file, encoding="latin-1")
35
+ super().__init__(file, mode="r", encoding="latin-1")
36
+
37
+ try:
38
+ self._read_header()
39
+ except Exception:
40
+ if isinstance(file, (str, os.PathLike)): # Only close the file if opened here
41
+ self.file.close()
42
+ raise
43
+
44
+ def _read_header(self) -> None:
45
+ # Header: lines starting with "#", formatted as "# Key: value"
46
+ self._header: dict[str, str] = {}
47
+ line = self.file.readline()
48
+ while line.startswith("#"):
49
+ key, _, value = line.lstrip("#").strip().partition(": ")
50
+ self._header[key] = value
51
+ line = self.file.readline()
52
+
53
+ # Column header follows the header, e.g. "Timestamp;Type;ID;Data"
54
+ self._separator = self._quoted("Value separator")
55
+ self._columns = self._split(line.rstrip("\r\n"))
56
+ if "Logger type" not in self._header or not self._separator or not set(self._columns) <= _COLUMNS:
57
+ raise ValueError("Not a CLX000 TXT log file")
58
+
59
+ self._time_format = int(_digits(self._header.get("Time format", "")) or 0)
60
+
61
+ # Start time from the header ("YYYYMMDDThhmmss"). Timestamps in the log only hold the least significant part of
62
+ # the time (depending on the time format), the remaining digits are taken from the start time.
63
+ start = _digits(self._header.get("Time", "")) # "YYYYMMDDhhmmss"
64
+ self._time_template = start + "19700101000000000"[len(start) :] # "YYYYMMDDhhmmsskkk"
65
+
66
+ def get_metadata(self) -> dict[str, Any]:
67
+ """Return the logger information stored in the file header."""
68
+ return {
69
+ "id": self._header.get("Logger ID", ""),
70
+ "hardware revision": self._header.get("HW rev", ""),
71
+ "firmware revision": self._header.get("FW rev", ""),
72
+ "session": int(self._header.get("Session No.", "0") or 0),
73
+ "split": int(self._header.get("Split No.", "0") or 0),
74
+ "bitrate": int(self._header.get("Bit-rate", "0") or 0),
75
+ }
76
+
77
+ def __iter__(self) -> Generator[Message, None, None]:
78
+ wraps = 0
79
+ parsed_previous = self._parse_timestamp("", 0) # The header start time
80
+ emitted_previous = 0.0
81
+
82
+ for line in self.file:
83
+ line = line.rstrip("\r\n")
84
+ fields = self._split(line)
85
+ if len(fields) != len(self._columns):
86
+ logger.warning("Skipping invalid line: %r", line) # E.g. cut short by a power loss
87
+ continue
88
+ row = dict(zip(self._columns, fields))
89
+
90
+ try:
91
+ timestamp = 0.0
92
+ if "Timestamp" in row:
93
+ timestamp = self._parse_timestamp(row["Timestamp"], wraps)
94
+ # A step back in time means the timestamp wrapped around. The CLX000 occasionally logs a timestamp
95
+ # up to one second too late, so a step back of up to one second is not a wrap. Format 0 does not
96
+ # show seconds, so there any step back is a wrap.
97
+ tolerance = 0 if self._time_format == 0 else 1
98
+ if timestamp < parsed_previous - tolerance and self._time_format in range(6):
99
+ wraps += 1
100
+ timestamp = self._parse_timestamp(row["Timestamp"], wraps)
101
+ parsed_previous = timestamp
102
+
103
+ msg_type = int(row.get("Type") or 0)
104
+ message = Message(
105
+ timestamp=timestamp,
106
+ arbitration_id=int(row.get("ID") or "0", 16),
107
+ is_extended_id=bool(msg_type & 0x1),
108
+ is_rx=not msg_type & 0x8,
109
+ data=bytes.fromhex(row.get("Data", "")),
110
+ )
111
+ except ValueError:
112
+ logger.warning("Skipping invalid line: %r", line)
113
+ continue
114
+
115
+ # After a timestamp that was logged too late, skip the following messages until time has caught up
116
+ if timestamp < emitted_previous:
117
+ logger.warning("Skipping non-increasing timestamp: %f", timestamp)
118
+ continue
119
+ emitted_previous = timestamp
120
+
121
+ yield message
122
+
123
+ def _quoted(self, key: str) -> str:
124
+ """Header separator values are quoted, e.g. '";"'. Empty when not set."""
125
+ value = self._header.get(key, "")
126
+ return value[1] if len(value) == 3 else ""
127
+
128
+ def _split(self, line: str) -> list[str]:
129
+ return line.split(self._separator)
130
+
131
+ def _parse_timestamp(self, text: str, wraps: int) -> float:
132
+ # The log only holds the least significant digits of the time, the rest are taken from the header start time
133
+ digits = _digits(text)
134
+ full = self._time_template[: len(self._time_template) - len(digits)] + digits
135
+ year = int(full[0:4])
136
+ month, day, hour, minute, second = (int(full[i : i + 2]) for i in (4, 6, 8, 10, 12))
137
+
138
+ if self._time_format == 4:
139
+ year, month = year + (month - 1 + wraps) // 12, (month - 1 + wraps) % 12 + 1
140
+ elif self._time_format == 5:
141
+ year += wraps
142
+
143
+ # timegm accepts days beyond the end of the month (e.g. 31 February), rolling over into the next month
144
+ seconds = calendar.timegm((year, month, day, hour, minute, second))
145
+ return seconds + _WRAP_SECONDS.get(self._time_format, 0) * wraps + int(full[14:17]) / 1000
146
+
147
+
148
+ def _digits(text: str) -> str:
149
+ return "".join(c for c in text if c.isdigit())
@@ -0,0 +1,44 @@
1
+ Metadata-Version: 2.5
2
+ Name: python-can-csscan-txt
3
+ Version: 2026.11.20
4
+ Summary: Read TXT log files from the CSS Electronics CLX000 CAN loggers through python-can
5
+ Project-URL: Homepage, https://csselectronics.com/
6
+ Project-URL: Source, https://github.com/CSS-Electronics/python-can-csscan-txt
7
+ Author: CSS Electronics
8
+ Author-email: contact@csselectronics.com
9
+ License-Expression: MIT
10
+ License-File: LICENSE
11
+ Classifier: Operating System :: OS Independent
12
+ Classifier: Programming Language :: Python :: 3
13
+ Requires-Python: >=3.12
14
+ Requires-Dist: python-can>=4.6.0
15
+ Provides-Extra: test
16
+ Requires-Dist: pytest>=8.0; extra == 'test'
17
+ Description-Content-Type: text/markdown
18
+
19
+ # python-can-csscan-txt
20
+
21
+ Read TXT log files from the [CSS Electronics](https://www.csselectronics.com/) CLX000 CAN loggers through [python-can](https://python-can.readthedocs.io/).
22
+
23
+ ```
24
+ pip install python-can-csscan-txt
25
+ ```
26
+
27
+ ```python
28
+ import can
29
+
30
+ with can.LogReader("00000001.TXT") as reader:
31
+ for msg in reader:
32
+ print(msg)
33
+ ```
34
+
35
+ The logger information from the file header is available through `LogFile`:
36
+
37
+ ```python
38
+ from python_can_csscan_txt import LogFile
39
+
40
+ with LogFile("00000001.TXT") as reader:
41
+ print(reader.get_metadata()) # id, hardware/firmware revision, session, split, bitrate
42
+ for msg in reader:
43
+ print(msg)
44
+ ```
@@ -0,0 +1,6 @@
1
+ python_can_csscan_txt/__init__.py,sha256=5g0a3HvyfwgyOSmwlYzrCULXbJdUvgpSP8u5fVi5PDI,6684
2
+ python_can_csscan_txt-2026.11.20.dist-info/METADATA,sha256=YR3xVBSIT1hsV57LXIAkO5SmVKAS_6yEDecLbcZknkU,1307
3
+ python_can_csscan_txt-2026.11.20.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
4
+ python_can_csscan_txt-2026.11.20.dist-info/entry_points.txt,sha256=yjX2gdF5pCMt5GQBOVoxLJUbUJtjoE1iajruSvJ-Biw,61
5
+ python_can_csscan_txt-2026.11.20.dist-info/licenses/LICENSE,sha256=4iHFp_LQPbL--0WKDju3Bl2_thrgpw9_46vuuV9g0eA,1072
6
+ python_can_csscan_txt-2026.11.20.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [can.io.message_reader]
2
+ .txt = python_can_csscan_txt:LogFile
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2023 CSS-Electronics
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.