canconf 0.3.0__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.
canconf/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ """canconf — reconfigure all CAN / CAN-FD interfaces in one shot."""
2
+
3
+ __version__ = "0.3.0"
canconf/__main__.py ADDED
@@ -0,0 +1,6 @@
1
+ import sys
2
+
3
+ from .cli import main
4
+
5
+ if __name__ == "__main__":
6
+ sys.exit(main())
canconf/cli.py ADDED
@@ -0,0 +1,306 @@
1
+ """
2
+ canconf - reconfigure all CAN / CAN-FD interfaces in one shot.
3
+
4
+ Usage:
5
+ canconf show status of all can* interfaces
6
+ canconf 500k classic CAN @ 500 kbit/s, up
7
+ canconf 500k/2M CAN-FD: nominal 500k, data 2M, up
8
+ canconf 500k/2M@0.8/0.75 same, with nominal/data sample points
9
+ canconf off | down bring all interfaces down
10
+ canconf up bring all interfaces up (no reconfigure)
11
+ canconf bitrates show achievable bitrates per interface
12
+
13
+ -i, --ifaces a,b,c only these (default: all can*)
14
+ -r, --restart-ms N auto-restart on bus-off after N ms
15
+ --listen-only listen-only mode
16
+ --loopback loopback mode
17
+ --one-shot one-shot mode
18
+ --berr enable bus error reporting
19
+ --term OHM set termination resistor (if supported)
20
+ --txqueuelen N set tx queue length (default: 10000)
21
+ -n, --dry-run print ip commands, do not execute
22
+ -v, --verbose print ip commands as they run
23
+ -q, --quiet suppress post-apply status print
24
+ -V, --version print version and exit
25
+ -h, --help
26
+
27
+ Bitrates: plain int, or K/M suffix (125k, 500k, 1M, 2M, 5M, 8M).
28
+ Requires root; self-elevates with sudo if needed.
29
+ """
30
+ from __future__ import annotations
31
+
32
+ import argparse
33
+ import os
34
+ import shlex
35
+ import subprocess
36
+ import sys
37
+
38
+ from . import __version__
39
+ from . import common
40
+ from .common import (
41
+ BOLD, CYAN, DIM, MAGENTA,
42
+ c, color_state, discover_ifaces, fmt_rate, get_links,
43
+ )
44
+
45
+ DEFAULT_TXQUEUELEN = 10000
46
+
47
+ # Standard CAN bitrates worth highlighting in `canconf bitrates`.
48
+ STD_NOMINAL = [10_000, 20_000, 50_000, 100_000, 125_000, 250_000,
49
+ 500_000, 800_000, 1_000_000]
50
+ STD_DATA = [1_000_000, 2_000_000, 4_000_000, 5_000_000, 8_000_000]
51
+
52
+
53
+ def parse_rate(s: str) -> int:
54
+ s = s.strip()
55
+ if not s:
56
+ raise ValueError("empty bitrate")
57
+ mult = 1
58
+ if s[-1] in "kK":
59
+ mult, s = 1_000, s[:-1]
60
+ elif s[-1] in "mM":
61
+ mult, s = 1_000_000, s[:-1]
62
+ return int(float(s) * mult)
63
+
64
+
65
+ def parse_spec(spec: str) -> dict:
66
+ """Parse BITRATE[/DBITRATE][@SP[/DSP]] or 'off'/'down'/'up'."""
67
+ if spec in ("off", "down"):
68
+ return {"action": "down"}
69
+ if spec == "up":
70
+ return {"action": "up"}
71
+
72
+ rate_part, _, sp_part = spec.partition("@")
73
+ nom_s, sep, data_s = rate_part.partition("/")
74
+ out: dict = {"action": "configure", "bitrate": parse_rate(nom_s), "fd": bool(sep)}
75
+ if sep:
76
+ out["dbitrate"] = parse_rate(data_s)
77
+
78
+ if sp_part:
79
+ nsp_s, _, dsp_s = sp_part.partition("/")
80
+ if nsp_s:
81
+ out["sample_point"] = float(nsp_s)
82
+ if dsp_s:
83
+ out["dsample_point"] = float(dsp_s)
84
+ return out
85
+
86
+
87
+ def run(cmd: list[str], *, dry: bool, verbose: bool) -> None:
88
+ if dry or verbose:
89
+ print("+ " + " ".join(shlex.quote(c) for c in cmd))
90
+ if dry:
91
+ return
92
+ r = subprocess.run(cmd)
93
+ if r.returncode != 0:
94
+ sys.exit(r.returncode)
95
+
96
+
97
+ def show_status(ifaces: list[str]) -> None:
98
+ if not ifaces:
99
+ print("no CAN interfaces found")
100
+ return
101
+ links = get_links()
102
+
103
+ rows = []
104
+ for name in ifaces:
105
+ link = links.get(name, {})
106
+ state = link.get("operstate", "?")
107
+ qlen = link.get("txqlen")
108
+ data = link.get("linkinfo", {}).get("info_data", {}) or {}
109
+ bt = data.get("bittiming") or {}
110
+ dbt = data.get("data_bittiming")
111
+ driver = (data.get("bittiming_const") or {}).get("name") or "-"
112
+ mode = "CAN-FD" if dbt else "CAN"
113
+ if bt.get("bitrate"):
114
+ rate = fmt_rate(bt["bitrate"])
115
+ if dbt and dbt.get("bitrate"):
116
+ rate += f"/{fmt_rate(dbt['bitrate'])}"
117
+ else:
118
+ rate = "-"
119
+ sp = bt.get("sample_point")
120
+ dsp = (dbt or {}).get("sample_point")
121
+ if sp and dsp:
122
+ sp_col = f"{sp}/{dsp}"
123
+ elif sp:
124
+ sp_col = str(sp)
125
+ else:
126
+ sp_col = "-"
127
+ qlen_col = str(qlen) if qlen is not None else "-"
128
+ rows.append((name, state, mode, rate, sp_col, qlen_col, driver))
129
+
130
+ cols = list(zip(*rows))
131
+ w = [max(len(col_val) for col_val in col) for col in cols]
132
+ for name, state, mode, rate, sp_col, qlen_col, driver in rows:
133
+ mode_colored = c(mode, MAGENTA) if mode == "CAN-FD" else c(mode, CYAN)
134
+ # color_state pads internally so w[1] is still the correct visual width
135
+ print(
136
+ f"{c(name, BOLD):<{w[0] + len(c('', BOLD))}}"
137
+ f" {color_state(state, w[1])}"
138
+ f" {mode_colored + ' ' * (w[2] - len(mode))}"
139
+ f" {rate:<{w[3]}}"
140
+ f" {c('sp', DIM)} {sp_col:<{w[4]}}"
141
+ f" {c('qlen', DIM)} {qlen_col:<{w[5]}}"
142
+ f" {c('drv', DIM)} {c(driver, CYAN)}"
143
+ )
144
+
145
+
146
+ def bittiming_range(clock: int, const: dict) -> tuple[int, int]:
147
+ """Return (min_bitrate, max_bitrate) achievable by the given bittiming_const.
148
+
149
+ bitrate = clock / (brp * (1 + tseg1 + tseg2))
150
+ """
151
+ brp = const["brp"]
152
+ tseg1 = const["tseg1"]
153
+ tseg2 = const["tseg2"]
154
+ lo = clock // (brp["max"] * (1 + tseg1["max"] + tseg2["max"]))
155
+ hi = clock // (brp["min"] * (1 + tseg1["min"] + tseg2["min"]))
156
+ return lo, hi
157
+
158
+
159
+ def show_bitrates(ifaces: list[str]) -> None:
160
+ links = get_links()
161
+ for name in ifaces:
162
+ link = links.get(name, {})
163
+ data = link.get("linkinfo", {}).get("info_data") or {}
164
+ clock = data.get("clock")
165
+ btc = data.get("bittiming_const")
166
+ dbtc = data.get("data_bittiming_const")
167
+
168
+ print(f"=== {name} ===")
169
+ if not clock or not btc:
170
+ print(" (no bittiming constants reported — vcan or similar)")
171
+ print()
172
+ continue
173
+
174
+ lo, hi = bittiming_range(clock, btc)
175
+ std = [r for r in STD_NOMINAL if lo <= r <= hi]
176
+ print(f" driver: {btc.get('name', '-')}")
177
+ print(f" clock: {clock / 1_000_000:g} MHz")
178
+ print(f" nominal: {fmt_rate(lo)} .. {fmt_rate(hi)}")
179
+ print(f" standard: {', '.join(fmt_rate(r) for r in std) or '(none)'}")
180
+
181
+ if dbtc:
182
+ dlo, dhi = bittiming_range(clock, dbtc)
183
+ dstd = [r for r in STD_DATA if dlo <= r <= dhi]
184
+ print(f" FD data: {fmt_rate(dlo)} .. {fmt_rate(dhi)}")
185
+ print(f" FD std: {', '.join(fmt_rate(r) for r in dstd) or '(none)'}")
186
+ else:
187
+ print(f" FD: not supported")
188
+ print()
189
+
190
+
191
+ def elevate_if_needed() -> None:
192
+ if os.geteuid() == 0:
193
+ return
194
+ # Re-exec via `python -m canconf` so it works whether installed via pipx,
195
+ # pip, or run from a source checkout.
196
+ os.execvp("sudo", ["sudo", "--", sys.executable, "-m", "canconf"] + sys.argv[1:])
197
+
198
+
199
+ def build_type_args(spec: dict, args: argparse.Namespace) -> list[str]:
200
+ t = ["type", "can", "bitrate", str(spec["bitrate"])]
201
+ if "sample_point" in spec:
202
+ t += ["sample-point", f"{spec['sample_point']}"]
203
+ if spec.get("fd"):
204
+ t += ["dbitrate", str(spec["dbitrate"])]
205
+ if "dsample_point" in spec:
206
+ t += ["dsample-point", f"{spec['dsample_point']}"]
207
+ t += ["fd", "on"]
208
+ if args.restart_ms is not None:
209
+ t += ["restart-ms", str(args.restart_ms)]
210
+ if args.listen_only:
211
+ t += ["listen-only", "on"]
212
+ if args.loopback:
213
+ t += ["loopback", "on"]
214
+ if args.one_shot:
215
+ t += ["one-shot", "on"]
216
+ if args.berr:
217
+ t += ["berr-reporting", "on"]
218
+ if args.term is not None:
219
+ t += ["termination", str(args.term)]
220
+ return t
221
+
222
+
223
+ def main() -> int:
224
+ ap = argparse.ArgumentParser(
225
+ prog="canconf", add_help=False,
226
+ usage="canconf [OPTIONS] [SPEC] (SPEC: e.g. 500k, 500k/2M, 500k/2M@0.8/0.75, off, up)",
227
+ )
228
+ ap.add_argument("spec", nargs="?")
229
+ ap.add_argument("-i", "--ifaces")
230
+ ap.add_argument("-r", "--restart-ms", type=int)
231
+ ap.add_argument("--listen-only", action="store_true")
232
+ ap.add_argument("--loopback", action="store_true")
233
+ ap.add_argument("--one-shot", action="store_true")
234
+ ap.add_argument("--berr", action="store_true")
235
+ ap.add_argument("--term", type=int)
236
+ ap.add_argument("--txqueuelen", type=int, default=DEFAULT_TXQUEUELEN)
237
+ ap.add_argument("-n", "--dry-run", action="store_true")
238
+ ap.add_argument("-v", "--verbose", action="store_true")
239
+ ap.add_argument("-q", "--quiet", action="store_true")
240
+ ap.add_argument("--no-color", action="store_true", help="disable ANSI colour")
241
+ ap.add_argument("-V", "--version", action="store_true")
242
+ ap.add_argument("-h", "--help", action="store_true")
243
+ args = ap.parse_args()
244
+
245
+ if args.no_color:
246
+ common.set_color(False)
247
+
248
+ if args.help:
249
+ print(__doc__.strip())
250
+ return 0
251
+ if args.version:
252
+ print(f"canconf {__version__}")
253
+ return 0
254
+
255
+ if args.ifaces:
256
+ ifaces = [x.strip() for x in args.ifaces.split(",") if x.strip()]
257
+ else:
258
+ ifaces = discover_ifaces()
259
+
260
+ if not ifaces:
261
+ print("canconf: no CAN interfaces found (pass --ifaces to override)", file=sys.stderr)
262
+ return 1
263
+
264
+ if args.spec is None:
265
+ show_status(ifaces)
266
+ return 0
267
+
268
+ if args.spec == "bitrates":
269
+ show_bitrates(ifaces)
270
+ return 0
271
+
272
+ try:
273
+ spec = parse_spec(args.spec)
274
+ except ValueError as e:
275
+ print(f"canconf: bad spec {args.spec!r}: {e}", file=sys.stderr)
276
+ return 2
277
+
278
+ if not args.dry_run:
279
+ elevate_if_needed()
280
+
281
+ for i in ifaces:
282
+ run(["ip", "link", "set", i, "down"], dry=args.dry_run, verbose=args.verbose)
283
+
284
+ if spec["action"] == "down":
285
+ if not args.dry_run and not args.quiet:
286
+ show_status(ifaces)
287
+ return 0
288
+
289
+ if spec["action"] == "configure":
290
+ type_args = build_type_args(spec, args)
291
+ for i in ifaces:
292
+ run(["ip", "link", "set", i] + type_args, dry=args.dry_run, verbose=args.verbose)
293
+ if args.txqueuelen is not None:
294
+ run(["ip", "link", "set", i, "txqueuelen", str(args.txqueuelen)],
295
+ dry=args.dry_run, verbose=args.verbose)
296
+
297
+ for i in ifaces:
298
+ run(["ip", "link", "set", i, "up"], dry=args.dry_run, verbose=args.verbose)
299
+
300
+ if not args.dry_run and not args.quiet:
301
+ show_status(ifaces)
302
+ return 0
303
+
304
+
305
+ if __name__ == "__main__":
306
+ sys.exit(main())
canconf/common.py ADDED
@@ -0,0 +1,110 @@
1
+ """Helpers shared between canconf and canmon."""
2
+ from __future__ import annotations
3
+
4
+ import json
5
+ import os
6
+ import pathlib
7
+ import subprocess
8
+ import sys
9
+
10
+
11
+ # ---- colour ------------------------------------------------------------------
12
+
13
+ RESET = "\033[0m"
14
+ BOLD = "\033[1m"
15
+ DIM = "\033[2m"
16
+ RED = "\033[31m"
17
+ GREEN = "\033[32m"
18
+ YELLOW = "\033[33m"
19
+ BLUE = "\033[34m"
20
+ MAGENTA = "\033[35m"
21
+ CYAN = "\033[36m"
22
+ BRIGHT_RED = "\033[91m"
23
+ BRIGHT_YELLOW = "\033[93m"
24
+
25
+ _use_color: bool | None = None
26
+
27
+
28
+ def use_color() -> bool:
29
+ global _use_color
30
+ if _use_color is not None:
31
+ return _use_color
32
+ if os.environ.get("NO_COLOR"):
33
+ _use_color = False
34
+ elif os.environ.get("FORCE_COLOR"):
35
+ _use_color = True
36
+ else:
37
+ _use_color = sys.stdout.isatty()
38
+ return _use_color
39
+
40
+
41
+ def set_color(enabled: bool) -> None:
42
+ global _use_color
43
+ _use_color = enabled
44
+
45
+
46
+ def c(text: str, *codes: str) -> str:
47
+ """Wrap text in ANSI codes if colour is enabled; otherwise return as-is."""
48
+ if not use_color() or not codes:
49
+ return text
50
+ return "".join(codes) + text + RESET
51
+
52
+
53
+ STATE_STYLE = {
54
+ "ERROR-ACTIVE": (GREEN,),
55
+ "ERROR-WARNING": (YELLOW,),
56
+ "ERROR-PASSIVE": (BRIGHT_YELLOW,),
57
+ "BUS-OFF": (BRIGHT_RED, BOLD),
58
+ "STOPPED": (DIM,),
59
+ "SLEEPING": (DIM,),
60
+ "UP": (GREEN,),
61
+ "DOWN": (DIM,),
62
+ }
63
+
64
+
65
+ def color_state(state: str, width: int = 0) -> str:
66
+ """Pad state to width (if given), then wrap in its colour."""
67
+ padded = f"{state:<{width}}" if width else state
68
+ codes = STATE_STYLE.get(state, ())
69
+ return c(padded, *codes) if codes else padded
70
+
71
+
72
+ # ---- interface discovery -----------------------------------------------------
73
+
74
+
75
+ def discover_ifaces() -> list[str]:
76
+ """Return sorted names of every CAN-typed netdev on the host."""
77
+ root = pathlib.Path("/sys/class/net")
78
+ if not root.exists():
79
+ return []
80
+ found = []
81
+ for p in sorted(root.iterdir()):
82
+ # CAN ARPHRD is 280
83
+ try:
84
+ if (p / "type").read_text().strip() == "280":
85
+ found.append(p.name)
86
+ except OSError:
87
+ pass
88
+ return found
89
+
90
+
91
+ def fmt_rate(r: int) -> str:
92
+ """500000 -> '500k', 2000000 -> '2M', other -> str(r)."""
93
+ if r % 1_000_000 == 0:
94
+ return f"{r // 1_000_000}M"
95
+ if r % 1_000 == 0:
96
+ return f"{r // 1_000}k"
97
+ return str(r)
98
+
99
+
100
+ def get_links(stats: bool = False) -> dict[str, dict]:
101
+ """Parse `ip -j -details [-s] link show` into a dict keyed by ifname."""
102
+ cmd = ["ip", "-j", "-details"]
103
+ if stats:
104
+ cmd.append("-stats")
105
+ cmd += ["link", "show"]
106
+ r = subprocess.run(cmd, capture_output=True, text=True)
107
+ try:
108
+ return {l["ifname"]: l for l in json.loads(r.stdout)}
109
+ except (ValueError, KeyError):
110
+ return {}
canconf/monitor.py ADDED
@@ -0,0 +1,235 @@
1
+ """
2
+ canmon - monitor SocketCAN / CAN-FD interface health.
3
+
4
+ Usage:
5
+ canmon monitor all can* interfaces, 1 Hz, forever
6
+ canmon -i can0,can1 restrict to these interfaces
7
+ canmon -r 0.5 tick every 500 ms
8
+ canmon -t 10 flag ticks with > 10 bus-errors / sec
9
+ canmon -o snapshot the current state and exit
10
+ canmon -v verbose: emit a row every tick
11
+
12
+ Default behaviour: print the current state of every selected interface once
13
+ at startup, then stay silent until something changes. A per-interface row is
14
+ emitted only on a state transition, bittiming change, auto-restart, or when
15
+ the bit-error rate exceeds the --err-rate threshold.
16
+
17
+ Columns:
18
+ TIME STATE BITRATE Δerr/s Δbus/s restarts notes
19
+
20
+ Δerr/s frame-level rx+tx errors per second (driver stats64)
21
+ Δbus/s CAN controller bit-errors per second (info_xstats.bus_error)
22
+ notes state transitions, config changes, auto-restarts, threshold flags
23
+
24
+ Does not require root — it only reads kernel stats.
25
+ """
26
+ from __future__ import annotations
27
+
28
+ import argparse
29
+ import signal
30
+ import sys
31
+ import time
32
+ from dataclasses import dataclass
33
+ from datetime import datetime
34
+
35
+ from . import __version__
36
+ from . import common
37
+ from .common import (
38
+ BOLD, BRIGHT_RED, CYAN, DIM, MAGENTA, RED, YELLOW,
39
+ c, color_state, discover_ifaces, fmt_rate, get_links,
40
+ )
41
+
42
+
43
+ @dataclass
44
+ class Snapshot:
45
+ state: str
46
+ bitrate: int | None
47
+ dbitrate: int | None
48
+ sample_point: str | None
49
+ dsample_point: str | None
50
+ rx_errors: int
51
+ tx_errors: int
52
+ bus_error: int
53
+ arbitration_lost: int
54
+ restarts: int
55
+ error_warning: int
56
+ error_passive: int
57
+ bus_off: int
58
+
59
+ @classmethod
60
+ def from_link(cls, link: dict) -> "Snapshot":
61
+ li = link.get("linkinfo") or {}
62
+ info_data = li.get("info_data") or {}
63
+ xstats = li.get("info_xstats") or {}
64
+ bt = info_data.get("bittiming") or {}
65
+ dbt = info_data.get("data_bittiming") or {}
66
+ stats = link.get("stats64") or {}
67
+ rx = stats.get("rx") or {}
68
+ tx = stats.get("tx") or {}
69
+ return cls(
70
+ state=info_data.get("state", "?"),
71
+ bitrate=bt.get("bitrate"),
72
+ dbitrate=dbt.get("bitrate"),
73
+ sample_point=bt.get("sample_point"),
74
+ dsample_point=dbt.get("sample_point"),
75
+ rx_errors=rx.get("errors", 0),
76
+ tx_errors=tx.get("errors", 0),
77
+ bus_error=xstats.get("bus_error", 0),
78
+ arbitration_lost=xstats.get("arbitration_lost", 0),
79
+ restarts=xstats.get("restarts", 0),
80
+ error_warning=xstats.get("error_warning", 0),
81
+ error_passive=xstats.get("error_passive", 0),
82
+ bus_off=xstats.get("bus_off", 0),
83
+ )
84
+
85
+ def rate_str(self) -> str:
86
+ if self.bitrate is None:
87
+ return "-"
88
+ r = fmt_rate(self.bitrate)
89
+ if self.dbitrate:
90
+ r += f"/{fmt_rate(self.dbitrate)}"
91
+ return r
92
+
93
+ def bittiming_key(self) -> tuple:
94
+ return (self.bitrate, self.dbitrate, self.sample_point, self.dsample_point)
95
+
96
+
97
+ def snapshot_all(ifaces: list[str]) -> dict[str, Snapshot]:
98
+ links = get_links(stats=True)
99
+ return {i: Snapshot.from_link(links.get(i, {})) for i in ifaces}
100
+
101
+
102
+ def header() -> str:
103
+ return c(
104
+ f"{'TIME':>8} {'IFACE':<6} {'STATE':<14} {'BITRATE':<10} "
105
+ f"{'Δerr/s':>6} {'Δbus/s':>6} {'restarts':>8} notes",
106
+ BOLD,
107
+ )
108
+
109
+
110
+ def color_note(note: str) -> str:
111
+ if note.startswith("STATE "):
112
+ tail = note[len("STATE "):]
113
+ arrow = tail.find("→")
114
+ if arrow != -1:
115
+ old, new = tail[:arrow], tail[arrow + 1:]
116
+ return f"STATE {color_state(old)}→{color_state(new)}"
117
+ return c(note, MAGENTA)
118
+ if note.startswith("CONFIG "):
119
+ return c(note, MAGENTA)
120
+ if note.startswith("RESTART "):
121
+ return c(note, CYAN, BOLD)
122
+ if note.startswith("BIT-ERRORS "):
123
+ return c(note, BRIGHT_RED, BOLD)
124
+ return note
125
+
126
+
127
+ def color_rate_delta(per_s: float, flagged: bool) -> str:
128
+ cell = f"{per_s:>6.0f}"
129
+ if flagged:
130
+ return c(cell, BRIGHT_RED, BOLD)
131
+ if per_s > 0:
132
+ return c(cell, YELLOW)
133
+ return cell
134
+
135
+
136
+ def fmt_row(ts: str, iface: str, n: Snapshot, err_per_s: float,
137
+ bus_per_s: float, flagged: bool, notes: list[str]) -> str:
138
+ flag = c("!", BRIGHT_RED, BOLD) if flagged else " "
139
+ note_str = " ".join(color_note(x) for x in notes)
140
+ err_cell = color_rate_delta(err_per_s, err_per_s > 0 and not flagged)
141
+ bus_cell = color_rate_delta(bus_per_s, flagged)
142
+ restarts_cell = f"{n.restarts:>8}"
143
+ if n.restarts > 0:
144
+ restarts_cell = c(restarts_cell, CYAN)
145
+ return (
146
+ f"{c(ts, DIM)} {iface:<6} {color_state(n.state, 14)} {n.rate_str():<10} "
147
+ f"{err_cell} {bus_cell} {restarts_cell} "
148
+ f"{flag} {note_str}".rstrip()
149
+ )
150
+
151
+
152
+ def main() -> int:
153
+ ap = argparse.ArgumentParser(
154
+ prog="canmon", add_help=False,
155
+ description="Monitor SocketCAN / CAN-FD state, configuration, and bit-error rate.",
156
+ )
157
+ ap.add_argument("-i", "--ifaces")
158
+ ap.add_argument("-r", "--rate", type=float, default=1.0,
159
+ help="tick interval in seconds (default: 1.0)")
160
+ ap.add_argument("-t", "--err-rate", type=float, default=1.0,
161
+ help="flag ticks when bus-errors/sec exceeds this (default: 1)")
162
+ ap.add_argument("-o", "--once", action="store_true",
163
+ help="print the initial snapshot and exit")
164
+ ap.add_argument("-v", "--verbose", action="store_true",
165
+ help="emit a row every tick, not only on change")
166
+ ap.add_argument("--no-color", action="store_true", help="disable ANSI colour")
167
+ ap.add_argument("-V", "--version", action="store_true")
168
+ ap.add_argument("-h", "--help", action="store_true")
169
+ args = ap.parse_args()
170
+
171
+ if args.no_color:
172
+ common.set_color(False)
173
+
174
+ if args.help:
175
+ print(__doc__.strip())
176
+ return 0
177
+ if args.version:
178
+ print(f"canmon {__version__}")
179
+ return 0
180
+
181
+ if args.ifaces:
182
+ ifaces = [x.strip() for x in args.ifaces.split(",") if x.strip()]
183
+ else:
184
+ ifaces = discover_ifaces()
185
+ if not ifaces:
186
+ print("canmon: no CAN interfaces found (pass --ifaces to override)", file=sys.stderr)
187
+ return 1
188
+
189
+ signal.signal(signal.SIGINT, lambda *_: (print(), sys.exit(0)))
190
+
191
+ # Initial snapshot: always printed, so the user sees what is being monitored.
192
+ prev = snapshot_all(ifaces)
193
+ print(header())
194
+ ts = datetime.now().strftime("%H:%M:%S")
195
+ for iface in ifaces:
196
+ print(fmt_row(ts, iface, prev[iface], 0.0, 0.0, flagged=False, notes=[]))
197
+ sys.stdout.flush()
198
+
199
+ if args.once:
200
+ return 0
201
+
202
+ while True:
203
+ time.sleep(args.rate)
204
+ now = snapshot_all(ifaces)
205
+ ts = datetime.now().strftime("%H:%M:%S")
206
+ for iface in ifaces:
207
+ p = prev[iface]
208
+ n = now[iface]
209
+
210
+ notes = []
211
+ if p.state != n.state:
212
+ notes.append(f"STATE {p.state}→{n.state}")
213
+ if p.bittiming_key() != n.bittiming_key():
214
+ notes.append(f"CONFIG {p.rate_str()}→{n.rate_str()}")
215
+ if n.restarts > p.restarts:
216
+ notes.append(f"RESTART #{n.restarts}")
217
+
218
+ d_err = (n.rx_errors - p.rx_errors) + (n.tx_errors - p.tx_errors)
219
+ d_bus = n.bus_error - p.bus_error
220
+ err_per_s = d_err / args.rate
221
+ bus_per_s = d_bus / args.rate
222
+
223
+ flagged = bus_per_s > args.err_rate
224
+ if flagged:
225
+ notes.append(f"BIT-ERRORS {bus_per_s:.0f}/s > {args.err_rate:.0f}/s")
226
+
227
+ if args.verbose or notes:
228
+ print(fmt_row(ts, iface, n, err_per_s, bus_per_s, flagged, notes))
229
+
230
+ prev = now
231
+ sys.stdout.flush()
232
+
233
+
234
+ if __name__ == "__main__":
235
+ sys.exit(main())
@@ -0,0 +1,285 @@
1
+ Metadata-Version: 2.4
2
+ Name: canconf
3
+ Version: 0.3.0
4
+ Summary: One-shot reconfiguration and live monitoring of SocketCAN / CAN-FD interfaces
5
+ Project-URL: Homepage, https://github.com/mickeyl/canconf
6
+ Project-URL: Repository, https://github.com/mickeyl/canconf
7
+ Project-URL: Issues, https://github.com/mickeyl/canconf/issues
8
+ Author-email: "Dr. Michael Lauer" <mickey@vanille-media.de>
9
+ License-Expression: MIT
10
+ License-File: LICENSE
11
+ Keywords: automotive,can,canbus,canfd,linux,socketcan
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Environment :: Console
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Intended Audience :: System Administrators
16
+ Classifier: License :: OSI Approved :: MIT License
17
+ Classifier: Operating System :: POSIX :: Linux
18
+ Classifier: Programming Language :: Python :: 3
19
+ Classifier: Topic :: System :: Hardware
20
+ Classifier: Topic :: System :: Networking
21
+ Classifier: Topic :: Utilities
22
+ Requires-Python: >=3.9
23
+ Description-Content-Type: text/markdown
24
+
25
+ # canconf / canmon
26
+
27
+ Two small, single-purpose tools for people who spend their day staring at CAN
28
+ buses on Linux:
29
+
30
+ - **`canconf`** — reconfigure every SocketCAN / CAN-FD interface in one terse
31
+ command, introspect the hardware, inspect the live configuration.
32
+ - **`canmon`** — passive, read-only health monitor: state transitions,
33
+ configuration changes, auto-restarts, and bit-error bursts — printed only
34
+ when something actually happens.
35
+
36
+ Both are pure Python 3.9+ stdlib, zero runtime dependencies, installable as a
37
+ single `pipx install canconf` and immediately useful.
38
+
39
+ ## Why this exists
40
+
41
+ Automotive CAN work — diagnostics, ECU flashing, gateway reverse-engineering,
42
+ bench-testing on the sofa — spends an embarrassing amount of time on the same
43
+ fiddly chores:
44
+
45
+ - **Changing bitrates**. Different ECUs, different generations, different
46
+ vehicle platforms all want different line speeds. Switching from 500k to 250k
47
+ to 1M to FD-at-2M happens several times a day. The stock `ip link` CLI
48
+ wants half a dozen sudo-flavoured incantations for each iface, in the right
49
+ order, with the right keywords — an error-prone tax on iteration speed.
50
+ - **Keeping two interfaces in lock-step.** Dual-channel USB adapters and
51
+ bench rigs with T-tap into the same bus mean every parameter change has to
52
+ be mirrored across both ifaces. Forget one and your capture is misleading.
53
+ - **Knowing the bus is healthy.** When an ECU flash spirals into bus-off, or
54
+ a faulty transceiver starts cooking bit errors, you want to *see it* — not
55
+ realise hours later that half your log is garbage.
56
+ - **Knowing what the hardware can actually do.** Is this adapter FD-capable?
57
+ What bitrates will its clock + timing constants support? Which kernel driver
58
+ backs it? The answers are all there in `/sys` and netlink, but nobody types
59
+ `jq '.linkinfo.info_data.bittiming_const'` for fun.
60
+
61
+ `canconf` and `canmon` compress those chores into commands short enough to
62
+ actually type during a debug loop. If you use `mcangen`, `candump`, python-can,
63
+ or any of the canmatrix family to do real work on the bus, these are the tools
64
+ that keep the plumbing out of your way.
65
+
66
+ ## Installation
67
+
68
+ ### pipx — recommended
69
+
70
+ Installs the two binaries into an isolated venv and puts `canconf` and `canmon`
71
+ on your `PATH`:
72
+
73
+ ```bash
74
+ pipx install canconf
75
+ ```
76
+
77
+ ### pip
78
+
79
+ ```bash
80
+ pip install canconf
81
+ ```
82
+
83
+ ### From source
84
+
85
+ ```bash
86
+ git clone https://github.com/mickeyl/canconf
87
+ cd canconf
88
+ pipx install . # or: pip install -e .
89
+ ```
90
+
91
+ No runtime deps. Needs only `iproute2` (you already have it) and `sudo`
92
+ (`canconf` self-elevates; `canmon` stays non-privileged).
93
+
94
+ ## canconf
95
+
96
+ Replaces:
97
+
98
+ ```bash
99
+ sudo ip link set can0 down
100
+ sudo ip link set can1 down
101
+ sudo ip link set can0 type can bitrate 500000 dbitrate 2000000 sample-point 0.875 dsample-point 0.75 fd on
102
+ sudo ip link set can1 type can bitrate 500000 dbitrate 2000000 sample-point 0.875 dsample-point 0.75 fd on
103
+ sudo ip link set can0 txqueuelen 10000
104
+ sudo ip link set can1 txqueuelen 10000
105
+ sudo ip link set can0 up
106
+ sudo ip link set can1 up
107
+ ```
108
+
109
+ with:
110
+
111
+ ```bash
112
+ canconf 500k/2M@0.875/0.75
113
+ ```
114
+
115
+ ### Grammar
116
+
117
+ ```
118
+ canconf show status of all can* interfaces
119
+ canconf 500k classic CAN @ 500 kbit/s, all interfaces, up
120
+ canconf 500k/2M CAN-FD: nominal 500k, data 2M
121
+ canconf 500k/2M@0.875/0.75 same, with nominal & data sample points
122
+ canconf off | down bring all interfaces down
123
+ canconf up bring all interfaces up (no reconfigure)
124
+ canconf bitrates show achievable bitrates per interface
125
+ ```
126
+
127
+ Positional spec: `BITRATE[/DBITRATE][@SP[/DSP]]`. Bitrates accept the suffixes
128
+ `k`/`M` (`125k`, `500k`, `1M`, `2M`, `5M`, `8M`).
129
+
130
+ ### Features
131
+
132
+ - Discovers all CAN interfaces by ARPHRD type (so `can*`, `vcan*`, `slcan*` are all picked up — no name matching).
133
+ - One compact spec for classic CAN and CAN-FD alike.
134
+ - `canconf bitrates` reports the driver, reference clock, the achievable bitrate envelope (derived from `bittiming_const`), which standard bitrates fall within it, and whether the hardware supports CAN-FD at all. No brute-forcing, all introspection.
135
+ - Sets `txqueuelen 10000` by default (the kernel default of 10 is painfully low for anything other than idle buses).
136
+ - Prints the live post-apply state — including `qlen` and the underlying driver — so you can verify the driver actually accepted what you asked for (drivers silently round bitrates to what the clock can produce).
137
+ - ANSI colour with sensible auto-detection, `NO_COLOR`/`FORCE_COLOR`, and a `--no-color` flag.
138
+ - Self-elevates to root via `sudo`; `--dry-run` is completely non-privileged.
139
+
140
+ ### Options
141
+
142
+ | Flag | Description |
143
+ |------|-------------|
144
+ | `-i`, `--ifaces a,b,c` | Restrict to these interfaces (default: all CAN interfaces) |
145
+ | `-r`, `--restart-ms N` | Auto-restart on bus-off after N ms |
146
+ | `--listen-only` | Listen-only mode |
147
+ | `--loopback` | Loopback mode |
148
+ | `--one-shot` | One-shot mode |
149
+ | `--berr` | Enable bus error reporting |
150
+ | `--term OHM` | Set termination resistor (if the hardware supports it) |
151
+ | `--txqueuelen N` | Override the tx queue length (default: 10000) |
152
+ | `-n`, `--dry-run` | Print the `ip` commands that would run, do nothing |
153
+ | `-v`, `--verbose` | Print each `ip` command as it runs |
154
+ | `-q`, `--quiet` | Suppress the post-apply status dump |
155
+ | `--no-color` | Disable ANSI colour |
156
+ | `-V`, `--version` | Print version and exit |
157
+ | `-h`, `--help` | Show help |
158
+
159
+ ### Example session
160
+
161
+ ```
162
+ ❯ canconf
163
+ can0 UP CAN 500k sp 0.875 qlen 10000 drv gs_usb
164
+ can1 UP CAN 500k sp 0.875 qlen 10000 drv gs_usb
165
+
166
+ ❯ canconf 500k/2M@0.875/0.75
167
+ [sudo] password for mickey:
168
+ can0 UP CAN-FD 500k/2M sp 0.875/0.750 qlen 10000 drv gs_usb
169
+ can1 UP CAN-FD 500k/2M sp 0.875/0.750 qlen 10000 drv gs_usb
170
+
171
+ ❯ canconf bitrates
172
+ === can0 ===
173
+ driver: gs_usb
174
+ clock: 40 MHz
175
+ nominal: 202 .. 13333333
176
+ standard: 10k, 20k, 50k, 100k, 125k, 250k, 500k, 800k, 1M
177
+ FD data: 25510 .. 13333333
178
+ FD std: 1M, 2M, 4M, 5M, 8M
179
+
180
+ === can1 ===
181
+ driver: gs_usb
182
+ clock: 48 MHz
183
+ nominal: 1875 .. 16M
184
+ standard: 10k, 20k, 50k, 100k, 125k, 250k, 500k, 800k, 1M
185
+ FD: not supported
186
+
187
+ ❯ canconf -n 1M -i can0
188
+ + ip link set can0 down
189
+ + ip link set can0 type can bitrate 1000000
190
+ + ip link set can0 txqueuelen 10000
191
+ + ip link set can0 up
192
+ ```
193
+
194
+ ## canmon
195
+
196
+ `canmon` tails every CAN interface at 1 Hz (tunable). It prints the current
197
+ state once at startup and then **stays silent**, emitting a new row only when
198
+ something actually changes: a state transition, a bittiming change, an
199
+ auto-restart, or a tick in which the CAN controller bit-error rate exceeds a
200
+ threshold. It needs no root and reads only from `ip -j -details -s link show`
201
+ plus `/sys/class/net` — no CAN traffic is injected, intercepted, or generated.
202
+
203
+ ```
204
+ ❯ canmon -r 0.5 -t 5
205
+ TIME IFACE STATE BITRATE Δerr/s Δbus/s restarts notes
206
+ 14:23:45 can0 ERROR-ACTIVE 500k 0 0 0
207
+ 14:23:45 can1 ERROR-ACTIVE 500k/2M 0 0 0
208
+ 14:23:46 can0 ERROR-WARNING 500k 12 8 0 STATE ERROR-ACTIVE→ERROR-WARNING BIT-ERRORS 8/s > 5/s
209
+ 14:23:48 can0 BUS-OFF 500k 4 14 0 STATE ERROR-WARNING→BUS-OFF BIT-ERRORS 14/s > 5/s
210
+ 14:23:52 can0 ERROR-ACTIVE 500k 0 0 1 STATE BUS-OFF→ERROR-ACTIVE RESTART #1
211
+ ```
212
+
213
+ (Between 14:23:46 and 14:23:48, and at any other tick with no change, nothing
214
+ is printed. Pass `-v` to force a row every tick.)
215
+
216
+ ### Options
217
+
218
+ | Flag | Description |
219
+ |------|-------------|
220
+ | `-i`, `--ifaces a,b,c` | Restrict to these interfaces |
221
+ | `-r`, `--rate SECONDS` | Tick interval (default: 1.0) |
222
+ | `-t`, `--err-rate N` | Threshold for the `Δbus/s` flag (default: 1) |
223
+ | `-o`, `--once` | Print initial snapshot and exit |
224
+ | `-v`, `--verbose` | Emit a row every tick, not just on change |
225
+ | `--no-color` | Disable ANSI colour |
226
+ | `-V`, `--version` | Print version and exit |
227
+ | `-h`, `--help` | Show help |
228
+
229
+ ### Columns
230
+
231
+ - **Δerr/s** — frame-level `rx+tx` error delta per second (from driver `stats64`).
232
+ - **Δbus/s** — CAN controller bit-error delta per second (from `info_xstats.bus_error`). The number you probably care about most during ECU flashes, cable swaps, or suspect wiring.
233
+ - **restarts** — running total of driver-initiated auto-restarts after bus-off (requires `canconf … -r MS` to be non-zero at configure time).
234
+ - **notes** — event tags: `STATE a→b`, `CONFIG a→b`, `RESTART #N`, `BIT-ERRORS N/s > T/s`. In a colour-capable terminal each tag is coloured by severity, and state tokens are rendered in the same colour as the state column so bus-off transitions jump out.
235
+
236
+ ## Roadmap
237
+
238
+ Things I intend to build as soon as the underlying itch scratches hard enough.
239
+ Contributions welcome; open an issue first if it's non-trivial.
240
+
241
+ ### Short-term
242
+
243
+ - **JSON output** (`canconf --json`, `canmon --json`) for scripting and for
244
+ wiring the tools into dashboards or CI.
245
+ - **Bus-load metrics in `canmon`** — frames/s, bytes/s, and estimated line
246
+ utilisation (%) derived from the driver's rx/tx counters and the active
247
+ bitrate. All the inputs are already read each tick.
248
+ - **Config profiles** — `~/.config/canconf/profiles.toml` so you can name
249
+ frequently-used configurations and apply them with `canconf @passive-500k`
250
+ or `canconf @my-ecu`. Profile files track sample-point, FD, termination,
251
+ listen-only, restart-ms, and per-iface overrides.
252
+ - **`canconf save`/`canconf apply`** — dump the current configuration of all
253
+ interfaces to a profile file, and re-apply it later. Handy for sharing bus
254
+ setups between workstations.
255
+
256
+ ### Medium-term
257
+
258
+ - **`canscan`** — sibling tool. Auto-detect the bitrate of an unknown bus by
259
+ entering listen-only mode and trying each standard rate until frames arrive
260
+ cleanly. Useful when probing an unknown vehicle network.
261
+ - **`canfind`** — map `canX` interfaces back to the physical adapter: USB
262
+ VID:PID, serial number, USB port path, product string. Indispensable when
263
+ four identical USB-CAN dongles are plugged in.
264
+ - **`cansync`** — one-shot synchronised down→configure→up across interfaces,
265
+ with an optional `--at <time>` for lab rigs that need deterministic startup.
266
+ - **Daemon mode for `canmon`** — long-running process that emits to
267
+ syslog/journald (for ops use) and exposes a Prometheus text-format
268
+ endpoint (for lab dashboards and long-term bus health recording).
269
+
270
+ ### Longer-term / speculative
271
+
272
+ - **python-can integration** — provide a small import so `canconf.discover()`
273
+ can feed bus factories, and so python-can users get the same topology
274
+ awareness without re-implementing it.
275
+ - **Test-mode** — `canconf test` sends a handful of frames between discovered
276
+ interfaces (pair-wise or via loopback) and verifies the wiring and bitrate
277
+ match end-to-end. Catches bench setup errors before you chase them in
278
+ protocol logs.
279
+ - **Termination auto-probe** — some CAN transceivers can report whether the
280
+ bus looks correctly terminated. If the driver exposes it, `canmon` should
281
+ surface it alongside the state column.
282
+
283
+ ## License
284
+
285
+ MIT — see [LICENSE](LICENSE).
@@ -0,0 +1,10 @@
1
+ canconf/__init__.py,sha256=KTCV3Ow4NjRYdtRU0Y2XAYq8rZyg2n92MRZv_fPS0U8,94
2
+ canconf/__main__.py,sha256=4JMK66Wj4uLZTKbF-sT3LAxOsr6buig77PmOkJCRRxw,83
3
+ canconf/cli.py,sha256=XKJTve7dYo3CzKIQtugRFb-atQHoR1NFGxrhsMa9qKs,10524
4
+ canconf/common.py,sha256=0zee7GUmp8FHCKGJZUIC7e8DHudoV1ToYqdusZXdJag,2812
5
+ canconf/monitor.py,sha256=YHy0ChrukEhd6J3fMKUZHTy_JSMbaLWU8vuypKX8t_k,7973
6
+ canconf-0.3.0.dist-info/METADATA,sha256=Ns-7PeYS5NT9dDEzLBP6A7KBiXRpLBGcfP3j6QbdVW0,12283
7
+ canconf-0.3.0.dist-info/WHEEL,sha256=QccIxa26bgl1E6uMy58deGWi-0aeIkkangHcxk2kWfw,87
8
+ canconf-0.3.0.dist-info/entry_points.txt,sha256=z424Tmlg5ZHRTt5NULejMmKyIiKujZHj5MPrt-KUp4Q,75
9
+ canconf-0.3.0.dist-info/licenses/LICENSE,sha256=dlTMJRRTmnDIT8NgnBz7g7pOuBeZXik3amSx_eCBMtA,1074
10
+ canconf-0.3.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.29.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,3 @@
1
+ [console_scripts]
2
+ canconf = canconf.cli:main
3
+ canmon = canconf.monitor:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Dr. Michael Lauer
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.