Coverage for src/signalk_cli/history/api.py: 99%

181 statements  

« prev     ^ index     » next       coverage.py v7.17.2, created at 2026-11-22 09:25 +0000

1"""Python API for the SignalK v2 History API. 

2 

3Examples: 

4 ```python 

5 from signalk_cli.history import HistoryClient, TimeRange 

6 with HistoryClient("http://boat.local:3000") as client: 

7 table = client.query(["navigation.speedOverGround"], TimeRange(duration="PT1H")) 

8 import polars as pl 

9 df = pl.DataFrame(table) 

10 ``` 

11""" 

12 

13from __future__ import annotations 

14 

15import fnmatch 

16import logging 

17import re 

18from collections.abc import Sequence 

19from pathlib import Path 

20from typing import Any, Literal, Self 

21 

22import nanoarrow as na 

23import niquests 

24 

25from .._arrow import ArrowTable 

26from ..errors import SignalKError 

27from ..net import CACHE_DIR, normalise_host 

28from . import _results 

29from ._time import TimeRange 

30 

31logger = logging.getLogger("signalk_cli") 

32 

33HISTORY_BASE = "/signalk/v2/api/history" 

34 

35AGGREGATION_METHODS = ( 

36 "average", 

37 "min", 

38 "max", 

39 "first", 

40 "last", 

41 "mid", 

42 "middle_index", 

43 "sma", 

44 "ema", 

45) 

46 

47Shape = Literal["long", "wide"] 

48 

49# "." is left out: it's in every SignalK path, so a plain dotted path is a literal 

50_PATTERN_CHARS = set(r"*+?[](){}|^$\\") 

51_GLOB_ONLY_RE = re.compile(r"^[^.+(){}|^$\\]+$") 

52 

53 

54# --------------------------------------------------------------------------- 

55# Path specs and patterns 

56# --------------------------------------------------------------------------- 

57 

58 

59def build_path_specs( 

60 paths: Sequence[str], 

61 aggregation: str | None = None, 

62 samples: int | None = None, 

63 alpha: float | None = None, 

64) -> tuple[str, bool]: 

65 """Build the `paths` query parameter, with an aggregation method per path. 

66 

67 Paths that already carry a method (`navigation.speedOverGround:sma:5`) 

68 pass through unchanged. With no aggregation and no inline methods, each 

69 path is requested as min, average and max (wide shape), except position 

70 paths, which don't support those and are requested with `mid`. 

71 

72 Returns: 

73 `(paths_param, wide)`, where `wide` says the response should be 

74 read in the wide shape. 

75 """ 

76 if aggregation: 

77 specs = [] 

78 for path in paths: 

79 if ":" in path: 

80 specs.append(path) 

81 continue 

82 spec = f"{path}:{aggregation}" 

83 if aggregation == "sma" and samples is not None: 

84 spec += f":{samples}" 

85 elif aggregation == "ema" and alpha is not None: 

86 spec += f":{alpha}" 

87 specs.append(spec) 

88 return ",".join(specs), False 

89 

90 if any(":" in p for p in paths): 

91 return ",".join(paths), False 

92 

93 specs = [] 

94 for p in paths: 

95 if _results.POSITION_RE.fullmatch(p): 

96 specs.append(f"{p}:mid") 

97 else: 

98 specs.extend(f"{p}:{m}" for m in ("min", "average", "max")) 

99 return ",".join(specs), True 

100 

101 

102def _is_pattern(path: str) -> bool: 

103 return ":" not in path and any(c in path for c in _PATTERN_CHARS) 

104 

105 

106def _compile(pattern: str) -> re.Pattern[str]: 

107 if _GLOB_ONLY_RE.match(pattern): 

108 return re.compile(fnmatch.translate(pattern)) 

109 try: 

110 return re.compile(pattern) 

111 except re.PatternError: 

112 logger.info("Note: '%s' is not valid regex, treating as glob", pattern) 

113 return re.compile(fnmatch.translate(pattern)) 

