openloggernet 0.1.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.
File without changes
@@ -0,0 +1,113 @@
1
+ #!/usr/bin/env python3
2
+ """Read stored data table records off a running logger (CR6, CR1000X, CR300 or CR350).
3
+
4
+ The counterpart to `read_values.py`, which sees only the newest value of a field. This reads the
5
+ tables themselves, which is what makes a run's full-resolution data survive: the serial trace
6
+ carries only what a program chose to print, and a reflash deletes the tables.
7
+
8
+ uv run collect_data --list
9
+ uv run collect_data DailyPower
10
+ uv run collect_data Shunt_Data --count 60 --csv shunt.csv
11
+ uv run collect_data TString_Data --count 5
12
+ """
13
+
14
+ import argparse
15
+ import csv
16
+ import itertools
17
+ import sys
18
+
19
+ from .pakbus import PakBusError, PakBusLink, find_port
20
+
21
+
22
+ def flatten(name: str, value) -> list[tuple[str, object]]:
23
+ if isinstance(value, list):
24
+ return [(f"{name}({i})", v) for i, v in enumerate(value, 1)]
25
+ return [(name, value)]
26
+
27
+
28
+ def main() -> int:
29
+ parser = argparse.ArgumentParser(description=__doc__.split("\n")[0])
30
+ parser.add_argument("table", nargs="?", help="table name, e.g. DailyPower")
31
+ parser.add_argument("--list", action="store_true", help="list the logger's tables and exit")
32
+ parser.add_argument("--count", type=int, default=10, help="most recent N records (default 10)")
33
+ parser.add_argument("--csv", help="write the records to this CSV file instead of printing")
34
+ parser.add_argument("--port", help="serial port (default: autodetected logger)")
35
+ args = parser.parse_args()
36
+
37
+ port = args.port or find_port()
38
+ if port is None:
39
+ print("no Campbell logger serial port found; is it attached to this host or WSL?", file=sys.stderr)
40
+ return 1
41
+
42
+ with PakBusLink(port) as link:
43
+ if not link.hello():
44
+ print("the logger did not answer a hello", file=sys.stderr)
45
+ return 1
46
+ tables = link.table_definitions()
47
+
48
+ if args.list or not args.table:
49
+ limit = f", replies limited to {link.max_reply_frame} B" if link.max_reply_frame else ""
50
+ print(f"{link.model or 'unknown model'} on {port}{limit}")
51
+ print(f"{'#':>3s} {'table':22s} {'rec':>5s} {'interval':>9s} {'size':>8s} fields")
52
+ for t in tables:
53
+ interval = f"{t.interval_sec}s" if t.interval_sec else "event"
54
+ print(f"{t.number:3d} {t.name:22s} {t.record_size:4d}B {interval:>9s} {t.size:8d} {len(t.fields)}")
55
+ return 0
56
+
57
+ table = next((t for t in tables if t.name.lower() == args.table.lower()), None)
58
+ if table is None:
59
+ print(f"no table named {args.table!r}; try --list", file=sys.stderr)
60
+ return 1
61
+
62
+ try:
63
+ records = link.collect_recent(table, args.count)
64
+ except PakBusError as exc:
65
+ print(f"collect failed: {exc}", file=sys.stderr)
66
+ return 1
67
+
68
+ if not records:
69
+ print(f"{table.name}: no records stored")
70
+ return 0
71
+
72
+ columns = ["record", "time"]
73
+ for field in table.fields:
74
+ columns.extend(n for n, _ in flatten(field.name, records[0][2][field.name]))
75
+
76
+ rows = []
77
+ for number, when, values in records:
78
+ row = {"record": number, "time": when.isoformat(sep=" ", timespec="seconds")}
79
+ for field in table.fields:
80
+ row.update(flatten(field.name, values[field.name]))
81
+ rows.append(row)
82
+
83
+ if args.csv:
84
+ with open(args.csv, "w", newline="") as handle:
85
+ writer = csv.DictWriter(handle, fieldnames=columns)
86
+ writer.writeheader()
87
+ writer.writerows(rows)
88
+ print(f"{len(rows)} record(s) from {table.name} -> {args.csv}")
89
+ return 0
90
+
91
+ print(
92
+ f"{table.name}: {len(rows)} record(s), "
93
+ f"{'interval ' + str(table.interval_sec) + 's' if table.is_interval else 'event driven'}"
94
+ )
95
+ wide = len(columns) > 12
96
+ for row in rows:
97
+ head = f" #{row['record']} {row['time']}"
98
+ if wide:
99
+ print(head)
100
+ body = [f"{c}={row[c]}" for c in columns[2:]]
101
+ for line in itertools.batched(body, 6, strict=False):
102
+ print(" " + " ".join(line))
103
+ else:
104
+ print(
105
+ head
106
+ + " "
107
+ + " ".join(f"{c}={row[c]:.4g}" if isinstance(row[c], float) else f"{c}={row[c]}" for c in columns[2:])
108
+ )
109
+ return 0
110
+
111
+
112
+ if __name__ == "__main__":
113
+ raise SystemExit(main())
@@ -0,0 +1,121 @@
1
+ #!/usr/bin/env python3
2
+ """Capture timestamped CR6 ComUSB text and send tester keys through a FIFO."""
3
+
4
+ import argparse
5
+ import os
6
+ import select
7
+ import sys
8
+ import threading
9
+ import time
10
+ from contextlib import ExitStack
11
+ from pathlib import Path
12
+ from typing import TextIO
13
+
14
+ import serial
15
+
16
+ from .pakbus import TextFilter, find_port
17
+
18
+
19
+ def now() -> str:
20
+ return time.strftime("%H:%M:%S")
21
+
22
+
23
+ def reader(
24
+ port: serial.Serial,
25
+ log: TextIO,
26
+ stop: threading.Event,
27
+ raw: TextIO | None = None,
28
+ ) -> None:
29
+ pending = bytearray()
30
+ text_filter = TextFilter()
31
+ while not stop.is_set():
32
+ try:
33
+ data = port.read(port.in_waiting or 1)
34
+ except serial.SerialException as exc:
35
+ log.write(f"[{now()}] !! serial error: {exc}\n")
36
+ log.flush()
37
+ stop.set()
38
+ return
39
+ if not data:
40
+ continue
41
+ if raw is not None:
42
+ raw.write(f"[{now()}] {data.hex(' ')}\n")
43
+ raw.flush()
44
+ pending.extend(text_filter.feed(data))
45
+ while b"\n" in pending:
46
+ line, _, remainder = pending.partition(b"\n")
47
+ pending = bytearray(remainder)
48
+ decoded = line.decode("ascii", "replace").rstrip("\r")
49
+ if decoded:
50
+ log.write(f"[{now()}] {decoded}\n")
51
+ log.flush()
52
+
53
+
54
+ def serve(args: argparse.Namespace) -> int:
55
+ fifo = Path(args.fifo)
56
+ if fifo.exists():
57
+ fifo.unlink()
58
+ os.mkfifo(fifo)
59
+
60
+ port_name = args.port or find_port()
61
+ if port_name is None:
62
+ fifo.unlink()
63
+ print("no CR6 serial port found; is it attached to WSL?", file=sys.stderr)
64
+ return 1
65
+
66
+ stop = threading.Event()
67
+ fifo_fd = -1
68
+ thread: threading.Thread | None = None
69
+ try:
70
+ with ExitStack() as stack:
71
+ port = stack.enter_context(serial.Serial(port_name, args.baud, timeout=0.1))
72
+ log = stack.enter_context(open(args.log, "a", buffering=1))
73
+ raw = (
74
+ stack.enter_context(open(str(args.log) + ".hex", "a", buffering=1, encoding="ascii"))
75
+ if args.rawlog
76
+ else None
77
+ )
78
+ log.write(f"\n[{now()}] === opened {port_name} @ {args.baud} 8N1 ===\n")
79
+
80
+ thread = threading.Thread(target=reader, args=(port, log, stop, raw), daemon=True)
81
+ thread.start()
82
+ fifo_fd = os.open(fifo, os.O_RDWR | os.O_NONBLOCK)
83
+
84
+ while not stop.is_set():
85
+ if not select.select([fifo_fd], [], [], 1.0)[0]:
86
+ continue
87
+ payload = os.read(fifo_fd, 4096)
88
+ if not payload:
89
+ continue
90
+ if payload.startswith(b"#"):
91
+ log.write(f"[{now()}] {payload.decode('utf-8', 'replace').strip()}\n")
92
+ continue
93
+ if payload == b"\x00quit":
94
+ break
95
+ log.write(f"[{now()}] >>> sent {payload!r}\n")
96
+ port.write(payload)
97
+ port.flush()
98
+ log.write(f"[{now()}] === closed ===\n")
99
+ return 0
100
+ finally:
101
+ stop.set()
102
+ if thread is not None:
103
+ thread.join(timeout=1)
104
+ if fifo_fd >= 0:
105
+ os.close(fifo_fd)
106
+ if fifo.exists():
107
+ fifo.unlink()
108
+
109
+
110
+ def main() -> int:
111
+ parser = argparse.ArgumentParser(description=__doc__)
112
+ parser.add_argument("--port", help="serial port (default: autodetected CR6)")
113
+ parser.add_argument("--baud", type=int, default=115200)
114
+ parser.add_argument("--log", type=Path, required=True)
115
+ parser.add_argument("--fifo", default="/tmp/cr6-comusb.key")
116
+ parser.add_argument("--rawlog", action="store_true")
117
+ return serve(parser.parse_args())
118
+
119
+
120
+ if __name__ == "__main__":
121
+ raise SystemExit(main())
@@ -0,0 +1,102 @@
1
+ """Run the Campbell compiler from WSL (through powershell.exe) or macOS/Linux (through Wine).
2
+
3
+ Set CR6COMP=opencrbasic to use the native re-implementation (the `opencrbasic` package, installed
4
+ separately) instead of the exe. It reproduces CR6Comp's output for the FirnMelt programs but is not
5
+ the reference compiler; see the opencrbasic README for its verified scope.
6
+
7
+ The program's extension picks the compiler: `.CR6` uses compiler/CR6Comp.exe and `.CR1X` uses
8
+ compiler/cr1000xcomp.exe. `compiler/` is found in the program's directory or the nearest parent
9
+ that has it. Used by flash.py. Not a script.
10
+ """
11
+
12
+ import importlib.util
13
+ import os
14
+ import shutil
15
+ import subprocess
16
+ import sys
17
+ from pathlib import Path
18
+
19
+ COMPILER_BY_SUFFIX = {".cr6": "CR6Comp.exe", ".cr1x": "cr1000xcomp.exe"}
20
+
21
+ DEFAULT_WINE = Path.home() / ".local" / "wine" / "Wine Devel.app" / "Contents" / "Resources" / "wine" / "bin" / "wine"
22
+ DEFAULT_WINEPREFIX = Path.home() / ".wine-cr6"
23
+
24
+
25
+ def find_up(start: Path, relative: str) -> Path | None:
26
+ """`relative` under `start` or the nearest parent that has it."""
27
+ for directory in (start.resolve(), *start.resolve().parents):
28
+ if (directory / relative).exists():
29
+ return directory / relative
30
+ return None
31
+
32
+
33
+ def find_wine() -> str | None:
34
+ """Wine binary: $CR6_WINE, then the ~/.local/wine install, then `wine` on PATH."""
35
+ override = os.environ.get("CR6_WINE")
36
+ if override:
37
+ return override if Path(override).is_file() else None
38
+ if DEFAULT_WINE.is_file():
39
+ return str(DEFAULT_WINE)
40
+ return shutil.which("wine")
41
+
42
+
43
+ def native() -> bool:
44
+ """True when CR6COMP=opencrbasic selects the native re-implementation."""
45
+ return os.environ.get("CR6COMP", "").lower() == "opencrbasic"
46
+
47
+
48
+ def available(platform: str = sys.platform) -> bool:
49
+ if native():
50
+ return importlib.util.find_spec("opencrbasic") is not None
51
+ if platform == "darwin":
52
+ return find_wine() is not None
53
+ return shutil.which("powershell.exe") is not None or find_wine() is not None
54
+
55
+
56
+ def compiler_for(program: Path) -> Path:
57
+ """The compiler for `program`'s logger, chosen by its extension."""
58
+ name = COMPILER_BY_SUFFIX.get(program.suffix.lower())
59
+ if name is None:
60
+ raise ValueError(f"{program.name}: no compiler for extension {program.suffix!r}")
61
+ compiler = find_up(program.parent, f"compiler/{name}")
62
+ if compiler is None:
63
+ raise FileNotFoundError(f"{program.name}: no compiler/{name} in its directory or a parent")
64
+ return compiler
65
+
66
+
67
+ def command(program: Path, platform: str = sys.platform) -> tuple[list[str], dict[str, str]]:
68
+ """Command line and environment that compile `program` from its own directory."""
69
+ env = dict(os.environ)
70
+ if native():
71
+ return [sys.executable, "-m", "opencrbasic", "--no-message-file", program.name], env
72
+ compiler = compiler_for(program)
73
+ if platform == "darwin" or shutil.which("powershell.exe") is None:
74
+ wine = find_wine()
75
+ if wine is None:
76
+ raise FileNotFoundError("Wine not found; see the openloggernet README, 'Compiling on macOS'")
77
+ env.setdefault("WINEPREFIX", str(DEFAULT_WINEPREFIX))
78
+ env.setdefault("WINEDEBUG", "-all")
79
+ return [wine, str(compiler), program.name], env
80
+ windows_path = subprocess.run(
81
+ ["wslpath", "-w", str(compiler)], capture_output=True, text=True, check=True
82
+ ).stdout.strip()
83
+ return ["powershell.exe", "-Command", f"& '{windows_path}' {program.name}"], env
84
+
85
+
86
+ def compiled(output: str) -> bool:
87
+ return "Compiled in" in output and "Compile Failed" not in output
88
+
89
+
90
+ def compile_program(program: Path) -> tuple[bool, str]:
91
+ """Compile `program`; returns (success, compiler output)."""
92
+ if not available():
93
+ if native():
94
+ return False, "CR6COMP=opencrbasic needs the opencrbasic package: pip install opencrbasic"
95
+ return False, "no CR6Comp.exe runner: needs powershell.exe (WSL) or Wine (macOS/Linux), or CR6COMP=opencrbasic"
96
+ try:
97
+ args, env = command(program)
98
+ except FileNotFoundError as exc:
99
+ return False, str(exc)
100
+ result = subprocess.run(args, cwd=program.parent, env=env, capture_output=True, text=True)
101
+ output = (result.stdout + result.stderr).strip()
102
+ return compiled(output), output
openloggernet/flash.py ADDED
@@ -0,0 +1,240 @@
1
+ #!/usr/bin/env python3
2
+ """Compile a CRBasic program and send it to a CR6 over the USB (PakBus) port.
3
+
4
+ uv run flash ../crbasic/PowerProfile_tester.CR6
5
+ uv run flash ../crbasic/Main.CR6 --monitor 60
6
+
7
+ Replaces the manual "flash it with Device Configuration Utility / LoggerNet"
8
+ step: it compiles with the validated CR6Comp.exe, writes the file to CPU:,
9
+ tells the logger to compile and run it, and reads the compile results back
10
+ out of the logger.
11
+ """
12
+
13
+ import argparse
14
+ import os
15
+ import re
16
+ import sys
17
+ import time
18
+ from pathlib import Path
19
+
20
+ import serial
21
+
22
+ from . import cr6comp
23
+ from .pakbus import FILECTL_COMPILE_RUN_POWERUP, PakBusError, PakBusLink, TextFilter, find_port
24
+
25
+
26
+ def compile_program(program: Path) -> bool:
27
+ """Compile with CR6Comp.exe. Returns True if the compiler reported success."""
28
+ ok, output = cr6comp.compile_program(program)
29
+ if output:
30
+ print(output)
31
+ return ok
32
+
33
+
34
+ INCLUDE_RE = re.compile(r"""["'](CPU:|USR:|CRD:|USB:)([^"']+)["']""")
35
+
36
+
37
+ def included_files(program: Path) -> list[str]:
38
+ """Logger paths of the library files the program includes, in source order.
39
+
40
+ Programs reference their libraries as IncludeSection("Functions",
41
+ "CPU:SomeLib.crb"); those files have to be on the logger before it can
42
+ compile the program.
43
+ """
44
+ found: list[str] = []
45
+ for line in program.read_text(errors="replace").splitlines():
46
+ if "include" not in line.lower():
47
+ continue
48
+ for drive, name in INCLUDE_RE.findall(line):
49
+ target = f"{drive}{name}"
50
+ if target not in found:
51
+ found.append(target)
52
+ return found
53
+
54
+
55
+ def reconnect(link: PakBusLink, port_override: str | None, timeout: float = 90) -> str | None:
56
+ """Wait for the logger's USB port to come back and reopen it.
57
+
58
+ The CR6 disconnects and re-enumerates its USB device while it compiles a
59
+ newly sent program, and the device node it comes back on can differ from
60
+ the one it left (ttyACM1 -> ttyACM0), so the port is looked up again.
61
+ """
62
+ link.close()
63
+ deadline = time.monotonic() + timeout
64
+ while time.monotonic() < deadline:
65
+ path = port_override or find_port()
66
+ if path and os.path.exists(path):
67
+ try:
68
+ link.open(path)
69
+ except serial.SerialException:
70
+ time.sleep(0.5)
71
+ continue
72
+ if link.hello():
73
+ return path
74
+ link.close()
75
+ time.sleep(0.5)
76
+ return None
77
+
78
+
79
+ def send_file(link: PakBusLink, source: Path, target: str) -> bool:
80
+ data = source.read_bytes()
81
+
82
+ def progress(sent: int, total: int) -> None:
83
+ print(f"\r {target}: {sent}/{total} bytes", end="", flush=True)
84
+
85
+ code = link.file_download(target, data, progress=progress)
86
+ print()
87
+ if code != 0:
88
+ print(f" {target}: download failed, response code {code}", file=sys.stderr)
89
+ return False
90
+ return True
91
+
92
+
93
+ def describe(stats: dict) -> str:
94
+ if stats.get("resp_code"):
95
+ return f"(get programming statistics failed, response code {stats['resp_code']})"
96
+ return f"OS {stats['os_version']}, serial {stats['serial_number']}, running {stats['program_name'] or '<none>'}"
97
+
98
+
99
+ def monitor(link: PakBusLink, seconds: float, send: bytes = b"") -> None:
100
+ """Print whatever the running program writes to ComUSB.
101
+
102
+ The tester programs in crbasic/ are menu driven and stay silent until they
103
+ receive a keystroke, so `send` is written first when given.
104
+ """
105
+ if send:
106
+ link.port.write(send)
107
+ link.port.flush()
108
+ print(f"--- ComUSB output for {seconds:g} s ---")
109
+ deadline = time.monotonic() + seconds
110
+ pending = bytearray()
111
+ text = TextFilter()
112
+ while time.monotonic() < deadline:
113
+ chunk = link.port.read(256)
114
+ if not chunk:
115
+ continue
116
+ pending.extend(text.feed(chunk))
117
+ while b"\n" in pending:
118
+ line, _, rest = pending.partition(b"\n")
119
+ pending = bytearray(rest)
120
+ print(line.decode("ascii", "replace").rstrip("\r"))
121
+ if pending:
122
+ print(pending.decode("ascii", "replace").rstrip())
123
+ print("--- end of ComUSB output ---")
124
+
125
+
126
+ def main() -> int:
127
+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
128
+ parser.add_argument("program", type=Path, help="CRBasic program to send (.CR6)")
129
+ parser.add_argument("--port", help="serial port (default: autodetected CR6)")
130
+ parser.add_argument("--baudrate", type=int, default=115200)
131
+ parser.add_argument("--address", type=int, default=1, help="PakBus address of the logger (default: 1)")
132
+ parser.add_argument(
133
+ "--my-address", type=int, default=4094, help="PakBus address to use for this host (default: 4094)"
134
+ )
135
+ parser.add_argument("--drive", default="CPU:", help="target drive (default: CPU:)")
136
+ parser.add_argument("--no-compile", action="store_true", help="skip the CR6Comp.exe check and send the file as-is")
137
+ parser.add_argument("--no-includes", action="store_true", help="do not send the library files the program includes")
138
+ parser.add_argument(
139
+ "--no-run", action="store_true", help="write the file to the logger but do not compile and run it"
140
+ )
141
+ parser.add_argument(
142
+ "--monitor", type=float, metavar="SECONDS", default=0, help="after flashing, print ComUSB output for this long"
143
+ )
144
+ parser.add_argument(
145
+ "--send",
146
+ metavar="TEXT",
147
+ default="",
148
+ help=r"text to write to ComUSB before monitoring, e.g. '\r' "
149
+ "to make a menu-driven tester show its menu",
150
+ )
151
+ parser.add_argument("--timeout", type=float, default=60, help="seconds to wait for compile results (default: 60)")
152
+ parser.add_argument("--debug", action="store_true", help="dump PakBus packets")
153
+ args = parser.parse_args()
154
+
155
+ program = args.program.resolve()
156
+ if not program.is_file():
157
+ print(f"no such program: {program}", file=sys.stderr)
158
+ return 1
159
+
160
+ if not args.no_compile:
161
+ if not compile_program(program):
162
+ print("compilation failed - nothing was sent to the logger", file=sys.stderr)
163
+ return 1
164
+
165
+ port = args.port or find_port()
166
+ if not port:
167
+ print("no CR6 serial port found (is the logger attached to WSL?)", file=sys.stderr)
168
+ return 1
169
+
170
+ target = f"{args.drive}{program.name}"
171
+ includes = [] if args.no_includes else included_files(program)
172
+ print(f"{program.name} -> {target} via {port}")
173
+
174
+ try:
175
+ with PakBusLink(port, args.baudrate, node=args.address, my_node=args.my_address, debug=args.debug) as link:
176
+ if not link.hello():
177
+ print("logger did not answer the hello; trying the transfer anyway")
178
+ print(describe(link.get_program_stats()))
179
+
180
+ for include in includes:
181
+ source = program.parent / Path(include.split(":", 1)[1]).name
182
+ if not source.is_file():
183
+ print(f" {include}: no local copy next to the program, not sent")
184
+ continue
185
+ if not send_file(link, source, include):
186
+ return 1
187
+ if not send_file(link, program, target):
188
+ return 1
189
+
190
+ if args.no_run:
191
+ return 0
192
+
193
+ code, hold_off = link.file_control(target, FILECTL_COMPILE_RUN_POWERUP)
194
+ if code != 0:
195
+ print(f"file control failed, response code {code}", file=sys.stderr)
196
+ return 1
197
+ print(f"compiling and running {target}" + (f" (logger asked for {hold_off} s)" if hold_off else ""))
198
+ time.sleep(max(hold_off, 2))
199
+
200
+ path = reconnect(link, args.port)
201
+ if path is None:
202
+ print("the logger's USB port did not come back after the compile", file=sys.stderr)
203
+ return 1
204
+ if path != port:
205
+ print(f"logger came back on {path}")
206
+
207
+ deadline = time.monotonic() + args.timeout
208
+ stats: dict = {}
209
+ while time.monotonic() < deadline:
210
+ try:
211
+ stats = link.get_program_stats()
212
+ except PakBusError:
213
+ time.sleep(1)
214
+ continue
215
+ if stats.get("resp_code") == 0 and stats.get("program_name", "").endswith(program.name):
216
+ break
217
+ time.sleep(1)
218
+
219
+ if not stats or stats.get("resp_code"):
220
+ print("could not read compile results back from the logger", file=sys.stderr)
221
+ return 1
222
+
223
+ print(f"running program: {stats['program_name']}")
224
+ print(f"compile results: {stats['compile_result'].strip() or '<empty>'}")
225
+ failed = "error" in stats["compile_result"].lower()
226
+
227
+ if args.monitor:
228
+ monitor(link, args.monitor, args.send.encode().decode("unicode_escape").encode("ascii"))
229
+
230
+ return 1 if failed else 0
231
+ except PakBusError as exc:
232
+ print(f"PakBus error: {exc}", file=sys.stderr)
233
+ return 1
234
+ except serial.SerialException as exc:
235
+ print(f"serial error: {exc}", file=sys.stderr)
236
+ return 1
237
+
238
+
239
+ if __name__ == "__main__":
240
+ sys.exit(main())
@@ -0,0 +1,84 @@
1
+ #!/usr/bin/env python3
2
+ """Read the CR6 clock, or set it to the host's UTC time.
3
+
4
+ `architecture.md` derives every schedule index in `Main.CR6` from the logger's own clock and
5
+ requires that clock to be UTC. The logger stores no time zone, so a logger left on local time
6
+ silently shifts the whole grid, including the SBD send unit of day.
7
+ """
8
+
9
+ import argparse
10
+ import datetime
11
+ import sys
12
+ import time
13
+
14
+ from .pakbus import PakBusError, PakBusLink, find_port
15
+
16
+
17
+ def main() -> int:
18
+ parser = argparse.ArgumentParser(description=__doc__)
19
+ parser.add_argument("--port", help="serial port (default: autodetected CR6)")
20
+ parser.add_argument(
21
+ "--set-utc",
22
+ action="store_true",
23
+ help="set the logger to the host's current UTC time",
24
+ )
25
+ parser.add_argument(
26
+ "--max-drift",
27
+ type=float,
28
+ default=0.5,
29
+ help="seconds of remaining offset to accept after a set (default: 0.5)",
30
+ )
31
+ args = parser.parse_args()
32
+
33
+ port = args.port or find_port()
34
+ if port is None:
35
+ print("no CR6 serial port found; is it attached to WSL?", file=sys.stderr)
36
+ return 1
37
+
38
+ with PakBusLink(port) as link:
39
+ if not link.hello():
40
+ print("the logger did not answer a hello", file=sys.stderr)
41
+ return 1
42
+
43
+ before = time.time()
44
+ logger = link.clock()
45
+ after = time.time()
46
+ host = datetime.datetime.fromtimestamp((before + after) / 2, datetime.UTC)
47
+ offset = (logger - host).total_seconds()
48
+
49
+ print(f"logger {logger.isoformat(timespec='milliseconds')}")
50
+ print(f"host UTC {host.isoformat(timespec='milliseconds')}")
51
+ print(f"offset {offset:+.3f} s (logger minus host, round trip {after - before:.3f} s)")
52
+
53
+ if not args.set_utc:
54
+ return 0
55
+
56
+ # The adjustment is applied by the logger to its own clock, so it is sent as the
57
+ # negated offset measured a moment earlier; the transport delay is what limits the
58
+ # result, which is why the outcome is measured again rather than assumed.
59
+ adjust = -offset
60
+ whole = int(adjust)
61
+ nanos = int(round((adjust - whole) * 1e9))
62
+ print(f"adjusting {adjust:+.3f} s")
63
+ try:
64
+ link.clock(whole, nanos)
65
+ except PakBusError as exc:
66
+ print(f"clock set failed: {exc}", file=sys.stderr)
67
+ return 1
68
+
69
+ before = time.time()
70
+ logger = link.clock()
71
+ after = time.time()
72
+ host = datetime.datetime.fromtimestamp((before + after) / 2, datetime.UTC)
73
+ offset = (logger - host).total_seconds()
74
+ print(f"logger now {logger.isoformat(timespec='milliseconds')}")
75
+ print(f"offset now {offset:+.3f} s")
76
+
77
+ if abs(offset) > args.max_drift:
78
+ print(f"offset still above {args.max_drift} s", file=sys.stderr)
79
+ return 1
80
+ return 0
81
+
82
+
83
+ if __name__ == "__main__":
84
+ raise SystemExit(main())