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

255 statements  

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

1"""Click CLI for the SignalK v2 History API.""" 

2 

3from __future__ import annotations 

4 

5import contextlib 

6import csv 

7import json 

8import re 

9import sys 

10from collections.abc import Callable, Generator, Iterable 

11from datetime import UTC, datetime 

12from pathlib import Path 

13from typing import Any 

14from urllib.parse import urlparse 

15 

16import click 

17import niquests 

18 

19from .._arrow import FEATHER_EXTENSIONS, write_feather 

20from .._cli import bare_option, host_option, resolve_host, stderr_ctx 

21from ..errors import SignalKError, api_error 

22from ._results import CARDINALITY_COLUMNS 

23from ._time import TimeRange 

24from .api import AGGREGATION_METHODS, HistoryClient, HistoryResult 

25from .output import ( 

26 cardinality_text, 

27 write_csv, 

28 write_csv_wide, 

29 write_json, 

30 write_json_wide, 

31) 

32 

33_AUTO_OUTPUT = "__auto_output__" 

34 

35# --------------------------------------------------------------------------- 

36# Shared option decorators 

37# --------------------------------------------------------------------------- 

38 

39 

40def _list_fmt_callback( 

41 ctx: click.Context, param: click.Parameter, value: str | None 

42) -> str | None: 

43 if value is None: 43 ↛ 44line 43 didn't jump to line 44 because the condition on line 43 was never true

44 return value 

45 v = value.lower() 

46 if v in ("csv", "json", "raw"): 

47 return v 

48 if v == "feather": 

49 raise click.BadParameter( 

50 "feather output is only available on the `query` command " 

51 "(requires pip install 'signalk-cli[feather]')" 

52 ) 

53 raise click.BadParameter(f"'{value}' is not one of 'csv', 'json', 'raw'") 

54 

55 

56_host_option = host_option 

57_resolve_host = resolve_host 

58 

59 

60def _provider_options[F: Callable[..., Any]](f: F) -> F: 

61 f = click.option("--no-cache", is_flag=True, help="Ignore cached default provider")( 

62 f 

63 ) 

64 f = click.option( 

65 "--provider", 

66 help="History provider plugin id (default fetched and cached automatically)", 

67 )(f) 

68 return f 

69 

70 

71def _time_options[F: Callable[..., Any]](f: F) -> F: 

72 f = click.option( 

73 "--duration", 

74 metavar="DURATION", 

75 help="Duration: integer seconds or ISO 8601 (e.g. PT15M, 3600)", 

76 )(f) 

77 f = click.option("--to", metavar="DATETIME", help="End of range (ISO 8601)")(f) 

78 f = click.option( 

79 "--from", "from_", metavar="DATETIME", help="Start of range (ISO 8601)" 

80 )(f) 

81 return f 

82 

83 

84_bare_option = bare_option 

85_stderr_ctx = stderr_ctx 

86 

87 

88def _client( 

89 host: str | None, 

90 provider: str | None = None, 

91 no_cache: bool = False, 

92 context: str = "vessels.self", 

93) -> HistoryClient: 

94 return HistoryClient( 

95 resolve_host(host, no_cache), 

96 provider=provider, 

97 context=context, 

98 cache=not no_cache, 

99 ) 

100 

101 

102@contextlib.contextmanager 

103def _exit_on_error(doing: str) -> Generator[None]: 

104 """Report a failed request as 'Error <doing>: <message>' and exit 1.""" 

105 try: 

106 yield 

107 except SignalKError as e: 

108 click.echo(f"Error {doing}: {e}", err=True) 

109 sys.exit(1) 

110 except niquests.RequestException as e: # failures mid-way through a streamed body 

111 click.echo(f"Error {doing}: {api_error(e)}", err=True) 

112 sys.exit(1) 

113 

114 

115def _echo_time(time_params: dict[str, Any], width: int) -> None: 

116 for label, key, missing in ( 

117 ("From:", "from", "(server default)"), 

118 ("To:", "to", "(server default)"), 

119 ("Duration:", "duration", "(not specified)"), 

120 ): 

121 click.echo(f"{label:<{width}}{time_params.get(key, missing)}", err=True) 

122 

123 

124def _summary(table_paths: Iterable[str], row_count: int) -> str: 

125 unique = sorted(set(table_paths)) 