114 

115 

116def match_paths(patterns: Sequence[str], available: Sequence[str]) -> list[str]: 

117 """Expand path patterns against a list of known paths. 

118 

119 Literal paths and inline specs (`path:method`) pass through unchanged. 

120 A path is a pattern if it contains any of `* ? + [ ] ( ) { } | ^ $ \\` 

121 (a `.` alone doesn't count, so `navigation.speedOverGround` is literal). 

122 Patterns are matched as globs (`navigation.*`) when they only use glob 

123 characters, otherwise as Python regular expressions (searched, not 

124 anchored); an invalid regex falls back to a glob. 

125 

126 Returns: 

127 The literal paths in the order given, followed by all matched paths, sorted. 

128 """ 

129 literals = [p for p in patterns if not _is_pattern(p)] 

130 matched: set[str] = set() 

131 for pattern in (p for p in patterns if _is_pattern(p)): 

132 rx = _compile(pattern) 

133 hits = {path for path in available if rx.search(path)} 

134 if not hits: 

135 logger.warning("Warning: '%s' matched no paths", pattern) 

136 matched |= hits 

137 return literals + sorted(matched) 

138 

139 

140# --------------------------------------------------------------------------- 

141# Results 

142# --------------------------------------------------------------------------- 

143 

144 

145class HistoryResult: 

146 """A /values response, with conversions to tables and statistics. 

147 

148 Attributes: 

149 payload: The decoded JSON response, as the server sent it. 

150 wide: True when the request asked for min/average/max per path, so 

151 the result reads naturally in the wide shape. 

152 """ 

153 

154 def __init__(self, payload: dict[str, Any], *, wide: bool = False) -> None: 

155 self.payload = payload 

156 self.wide = wide 

157 

158 @property 

159 def paths(self) -> list[str]: 

160 """Distinct paths in the response, in the order the server listed them.""" 

161 return list( 

162 dict.fromkeys(v.get("path", "") for v in self.payload.get("values", [])) 

163 ) 

164 

165 def to_arrow(self, shape: Shape | None = None) -> ArrowTable: 

166 """Convert to a table; see [`query()`][signalk_cli.history.api.HistoryClient.query] for the two shapes. 

167 

168 Args: 

169 shape: `"long"` or `"wide"`. Defaults to wide when the request 

170 asked for min/average/max, otherwise long. 

171 """ 

172 if (shape or ("wide" if self.wide else "long")) == "wide": 

173 timestamps, paths, cols = _results.wide_rows(self.payload) 

174 return ArrowTable.from_rows( 

175 timestamps, {"path": paths, **cols}, text_columns=["path"] 

176 ) 

177 timestamps, paths, values = _results.long_rows(self.payload) 

178 return ArrowTable.from_rows( 

179 timestamps, {"path": paths, "value": values}, text_columns=["path"] 

180 ) 

181 

182 def cardinality(self) -> list[dict[str, Any]]: 

183 """Per-path statistics; see [`cardinality()`][signalk_cli.history.api.HistoryClient.cardinality].""" 

184 return _results.cardinality(self.payload) 

185 

186 

187def _cardinality_table(rows: list[dict[str, Any]]) -> ArrowTable: 

188 columns: dict[str, tuple[list[Any], Any]] = { 

189 "path": ([r["path"] for r in rows], na.string()) 

190 } 

191 for col in _results.CARDINALITY_COLUMNS[1:]: 

192 values = [r[col] for r in rows] 

193 if col in ("min", "max", "average"): 

194 columns[col] = ( 

195 [None if v is None else float(v) for v in values], 

196 na.float64(), 

197 ) 

198 else: 

199 columns[col] = (values, na.int64()) 

200 return ArrowTable(columns) 

201 

202 

203# --------------------------------------------------------------------------- 

204# Client 

205# --------------------------------------------------------------------------- 

206 

207 

208class HistoryClient: 

