Coverage for src/signalk_cli/stream/cli.py: 99%
106 statements
« prev ^ index » next coverage.py v7.17.2, created at 2026-11-22 09:25 +0000
« prev ^ index » next coverage.py v7.17.2, created at 2026-11-22 09:25 +0000
1"""Click CLI for the SignalK v1 Streaming (delta) API."""
3from __future__ import annotations
5import re
6import sys
7from datetime import UTC, datetime
8from pathlib import Path
9from urllib.parse import urlparse
11import click
13from .._arrow import FEATHER_EXTENSIONS, write_feather
14from .._cli import bare_option, host_option, resolve_host, stderr_ctx
15from ..errors import SignalKError
16from .api import (
17 SUBSCRIBE_POLICIES,
18 SUBSCRIPTION_POLICIES,
19 DeltaRow,
20 Policy,
21 StreamClient,
22 Subscribe,
23 rows_to_arrow,
24)
25from .output import (
26 write_csv_header,
27 write_csv_rows,
28 write_json_rows,
29 write_values_rows,
30)
32_AUTO_OUTPUT = "__auto_output__"
34# ---------------------------------------------------------------------------
35# CLI group
36# ---------------------------------------------------------------------------
39@click.group(context_settings={"help_option_names": ["-h", "--help"]})
40def cli() -> None:
41 """SignalK v1 streaming (delta) CLI."""
44# ---------------------------------------------------------------------------
45# deltas
46# ---------------------------------------------------------------------------
49@cli.command()
50@click.argument("paths", nargs=-1, required=False, metavar="PATH...")
51@host_option
52@click.option("--no-cache", is_flag=True, help="Ignore cached host")
53@click.option(
54 "--context",
55 "-c",
56 default="vessels.self",
57 show_default=True,
58 help="SignalK context for the explicit subscription this command "
59 "always sends. Also accepts the SignalK wildcard '*' (or 'vessels.*') "
60 "to subscribe to every vessel at your own --policy/--period — the "
61 "alternative to --subscribe all, which uses the server's default rate.",
62)
63@click.option(
64 "--subscribe",
65 type=click.Choice(SUBSCRIBE_POLICIES, case_sensitive=False),
66 default="none",
67 show_default=True,
68 help="Connection-level auto-subscribe at the server's OWN default "
69 "policy/period — separate from, and in addition to, this command's "
70 "explicit --context subscription above. Defaults to 'none' (the "
71 "SignalK spec's own default is 'self') to avoid double-subscribing "
72 "your own context. 'all' adds other vessels at the server's rate; for "
73 "other vessels at your chosen rate, use --context '*' instead.",
74)
75@click.option(
76 "--policy",
77 type=click.Choice(SUBSCRIPTION_POLICIES, case_sensitive=False),
78 default="ideal",
79 show_default=True,
80 help="Per-path subscribe policy (SignalK Subscription Protocol 'policy' "
81 "field): 'instant' sends every change, throttled by --min-period; "
82 "'ideal' (default) behaves like instant but resends the last value if "
83 "nothing changes within --period; 'fixed' always sends the last known "
84 "value every --period regardless of changes.",
85)
86@click.option(
87 "--period",
88 type=float,
89 default=60.0,
90 show_default=True,
91 metavar="SECONDS",
92 help="Subscribe period in seconds — the resend interval used by the "
93 "'ideal'/'fixed' policies. Converted to milliseconds on the wire.",
94)
95@click.option(
96 "--min-period",
97 "min_period",
98 type=float,
99 default=None,
100 metavar="SECONDS",
101 help="Fastest allowed transmission rate in seconds; only meaningful "
102 "with --policy instant. Converted to milliseconds on the wire.",
103)
104@click.option(
105 "--format",
106 "fmt",
107 default=None,
108 type=click.Choice(
109 ["csv", "json", "raw", "feather", "values"], case_sensitive=False
110 ),
111 help="Output format (default: inferred from --output extension, else csv). "
112 "json is JSON Lines (one row object per line). raw is the exact delta "
113 "message text, one per line. values is the bare value only, one per "
114 "line — no timestamp/context/source/path/kind columns. feather requires "
115 "pip install 'signalk-cli[feather]' and --output (cannot stream to stdout).",
116)
117@click.option("--no-header", is_flag=True, help="Suppress header row (CSV only)")
118@click.option(
119 "--include-meta",
120 is_flag=True,
121 help="Also emit rows for 'meta' entries (units, description, zones, etc.), "
122 "not just 'values'. Adds a 'kind' column (value/meta) to csv/json/feather "
123 "output. Ignored for --format raw, which always includes meta as-is.",
124)
125@click.option(
126 "--source",
127 "source",
128 multiple=True,
129 metavar="PATTERN",
130 help="Only include updates whose $source matches PATTERN. Repeatable "
131 "(OR'd together). PATTERN is a substring match unless it contains a "
132 "glob metacharacter (*/?/[), in which case it's matched as a glob, "
133 "e.g. --source Teltonika or --source '*.GP'. Filtering is client-side, "
134 "applied after receipt — for --format raw (whole message, verbatim) a "
135 "message passes if ANY of its updates match; other formats filter "
136 "per-update.",
137)
138@click.option(
139 "--output",
140 "-o",
141 is_flag=False,
142 flag_value=_AUTO_OUTPUT,
143 default=None,
144 metavar="FILE",
145 help="Write to FILE. Omit for stdout (default). Give without a filename to "
146 "auto-name the file. Required for --format feather.",
147)
148@click.option(
149 "--follow",
150 "-f",
151 is_flag=True,
152 help="Keep streaming until interrupted (Ctrl-C) or --count is reached. "
153 "Without this, print the next message then exit.",
154)
155@click.option(
156 "--count",
157 "-n",
158 type=int,
159 default=None,
160 metavar="N",
161 help="Number of delta messages to output. Default: 1 without --follow, "
162 "unlimited with --follow.",
163)
164@bare_option
165def deltas(
166 paths: tuple[str, ...],
167 host: str | None,
168 no_cache: bool,
169 context: str,
170 subscribe: Subscribe,
171 policy: Policy,
172 period: float,
173 min_period: float | None,
174 fmt: str | None,
175 no_header: bool,
176 include_meta: bool,
177 source: tuple[str, ...],
178 output: str | None,
179 follow: bool,
180 count: int | None,
181 bare: bool,
182) -> None:
183 """Stream live delta updates from the SignalK v1 Streaming API.
185 Connects via WebSocket and prints delta messages as they arrive, in
186 csv, json (JSON Lines), raw, values (bare value only), or Feather
187 format.
189 Always sends an explicit subscribe message for --context, covering
190 PATH arguments if given, otherwise every path ('*'). PATH arguments
191 are sent verbatim to the server, one per path. They may be literal
192 SignalK paths (e.g. navigation.speedOverGround) or contain the
193 SignalK subscription wildcard '*', matched server-side per the
194 Subscription Protocol: '*' at the end of a path matches any suffix
195 (navigation.*), and '*' as a middle segment matches any single
196 segment there (propulsion.*.oilTemperature). Quote wildcarded paths
197 to stop the shell expanding them. --policy/--period/--min-period
198 control how that subscription behaves; --subscribe only controls
199 whether the connection *additionally* auto-subscribes at the
200 server's own default policy.
202 \b
203 Examples:
204 # Next update for one path, then exit
205 signalk_cli.stream deltas --host 10.36.10.21 navigation.speedOverGround
207 # Tail all navigation updates every 5s until Ctrl-C
208 signalk_cli.stream deltas --host 10.36.10.21 --follow --period 5 'navigation.*'
210 # Tail oil temperature across every engine, sent instantly on change
211 signalk_cli.stream deltas --host 10.36.10.21 --follow --policy instant \\
212 'propulsion.*.oilTemperature'
214 # Next 20 messages across all paths, as JSON Lines
215 signalk_cli.stream deltas --host 10.36.10.21 --format json --count 20
217 # Capture 100 messages to a Feather file (requires signalk-cli[feather])
218 signalk_cli.stream deltas --host 10.36.10.21 --count 100 -o capture.feather
220 # Bare speed values from one sensor, piped straight into another tool
221 signalk_cli.stream deltas --host 10.36.10.21 --follow --format values \\
222 --source Teltonika --bare navigation.speedOverGround
223 """
224 with stderr_ctx(bare):
225 client = StreamClient(
226 resolve_host(host, no_cache), context=context, subscribe=subscribe
227 )
229 auto_name = output == _AUTO_OUTPUT
231 if fmt is None:
232 if output and not auto_name and output != "-":
233 suffix = Path(output).suffix.lower()
234 if suffix in FEATHER_EXTENSIONS:
235 fmt = "feather"
236 elif suffix == ".json":
237 fmt = "json"
238 else:
239 fmt = "csv"
240 else:
241 fmt = "csv"
243 if auto_name:
244 server_name = urlparse(client.host).hostname or re.sub(
245 r"[^\w.-]", "_", client.host
246 )
247 ts = datetime.now(UTC).strftime("%Y%m%dT%H%M%SZ")
248 ext = (
249 ".feather"
250 if fmt == "feather"
251 else ".json"
252 if fmt in ("json", "raw")
253 else ".txt"
254 if fmt == "values"
255 else ".csv"
256 )
257 output = f"signalk-stream-{server_name}-{ts}{ext}"
259 out_file = None if output is None or output == "-" else output
260 write_to_stdout = out_file is None
261 write_to_file = not write_to_stdout
263 if fmt == "feather" and write_to_stdout:
264 raise click.UsageError(
265 "feather cannot be written to stdout (binary format); "
266 "use --output FILE or --output to auto-name"
267 )
269 click.echo(f"Server: {client.host}", err=True)
270 click.echo(f"Context: {context}", err=True)
271 click.echo(f"Subscribe: {subscribe}", err=True)
272 min_period_note = (
273 f", min_period={min_period}s" if min_period is not None else ""
274 )
275 click.echo(
276 f"Policy: {policy} (period={period}s{min_period_note})", err=True
277 )
278 click.echo(f"Format: {fmt}", err=True)
280 try:
281 stream = client.open(
282 paths,
283 policy=policy,
284 period=period,
285 min_period=min_period,
286 timeout=None if follow else 30,
287 )
288 except SignalKError as e:
289 click.echo(f"Error connecting to stream: {e}", err=True)
290 sys.exit(1)
292 effective_count = count if count is not None else (None if follow else 1)
294 message_count = 0
295 row_total = 0
296 header_written = False
297 feather_rows: list[DeltaRow] = []
298 fh = (
299 open(out_file, "w", newline="") # noqa: SIM115
300 if out_file is not None and fmt != "feather"
301 else None
302 )
303 sink = fh or sys.stdout
304 try:
305 for message in stream.messages(effective_count):
306 message_count += 1
307 if fmt == "raw":
308 if message.matches_sources(source):
309 click.echo(message.text, file=sink)
310 continue
311 rows = message.rows(include_meta=include_meta, sources=source)
312 if fmt == "feather":
313 feather_rows.extend(rows)
314 row_total = len(feather_rows)
315 elif fmt == "json":
316 row_total += write_json_rows(rows, sink, include_meta=include_meta)
317 elif fmt == "values":
318 row_total += write_values_rows(rows, sink)
319 else:
320 if not header_written and not no_header:
321 write_csv_header(sink, include_meta=include_meta)
322 header_written = True
323 row_total += write_csv_rows(rows, sink, include_meta=include_meta)
324 except KeyboardInterrupt:
325 pass
326 except SignalKError as e:
327 click.echo(f"Stream connection lost: {e}", err=True)
328 finally:
329 stream.close()
330 if fh:
331 fh.close()
333 if fmt == "feather" and out_file is not None:
334 write_feather(
335 rows_to_arrow(feather_rows, include_meta=include_meta), out_file
336 )
338 if write_to_file:
339 click.echo(f"Wrote {output}", err=True)
341 if fmt == "raw":
342 click.echo(f"{message_count} message(s)", err=True)
343 else:
344 click.echo(f"{message_count} message(s), {row_total} row(s)", err=True)