126 return f"{row_count} rows, {len(unique)} unique path(s): {', '.join(unique)}" 

127 

128 

129# --------------------------------------------------------------------------- 

130# CLI group 

131# --------------------------------------------------------------------------- 

132 

133 

134@click.group(context_settings={"help_option_names": ["-h", "--help"]}) 

135def cli() -> None: 

136 """SignalK v2 history CLI.""" 

137 

138 

139# --------------------------------------------------------------------------- 

140# query 

141# --------------------------------------------------------------------------- 

142 

143 

144@cli.command() 

145@click.argument("paths", nargs=-1, required=True, metavar="PATH...") 

146@_host_option 

147@_time_options 

148@click.option( 

149 "--resolution", 

150 metavar="RESOLUTION", 

151 help="Sample window: integer seconds or time expression (1s, 1m, 1h, 1d)", 

152) 

153@click.option( 

154 "--context", "-c", default="vessels.self", show_default=True, help="SignalK context" 

155) 

156@_provider_options 

157@click.option( 

158 "--aggregation", 

159 "--agg", 

160 "aggregation", 

161 type=click.Choice(AGGREGATION_METHODS, case_sensitive=False), 

162 default=None, 

163 help=( 

164 "Aggregation method applied to all paths. " 

165 "Omit for wide mode (min/max/average columns). " 

166 "Paths may also carry an inline ':method[:param]' suffix." 

167 ), 

168) 

169@click.option( 

170 "--samples", 

171 type=int, 

172 default=None, 

173 metavar="N", 

174 help="Sample count for --aggregation sma", 

175) 

176@click.option( 

177 "--alpha", 

178 type=float, 

179 default=None, 

180 metavar="FLOAT", 

181 help="Alpha value (0-1) for --aggregation ema", 

182) 

183@click.option( 

184 "--format", 

185 "fmt", 

186 default=None, 

187 type=click.Choice(["csv", "feather", "json", "raw"], case_sensitive=False), 

188 help="Output format (default: inferred from --output extension, else csv)", 

189) 

190@click.option("--no-header", is_flag=True, help="Suppress header row (CSV only)") 

191@click.option( 

192 "--output", 

193 "-o", 

194 is_flag=False, 

195 flag_value=_AUTO_OUTPUT, 

196 default=None, 

197 metavar="FILE", 

198 help="Write to FILE. Omit for stdout (default). Give without a filename to auto-name the file.", 

199) 

200@click.option( 

201 "--pretty", 

202 is_flag=True, 

203 help="Pretty-print JSON output (json/raw formats). Buffers the full response.", 

204) 

205@_bare_option 

206def query( 

207 paths: tuple[str, ...], 

208 host: str | None, 

209 from_: str | None, 

210 to: str | None, 

211 duration: str | None, 

212 resolution: str | None, 

213 context: str, 

214 provider: str | None, 

215 no_cache: bool, 

216 aggregation: str | None, 

217 samples: int | None, 

218 alpha: float | None, 

219 fmt: str | None, 

220 no_header: bool, 

221 output: str | None, 

222 pretty: bool, 

223 bare: bool, 

224) -> None: 

225 """Query history and write results as CSV, JSON, or Feather. 

226 

227 Outputs to stdout by default. Use --output to write to a file. 

228 

229 PATH arguments may be literal SignalK paths, Python regex/glob patterns, 

230 or inline path specs with aggregation (e.g. navigation.speedOverGround:sma:5). 

231 

232 Without --aggregation and without inline specs, the default is wide mode: 

233 min/max/average are fetched per path and written as separate columns. 

234 

235 \b 

236 Examples: 

237 signalk_cli.history query --host 10.36.10.21 --duration PT1H navigation.speedOverGround 

238 signalk_cli.history query --host 10.36.10.21 --duration PT1H --agg sma --samples 5 '*' 

239 signalk_cli.history query --host 10.36.10.21 --duration PT1H navigation.speedOverGround:ema:0.2 

240 signalk_cli.history query --host 10.36.10.21 --from 2026-05-26T00:00:00Z --to 2026-05-27T00:00:00Z '*' 

241 """ 

242 with _stderr_ctx(bare): 

243 client = _client(host, provider, no_cache, context) 

244 time = TimeRange(from_, to, duration).resolved() 

245 time_params = time.params() 

246 