209 """Client for a SignalK server's v2 History API. 

210 

211 Args: 

212 host: Server URL, e.g. `http://boat.local:3000` (`http://` is 

213 added if there's no scheme). 

214 provider: History provider plugin id. Defaults to the server's 

215 default provider, looked up on first use. 

216 context: SignalK context to query, e.g. `vessels.self`. 

217 session: A niquests session to send requests with. One is created 

218 (and closed with the client) if not given. 

219 cache: Remember each server's default provider on disk, under 

220 `~/.cache/signalk-cli`, to save a request next time. 

221 timeout: Seconds to wait for each response. 

222 

223 Raises: 

224 SignalKError: From any method, when a request fails. 

225 """ 

226 

227 def __init__( 

228 self, 

229 host: str, 

230 *, 

231 provider: str | None = None, 

232 context: str = "vessels.self", 

233 session: niquests.Session | None = None, 

234 cache: bool = False, 

235 timeout: float = 60, 

236 ) -> None: 

237 self.host = normalise_host(host).rstrip("/") 

238 self.base_url = self.host + HISTORY_BASE 

239 self.context = context 

240 self.timeout = timeout 

241 self._provider = provider 

242 self._provider_resolved = provider is not None 

243 self._cache = cache 

244 self._owns_session = session is None 

245 self._session = session if session is not None else niquests.Session() 

246 

247 def __enter__(self) -> Self: 

248 return self 

249 

250 def __exit__(self, *exc: object) -> None: 

251 self.close() 

252 

253 def close(self) -> None: 

254 """Close the session, if the client created it.""" 

255 if self._owns_session: 

256 self._session.close() 

257 

258 # -- low level ---------------------------------------------------------- 

259 

260 def fetch( 

261 self, 

262 endpoint: str, 

263 params: dict[str, Any] | None = None, 

264 *, 

265 stream: bool = False, 

266 ) -> niquests.Response: 

267 """GET a History API endpoint (e.g. `"values"`, `"paths"`) and return the response. 

268 

269 A low-level escape hatch for callers that want the raw response body; 

270 the other methods are usually more convenient. 

271 """ 

272 try: 

273 resp = self._session.get( 

274 f"{self.base_url}/{endpoint}", 

275 params=params, 

276 timeout=self.timeout, 

277 stream=stream, 

278 ) 

279 resp.raise_for_status() 

280 except niquests.RequestException as e: 

281 raise SignalKError.from_request(e) from e 

282 return resp 

283 

284 def _get_json(self, endpoint: str, params: dict[str, Any] | None = None) -> Any: 

285 return self.fetch(endpoint, params).json() 

286 

287 # -- providers ---------------------------------------------------------- 

288 

289 def providers(self) -> dict[str, dict[str, Any]]: 

290 """Registered history providers, as `{id: {"isDefault": bool, ...}}`.""" 

291 providers: dict[str, dict[str, Any]] = self._get_json("_providers") 

292 return providers 

293 

294 def default_provider(self) -> str: 

295 """The id of the server's default history provider.""" 

296 provider_id: str = self._get_json("_providers/_default")["id"] 

297 return provider_id 

298 

299 def _provider_cache_file(self) -> Path: 

300 return CACHE_DIR / f"{re.sub(r'[^\w.-]', '_', self.host)}.provider" 

301 

302 @property 

303 def provider(self) -> str | None: 

304 """The provider used for requests: the one given, else the server's default. 

305 

306 The default is fetched once (or read from the disk cache if enabled). 

307 If it can't be fetched, requests go without one and the server picks. 

308 """ 

309 if self._provider_resolved: 

310 return self._provider 

311 self._provider_resolved = True 

312 cache_file = self._provider_cache_file() 

313 if self._cache: 

314 try: 

315 self._provider = cache_file.read_text().strip() or None 

316 except OSError: 

317 pass 

318 if not self._provider: 

319 try: 

320 self._provider = self.default_provider() 

321 except SignalKError as e: 

322 logger.warning("Warning: could not fetch default provider: %s", e) 

