Реализован встроенный navigation API поверх текущего MQTT backend. Добавлены api и каталог объектов в config/r2z-backend.yaml (line 55), новые типы и парсинг конфига в types.py (line 87) и config.py (line 24), in-memory state store в navigation_state.py (line 1) и aiohttp REST/WebSocket сервер в navigation_api.py (line 1). Сервис в service.py (line 1) теперь обновляет object state на валидных MQTT сообщениях, запускает API в том же процессе и рассылает full snapshot при изменениях.
API покрывает GET /api/v1/objects, GET /api/v1/objects/locations, GET /api/v1/objects/{object_id} и GET /api/v1/stream/locations. Статусы вычисляются из heartbeat/location freshness, object_id берётся из agent_id, а name и object_type идут из каталога в конфиге. Обновил README и добавил aiohttp в pyproject.toml (line 1).
This commit is contained in:
parent
05e9ad4743
commit
f3a1472f62
13
README.md
13
README.md
|
|
@ -2,6 +2,8 @@
|
|||
|
||||
Python service that subscribes to MQTT telemetry topics and forwards mapped metrics to Zabbix through `zabbix_sender`.
|
||||
|
||||
It also exposes a built-in navigation API that serves the current object catalog and live coordinates over REST and WebSocket.
|
||||
|
||||
## Spool
|
||||
|
||||
When `spool.enabled` is set, every incoming MQTT message is persisted as NDJSON for downstream machine processing.
|
||||
|
|
@ -11,6 +13,17 @@ When `spool.enabled` is set, every incoming MQTT message is persisted as NDJSON
|
|||
|
||||
Each valid record contains `status`, `received_at`, `topic`, and `event`. Invalid records contain `status`, `received_at`, `topic`, `raw_payload`, and `parse_error`.
|
||||
|
||||
## Navigation API
|
||||
|
||||
When `api.enabled` is set, the backend keeps an in-memory object state store keyed by MQTT `agent_id` and exposes:
|
||||
|
||||
- `GET /api/v1/objects`
|
||||
- `GET /api/v1/objects/locations`
|
||||
- `GET /api/v1/objects/{object_id}`
|
||||
- `GET /api/v1/stream/locations`
|
||||
|
||||
Object metadata (`name`, `object_type`) comes from `api.objects` in the YAML config. Status values are derived from heartbeat freshness and location freshness using `offline_timeout_ms` and `stale_timeout_ms`.
|
||||
|
||||
## Run
|
||||
|
||||
```bash
|
||||
|
|
|
|||
|
|
@ -52,6 +52,30 @@ spool:
|
|||
# Flush each appended record to disk immediately.
|
||||
flush_each_write: true
|
||||
|
||||
api:
|
||||
# Enable built-in navigation REST/WebSocket API.
|
||||
enabled: true
|
||||
# API bind host.
|
||||
host: 127.0.0.1
|
||||
# API bind port.
|
||||
port: 8080
|
||||
# Mark location as stale after this age.
|
||||
stale_timeout_ms: 5000
|
||||
# Mark object as offline after this heartbeat age.
|
||||
offline_timeout_ms: 10000
|
||||
coordinate_system:
|
||||
type: local_relative
|
||||
unit: meter
|
||||
origin: site_origin
|
||||
axis:
|
||||
x: east
|
||||
y: north
|
||||
z: up
|
||||
objects:
|
||||
h1500-09-01-00011:
|
||||
name: Robot 31
|
||||
object_type: robot
|
||||
|
||||
zabbix:
|
||||
# Path to the zabbix_sender binary.
|
||||
sender_path: zabbix_sender
|
||||
|
|
@ -130,55 +154,6 @@ mapping:
|
|||
host_path: agent_id
|
||||
value_path: payload.freq
|
||||
|
||||
#{
|
||||
# "message_id": "cmd-7755693f6c8a4a4bb027493a94bf6c55",
|
||||
# "agent_id": "wfagent",
|
||||
# "agent_instance_id": "wfagent_wlp3s0_imac",
|
||||
# "site_id": "lab",
|
||||
# "created_at": "2026-07-01T15:18:14.158123Z",
|
||||
# "payload": {
|
||||
# "command_result": {
|
||||
# "returned_data": {
|
||||
# "data_type": "kv",
|
||||
# "payload": { "TXGOOD": "227658", "TXBAD": "0", "RXGOOD": "541721" }
|
||||
|
||||
# metrics:
|
||||
# - key: wifi.pktcnt.tx_good
|
||||
# # Send the metric to the Zabbix host named after the agent instance.
|
||||
# host_path: agent_instance_id
|
||||
# # Successful TX packet counter from `PKTCNT_POLL`.
|
||||
# value_path: payload.command_result.returned_data.payload.TXGOOD
|
||||
# - key: wifi.pktcnt.tx_bad
|
||||
# # Send the metric to the same host as the rest of the agent metrics.
|
||||
# host_path: agent_instance_id
|
||||
# # Failed TX packet counter from `PKTCNT_POLL`.
|
||||
# value_path: payload.command_result.returned_data.payload.TXBAD
|
||||
# - key: wifi.pktcnt.rx_good
|
||||
# # Send the metric to the same host as the rest of the agent metrics.
|
||||
# host_path: agent_instance_id
|
||||
# # Successful RX packet counter from `PKTCNT_POLL`.
|
||||
# value_path: payload.command_result.returned_data.payload.RXGOOD
|
||||
|
||||
# wifi/vostok/31/wifi_counter
|
||||
# {
|
||||
# "schema_version": "1.1",
|
||||
# "message_id": "caccc538-82b8-4844-89bf-cf2aa118e467",
|
||||
# "message_kind": "wifi_counter",
|
||||
# "agent_id": "h1500-09-01-00011",
|
||||
# "robot_id": "h1500",
|
||||
# "platform": "linux",
|
||||
# "observed_at_unix_ms": 1782483081730,
|
||||
# "sent_at_unix_ms": 1782483081746,
|
||||
# "payload": {
|
||||
# "tx_pkt_good":255,
|
||||
# "tx_pkt_bad":0,
|
||||
# "rx_pkt_good":634,
|
||||
# "location":{
|
||||
# "x": -91.9,
|
||||
# "y": 64.7
|
||||
# }
|
||||
# }
|
||||
# }
|
||||
- id: mqtt-wifi-counter
|
||||
# Map Wi-Fi packet counters to long-lived numeric items.
|
||||
enabled: true
|
||||
|
|
@ -302,8 +277,8 @@ mapping:
|
|||
min_exclusive: -67
|
||||
- name: yellow
|
||||
key: wifi.scan.signal.yellow_count
|
||||
min_exclusive: -75
|
||||
min_exclusive: -78
|
||||
max_inclusive: -67
|
||||
- name: red
|
||||
key: wifi.scan.signal.red_count
|
||||
max_inclusive: -75
|
||||
max_inclusive: -78
|
||||
|
|
|
|||
|
|
@ -9,6 +9,7 @@ description = "MQTT to Zabbix adapter for robot Wi-Fi telemetry"
|
|||
readme = "README.md"
|
||||
requires-python = ">=3.11"
|
||||
dependencies = [
|
||||
"aiohttp>=3.9,<4",
|
||||
"paho-mqtt>=2.1.0,<3",
|
||||
"PyYAML>=6.0.1,<7",
|
||||
]
|
||||
|
|
|
|||
|
|
@ -5,13 +5,17 @@ from pathlib import Path
|
|||
import yaml
|
||||
|
||||
from .types import (
|
||||
ApiConfig,
|
||||
AppConfig,
|
||||
CoordinateAxisConfig,
|
||||
CoordinateSystemConfig,
|
||||
LoggingConfig,
|
||||
MappingRule,
|
||||
MatchConfig,
|
||||
MetricConfig,
|
||||
MqttConfig,
|
||||
MqttTlsConfig,
|
||||
ObjectCatalogEntry,
|
||||
ScanSignalBucket,
|
||||
ScanSignalBucketRule,
|
||||
SpoolConfig,
|
||||
|
|
@ -30,6 +34,9 @@ def load_config(path: str | Path) -> AppConfig:
|
|||
spool_raw = data.get("spool", {})
|
||||
if not isinstance(spool_raw, dict):
|
||||
raise ValueError("spool must be a mapping")
|
||||
api_raw = data.get("api", {})
|
||||
if not isinstance(api_raw, dict):
|
||||
raise ValueError("api must be a mapping")
|
||||
zabbix_raw = _require_mapping(data, "zabbix")
|
||||
mapping_raw = _require_mapping(data, "mapping")
|
||||
|
||||
|
|
@ -109,6 +116,26 @@ def load_config(path: str | Path) -> AppConfig:
|
|||
)
|
||||
)
|
||||
|
||||
coordinate_system_raw = api_raw.get("coordinate_system", {})
|
||||
if not isinstance(coordinate_system_raw, dict):
|
||||
raise ValueError("api.coordinate_system must be a mapping")
|
||||
axis_raw = coordinate_system_raw.get("axis", {})
|
||||
if not isinstance(axis_raw, dict):
|
||||
raise ValueError("api.coordinate_system.axis must be a mapping")
|
||||
objects_raw = api_raw.get("objects", {})
|
||||
if not isinstance(objects_raw, dict):
|
||||
raise ValueError("api.objects must be a mapping")
|
||||
objects: dict[str, ObjectCatalogEntry] = {}
|
||||
for object_id, object_raw in objects_raw.items():
|
||||
if not isinstance(object_id, str) or not object_id:
|
||||
raise ValueError("api.objects keys must be non-empty strings")
|
||||
if not isinstance(object_raw, dict):
|
||||
raise ValueError("Each api.objects entry must be a mapping")
|
||||
objects[object_id] = ObjectCatalogEntry(
|
||||
name=_require_str(object_raw, "name"),
|
||||
object_type=_require_str(object_raw, "object_type"),
|
||||
)
|
||||
|
||||
return AppConfig(
|
||||
mqtt=MqttConfig(
|
||||
enabled=bool(mqtt_raw.get("enabled", True)),
|
||||
|
|
@ -137,6 +164,24 @@ def load_config(path: str | Path) -> AppConfig:
|
|||
root_dir=str(spool_raw.get("root_dir", "spool")),
|
||||
flush_each_write=bool(spool_raw.get("flush_each_write", True)),
|
||||
),
|
||||
api=ApiConfig(
|
||||
enabled=bool(api_raw.get("enabled", False)),
|
||||
host=str(api_raw.get("host", "127.0.0.1")),
|
||||
port=int(api_raw.get("port", 8080)),
|
||||
stale_timeout_ms=int(api_raw.get("stale_timeout_ms", 5000)),
|
||||
offline_timeout_ms=int(api_raw.get("offline_timeout_ms", 10000)),
|
||||
coordinate_system=CoordinateSystemConfig(
|
||||
type=str(coordinate_system_raw.get("type", "local_relative")),
|
||||
unit=str(coordinate_system_raw.get("unit", "meter")),
|
||||
origin=str(coordinate_system_raw.get("origin", "site_origin")),
|
||||
axis=CoordinateAxisConfig(
|
||||
x=str(axis_raw.get("x", "east")),
|
||||
y=str(axis_raw.get("y", "north")),
|
||||
z=str(axis_raw.get("z", "up")),
|
||||
),
|
||||
),
|
||||
objects=objects,
|
||||
),
|
||||
zabbix=ZabbixConfig(
|
||||
sender_path=_require_str(zabbix_raw, "sender_path"),
|
||||
server_host=_require_str(zabbix_raw, "server_host"),
|
||||
|
|
|
|||
|
|
@ -0,0 +1,245 @@
|
|||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
import threading
|
||||
import time
|
||||
from dataclasses import asdict
|
||||
from typing import Any, Callable
|
||||
|
||||
from aiohttp import web
|
||||
|
||||
from .navigation_state import ObjectStateStore
|
||||
from .types import ApiConfig, ObjectState
|
||||
|
||||
|
||||
LOGGER = logging.getLogger(__name__)
|
||||
SCHEMA_VERSION = "1.0"
|
||||
|
||||
|
||||
class _WsClient:
|
||||
def __init__(self, ws: web.WebSocketResponse) -> None:
|
||||
self.ws = ws
|
||||
self.queue: asyncio.Queue[dict[str, Any] | None] = asyncio.Queue(maxsize=1)
|
||||
self.task: asyncio.Task[None] | None = None
|
||||
|
||||
|
||||
class _WebSocketHub:
|
||||
def __init__(self, payload_factory: Callable[[], dict[str, Any]]) -> None:
|
||||
self._payload_factory = payload_factory
|
||||
self._clients: set[_WsClient] = set()
|
||||
|
||||
async def register(self, ws: web.WebSocketResponse) -> _WsClient:
|
||||
client = _WsClient(ws)
|
||||
client.task = asyncio.create_task(self._writer(client))
|
||||
self._clients.add(client)
|
||||
await self._enqueue(client, self._payload_factory())
|
||||
return client
|
||||
|
||||
async def unregister(self, client: _WsClient) -> None:
|
||||
if client not in self._clients:
|
||||
return
|
||||
self._clients.discard(client)
|
||||
while client.queue.full():
|
||||
client.queue.get_nowait()
|
||||
client.queue.put_nowait(None)
|
||||
if client.task is not None:
|
||||
await client.task
|
||||
|
||||
async def broadcast(self) -> None:
|
||||
payload = self._payload_factory()
|
||||
for client in list(self._clients):
|
||||
if client.ws.closed:
|
||||
await self.unregister(client)
|
||||
continue
|
||||
if client.queue.full():
|
||||
LOGGER.warning("Disconnecting slow WebSocket client")
|
||||
await client.ws.close()
|
||||
await self.unregister(client)
|
||||
continue
|
||||
await self._enqueue(client, payload)
|
||||
|
||||
async def close(self) -> None:
|
||||
for client in list(self._clients):
|
||||
await client.ws.close()
|
||||
await self.unregister(client)
|
||||
|
||||
async def _enqueue(self, client: _WsClient, payload: dict[str, Any] | None) -> None:
|
||||
client.queue.put_nowait(payload)
|
||||
|
||||
async def _writer(self, client: _WsClient) -> None:
|
||||
while True:
|
||||
payload = await client.queue.get()
|
||||
if payload is None:
|
||||
break
|
||||
await client.ws.send_json(payload)
|
||||
|
||||
|
||||
class NavigationApiServer:
|
||||
def __init__(self, config: ApiConfig, state_store: ObjectStateStore) -> None:
|
||||
self._config = config
|
||||
self._state_store = state_store
|
||||
self._hub = _WebSocketHub(self.build_stream_payload)
|
||||
self.app = web.Application()
|
||||
self.app.add_routes(
|
||||
[
|
||||
web.get("/api/v1/objects", self._handle_objects),
|
||||
web.get("/api/v1/objects/locations", self._handle_locations),
|
||||
web.get("/api/v1/objects/{object_id}", self._handle_object_card),
|
||||
web.get("/api/v1/stream/locations", self._handle_stream_locations),
|
||||
]
|
||||
)
|
||||
self._loop: asyncio.AbstractEventLoop | None = None
|
||||
self._runner: web.AppRunner | None = None
|
||||
self._thread: threading.Thread | None = None
|
||||
self._ready = threading.Event()
|
||||
|
||||
def start(self) -> None:
|
||||
if not self._config.enabled or self._thread is not None:
|
||||
return
|
||||
self._thread = threading.Thread(target=self._run_thread, name="navigation-api", daemon=True)
|
||||
self._thread.start()
|
||||
self._ready.wait(timeout=5)
|
||||
|
||||
def stop(self) -> None:
|
||||
if self._loop is None or self._thread is None:
|
||||
return
|
||||
future = asyncio.run_coroutine_threadsafe(self._shutdown_async(), self._loop)
|
||||
future.result(timeout=5)
|
||||
self._thread.join(timeout=5)
|
||||
self._thread = None
|
||||
self._loop = None
|
||||
self._runner = None
|
||||
self._ready.clear()
|
||||
|
||||
def publish_full_snapshot(self) -> None:
|
||||
if not self._config.enabled or self._loop is None:
|
||||
return
|
||||
future = asyncio.run_coroutine_threadsafe(self.broadcast_full_snapshot_async(), self._loop)
|
||||
future.add_done_callback(self._log_future_error)
|
||||
|
||||
async def broadcast_full_snapshot_async(self) -> None:
|
||||
await self._hub.broadcast()
|
||||
|
||||
def build_stream_payload(self) -> dict[str, Any]:
|
||||
locations_response = self.build_locations_response()
|
||||
return {
|
||||
"event": "location_update",
|
||||
"server_time_unix_ms": locations_response["server_time_unix_ms"],
|
||||
"objects": locations_response["objects"],
|
||||
}
|
||||
|
||||
def build_objects_response(self) -> dict[str, Any]:
|
||||
return {
|
||||
"schema_version": SCHEMA_VERSION,
|
||||
"coordinate_system": {
|
||||
"type": self._config.coordinate_system.type,
|
||||
"unit": self._config.coordinate_system.unit,
|
||||
"origin": self._config.coordinate_system.origin,
|
||||
},
|
||||
"objects": [
|
||||
{
|
||||
"object_id": state.object_id,
|
||||
"object_type": state.object_type,
|
||||
"name": state.name,
|
||||
"status": state.status,
|
||||
}
|
||||
for state in self._state_store.list_object_states()
|
||||
],
|
||||
}
|
||||
|
||||
def build_locations_response(self) -> dict[str, Any]:
|
||||
return {
|
||||
"schema_version": SCHEMA_VERSION,
|
||||
"server_time_unix_ms": _server_time_unix_ms(),
|
||||
"coordinate_system": {
|
||||
"type": self._config.coordinate_system.type,
|
||||
"unit": self._config.coordinate_system.unit,
|
||||
"axis": asdict(self._config.coordinate_system.axis),
|
||||
},
|
||||
"objects": [self._serialize_location_state(state) for state in self._state_store.list_location_states()],
|
||||
}
|
||||
|
||||
def build_object_card(self, object_id: str) -> dict[str, Any] | None:
|
||||
state = self._state_store.get_object_state(object_id)
|
||||
if state is None:
|
||||
return None
|
||||
return self._serialize_object_state(state)
|
||||
|
||||
async def _handle_objects(self, _request: web.Request) -> web.Response:
|
||||
return web.json_response(self.build_objects_response())
|
||||
|
||||
async def _handle_locations(self, _request: web.Request) -> web.Response:
|
||||
return web.json_response(self.build_locations_response())
|
||||
|
||||
async def _handle_object_card(self, request: web.Request) -> web.Response:
|
||||
object_id = request.match_info["object_id"]
|
||||
payload = self.build_object_card(object_id)
|
||||
if payload is None:
|
||||
return web.json_response({"error": "object not found"}, status=404)
|
||||
return web.json_response(payload)
|
||||
|
||||
async def _handle_stream_locations(self, request: web.Request) -> web.StreamResponse:
|
||||
ws = web.WebSocketResponse()
|
||||
await ws.prepare(request)
|
||||
client = await self._hub.register(ws)
|
||||
try:
|
||||
async for _message in ws:
|
||||
pass
|
||||
finally:
|
||||
await self._hub.unregister(client)
|
||||
return ws
|
||||
|
||||
def _run_thread(self) -> None:
|
||||
self._loop = asyncio.new_event_loop()
|
||||
asyncio.set_event_loop(self._loop)
|
||||
self._loop.run_until_complete(self._startup_async())
|
||||
self._ready.set()
|
||||
self._loop.run_forever()
|
||||
self._loop.close()
|
||||
|
||||
async def _startup_async(self) -> None:
|
||||
self._runner = web.AppRunner(self.app)
|
||||
await self._runner.setup()
|
||||
site = web.TCPSite(self._runner, self._config.host, self._config.port)
|
||||
await site.start()
|
||||
|
||||
async def _shutdown_async(self) -> None:
|
||||
await self._hub.close()
|
||||
if self._runner is not None:
|
||||
await self._runner.cleanup()
|
||||
loop = asyncio.get_running_loop()
|
||||
loop.call_soon(loop.stop)
|
||||
|
||||
def _serialize_location_state(self, state: ObjectState) -> dict[str, Any]:
|
||||
payload = {
|
||||
"object_id": state.object_id,
|
||||
"status": state.status,
|
||||
"navigation_status": state.navigation_status,
|
||||
"location": asdict(state.location) if state.location is not None else None,
|
||||
"observed_at_unix_ms": state.observed_at_unix_ms,
|
||||
"updated_at_unix_ms": state.updated_at_unix_ms,
|
||||
}
|
||||
return payload
|
||||
|
||||
def _serialize_object_state(self, state: ObjectState) -> dict[str, Any]:
|
||||
return {
|
||||
"object_id": state.object_id,
|
||||
"object_type": state.object_type,
|
||||
"name": state.name,
|
||||
"status": state.status,
|
||||
"navigation_status": state.navigation_status,
|
||||
"location": asdict(state.location) if state.location is not None else None,
|
||||
"observed_at_unix_ms": state.observed_at_unix_ms,
|
||||
"updated_at_unix_ms": state.updated_at_unix_ms,
|
||||
}
|
||||
|
||||
def _log_future_error(self, future: asyncio.Future[Any]) -> None:
|
||||
try:
|
||||
future.result()
|
||||
except Exception:
|
||||
LOGGER.exception("Navigation API broadcast failed")
|
||||
|
||||
|
||||
def _server_time_unix_ms() -> int:
|
||||
return int(time.time() * 1000)
|
||||
|
|
@ -0,0 +1,140 @@
|
|||
from __future__ import annotations
|
||||
|
||||
import threading
|
||||
import time
|
||||
from dataclasses import dataclass
|
||||
|
||||
from .types import ApiConfig, NormalizedMqttEvent, ObjectLocation, ObjectState
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class _RuntimeObjectState:
|
||||
last_heartbeat_unix_ms: int | None = None
|
||||
location: ObjectLocation | None = None
|
||||
observed_at_unix_ms: int | None = None
|
||||
updated_at_unix_ms: int | None = None
|
||||
|
||||
|
||||
class ObjectStateStore:
|
||||
def __init__(self, config: ApiConfig) -> None:
|
||||
self._config = config
|
||||
self._states: dict[str, _RuntimeObjectState] = {}
|
||||
self._lock = threading.Lock()
|
||||
|
||||
def has_object(self, object_id: str) -> bool:
|
||||
return object_id in self._config.objects
|
||||
|
||||
def update_from_event(self, event: NormalizedMqttEvent, received_at_unix_ms: int | None = None) -> bool:
|
||||
object_id = event.payload.get("agent_id")
|
||||
if not isinstance(object_id, str) or object_id not in self._config.objects:
|
||||
return False
|
||||
|
||||
now_ms = received_at_unix_ms if received_at_unix_ms is not None else _now_unix_ms()
|
||||
observed_at_unix_ms = event.observed_at_unix_ms or now_ms
|
||||
location = _extract_location(event)
|
||||
|
||||
with self._lock:
|
||||
state = self._states.setdefault(object_id, _RuntimeObjectState())
|
||||
changed = False
|
||||
if event.event_kind == "heartbeat" and state.last_heartbeat_unix_ms != observed_at_unix_ms:
|
||||
state.last_heartbeat_unix_ms = observed_at_unix_ms
|
||||
changed = True
|
||||
if location is not None and (
|
||||
state.location != location or state.observed_at_unix_ms != observed_at_unix_ms
|
||||
):
|
||||
state.location = location
|
||||
state.observed_at_unix_ms = observed_at_unix_ms
|
||||
changed = True
|
||||
if changed:
|
||||
state.updated_at_unix_ms = now_ms
|
||||
return changed
|
||||
|
||||
def get_object_state(self, object_id: str, now_unix_ms: int | None = None) -> ObjectState | None:
|
||||
if object_id not in self._config.objects:
|
||||
return None
|
||||
now_ms = now_unix_ms if now_unix_ms is not None else _now_unix_ms()
|
||||
with self._lock:
|
||||
runtime = self._states.get(object_id)
|
||||
return self._build_object_state(object_id, runtime, now_ms)
|
||||
|
||||
def list_object_states(self, now_unix_ms: int | None = None) -> list[ObjectState]:
|
||||
now_ms = now_unix_ms if now_unix_ms is not None else _now_unix_ms()
|
||||
with self._lock:
|
||||
return [
|
||||
self._build_object_state(object_id, self._states.get(object_id), now_ms)
|
||||
for object_id in self._config.objects
|
||||
]
|
||||
|
||||
def list_location_states(self, now_unix_ms: int | None = None) -> list[ObjectState]:
|
||||
return [
|
||||
state
|
||||
for state in self.list_object_states(now_unix_ms=now_unix_ms)
|
||||
if state.location is not None
|
||||
]
|
||||
|
||||
def _build_object_state(
|
||||
self,
|
||||
object_id: str,
|
||||
runtime: _RuntimeObjectState | None,
|
||||
now_unix_ms: int,
|
||||
) -> ObjectState:
|
||||
catalog = self._config.objects[object_id]
|
||||
status, navigation_status = self._derive_statuses(runtime, now_unix_ms)
|
||||
return ObjectState(
|
||||
object_id=object_id,
|
||||
object_type=catalog.object_type,
|
||||
name=catalog.name,
|
||||
status=status,
|
||||
navigation_status=navigation_status,
|
||||
location=runtime.location if runtime is not None else None,
|
||||
observed_at_unix_ms=runtime.observed_at_unix_ms if runtime is not None else None,
|
||||
updated_at_unix_ms=runtime.updated_at_unix_ms if runtime is not None else None,
|
||||
)
|
||||
|
||||
def _derive_statuses(self, runtime: _RuntimeObjectState | None, now_unix_ms: int) -> tuple[str, str]:
|
||||
if runtime is None or (runtime.last_heartbeat_unix_ms is None and runtime.location is None):
|
||||
return "unknown", "lost"
|
||||
|
||||
if runtime.last_heartbeat_unix_ms is not None:
|
||||
heartbeat_age_ms = now_unix_ms - runtime.last_heartbeat_unix_ms
|
||||
if heartbeat_age_ms > self._config.offline_timeout_ms:
|
||||
return "offline", "lost"
|
||||
|
||||
if runtime.location is None or runtime.observed_at_unix_ms is None:
|
||||
return "stale", "lost"
|
||||
|
||||
location_age_ms = now_unix_ms - runtime.observed_at_unix_ms
|
||||
if location_age_ms > self._config.stale_timeout_ms:
|
||||
return "stale", "degraded"
|
||||
|
||||
return "online", "valid"
|
||||
|
||||
|
||||
def _extract_location(event: NormalizedMqttEvent) -> ObjectLocation | None:
|
||||
payload = event.payload.get("payload")
|
||||
if not isinstance(payload, dict):
|
||||
return None
|
||||
location_raw = payload.get("location")
|
||||
if not isinstance(location_raw, dict):
|
||||
return None
|
||||
x = _coerce_number(location_raw.get("x"))
|
||||
y = _coerce_number(location_raw.get("y"))
|
||||
if x is None or y is None:
|
||||
return None
|
||||
return ObjectLocation(
|
||||
x=x,
|
||||
y=y,
|
||||
z=_coerce_number(location_raw.get("z")),
|
||||
heading=_coerce_number(location_raw.get("heading")),
|
||||
accuracy=_coerce_number(location_raw.get("accuracy")),
|
||||
)
|
||||
|
||||
|
||||
def _coerce_number(value: object) -> float | None:
|
||||
if isinstance(value, (int, float)):
|
||||
return float(value)
|
||||
return None
|
||||
|
||||
|
||||
def _now_unix_ms() -> int:
|
||||
return int(time.time() * 1000)
|
||||
|
|
@ -4,6 +4,7 @@ import logging
|
|||
import signal
|
||||
import ssl
|
||||
import threading
|
||||
import time
|
||||
from concurrent.futures import Future, ThreadPoolExecutor
|
||||
from typing import Any
|
||||
|
||||
|
|
@ -15,6 +16,8 @@ except ModuleNotFoundError: # pragma: no cover - exercised in test environments
|
|||
from .config import load_config
|
||||
from .logging_utils import configure_logging, emit_ndjson
|
||||
from .mapping import map_event_to_metrics
|
||||
from .navigation_api import NavigationApiServer
|
||||
from .navigation_state import ObjectStateStore
|
||||
from .parser import InvalidPayloadError, InvalidTopicError, event_to_log_dict, parse_mqtt_message
|
||||
from .spool import SpoolWriter
|
||||
from .sender import ZabbixSender, ZabbixSenderError
|
||||
|
|
@ -25,10 +28,22 @@ LOGGER = logging.getLogger(__name__)
|
|||
|
||||
|
||||
class Robot2ZabbixService:
|
||||
def __init__(self, config: AppConfig, max_workers: int = 4, client: Any | None = None) -> None:
|
||||
def __init__(
|
||||
self,
|
||||
config: AppConfig,
|
||||
max_workers: int = 4,
|
||||
client: Any | None = None,
|
||||
object_state_store: ObjectStateStore | None = None,
|
||||
navigation_api_server: NavigationApiServer | None = None,
|
||||
) -> None:
|
||||
self._config = config
|
||||
self._sender = ZabbixSender(config.zabbix)
|
||||
self._spool = SpoolWriter(config.spool)
|
||||
self._object_state_store = object_state_store or ObjectStateStore(config.api)
|
||||
self._navigation_api_server = navigation_api_server or NavigationApiServer(
|
||||
config.api,
|
||||
self._object_state_store,
|
||||
)
|
||||
self._executor = ThreadPoolExecutor(max_workers=max_workers, thread_name_prefix="r2z")
|
||||
self._stop_event = threading.Event()
|
||||
self._client = client or self._build_client()
|
||||
|
|
@ -40,6 +55,7 @@ class Robot2ZabbixService:
|
|||
raise RuntimeError("MQTT ingestion is disabled in config")
|
||||
|
||||
self._install_signal_handlers()
|
||||
self._navigation_api_server.start()
|
||||
self._connect()
|
||||
self._client.loop_start()
|
||||
LOGGER.info("Service started")
|
||||
|
|
@ -59,6 +75,10 @@ class Robot2ZabbixService:
|
|||
self._client.disconnect()
|
||||
except Exception:
|
||||
LOGGER.exception("Failed to stop MQTT client cleanly")
|
||||
try:
|
||||
self._navigation_api_server.stop()
|
||||
except Exception:
|
||||
LOGGER.exception("Failed to stop navigation API cleanly")
|
||||
self._executor.shutdown(wait=True, cancel_futures=False)
|
||||
LOGGER.info("Service stopped")
|
||||
|
||||
|
|
@ -161,6 +181,12 @@ class Robot2ZabbixService:
|
|||
return
|
||||
|
||||
self._write_valid_spool(topic, payload_bytes, event)
|
||||
state_changed = self._object_state_store.update_from_event(
|
||||
event,
|
||||
received_at_unix_ms=int(time.time() * 1000),
|
||||
)
|
||||
if state_changed:
|
||||
self._navigation_api_server.publish_full_snapshot()
|
||||
metrics = map_event_to_metrics(
|
||||
event,
|
||||
self._config.mapping_rules,
|
||||
|
|
|
|||
|
|
@ -83,6 +83,38 @@ class SpoolConfig:
|
|||
flush_each_write: bool
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class ObjectCatalogEntry:
|
||||
name: str
|
||||
object_type: str
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class CoordinateAxisConfig:
|
||||
x: str
|
||||
y: str
|
||||
z: str
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class CoordinateSystemConfig:
|
||||
type: str
|
||||
unit: str
|
||||
origin: str
|
||||
axis: CoordinateAxisConfig
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class ApiConfig:
|
||||
enabled: bool
|
||||
host: str
|
||||
port: int
|
||||
stale_timeout_ms: int
|
||||
offline_timeout_ms: int
|
||||
coordinate_system: CoordinateSystemConfig
|
||||
objects: dict[str, ObjectCatalogEntry]
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class ZabbixConfig:
|
||||
sender_path: str
|
||||
|
|
@ -97,6 +129,7 @@ class AppConfig:
|
|||
mqtt: MqttConfig
|
||||
logging: LoggingConfig
|
||||
spool: SpoolConfig
|
||||
api: ApiConfig
|
||||
zabbix: ZabbixConfig
|
||||
mapping_rules: list[MappingRule]
|
||||
scan_signal_bucket_rules: list[ScanSignalBucketRule]
|
||||
|
|
@ -120,3 +153,24 @@ class MappedMetric:
|
|||
key: str
|
||||
value: Any
|
||||
value_kind: str = "auto"
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class ObjectLocation:
|
||||
x: float
|
||||
y: float
|
||||
z: float | None
|
||||
heading: float | None
|
||||
accuracy: float | None
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class ObjectState:
|
||||
object_id: str
|
||||
object_type: str
|
||||
name: str
|
||||
status: str
|
||||
navigation_status: str
|
||||
location: ObjectLocation | None
|
||||
observed_at_unix_ms: int | None
|
||||
updated_at_unix_ms: int | None
|
||||
|
|
|
|||
|
|
@ -55,8 +55,8 @@ def test_scan_signal_buckets_are_counted() -> None:
|
|||
)
|
||||
values = {metric.key: metric.value for metric in metrics}
|
||||
assert values["wifi.scan.signal.green_count"] == 1
|
||||
assert values["wifi.scan.signal.yellow_count"] == 1
|
||||
assert values["wifi.scan.signal.red_count"] == 2
|
||||
assert values["wifi.scan.signal.yellow_count"] == 2
|
||||
assert values["wifi.scan.signal.red_count"] == 1
|
||||
|
||||
|
||||
def test_missing_path_skips_single_metric() -> None:
|
||||
|
|
|
|||
|
|
@ -0,0 +1,133 @@
|
|||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
|
||||
from aiohttp.test_utils import TestClient, TestServer
|
||||
|
||||
from robot2zabbix_backend.config import load_config
|
||||
from robot2zabbix_backend.navigation_api import NavigationApiServer
|
||||
from robot2zabbix_backend.navigation_state import ObjectStateStore
|
||||
from robot2zabbix_backend.parser import parse_mqtt_message
|
||||
|
||||
|
||||
def test_config_loads_api_settings() -> None:
|
||||
config = load_config("config/r2z-backend.yaml")
|
||||
assert config.api.enabled is True
|
||||
assert config.api.host == "127.0.0.1"
|
||||
assert config.api.port == 8080
|
||||
assert "h1500-09-01-00011" in config.api.objects
|
||||
|
||||
|
||||
def test_invalid_api_object_catalog_entry_rejected(tmp_path) -> None:
|
||||
config_path = tmp_path / "broken.yaml"
|
||||
config_path.write_text(
|
||||
"""
|
||||
mqtt:
|
||||
host: broker
|
||||
topics: {base: "wifi/{site_id}/{agent_instance_id}"}
|
||||
client_id: client
|
||||
tls: {}
|
||||
logging: {}
|
||||
spool: {}
|
||||
api:
|
||||
objects:
|
||||
bad-object:
|
||||
object_type: robot
|
||||
zabbix:
|
||||
sender_path: zabbix_sender
|
||||
server_host: 127.0.0.1
|
||||
mapping: {}
|
||||
""".strip(),
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
try:
|
||||
load_config(config_path)
|
||||
except ValueError as exc:
|
||||
assert str(exc) == "name must be a non-empty string"
|
||||
else:
|
||||
raise AssertionError("Expected invalid api catalog entry to be rejected")
|
||||
|
||||
|
||||
def test_get_objects_locations_and_object_card() -> None:
|
||||
async def _run() -> None:
|
||||
config = load_config("config/r2z-backend.yaml")
|
||||
store = ObjectStateStore(config.api)
|
||||
store.update_from_event(
|
||||
_event(
|
||||
"wifi/vostok/31/wifi_signal",
|
||||
{
|
||||
"agent_id": "h1500-09-01-00011",
|
||||
"observed_at_unix_ms": 5_000,
|
||||
"payload": {"rssi": -65, "location": {"x": -1.0, "y": 2.5}},
|
||||
},
|
||||
),
|
||||
received_at_unix_ms=5_100,
|
||||
)
|
||||
api_server = NavigationApiServer(config.api, store)
|
||||
client = TestClient(TestServer(api_server.app))
|
||||
await client.start_server()
|
||||
try:
|
||||
response = await client.get("/api/v1/objects")
|
||||
payload = await response.json()
|
||||
assert payload["schema_version"] == "1.0"
|
||||
assert payload["objects"][0]["object_id"] == "h1500-09-01-00011"
|
||||
|
||||
response = await client.get("/api/v1/objects/locations")
|
||||
payload = await response.json()
|
||||
assert payload["coordinate_system"]["axis"]["x"] == "east"
|
||||
assert payload["objects"][0]["location"]["x"] == -1.0
|
||||
|
||||
response = await client.get("/api/v1/objects/h1500-09-01-00011")
|
||||
payload = await response.json()
|
||||
assert payload["name"] == "Robot 11"
|
||||
assert payload["location"]["y"] == 2.5
|
||||
|
||||
response = await client.get("/api/v1/objects/missing")
|
||||
assert response.status == 404
|
||||
finally:
|
||||
await client.close()
|
||||
|
||||
asyncio.run(_run())
|
||||
|
||||
|
||||
def test_websocket_receives_initial_and_broadcast_snapshots() -> None:
|
||||
async def _run() -> None:
|
||||
config = load_config("config/r2z-backend.yaml")
|
||||
store = ObjectStateStore(config.api)
|
||||
api_server = NavigationApiServer(config.api, store)
|
||||
client = TestClient(TestServer(api_server.app))
|
||||
await client.start_server()
|
||||
try:
|
||||
ws = await client.ws_connect("/api/v1/stream/locations")
|
||||
first = await ws.receive_json()
|
||||
assert first["event"] == "location_update"
|
||||
assert first["objects"] == []
|
||||
|
||||
store.update_from_event(
|
||||
_event(
|
||||
"wifi/vostok/31/wifi_counter",
|
||||
{
|
||||
"agent_id": "h1500-09-01-00011",
|
||||
"observed_at_unix_ms": 7_000,
|
||||
"payload": {"tx_pkt_good": 1, "location": {"x": 3.0, "y": 4.0}},
|
||||
},
|
||||
),
|
||||
received_at_unix_ms=7_100,
|
||||
)
|
||||
await api_server.broadcast_full_snapshot_async()
|
||||
second = await ws.receive_json()
|
||||
assert second["event"] == "location_update"
|
||||
assert second["objects"][0]["object_id"] == "h1500-09-01-00011"
|
||||
assert second["objects"][0]["location"]["x"] == 3.0
|
||||
await ws.close()
|
||||
finally:
|
||||
await client.close()
|
||||
|
||||
asyncio.run(_run())
|
||||
|
||||
|
||||
def _event(topic: str, payload: dict) -> object:
|
||||
wrapper = {"data": json.dumps(payload)}
|
||||
return parse_mqtt_message(topic, json.dumps(wrapper).encode("utf-8"))
|
||||
|
|
@ -0,0 +1,141 @@
|
|||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
|
||||
from robot2zabbix_backend.config import load_config
|
||||
from robot2zabbix_backend.navigation_state import ObjectStateStore
|
||||
from robot2zabbix_backend.parser import parse_mqtt_message
|
||||
|
||||
|
||||
def test_unknown_object_without_telemetry() -> None:
|
||||
config = load_config("config/r2z-backend.yaml")
|
||||
store = ObjectStateStore(config.api)
|
||||
|
||||
state = store.get_object_state("h1500-09-01-00011", now_unix_ms=1000)
|
||||
|
||||
assert state is not None
|
||||
assert state.status == "unknown"
|
||||
assert state.navigation_status == "lost"
|
||||
|
||||
|
||||
def test_fresh_heartbeat_and_location_are_online_and_valid() -> None:
|
||||
config = load_config("config/r2z-backend.yaml")
|
||||
store = ObjectStateStore(config.api)
|
||||
event = _build_event(
|
||||
"wifi/vostok/31/wifi_signal",
|
||||
{
|
||||
"agent_id": "h1500-09-01-00011",
|
||||
"observed_at_unix_ms": 5_000,
|
||||
"payload": {"rssi": -65, "location": {"x": 1.0, "y": 2.0}},
|
||||
},
|
||||
)
|
||||
heartbeat = _build_event(
|
||||
"wifi/vostok/31/heartbeat",
|
||||
{
|
||||
"agent_id": "h1500-09-01-00011",
|
||||
"observed_at_unix_ms": 5_100,
|
||||
"payload": {"state": "running"},
|
||||
},
|
||||
)
|
||||
|
||||
assert store.update_from_event(event, received_at_unix_ms=5_200) is True
|
||||
assert store.update_from_event(heartbeat, received_at_unix_ms=5_200) is True
|
||||
|
||||
state = store.get_object_state("h1500-09-01-00011", now_unix_ms=8_000)
|
||||
assert state is not None
|
||||
assert state.status == "online"
|
||||
assert state.navigation_status == "valid"
|
||||
|
||||
|
||||
def test_fresh_heartbeat_and_stale_location_are_stale_and_degraded() -> None:
|
||||
config = load_config("config/r2z-backend.yaml")
|
||||
store = ObjectStateStore(config.api)
|
||||
event = _build_event(
|
||||
"wifi/vostok/31/wifi_signal",
|
||||
{
|
||||
"agent_id": "h1500-09-01-00011",
|
||||
"observed_at_unix_ms": 1_000,
|
||||
"payload": {"rssi": -65, "location": {"x": 1.0, "y": 2.0}},
|
||||
},
|
||||
)
|
||||
heartbeat = _build_event(
|
||||
"wifi/vostok/31/heartbeat",
|
||||
{
|
||||
"agent_id": "h1500-09-01-00011",
|
||||
"observed_at_unix_ms": 6_000,
|
||||
"payload": {"state": "running"},
|
||||
},
|
||||
)
|
||||
|
||||
store.update_from_event(event, received_at_unix_ms=1_100)
|
||||
store.update_from_event(heartbeat, received_at_unix_ms=6_100)
|
||||
|
||||
state = store.get_object_state("h1500-09-01-00011", now_unix_ms=7_000)
|
||||
assert state is not None
|
||||
assert state.status == "stale"
|
||||
assert state.navigation_status == "degraded"
|
||||
|
||||
|
||||
def test_expired_heartbeat_is_offline_and_lost() -> None:
|
||||
config = load_config("config/r2z-backend.yaml")
|
||||
store = ObjectStateStore(config.api)
|
||||
event = _build_event(
|
||||
"wifi/vostok/31/wifi_signal",
|
||||
{
|
||||
"agent_id": "h1500-09-01-00011",
|
||||
"observed_at_unix_ms": 1_000,
|
||||
"payload": {"rssi": -65, "location": {"x": 1.0, "y": 2.0}},
|
||||
},
|
||||
)
|
||||
heartbeat = _build_event(
|
||||
"wifi/vostok/31/heartbeat",
|
||||
{
|
||||
"agent_id": "h1500-09-01-00011",
|
||||
"observed_at_unix_ms": 1_000,
|
||||
"payload": {"state": "running"},
|
||||
},
|
||||
)
|
||||
|
||||
store.update_from_event(event, received_at_unix_ms=1_100)
|
||||
store.update_from_event(heartbeat, received_at_unix_ms=1_100)
|
||||
|
||||
state = store.get_object_state("h1500-09-01-00011", now_unix_ms=12_000)
|
||||
assert state is not None
|
||||
assert state.status == "offline"
|
||||
assert state.navigation_status == "lost"
|
||||
|
||||
|
||||
def test_latest_location_overwrites_previous_one() -> None:
|
||||
config = load_config("config/r2z-backend.yaml")
|
||||
store = ObjectStateStore(config.api)
|
||||
first = _build_event(
|
||||
"wifi/vostok/31/wifi_signal",
|
||||
{
|
||||
"agent_id": "h1500-09-01-00011",
|
||||
"observed_at_unix_ms": 1_000,
|
||||
"payload": {"rssi": -65, "location": {"x": 1.0, "y": 2.0}},
|
||||
},
|
||||
)
|
||||
second = _build_event(
|
||||
"wifi/vostok/31/netlink_state",
|
||||
{
|
||||
"agent_id": "h1500-09-01-00011",
|
||||
"observed_at_unix_ms": 2_000,
|
||||
"payload": {"interface": "wlp3s0", "location": {"x": 5.0, "y": 7.0, "z": 0}},
|
||||
},
|
||||
)
|
||||
|
||||
store.update_from_event(first, received_at_unix_ms=1_100)
|
||||
store.update_from_event(second, received_at_unix_ms=2_100)
|
||||
|
||||
state = store.get_object_state("h1500-09-01-00011", now_unix_ms=2_500)
|
||||
assert state is not None
|
||||
assert state.location is not None
|
||||
assert state.location.x == 5.0
|
||||
assert state.location.y == 7.0
|
||||
assert state.observed_at_unix_ms == 2_000
|
||||
|
||||
|
||||
def _build_event(topic: str, payload: dict) -> object:
|
||||
wrapper = {"data": json.dumps(payload)}
|
||||
return parse_mqtt_message(topic, json.dumps(wrapper).encode("utf-8"))
|
||||
|
|
@ -6,6 +6,7 @@ from pathlib import Path
|
|||
from unittest.mock import MagicMock
|
||||
|
||||
from robot2zabbix_backend.config import load_config
|
||||
from robot2zabbix_backend.navigation_state import ObjectStateStore
|
||||
from robot2zabbix_backend.service import Robot2ZabbixService, _expand_topics
|
||||
|
||||
|
||||
|
|
@ -135,3 +136,41 @@ def test_process_message_spools_invalid_topic(tmp_path: Path) -> None:
|
|||
assert record["topic"] == "broken/topic"
|
||||
assert record["parse_error"] == "Unsupported topic format: broken/topic"
|
||||
assert service._sender.send.call_count == 0
|
||||
|
||||
|
||||
def test_process_message_updates_navigation_state_and_broadcasts(tmp_path: Path) -> None:
|
||||
config = load_config("config/r2z-backend.yaml")
|
||||
config.spool.root_dir = str(tmp_path)
|
||||
client = MagicMock()
|
||||
object_state_store = ObjectStateStore(config.api)
|
||||
navigation_api_server = MagicMock()
|
||||
service = Robot2ZabbixService(
|
||||
config,
|
||||
max_workers=1,
|
||||
client=client,
|
||||
object_state_store=object_state_store,
|
||||
navigation_api_server=navigation_api_server,
|
||||
)
|
||||
service._sender = MagicMock()
|
||||
service._sender.send.return_value = subprocess.CompletedProcess(
|
||||
args=["zabbix_sender"], returncode=0, stdout="processed: 1", stderr=""
|
||||
)
|
||||
|
||||
wrapper = {
|
||||
"data": json.dumps(
|
||||
{
|
||||
"message_id": "state-1",
|
||||
"agent_id": "h1500-09-01-00011",
|
||||
"observed_at_unix_ms": 1000,
|
||||
"payload": {"connected": 1, "location": {"x": 1.0, "y": 2.0}},
|
||||
}
|
||||
)
|
||||
}
|
||||
service._process_message("wifi/vostok/31/wifi_state", json.dumps(wrapper).encode("utf-8"))
|
||||
|
||||
state = object_state_store.get_object_state("h1500-09-01-00011", now_unix_ms=1000)
|
||||
assert state is not None
|
||||
assert state.location is not None
|
||||
assert state.location.x == 1.0
|
||||
assert navigation_api_server.publish_full_snapshot.call_count == 1
|
||||
assert service._sender.send.call_count == 1
|
||||
|
|
|
|||
Loading…
Reference in New Issue