247 auto_name = output == _AUTO_OUTPUT 

248 

249 # Infer format from explicit output filename extension 

250 if fmt is None: 

251 if output and output not in (_AUTO_OUTPUT, "-"): 

252 suffix = Path(output).suffix.lower() 

253 if suffix in FEATHER_EXTENSIONS: 

254 fmt = "feather" 

255 elif suffix == ".json": 

256 fmt = "json" 

257 else: 

258 fmt = "csv" 

259 else: 

260 fmt = "csv" 

261 

262 # Generate auto-named file path now that format is known 

263 if auto_name: 

264 server_name = urlparse(client.host).hostname or re.sub( 

265 r"[^\w.-]", "_", client.host 

266 ) 

267 ts = datetime.now(UTC).strftime("%Y%m%dT%H%M%SZ") 

268 ext = ( 

269 ".feather" 

270 if fmt == "feather" 

271 else ".json" 

272 if fmt in ("json", "raw") 

273 else ".csv" 

274 ) 

275 output = f"signalk-history-{server_name}-{ts}{ext}" 

276 

277 out_file = None if output is None or output == "-" else output 

278 write_to_stdout = out_file is None 

279 write_to_file = not write_to_stdout 

280 

281 if fmt == "feather" and write_to_stdout: 

282 raise click.UsageError( 

283 "feather cannot be written to stdout (binary format); " 

284 "use --output FILE or --output to auto-name" 

285 ) 

286 

287 click.echo(f"Server: {client.host}", err=True) 

288 click.echo(f"Provider: {client.provider or '(none)'}", err=True) 

289 click.echo(f"Context: {context}", err=True) 

290 _echo_time(time_params, 13) 

291 click.echo(f"Resolution: {resolution or '(server default)'}", err=True) 

292 click.echo(f"Format: {fmt}", err=True) 

293 

294 with _exit_on_error("resolving paths"): 

295 resolved = client.expand_paths(list(paths), time) 

296 

297 if not resolved: 

298 click.echo("No paths matched — nothing to query.", err=True) 

299 sys.exit(1) 

300 

301 params, wide_mode = client.value_params( 

302 resolved, 

303 time, 

304 aggregation=aggregation, 

305 samples=samples, 

306 alpha=alpha, 

307 resolution=resolution, 

308 expand=False, 

309 ) 

310 agg_label = aggregation or ("wide (min/max/average)" if wide_mode else "inline") 

311 click.echo(f"Aggregation: {agg_label}", err=True) 

312 

313 # raw + stdout + no pretty: stream response bytes directly 

314 if fmt == "raw" and write_to_stdout and not pretty: 

315 with ( 

316 _exit_on_error("fetching history"), 

317 client.fetch("values", params, stream=True) as resp, 

318 ): 

319 for chunk in resp.iter_content(chunk_size=65536, decode_unicode=True): 

320 sys.stdout.write(chunk) 

321 sys.stdout.write("\n") 

322 return 

323 

324 with _exit_on_error("fetching history"): 

325 resp = client.fetch("values", params) 

326 

327 indent = 2 if pretty else None 

328 

329 if fmt == "feather" and out_file is not None: 

330 table = HistoryResult(resp.json(), wide=wide_mode).to_arrow() 

331 write_feather(table, out_file) 

332 click.echo(f"Wrote {output}", err=True) 

333 click.echo(_summary(table.to_pydict()["path"], table.num_rows), err=True) 

334 return 

335 

336 if fmt == "raw": 

337 text = ( 

338 json.dumps(resp.json(), indent=indent) if pretty else (resp.text or "") 

339 ) 

340 if out_file is not None: 

341 Path(out_file).write_text(text) 

342 click.echo(f"Wrote {output}", err=True) 

343 else: 

344 sys.stdout.write(text + "\n") 

345 return 

346 

347 result = resp.json() 

348 with ( 

349 open(out_file, "w", newline="") 

350 if out_file is not None 

351 else contextlib.nullcontext(sys.stdout) 

352 ) as sink: 

353 if fmt == "json": 

354 writer = write_json_wide if wide_mode else write_json 

355 row_count, unique_paths = writer(result, sink, indent=indent) 

356 if not write_to_file: 

357 sink.write("\n") 

358 else: 

359 csv_writer = write_csv_wide if wide_mode else write_csv 

360 row_count, unique_paths = csv_writer(result, sink, no_header) 