323 return None 

324 if self._cache: 

325 try: 

326 CACHE_DIR.mkdir(parents=True, exist_ok=True) 

327 cache_file.write_text(self._provider) 

328 except OSError: 

329 pass 

330 return self._provider 

331 

332 def request_params( 

333 self, time: TimeRange | None = None, **extra: Any 

334 ) -> dict[str, Any]: 

335 """Query parameters for a request: the time range, provider, and any extras given. 

336 

337 Useful with [`fetch()`][signalk_cli.history.api.HistoryClient.fetch]; `None` extras are left out. 

338 """ 

339 params: dict[str, Any] = (time or TimeRange()).resolved().params() 

340 if self.provider: 

341 params["provider"] = self.provider 

342 params.update({k: v for k, v in extra.items() if v is not None}) 

343 return params 

344 

345 # -- discovery ---------------------------------------------------------- 

346 

347 def contexts(self, time: TimeRange | None = None) -> list[str]: 

348 """Contexts (vessels, aircraft, ...) with data in the time range, sorted.""" 

349 return sorted(self._get_json("contexts", self.request_params(time))) 

350 

351 def paths(self, time: TimeRange | None = None) -> list[str]: 

352 """Paths with data in the time range, sorted.""" 

353 return sorted(self._get_json("paths", self.request_params(time))) 

354 

355 def expand_paths( 

356 self, patterns: Sequence[str], time: TimeRange | None = None 

357 ) -> list[str]: 

358 """Expand glob/regex patterns to the matching paths with data in the time range. 

359 

360 Only fetches the server's path list if there's a pattern to match. 

361 See [`match_paths()`][signalk_cli.history.api.match_paths] for the matching rules. 

362 """ 

363 if not any(_is_pattern(p) for p in patterns): 

364 return list(patterns) 

365 logger.info("Resolving patterns against server paths...") 

366 return match_paths(patterns, self.paths(time)) 

367 

368 # -- data --------------------------------------------------------------- 

369 

370 def value_params( 

371 self, 

372 paths: Sequence[str], 

373 time: TimeRange | None = None, 

374 *, 

375 aggregation: str | None = None, 

376 samples: int | None = None, 

377 alpha: float | None = None, 

378 resolution: str | int | None = None, 

379 context: str | None = None, 

380 expand: bool = True, 

381 ) -> tuple[dict[str, Any], bool]: 

382 """The query parameters [`values()`][signalk_cli.history.api.HistoryClient.values] sends, and whether the result is wide. 

383 

384 Useful with [`fetch()`][signalk_cli.history.api.HistoryClient.fetch] to get the raw response body. Arguments are 

385 as for [`values()`][signalk_cli.history.api.HistoryClient.values]. 

386 """ 

387 time = (time or TimeRange()).resolved() 

388 resolved = self.expand_paths(paths, time) if expand else list(paths) 

389 if not resolved: 

390 raise ValueError("No paths to query") 

391 spec, wide = build_path_specs(resolved, aggregation, samples, alpha) 

392 params = self.request_params( 

393 time, 

394 paths=spec, 

395 context=context or self.context, 

396 resolution=resolution, 

397 ) 

398 return params, wide 

399 

400 def values( 

401 self, 

402 paths: Sequence[str], 

403 time: TimeRange | None = None, 

404 *, 

405 aggregation: str | None = None, 

406 samples: int | None = None, 

407 alpha: float | None = None, 

408 resolution: str | int | None = None, 

409 context: str | None = None, 

410 expand: bool = True, 

411 ) -> HistoryResult: 

