observe.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. #!/usr/bin/env python3
  2. """Subscribe to telemetry. Default: in-process MockClient (no daemon, no serial).
  3. Use --socket /run/hth/observe.sock to talk to a running hthd. Observe only.
  4. """
  5. from __future__ import annotations
  6. import argparse
  7. import asyncio
  8. import sys
  9. async def _run_mock(count: int) -> None:
  10. from hth_sdk.advanced import MockClient
  11. async with MockClient() as client:
  12. devices = await client.list_devices()
  13. print(f"devices={[d.device_id for d in devices]} backend=mock")
  14. n = 0
  15. async for event in client.subscribe_telemetry(devices[0].device_id):
  16. snap = event.snapshot
  17. print(
  18. f"seq={snap.snapshot_seq} epoch={snap.device_epoch} "
  19. f"lifecycle={snap.lifecycle} gap={event.data_gap} "
  20. f"epoch_changed={event.epoch_changed} confirm={snap.device_confirmation}"
  21. )
  22. n += 1
  23. if n >= count:
  24. return
  25. async def _run_socket(socket: str, count: int) -> None:
  26. from hth_sdk.advanced import connect_observe
  27. async with await connect_observe(socket) as client:
  28. devices = await client.list_devices()
  29. if not devices:
  30. print("no devices", file=sys.stderr)
  31. return
  32. n = 0
  33. async for event in client.subscribe_telemetry(devices[0].device_id):
  34. snap = event.snapshot
  35. print(
  36. f"seq={snap.snapshot_seq} epoch={snap.device_epoch} "
  37. f"lifecycle={snap.lifecycle} gap={event.data_gap} "
  38. f"epoch_changed={event.epoch_changed}"
  39. )
  40. n += 1
  41. if n >= count:
  42. return
  43. def main() -> int:
  44. p = argparse.ArgumentParser(description="Observe hth telemetry (mock by default).")
  45. p.add_argument("--socket", default="", help="observe Unix socket; empty = in-process mock")
  46. p.add_argument("--count", type=int, default=3)
  47. args = p.parse_args()
  48. if args.socket:
  49. asyncio.run(_run_socket(args.socket, args.count))
  50. else:
  51. asyncio.run(_run_mock(args.count))
  52. return 0
  53. if __name__ == "__main__":
  54. raise SystemExit(main())