361 if write_to_file: 

362 click.echo(f"Wrote {output}", err=True) 

363 click.echo(_summary(unique_paths, row_count), err=True) 

364 

365 

366# --------------------------------------------------------------------------- 

367# cardinality 

368# --------------------------------------------------------------------------- 

369 

370 

371@cli.command() 

372@click.argument("paths", nargs=-1, required=False, metavar="PATH...") 

373@_host_option 

374@_time_options 

375@click.option( 

376 "--resolution", 

377 metavar="RESOLUTION", 

378 help="Sample window: integer seconds or time expression (1s, 1m, 1h, 1d)", 

379) 

380@click.option( 

381 "--context", "-c", default="vessels.self", show_default=True, help="SignalK context" 

382) 

383@_provider_options 

384@click.option( 

385 "--format", 

386 "fmt", 

387 metavar="[csv|json]", 

388 default="csv", 

389 callback=_list_fmt_callback, 

390 help="Output format: csv or json", 

391) 

392@click.option("--no-header", is_flag=True, help="Suppress header row (CSV only)") 

393@_bare_option 

394def cardinality( 

395 paths: tuple[str, ...], 

396 host: str | None, 

397 from_: str | None, 

398 to: str | None, 

399 duration: str | None, 

400 resolution: str | None, 

401 context: str, 

402 provider: str | None, 

403 no_cache: bool, 

404 fmt: str, 

405 no_header: bool, 

406 bare: bool, 

407) -> None: 

408 """Compute per-path value statistics for the given time range. 

409 

410 Outputs a table of: path, distinct_values, min, max, average, 

411 distinct_values_2_decimal_places, nulls. 

412 

413 For non-scalar values (e.g. navigation.position) min/max/average and 

414 distinct_values_2_decimal_places are left blank. 

415 

416 \b 

417 Examples: 

418 signalk_cli.history cardinality --host 10.36.10.21 --duration PT1H navigation.speedOverGround 

419 signalk_cli.history cardinality --host 10.36.10.21 --duration PT1H '*' 

420 """ 

421 with _stderr_ctx(bare): 

422 client = _client(host, provider, no_cache, context) 

423 time = TimeRange(from_, to, duration).resolved() 

424 

425 click.echo(f"Server: {client.host}", err=True) 

426 click.echo(f"Provider: {client.provider or '(none)'}", err=True) 

427 click.echo(f"Context: {context}", err=True) 

428 _echo_time(time.params(), 13) 

429 click.echo(f"Resolution: {resolution or '(server default)'}", err=True) 

430 

431 with _exit_on_error("resolving paths"): 

432 resolved = client.expand_paths(list(paths) or ["*"], time) 

433 

434 if not resolved: 

435 click.echo("No paths matched — nothing to query.", err=True) 

436 sys.exit(1) 

437 

438 with _exit_on_error("fetching history"): 

439 stat_rows = [ 

440 cardinality_text(r) 

441 for r in client.cardinality_rows(resolved, time, resolution=resolution) 

442 ] 

443 

444 if fmt == "json": 

445 click.echo(json.dumps(stat_rows, indent=2)) 

446 else: 

447 writer = csv.writer(sys.stdout) 

448 if not no_header: 

449 writer.writerow(CARDINALITY_COLUMNS) 

450 for row in stat_rows: 

451 writer.writerow([row[col] for col in CARDINALITY_COLUMNS]) 

452 

453 click.echo(f"{len(stat_rows)} path(s)", err=True) 

454 

455 

456# --------------------------------------------------------------------------- 

457# list-paths 

458# --------------------------------------------------------------------------- 

459 

460 

461@cli.command("list-paths") 

462@_host_option 

463@_time_options 

464@_provider_options 

465@click.option( 

466 "--context", "-c", default="vessels.self", show_default=True, help="SignalK context" 

467) 

468@click.option( 

469 "--format", 

470 "fmt", 

471 metavar="[csv|json|raw]", 

472 default="csv", 

473 callback=_list_fmt_callback, 

474 help="Output format: csv (one item per line), json (re-serialized), or raw (exact API response body). Feather is only available on `query` (requires signalk-cli[feather]).", 

475) 

476@_bare_option 