412 """Fetch values for the given paths, as a [`HistoryResult`][signalk_cli.history.api.HistoryResult]. 

413 

414 Args: 

415 paths: Paths, glob/regex patterns, or inline specs such as 

416 `navigation.speedOverGround:sma:5`. 

417 time: Time range; defaults to the last hour. 

418 aggregation: Method applied to each path without an inline spec, 

419 one of [`AGGREGATION_METHODS`][signalk_cli.history.api.AGGREGATION_METHODS]. If neither this nor 

420 inline specs are given, min/average/max are fetched (wide). 

421 samples: Window size for `sma`. 

422 alpha: Smoothing factor for `ema`. 

423 resolution: Sample window, as seconds or an expression like `1m`. 

424 context: Overrides the client's context for this request. 

425 expand: Expand patterns in `paths` first (see [`expand_paths()`][signalk_cli.history.api.HistoryClient.expand_paths]). 

426 

427 Raises: 

428 ValueError: If no paths are left to query after expansion. 

429 """ 

430 params, wide = self.value_params( 

431 paths, 

432 time, 

433 aggregation=aggregation, 

434 samples=samples, 

435 alpha=alpha, 

436 resolution=resolution, 

437 context=context, 

438 expand=expand, 

439 ) 

440 return HistoryResult(self._get_json("values", params), wide=wide) 

441 

442 def query( 

443 self, 

444 paths: Sequence[str], 

445 time: TimeRange | None = None, 

446 *, 

447 shape: Shape | None = None, 

448 aggregation: str | None = None, 

449 samples: int | None = None, 

450 alpha: float | None = None, 

451 resolution: str | int | None = None, 

452 context: str | None = None, 

453 ) -> ArrowTable: 

454 """Fetch values as a table for polars, pandas, pyarrow, DuckDB, etc. 

455 

456 Both shapes have one row per timestamp and path, with a UTC 

457 `timestamp` column and a `path` column: 

458 

459 - **long**: a single `value` column. It's float64 if every value is 

460 a number, otherwise text, with objects and arrays as JSON. 

461 - **wide**: `min_value`/`avg_value`/`max_value` for number paths, 

462 and one column per element for array paths (`longitude`/`latitude` 

463 for positions, otherwise `value_0`, `value_1`, ...). 

464 

465 !!! warning 

466 Wide column names may change in a future release. 

467 

468 The other arguments are as for 

469 [`values()`][signalk_cli.history.api.HistoryClient.values]. 

470 

471 Args: 

472 shape: Defaults to wide if no aggregation or inline spec is 

473 given (min/average/max are fetched), otherwise long. 

474 """ 

475 return self.values( 

476 paths, 

477 time, 

478 aggregation=aggregation, 

479 samples=samples, 

480 alpha=alpha, 

481 resolution=resolution, 

482 context=context, 

483 ).to_arrow(shape) 

484 

485 def cardinality( 

486 self, 

487 paths: Sequence[str] = ("*",), 

488 time: TimeRange | None = None, 

489 *, 

490 resolution: str | int | None = None, 

491 context: str | None = None, 

492 ) -> ArrowTable: 

493 """Per-path statistics over the time range, as a table. 

494 

495 Columns: `path`, `distinct_values`, 

496 `distinct_values_2_decimal_places`, `nulls`, `zeroes`, `min`, 

497 `max`, `average`. `min`/`max`/`average` are null unless every 

498 value of the path is a number. 

499 """ 

500 return _cardinality_table( 

501 self.cardinality_rows(paths, time, resolution=resolution, context=context) 

502 ) 

503 

504 def cardinality_rows( 

505 self, 

506 paths: Sequence[str] = ("*",), 

507 time: TimeRange | None = None, 

508 *, 

509 resolution: str | int | None = None, 

510 context: str | None = None, 

511 ) -> list[dict[str, Any]]: 

512 """Like [`cardinality()`][signalk_cli.history.api.HistoryClient.cardinality], as a list of dicts.""" 

513 time = (time or TimeRange()).resolved() 

514 resolved = self.expand_paths(paths, time) 

515 if not resolved: 

516 raise ValueError("No paths to query") 

517 params = self.request_params( 

518 time, 

519 paths=",".join(resolved), 

520 context=context or self.context, 

521 resolution=resolution, 

522 ) 

523 return _results.cardinality(self._get_json("values", params))