Coverage for src/signalk_cli/stream/api.py: 100%
134 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"""Python API for the SignalK v1 Streaming (delta) API.
3Spec: https://signalk.org/specification/1.8.2/doc/streaming_api.html
4Subscribe path wildcards: https://signalk.org/specification/1.8.2/doc/subscription_protocol.html
6Examples:
7 ```python
8 from signalk_cli.stream import StreamClient
9 client = StreamClient("http://boat.local:3000")
10 table = client.collect(["navigation.*"], count=100, policy="instant")
11 import polars as pl
12 df = pl.DataFrame(table)
13 ```
14"""
16from __future__ import annotations
18import fnmatch
19import json
20from collections.abc import Iterator, Sequence
21from dataclasses import dataclass
22from typing import Any, Literal, NamedTuple, Self
23from urllib.parse import urlparse, urlunparse
25import niquests
27from .._arrow import ArrowTable
28from ..errors import SignalKError
29from ..net import normalise_host
31STREAM_PATH = "/signalk/v1/stream"
33SUBSCRIBE_POLICIES = ["none", "self", "all"]
34SUBSCRIPTION_POLICIES = ["instant", "ideal", "fixed"]
36Subscribe = Literal["none", "self", "all"]
37Policy = Literal["instant", "ideal", "fixed"]
40def to_ws_url(host: str) -> str:
41 """Convert an http(s) host base URL to the ws(s) streaming endpoint URL."""
42 parsed = urlparse(host)
43 scheme = "wss" if parsed.scheme == "https" else "ws"
44 return urlunparse((scheme, parsed.netloc, STREAM_PATH, "", "", ""))
47def build_subscribe_message(
48 context: str,
49 paths: Sequence[str],
50 *,
51 period_ms: int | None = None,
52 policy: str | None = None,
53 min_period_ms: int | None = None,
54) -> dict[str, Any]:
55 """Build a client subscribe message for the given context and paths.
57 An empty path list subscribes to all paths within the context (equivalent
58 to a single "*" path). Paths are passed through unchanged — wildcarding is
59 handled server-side per the SignalK Subscription Protocol: "*" at the end
60 of a path matches any suffix (e.g. "navigation.*"), and "*" as a middle
61 segment matches any single segment there (e.g. "propulsion.*.oilTemperature").
63 period_ms/policy/min_period_ms map directly to the per-path "period",
64 "policy", and "minPeriod" fields of the Subscription Protocol and are
65 applied identically to every path when given. `policy`
66 ("instant"/"ideal"/"fixed") defaults to "ideal" server-side if omitted;
67 `min_period_ms` only affects the "instant" policy. The protocol also
68 defines a per-path "format" ("delta"/"full") field, but it's omitted
69 here: signalk-server rejects "full" outright and always sends delta
70 messages regardless, so exposing the choice would be misleading.
71 """
72 entry_extra: dict[str, Any] = {}
73 if period_ms is not None:
74 entry_extra["period"] = period_ms
75 if policy is not None:
76 entry_extra["policy"] = policy
77 if min_period_ms is not None:
78 entry_extra["minPeriod"] = min_period_ms
80 path_list = list(paths) if paths else ["*"]
81 return {
82 "context": context,
83 "subscribe": [{"path": p, **entry_extra} for p in path_list],
84 }
87# ---------------------------------------------------------------------------
88# Messages and rows
89# ---------------------------------------------------------------------------
92def source_matches(source: str, patterns: Sequence[str]) -> bool:
93 """Match a `$source` string against source filter patterns (OR'd).
95 No patterns means no filtering (always matches). A pattern containing
96 glob metacharacters (`*`/`?`/`[`) is matched as-is via `fnmatch`;
97 otherwise it's treated as a substring match, e.g. "Teltonika" matches
98 the source "Teltonika.GP".
99 """
100 if not patterns:
101 return True
102 return any(
103 fnmatch.fnmatch(source, p if any(c in p for c in "*?[") else f"*{p}*")
104 for p in patterns
105 )
108def _update_source(update: dict[str, Any]) -> str:
109 return update.get("$source") or json.dumps(update.get("source", {}))
112class DeltaRow(NamedTuple):
113 """One value (or meta entry) from a delta message.
115 `value` keeps its JSON type: a number, string, bool, object, array, or None.
116 `kind` is `"value"`, or `"meta"` for metadata entries (units,
117 description, zones, ...).
118 """
120 timestamp: str
121 context: str
122 source: str
123 path: str
124 kind: str
125 value: Any
128@dataclass(frozen=True)
129class DeltaMessage:
130 """A delta message from the server.
132 Attributes:
133 text: The message exactly as received.
134 payload: The decoded message.
135 """
137 text: str
138 payload: dict[str, Any]
140 def rows(
141 self, *, include_meta: bool = False, sources: Sequence[str] = ()
142 ) -> list[DeltaRow]:
143 """Flatten into rows, one per value.
145 Args:
146 include_meta: Also include each update's "meta" entries, as rows
147 with `kind="meta"`.
148 sources: Only include updates whose `$source` matches one of
149 these patterns (see [`source_matches()`][signalk_cli.stream.api.source_matches]).
150 """
151 context = self.payload.get("context", "")
152 rows: list[DeltaRow] = []
153 for update in self.payload.get("updates", []):
154 source = _update_source(update)
155 if not source_matches(source, sources):
156 continue
157 timestamp = update.get("timestamp", "")
158 kinds = ["values", "meta"] if include_meta else ["values"]
159 for key in kinds:
160 for entry in update.get(key, []):
161 rows.append(
162 DeltaRow(
163 timestamp,
164 context,
165 source,
166 entry.get("path", ""),
167 "value" if key == "values" else "meta",
168 entry.get("value"),
169 )
170 )
171 return rows
173 def matches_sources(self, sources: Sequence[str]) -> bool:
174 """True if any update in the message comes from a matching `$source`."""
175 return not sources or any(
176 source_matches(_update_source(u), sources)
177 for u in self.payload.get("updates", [])
178 )
181def rows_to_arrow(
182 rows: Sequence[DeltaRow], *, include_meta: bool = False
183) -> ArrowTable:
184 """Convert delta rows to a table: UTC `timestamp`, `context`, `source`,
185 `path`, `kind` (only with `include_meta`) and `value`.
187 `value` is float64 if every value is a number, otherwise text, with
188 objects and arrays as JSON.
189 """
190 text = ["context", "source", "path", "kind"]
191 columns: dict[str, list[Any]] = {
192 "context": [r.context for r in rows],
193 "source": [r.source for r in rows],
194 "path": [r.path for r in rows],
195 }
196 if include_meta:
197 columns["kind"] = [r.kind for r in rows]
198 columns["value"] = [r.value for r in rows]
199 return ArrowTable.from_rows(
200 [r.timestamp or None for r in rows], columns, text_columns=text
201 )
204# ---------------------------------------------------------------------------
205# Stream and client
206# ---------------------------------------------------------------------------
209class DeltaStream:
210 """An open subscription. Iterate it for [`DeltaMessage`][signalk_cli.stream.api.DeltaMessage] objects.
212 Use as a context manager, or call [`close()`][signalk_cli.stream.api.DeltaStream.close], to close the connection.
214 Raises:
215 SignalKError: While iterating, if the connection is lost.
216 """
218 def __init__(self, ws: Any) -> None:
219 self._ws = ws
221 def __enter__(self) -> Self:
222 return self
224 def __exit__(self, *exc: object) -> None:
225 self.close()
227 def close(self) -> None:
228 """Close the WebSocket connection."""
229 self._ws.close()
231 def __iter__(self) -> Iterator[DeltaMessage]:
232 return self.messages()
234 def messages(self, count: int | None = None) -> Iterator[DeltaMessage]:
235 """Yield delta messages, skipping control messages such as the server's hello.
237 Stops after `count` messages if given, or when the server closes
238 the connection.
239 """
240 yielded = 0
241 while count is None or yielded < count:
242 try:
243 payload = self._ws.next_payload()
244 except niquests.RequestException as e:
245 raise SignalKError.from_request(e) from e
246 if payload is None:
247 return
248 if isinstance(payload, bytes):
249 payload = payload.decode("utf-8", errors="replace")
250 try:
251 message = json.loads(payload)
252 except (TypeError, json.JSONDecodeError):
253 continue
254 if not isinstance(message, dict) or "updates" not in message:
255 continue
256 yield DeltaMessage(payload, message)
257 yielded += 1
259 def rows(
260 self,
261 count: int | None = None,
262 *,
263 include_meta: bool = False,
264 sources: Sequence[str] = (),
265 ) -> Iterator[DeltaRow]:
266 """Yield rows from the next `count` messages (see [`rows()`][signalk_cli.stream.api.DeltaMessage.rows])."""
267 for message in self.messages(count):
268 yield from message.rows(include_meta=include_meta, sources=sources)
270 def collect(
271 self,
272 count: int | None = None,
273 *,
274 include_meta: bool = False,
275 sources: Sequence[str] = (),
276 ) -> ArrowTable:
277 """Read `count` messages (or until the server closes) into a table.
279 See [`rows_to_arrow()`][signalk_cli.stream.api.rows_to_arrow] for the columns.
280 """
281 rows = list(self.rows(count, include_meta=include_meta, sources=sources))
282 return rows_to_arrow(rows, include_meta=include_meta)
285class StreamClient:
286 """Client for a SignalK server's v1 Streaming (delta) API.
288 Args:
289 host: Server URL, e.g. `http://boat.local:3000` (`http://` is
290 added if there's no scheme).
291 context: SignalK context to subscribe to. Accepts the wildcard
292 `*` (or `vessels.*`) for every vessel.
293 subscribe: The connection-level auto-subscription the server adds at
294 its own default rate: `"none"` (default), `"self"` or
295 `"all"`. It's in addition to the explicit subscription for
296 `context`; `"none"` avoids receiving your own vessel twice.
297 session: A niquests session to connect with. One is created (and
298 closed with the client) if not given.
299 """
301 def __init__(
302 self,
303 host: str,
304 *,
305 context: str = "vessels.self",
306 subscribe: Subscribe = "none",
307 session: niquests.Session | None = None,
308 ) -> None:
309 self.host = normalise_host(host).rstrip("/")
310 self.context = context
311 self.subscribe = subscribe
312 self._owns_session = session is None
313 self._session = session if session is not None else niquests.Session()
315 def __enter__(self) -> Self:
316 return self
318 def __exit__(self, *exc: object) -> None:
319 self.close()
321 def close(self) -> None:
322 """Close the session, if the client created it."""
323 if self._owns_session:
324 self._session.close()
326 def open(
327 self,
328 paths: Sequence[str] = (),
329 *,
330 policy: Policy | None = "ideal",
331 period: float | None = 60.0,
332 min_period: float | None = None,
333 timeout: float | None = 30,
334 ) -> DeltaStream:
335 """Connect and subscribe, returning the open [`DeltaStream`][signalk_cli.stream.api.DeltaStream].
337 Args:
338 paths: Paths to subscribe to; all paths if empty. `*` wildcards
339 are matched by the server, at the end of a path
340 (`navigation.*`) or as a whole segment
341 (`propulsion.*.oilTemperature`).
342 policy: `"instant"` sends every change (limited by
343 `min_period`); `"ideal"` also resends the last value if
344 nothing changes within `period`; `"fixed"` sends the last
345 value every `period`.
346 period: Resend interval in seconds for `ideal`/`fixed`.
347 min_period: Fastest send rate in seconds, for `instant`.
348 timeout: Seconds to wait for each message, or None to wait
349 indefinitely (a quiet subscription may send nothing for a
350 long time).
352 Raises:
353 SignalKError: If the connection fails.
354 """
355 try:
356 resp = self._session.get(
357 to_ws_url(self.host),
358 params={"subscribe": self.subscribe},
359 timeout=timeout,
360 )
361 resp.raise_for_status()
362 except niquests.RequestException as e:
363 raise SignalKError.from_request(e) from e
364 ws = resp.extension
365 if ws is None:
366 raise SignalKError(
367 f"{self.host} did not accept a WebSocket connection "
368 "(is niquests installed with the 'ws' extra?)"
369 )
370 message = build_subscribe_message(
371 self.context,
372 paths,
373 period_ms=None if period is None else int(period * 1000),
374 policy=policy,
375 min_period_ms=None if min_period is None else int(min_period * 1000),
376 )
377 ws.send_payload(json.dumps(message))
378 return DeltaStream(ws)
380 def collect(
381 self,
382 paths: Sequence[str] = (),
383 *,
384 count: int,
385 include_meta: bool = False,
386 sources: Sequence[str] = (),
387 policy: Policy | None = "ideal",
388 period: float | None = 60.0,
389 min_period: float | None = None,
390 timeout: float | None = 30,
391 ) -> ArrowTable:
392 """Subscribe, read `count` delta messages into a table, and disconnect.
394 Arguments are as for [`open()`][signalk_cli.stream.api.StreamClient.open] and [`collect()`][signalk_cli.stream.api.DeltaStream.collect].
395 """
396 with self.open(
397 paths,
398 policy=policy,
399 period=period,
400 min_period=min_period,
401 timeout=timeout,
402 ) as stream:
403 return stream.collect(count, include_meta=include_meta, sources=sources)