477def list_paths( 

478 host: str | None, 

479 from_: str | None, 

480 to: str | None, 

481 duration: str | None, 

482 provider: str | None, 

483 no_cache: bool, 

484 context: str, 

485 fmt: str, 

486 bare: bool, 

487) -> None: 

488 """List paths that have data for the given time range.""" 

489 with _stderr_ctx(bare): 

490 client = _client(host, provider, no_cache, context) 

491 time = TimeRange(from_, to, duration).resolved() 

492 

493 click.echo(f"Server: {client.host}", err=True) 

494 click.echo(f"Provider: {client.provider or '(none)'}", err=True) 

495 _echo_time(time.params(), 10) 

496 

497 with _exit_on_error("fetching paths"): 

498 if fmt == "raw": 

499 click.echo(client.fetch("paths", client.request_params(time)).text) 

500 return 

501 paths = client.paths(time) 

502 if fmt == "json": 

503 click.echo(json.dumps([{"path": p} for p in paths])) 

504 else: 

505 click.echo("path") 

506 for path in paths: 

507 click.echo(path) 

508 click.echo(f"{len(paths)} path(s)", err=True) 

509 

510 

511# --------------------------------------------------------------------------- 

512# list-providers 

513# --------------------------------------------------------------------------- 

514 

515 

516@cli.command("list-providers") 

517@_host_option 

518@click.option( 

519 "--format", 

520 "fmt", 

521 metavar="[csv|json|raw]", 

522 default="csv", 

523 callback=_list_fmt_callback, 

524 help="Output format: csv (one item per line), json (re-serialized), or raw (exact API response body). Feather is only available on `query` (requires signalk-cli[feather]).", 

525) 

526@_bare_option 

527def list_providers(host: str | None, fmt: str, bare: bool) -> None: 

528 """List registered history providers.""" 

529 with _stderr_ctx(bare): 

530 client = _client(host) 

531 click.echo(f"Server: {client.host}", err=True) 

532 

533 with _exit_on_error("fetching providers"): 

534 if fmt == "raw": 

535 click.echo(client.fetch("_providers").text) 

536 return 

537 providers = client.providers() 

538 

539 if fmt == "json": 

540 rows = [ 

541 {"provider": pid, **info} for pid, info in sorted(providers.items()) 

542 ] 

543 click.echo(json.dumps(rows)) 

544 else: 

545 writer = csv.writer(sys.stdout) 

546 writer.writerow(["provider", "isDefault"]) 

547 for pid, info in sorted(providers.items()): 

548 writer.writerow([pid, info.get("isDefault", False)]) 

549 click.echo(f"{len(providers)} provider(s)", err=True) 

550 

551 

552# --------------------------------------------------------------------------- 

553# list-contexts 

554# --------------------------------------------------------------------------- 

555 

556 

557@cli.command("list-contexts") 

558@_host_option 

559@_time_options 

560@_provider_options 

561@click.option( 

562 "--format", 

563 "fmt", 

564 metavar="[csv|json|raw]", 

565 default="csv", 

566 callback=_list_fmt_callback, 

567 help="Output format: csv (one item per line), json (re-serialized), or raw (exact API response body). Feather is only available on `query` (requires signalk-cli[feather]).", 

568) 

569@_bare_option 

570def list_contexts( 

571 host: str | None, 

572 from_: str | None, 

573 to: str | None, 

574 duration: str | None, 

575 provider: str | None, 

576 no_cache: bool, 

577 fmt: str, 

578 bare: bool, 

579) -> None: 

580 """List contexts that have historical data for the given time range.""" 

581 with _stderr_ctx(bare): 

582 client = _client(host, provider, no_cache) 

583 time = TimeRange(from_, to, duration).resolved() 

584 

585 click.echo(f"Server: {client.host}", err=True) 

586 click.echo(f"Provider: {client.provider or '(none)'}", err=True) 

587 _echo_time(time.params(), 10) 

588 

589 with _exit_on_error("fetching contexts"): 

590 if fmt == "raw": 

591 click.echo(client.fetch("contexts", client.request_params(time)).text) 

592 return 

593 contexts = client.contexts(time) 

594 

595 if fmt == "json": 

596 click.echo(json.dumps([{"context": c} for c in contexts])) 

597 else: 

598 click.echo("context") 

599 for ctx in contexts: 

600 click.echo(ctx) 

601 click.echo(f"{len(contexts)} context(s)", err=True)