Add floorplan support to backend
This commit is contained in:
parent
5625ee8432
commit
a4a3bc7b53
38
README.md
38
README.md
|
|
@ -2,7 +2,7 @@
|
|||
|
||||
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.
|
||||
It also exposes a built-in navigation API for the browser client and a Zabbix-backed floorplan endpoint that can be embedded into a Zabbix 7.4 dashboard through a URL or iframe widget.
|
||||
|
||||
When the browser client runs on a different machine, set `api.host: 0.0.0.0` in the backend config so the REST and WebSocket endpoints are reachable over the network.
|
||||
|
||||
|
|
@ -21,6 +21,7 @@ When `api.enabled` is set, the backend keeps an in-memory object state store key
|
|||
|
||||
- `GET /api/v1/objects`
|
||||
- `GET /api/v1/objects/locations`
|
||||
- `GET /api/v1/floorplan`
|
||||
- `GET /api/v1/objects/{object_id}`
|
||||
- `GET /api/v1/stream/locations`
|
||||
|
||||
|
|
@ -28,6 +29,35 @@ Object metadata (`name`, `object_type`) comes from `api.objects` in the YAML con
|
|||
|
||||
The API sends permissive CORS headers so a browser-based client can consume it from a separate static folder.
|
||||
|
||||
## Zabbix Floorplan
|
||||
|
||||
`GET /api/v1/floorplan` is intended for the warehouse floorplan viewer embedded in Zabbix 7.4. It reads the current robot state and recent coordinate history from Zabbix items through the Zabbix JSON-RPC API and returns one snapshot that already contains:
|
||||
|
||||
- current robot positions
|
||||
- derived `status`
|
||||
- current `BSSID` and `RSSI`
|
||||
- recent tail points for every robot
|
||||
|
||||
To enable this mode, configure the `zabbix` section with:
|
||||
|
||||
- `api_url`: full JSON-RPC endpoint, for example `http://zabbix.example/api_jsonrpc.php`
|
||||
- `api_token`: Zabbix API token with read access to hosts, items, and history
|
||||
- `history_window_sec`: how far back to read item history for tails
|
||||
- `tail_limit`: maximum returned tail points per robot
|
||||
|
||||
Required item keys per robot host:
|
||||
|
||||
- `wifi.location.x`
|
||||
- `wifi.location.y`
|
||||
- `wifi.state.bssid`
|
||||
- `wifi.signal.rssi_dbm`
|
||||
|
||||
Optional item key:
|
||||
|
||||
- `robot.status`
|
||||
|
||||
If `robot.status` is absent, the backend derives `online` / `stale` / `offline` from item freshness using `api.stale_timeout_ms` and `api.offline_timeout_ms`.
|
||||
|
||||
## Web Client
|
||||
|
||||
A lightweight static navigation client lives in `client/`:
|
||||
|
|
@ -36,7 +66,9 @@ A lightweight static navigation client lives in `client/`:
|
|||
- `client/styles.css`
|
||||
- `client/app.js`
|
||||
|
||||
It connects to the navigation API over WebSocket, renders object positions on a canvas, shows a configurable tail of recent points, derives speed from consecutive coordinate updates, highlights BSSID changes directly on the canvas, and loads estimated BSSID placement markers from the backend API.
|
||||
It first tries `GET /api/v1/floorplan` and, when that endpoint is configured, uses Zabbix as the source of truth for robot positions and tails. If the floorplan endpoint is unavailable, the client falls back to the older navigation API and WebSocket stream.
|
||||
|
||||
The viewer renders the local warehouse floorplan with robot markers, status colors, `BSSID` / `RSSI` labels, and tails with per-segment color changes when the robot switches access points.
|
||||
|
||||
Open `client/index.html` directly in a browser or serve the `client/` folder with any static file server. You can override the API base URL with the `api` query parameter, for example:
|
||||
|
||||
|
|
@ -44,6 +76,8 @@ Open `client/index.html` directly in a browser or serve the `client/` folder wit
|
|||
client/index.html?api=http://127.0.0.1:8080
|
||||
```
|
||||
|
||||
For Zabbix 7.4, publish the `client/` folder on an HTTP server reachable by the Zabbix frontend and add it to the dashboard with a URL or iframe-style widget. Use the backend base URL in the `api` query string so the viewer can call `/api/v1/floorplan`.
|
||||
|
||||
## Run
|
||||
|
||||
```bash
|
||||
|
|
|
|||
125
client/app.js
125
client/app.js
|
|
@ -39,6 +39,7 @@
|
|||
renderIntervalMs: DEFAULT_RENDER_INTERVAL_MS,
|
||||
tailLength: DEFAULT_TAIL_LENGTH,
|
||||
connectionStatus: "connecting",
|
||||
dataSource: "unknown",
|
||||
catalogById: new Map(),
|
||||
liveById: new Map(),
|
||||
historyById: new Map(),
|
||||
|
|
@ -54,6 +55,7 @@
|
|||
tailLayer: null,
|
||||
originLayer: null,
|
||||
hasFittedPlanView: false,
|
||||
isSnapshotLoading: false,
|
||||
};
|
||||
|
||||
const planBounds = L.latLngBounds(
|
||||
|
|
@ -78,7 +80,6 @@
|
|||
bindEvents();
|
||||
observeMapResize();
|
||||
refreshConnectionBadge();
|
||||
restartRenderLoop();
|
||||
initializeDataFlow();
|
||||
}
|
||||
|
||||
|
|
@ -134,6 +135,10 @@
|
|||
elements.applySettingsButton.addEventListener("click", applySettings);
|
||||
elements.reconnectButton.addEventListener("click", () => {
|
||||
clearReconnectTimer();
|
||||
if (state.dataSource === "floorplan") {
|
||||
void loadFloorplanSnapshot();
|
||||
return;
|
||||
}
|
||||
reconnectSocket(true);
|
||||
});
|
||||
}
|
||||
|
|
@ -166,15 +171,48 @@
|
|||
}
|
||||
|
||||
async function initializeDataFlow() {
|
||||
const floorplanLoaded = await loadFloorplanSnapshot();
|
||||
if (floorplanLoaded) {
|
||||
state.dataSource = "floorplan";
|
||||
restartRenderLoop();
|
||||
return;
|
||||
}
|
||||
|
||||
state.dataSource = "navigation";
|
||||
const catalogLoaded = await loadCatalog();
|
||||
await loadBssidLocations();
|
||||
renderMap();
|
||||
restartRenderLoop();
|
||||
if (!catalogLoaded) {
|
||||
return;
|
||||
}
|
||||
reconnectSocket(false);
|
||||
}
|
||||
|
||||
async function loadFloorplanSnapshot() {
|
||||
if (state.isSnapshotLoading) {
|
||||
return false;
|
||||
}
|
||||
state.isSnapshotLoading = true;
|
||||
try {
|
||||
const response = await fetchWithTimeout(composeUrl("/api/v1/floorplan"), { method: "GET" });
|
||||
if (!response.ok) {
|
||||
throw new Error("Floorplan request failed: " + response.status);
|
||||
}
|
||||
const payload = await response.json();
|
||||
applyFloorplanSnapshot(payload);
|
||||
setConnectionStatus("connected");
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.warn("Failed to load floorplan snapshot", error);
|
||||
if (state.dataSource !== "navigation") {
|
||||
setConnectionStatus("disconnected");
|
||||
}
|
||||
return false;
|
||||
} finally {
|
||||
state.isSnapshotLoading = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function loadCatalog() {
|
||||
try {
|
||||
const response = await fetchWithTimeout(composeUrl("/api/v1/objects"), { method: "GET" });
|
||||
|
|
@ -312,6 +350,46 @@
|
|||
renderMap();
|
||||
}
|
||||
|
||||
function applyFloorplanSnapshot(payload) {
|
||||
const nextCatalog = new Map();
|
||||
const nextLiveById = new Map();
|
||||
const nextHistoryById = new Map();
|
||||
const objects = Array.isArray(payload && payload.objects) ? payload.objects : [];
|
||||
|
||||
for (const item of objects) {
|
||||
const catalogEntry = {
|
||||
objectId: item.object_id,
|
||||
objectType: item.object_type || "unknown",
|
||||
name: item.name || item.object_id,
|
||||
status: item.status || "unknown",
|
||||
navigationStatus: item.navigation_status || "lost",
|
||||
location: item.location || null,
|
||||
bssid: item.bssid || null,
|
||||
rssiDbm: typeof item.rssi_dbm === "number" ? item.rssi_dbm : null,
|
||||
observedAtUnixMs: item.observed_at_unix_ms || null,
|
||||
updatedAtUnixMs: item.updated_at_unix_ms || null,
|
||||
};
|
||||
nextCatalog.set(catalogEntry.objectId, catalogEntry);
|
||||
nextLiveById.set(catalogEntry.objectId, catalogEntry);
|
||||
|
||||
const tailPoints = Array.isArray(item.tail_points)
|
||||
? item.tail_points
|
||||
.map((point) => normalizeTailPoint(point))
|
||||
.filter((point) => point !== null)
|
||||
: [];
|
||||
nextHistoryById.set(catalogEntry.objectId, tailPoints.slice(-state.tailLength));
|
||||
}
|
||||
|
||||
state.catalogById = nextCatalog;
|
||||
state.liveById = nextLiveById;
|
||||
state.historyById = nextHistoryById;
|
||||
if (!state.selectedObjectId || !nextCatalog.has(state.selectedObjectId)) {
|
||||
state.selectedObjectId = nextCatalog.size > 0 ? nextCatalog.keys().next().value : null;
|
||||
}
|
||||
renderSidebar();
|
||||
renderMap();
|
||||
}
|
||||
|
||||
function appendHistoryPoint(objectState) {
|
||||
if (!objectState.location || objectState.observedAtUnixMs === null) {
|
||||
return;
|
||||
|
|
@ -398,7 +476,13 @@
|
|||
if (state.renderTimerId !== null) {
|
||||
window.clearInterval(state.renderTimerId);
|
||||
}
|
||||
state.renderTimerId = window.setInterval(renderMap, state.renderIntervalMs);
|
||||
if (state.dataSource === "floorplan") {
|
||||
state.renderTimerId = window.setInterval(() => {
|
||||
void loadFloorplanSnapshot();
|
||||
}, state.renderIntervalMs);
|
||||
} else {
|
||||
state.renderTimerId = window.setInterval(renderMap, state.renderIntervalMs);
|
||||
}
|
||||
renderMap();
|
||||
}
|
||||
|
||||
|
|
@ -579,12 +663,18 @@
|
|||
trimHistories();
|
||||
restartRenderLoop();
|
||||
if (shouldReconnect) {
|
||||
loadCatalog().then((catalogLoaded) => {
|
||||
if (catalogLoaded) {
|
||||
reconnectSocket(true);
|
||||
}
|
||||
});
|
||||
clearReconnectTimer();
|
||||
clearSocketConnectTimer();
|
||||
if (state.socket) {
|
||||
state.socket.close();
|
||||
state.socket = null;
|
||||
}
|
||||
state.dataSource = "unknown";
|
||||
initializeDataFlow();
|
||||
} else {
|
||||
if (state.dataSource === "floorplan") {
|
||||
void loadFloorplanSnapshot();
|
||||
}
|
||||
renderSidebar();
|
||||
renderMap();
|
||||
}
|
||||
|
|
@ -666,6 +756,25 @@
|
|||
};
|
||||
}
|
||||
|
||||
function normalizeTailPoint(point) {
|
||||
if (!point) {
|
||||
return null;
|
||||
}
|
||||
const x = Number(point.x);
|
||||
const y = Number(point.y);
|
||||
const observedAtUnixMs = Number(point.observed_at_unix_ms);
|
||||
if (!Number.isFinite(x) || !Number.isFinite(y) || !Number.isFinite(observedAtUnixMs)) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
x: x,
|
||||
y: y,
|
||||
bssid: typeof point.bssid === "string" && point.bssid.trim() !== "" ? point.bssid : null,
|
||||
rssiDbm: typeof point.rssi_dbm === "number" ? point.rssi_dbm : null,
|
||||
observedAtUnixMs: observedAtUnixMs,
|
||||
};
|
||||
}
|
||||
|
||||
function setConnectionStatus(status) {
|
||||
state.connectionStatus = status;
|
||||
refreshConnectionBadge();
|
||||
|
|
|
|||
|
|
@ -85,6 +85,16 @@ zabbix:
|
|||
server_port: 10051
|
||||
# Sender timeout in milliseconds.
|
||||
timeout_ms: 3000
|
||||
# Zabbix JSON-RPC endpoint used by the floorplan adapter, for example http://zabbix/api_jsonrpc.php.
|
||||
api_url: null
|
||||
# Zabbix API token used to read current values and recent item history.
|
||||
api_token: null
|
||||
# Verify TLS certificates when calling the Zabbix API over HTTPS.
|
||||
verify_tls: true
|
||||
# Look back this many seconds when building robot tails from Zabbix item history.
|
||||
history_window_sec: 900
|
||||
# Maximum number of tail points returned per robot.
|
||||
tail_limit: 200
|
||||
# Extra sender arguments.
|
||||
extra_args: []
|
||||
|
||||
|
|
|
|||
|
|
@ -188,6 +188,11 @@ def load_config(path: str | Path) -> AppConfig:
|
|||
server_port=int(zabbix_raw.get("server_port", 10051)),
|
||||
timeout_ms=int(zabbix_raw.get("timeout_ms", 3000)),
|
||||
extra_args=[str(value) for value in zabbix_raw.get("extra_args", [])],
|
||||
api_url=_optional_string_or_null(zabbix_raw, "api_url"),
|
||||
api_token=_optional_string_or_null(zabbix_raw, "api_token"),
|
||||
verify_tls=bool(zabbix_raw.get("verify_tls", True)),
|
||||
history_window_sec=int(zabbix_raw.get("history_window_sec", 900)),
|
||||
tail_limit=int(zabbix_raw.get("tail_limit", 200)),
|
||||
),
|
||||
mapping_rules=rules,
|
||||
scan_signal_bucket_rules=scan_bucket_rules,
|
||||
|
|
@ -224,3 +229,13 @@ def _optional_string(data: dict, key: str) -> str | None:
|
|||
if isinstance(value, str) and value:
|
||||
return value
|
||||
raise ValueError(f"{key} must be a non-empty string when provided")
|
||||
|
||||
|
||||
def _optional_string_or_null(data: dict, key: str) -> str | None:
|
||||
value = data.get(key)
|
||||
if value is None:
|
||||
return None
|
||||
if isinstance(value, str):
|
||||
stripped = value.strip()
|
||||
return stripped or None
|
||||
raise ValueError(f"{key} must be a string or null when provided")
|
||||
|
|
|
|||
|
|
@ -12,7 +12,8 @@ from typing import Any, Callable
|
|||
from aiohttp import web
|
||||
|
||||
from .navigation_state import ObjectStateStore
|
||||
from .types import ApiConfig, ObjectState
|
||||
from .types import ApiConfig, ObjectState, ZabbixConfig
|
||||
from .zabbix_floorplan import ZabbixApiError, ZabbixFloorplanAdapter
|
||||
|
||||
|
||||
LOGGER = logging.getLogger(__name__)
|
||||
|
|
@ -79,9 +80,18 @@ class _WebSocketHub:
|
|||
|
||||
|
||||
class NavigationApiServer:
|
||||
def __init__(self, config: ApiConfig, state_store: ObjectStateStore) -> None:
|
||||
def __init__(
|
||||
self,
|
||||
config: ApiConfig,
|
||||
state_store: ObjectStateStore,
|
||||
zabbix_config: ZabbixConfig | None = None,
|
||||
floorplan_adapter: ZabbixFloorplanAdapter | None = None,
|
||||
) -> None:
|
||||
self._config = config
|
||||
self._state_store = state_store
|
||||
self._floorplan_adapter = floorplan_adapter
|
||||
if self._floorplan_adapter is None and zabbix_config is not None:
|
||||
self._floorplan_adapter = ZabbixFloorplanAdapter(config, zabbix_config)
|
||||
self._hub = _WebSocketHub(self.build_stream_payload)
|
||||
self.app = web.Application(middlewares=[_cors_middleware])
|
||||
self.app.add_routes(
|
||||
|
|
@ -89,6 +99,7 @@ class NavigationApiServer:
|
|||
web.get("/api/v1/objects", self._handle_objects),
|
||||
web.get("/api/v1/objects/locations", self._handle_locations),
|
||||
web.get("/api/v1/bssid-locations", self._handle_bssid_locations),
|
||||
web.get("/api/v1/floorplan", self._handle_floorplan),
|
||||
web.get("/api/v1/objects/{object_id}", self._handle_object_card),
|
||||
web.get("/api/v1/stream/locations", self._handle_stream_locations),
|
||||
]
|
||||
|
|
@ -179,6 +190,16 @@ class NavigationApiServer:
|
|||
async def _handle_bssid_locations(self, _request: web.Request) -> web.Response:
|
||||
return web.json_response(self.build_bssid_locations_response())
|
||||
|
||||
async def _handle_floorplan(self, _request: web.Request) -> web.Response:
|
||||
if self._floorplan_adapter is None or not self._floorplan_adapter.is_enabled():
|
||||
return web.json_response({"error": "floorplan source is not configured"}, status=503)
|
||||
try:
|
||||
payload = self._floorplan_adapter.build_floorplan_response()
|
||||
except ZabbixApiError as exc:
|
||||
LOGGER.warning("Floorplan adapter request failed: %s", exc)
|
||||
return web.json_response({"error": str(exc)}, status=502)
|
||||
return web.json_response(payload)
|
||||
|
||||
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)
|
||||
|
|
|
|||
|
|
@ -43,6 +43,7 @@ class Robot2ZabbixService:
|
|||
self._navigation_api_server = navigation_api_server or NavigationApiServer(
|
||||
config.api,
|
||||
self._object_state_store,
|
||||
config.zabbix,
|
||||
)
|
||||
self._executor = ThreadPoolExecutor(max_workers=max_workers, thread_name_prefix="r2z")
|
||||
self._stop_event = threading.Event()
|
||||
|
|
|
|||
|
|
@ -122,6 +122,11 @@ class ZabbixConfig:
|
|||
server_port: int
|
||||
timeout_ms: int
|
||||
extra_args: list[str]
|
||||
api_url: str | None
|
||||
api_token: str | None
|
||||
verify_tls: bool
|
||||
history_window_sec: int
|
||||
tail_limit: int
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
|
|
|
|||
|
|
@ -0,0 +1,442 @@
|
|||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import ssl
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
from dataclasses import asdict
|
||||
from typing import Any
|
||||
|
||||
from .types import ApiConfig, ObjectLocation, ZabbixConfig
|
||||
|
||||
|
||||
LOGGER = logging.getLogger(__name__)
|
||||
|
||||
_LOCATION_X_KEY = "wifi.location.x"
|
||||
_LOCATION_Y_KEY = "wifi.location.y"
|
||||
_BSSID_KEY = "wifi.state.bssid"
|
||||
_RSSI_KEY = "wifi.signal.rssi_dbm"
|
||||
_STATUS_KEY = "robot.status"
|
||||
_FLOAT_HISTORY_TYPE = 0
|
||||
_STRING_HISTORY_TYPE = 1
|
||||
|
||||
|
||||
class ZabbixApiError(RuntimeError):
|
||||
pass
|
||||
|
||||
|
||||
class ZabbixApiClient:
|
||||
def __init__(self, api_url: str, api_token: str, verify_tls: bool = True, timeout_sec: float = 10.0) -> None:
|
||||
self._api_url = api_url
|
||||
self._api_token = api_token
|
||||
self._timeout_sec = timeout_sec
|
||||
self._request_id = 0
|
||||
self._ssl_context = ssl.create_default_context() if verify_tls else ssl._create_unverified_context()
|
||||
|
||||
def call(self, method: str, params: dict[str, Any]) -> Any:
|
||||
self._request_id += 1
|
||||
payload = json.dumps(
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"method": method,
|
||||
"params": params,
|
||||
"id": self._request_id,
|
||||
}
|
||||
).encode("utf-8")
|
||||
request = urllib.request.Request(
|
||||
self._api_url,
|
||||
data=payload,
|
||||
headers={
|
||||
"Content-Type": "application/json-rpc",
|
||||
"Authorization": f"Bearer {self._api_token}",
|
||||
},
|
||||
method="POST",
|
||||
)
|
||||
try:
|
||||
with urllib.request.urlopen(request, timeout=self._timeout_sec, context=self._ssl_context) as response:
|
||||
raw_response = response.read()
|
||||
except urllib.error.URLError as exc:
|
||||
raise ZabbixApiError(f"Failed to reach Zabbix API: {exc}") from exc
|
||||
|
||||
try:
|
||||
decoded = json.loads(raw_response.decode("utf-8"))
|
||||
except (UnicodeDecodeError, json.JSONDecodeError) as exc:
|
||||
raise ZabbixApiError("Zabbix API returned invalid JSON") from exc
|
||||
|
||||
if not isinstance(decoded, dict):
|
||||
raise ZabbixApiError("Zabbix API response must be a JSON object")
|
||||
error = decoded.get("error")
|
||||
if isinstance(error, dict):
|
||||
message = error.get("data") or error.get("message") or "unknown error"
|
||||
raise ZabbixApiError(f"Zabbix API call {method} failed: {message}")
|
||||
return decoded.get("result", [])
|
||||
|
||||
|
||||
class ZabbixFloorplanAdapter:
|
||||
def __init__(
|
||||
self,
|
||||
api_config: ApiConfig,
|
||||
zabbix_config: ZabbixConfig,
|
||||
api_client: ZabbixApiClient | None = None,
|
||||
) -> None:
|
||||
self._api_config = api_config
|
||||
self._zabbix_config = zabbix_config
|
||||
self._api_client = api_client
|
||||
|
||||
def is_enabled(self) -> bool:
|
||||
return bool(self._zabbix_config.api_url and self._zabbix_config.api_token)
|
||||
|
||||
def build_floorplan_response(self) -> dict[str, Any]:
|
||||
if not self.is_enabled():
|
||||
raise ZabbixApiError("Zabbix floorplan adapter is not configured")
|
||||
|
||||
hosts_by_name = self._load_hosts()
|
||||
items_by_host = self._load_items(hosts_by_name)
|
||||
history_by_host = self._load_tail_history(items_by_host)
|
||||
server_time_unix_ms = _now_unix_ms()
|
||||
|
||||
objects = []
|
||||
for object_id, catalog_entry in self._api_config.objects.items():
|
||||
host = hosts_by_name.get(object_id)
|
||||
item_map = items_by_host.get(object_id, {})
|
||||
latest_state = _build_latest_state(
|
||||
item_map=item_map,
|
||||
object_id=object_id,
|
||||
stale_timeout_ms=self._api_config.stale_timeout_ms,
|
||||
offline_timeout_ms=self._api_config.offline_timeout_ms,
|
||||
server_time_unix_ms=server_time_unix_ms,
|
||||
)
|
||||
objects.append(
|
||||
{
|
||||
"object_id": object_id,
|
||||
"object_type": catalog_entry.object_type,
|
||||
"name": catalog_entry.name,
|
||||
"status": latest_state["status"],
|
||||
"navigation_status": latest_state["navigation_status"],
|
||||
"location": asdict(latest_state["location"]) if latest_state["location"] is not None else None,
|
||||
"bssid": latest_state["bssid"],
|
||||
"rssi_dbm": latest_state["rssi_dbm"],
|
||||
"observed_at_unix_ms": latest_state["observed_at_unix_ms"],
|
||||
"updated_at_unix_ms": latest_state["updated_at_unix_ms"],
|
||||
"tail_points": history_by_host.get(object_id, []),
|
||||
"host_id": host["hostid"] if host is not None else None,
|
||||
}
|
||||
)
|
||||
|
||||
return {
|
||||
"schema_version": "1.0",
|
||||
"server_time_unix_ms": server_time_unix_ms,
|
||||
"coordinate_system": {
|
||||
"type": self._api_config.coordinate_system.type,
|
||||
"unit": self._api_config.coordinate_system.unit,
|
||||
"origin": self._api_config.coordinate_system.origin,
|
||||
"axis": asdict(self._api_config.coordinate_system.axis),
|
||||
},
|
||||
"objects": objects,
|
||||
}
|
||||
|
||||
def _client(self) -> ZabbixApiClient:
|
||||
if self._api_client is None:
|
||||
assert self._zabbix_config.api_url is not None
|
||||
assert self._zabbix_config.api_token is not None
|
||||
self._api_client = ZabbixApiClient(
|
||||
api_url=self._zabbix_config.api_url,
|
||||
api_token=self._zabbix_config.api_token,
|
||||
verify_tls=self._zabbix_config.verify_tls,
|
||||
timeout_sec=max(self._zabbix_config.timeout_ms / 1000, 1),
|
||||
)
|
||||
return self._api_client
|
||||
|
||||
def _load_hosts(self) -> dict[str, dict[str, Any]]:
|
||||
host_names = list(self._api_config.objects.keys())
|
||||
result = self._client().call(
|
||||
"host.get",
|
||||
{
|
||||
"filter": {"host": host_names},
|
||||
"output": ["hostid", "host", "name"],
|
||||
},
|
||||
)
|
||||
hosts_by_name: dict[str, dict[str, Any]] = {}
|
||||
for host in result:
|
||||
if isinstance(host, dict) and isinstance(host.get("host"), str):
|
||||
hosts_by_name[host["host"]] = host
|
||||
return hosts_by_name
|
||||
|
||||
def _load_items(self, hosts_by_name: dict[str, dict[str, Any]]) -> dict[str, dict[str, dict[str, Any]]]:
|
||||
hostids = [host["hostid"] for host in hosts_by_name.values() if isinstance(host.get("hostid"), str)]
|
||||
if not hostids:
|
||||
return {}
|
||||
result = self._client().call(
|
||||
"item.get",
|
||||
{
|
||||
"hostids": hostids,
|
||||
"filter": {"key_": [_LOCATION_X_KEY, _LOCATION_Y_KEY, _BSSID_KEY, _RSSI_KEY, _STATUS_KEY]},
|
||||
"output": ["itemid", "hostid", "key_", "lastvalue", "lastclock", "value_type"],
|
||||
},
|
||||
)
|
||||
items_by_host: dict[str, dict[str, dict[str, Any]]] = {}
|
||||
host_name_by_id = {host["hostid"]: host_name for host_name, host in hosts_by_name.items()}
|
||||
for item in result:
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
host_name = host_name_by_id.get(item.get("hostid"))
|
||||
key = item.get("key_")
|
||||
if host_name is None or not isinstance(key, str):
|
||||
continue
|
||||
items_by_host.setdefault(host_name, {})[key] = item
|
||||
return items_by_host
|
||||
|
||||
def _load_tail_history(self, items_by_host: dict[str, dict[str, dict[str, Any]]]) -> dict[str, list[dict[str, Any]]]:
|
||||
item_ids: list[str] = []
|
||||
string_item_ids: list[str] = []
|
||||
for item_map in items_by_host.values():
|
||||
for key in (_LOCATION_X_KEY, _LOCATION_Y_KEY, _RSSI_KEY):
|
||||
item = item_map.get(key)
|
||||
if isinstance(item, dict) and isinstance(item.get("itemid"), str):
|
||||
item_ids.append(item["itemid"])
|
||||
bssid_item = item_map.get(_BSSID_KEY)
|
||||
if isinstance(bssid_item, dict) and isinstance(bssid_item.get("itemid"), str):
|
||||
string_item_ids.append(bssid_item["itemid"])
|
||||
|
||||
time_from = int(time.time()) - self._zabbix_config.history_window_sec
|
||||
float_events = self._load_history_events(item_ids, _FLOAT_HISTORY_TYPE, time_from)
|
||||
string_events = self._load_history_events(string_item_ids, _STRING_HISTORY_TYPE, time_from)
|
||||
return _build_tail_points(
|
||||
items_by_host=items_by_host,
|
||||
float_events=float_events,
|
||||
string_events=string_events,
|
||||
tail_limit=self._zabbix_config.tail_limit,
|
||||
)
|
||||
|
||||
def _load_history_events(self, itemids: list[str], history_type: int, time_from: int) -> list[dict[str, Any]]:
|
||||
if not itemids:
|
||||
return []
|
||||
limit = max(self._zabbix_config.tail_limit * max(len(itemids), 1), self._zabbix_config.tail_limit)
|
||||
result = self._client().call(
|
||||
"history.get",
|
||||
{
|
||||
"history": history_type,
|
||||
"itemids": itemids,
|
||||
"time_from": time_from,
|
||||
"sortfield": ["clock", "ns"],
|
||||
"sortorder": "ASC",
|
||||
"output": "extend",
|
||||
"limit": limit,
|
||||
},
|
||||
)
|
||||
return [event for event in result if isinstance(event, dict)]
|
||||
|
||||
|
||||
def _build_latest_state(
|
||||
item_map: dict[str, dict[str, Any]],
|
||||
object_id: str,
|
||||
stale_timeout_ms: int,
|
||||
offline_timeout_ms: int,
|
||||
server_time_unix_ms: int,
|
||||
) -> dict[str, Any]:
|
||||
del object_id
|
||||
x_value, x_clock = _parse_numeric_item(item_map.get(_LOCATION_X_KEY))
|
||||
y_value, y_clock = _parse_numeric_item(item_map.get(_LOCATION_Y_KEY))
|
||||
rssi_value, rssi_clock = _parse_numeric_item(item_map.get(_RSSI_KEY))
|
||||
bssid_value, bssid_clock = _parse_string_item(item_map.get(_BSSID_KEY))
|
||||
status_value, status_clock = _parse_string_item(item_map.get(_STATUS_KEY))
|
||||
|
||||
location_clock = _max_defined(x_clock, y_clock)
|
||||
wifi_clock = _max_defined(bssid_clock, rssi_clock)
|
||||
updated_at_unix_ms = _max_defined(location_clock, wifi_clock, status_clock)
|
||||
observed_at_unix_ms = location_clock or updated_at_unix_ms
|
||||
|
||||
location = None
|
||||
if x_value is not None and y_value is not None:
|
||||
location = ObjectLocation(
|
||||
x=x_value,
|
||||
y=y_value,
|
||||
z=None,
|
||||
heading=None,
|
||||
accuracy=None,
|
||||
)
|
||||
|
||||
derived_status = _derive_status(updated_at_unix_ms, stale_timeout_ms, offline_timeout_ms, server_time_unix_ms)
|
||||
status = status_value if status_value else derived_status
|
||||
navigation_status = "ok" if location is not None and status != "offline" else "lost"
|
||||
if derived_status != "online":
|
||||
bssid_value = None
|
||||
rssi_value = None
|
||||
|
||||
return {
|
||||
"status": status,
|
||||
"navigation_status": navigation_status,
|
||||
"location": location,
|
||||
"bssid": bssid_value,
|
||||
"rssi_dbm": rssi_value,
|
||||
"observed_at_unix_ms": observed_at_unix_ms,
|
||||
"updated_at_unix_ms": updated_at_unix_ms,
|
||||
}
|
||||
|
||||
|
||||
def _build_tail_points(
|
||||
items_by_host: dict[str, dict[str, dict[str, Any]]],
|
||||
float_events: list[dict[str, Any]],
|
||||
string_events: list[dict[str, Any]],
|
||||
tail_limit: int,
|
||||
) -> dict[str, list[dict[str, Any]]]:
|
||||
host_for_itemid: dict[str, str] = {}
|
||||
key_for_itemid: dict[str, str] = {}
|
||||
for host_name, item_map in items_by_host.items():
|
||||
for key, item in item_map.items():
|
||||
itemid = item.get("itemid")
|
||||
if isinstance(itemid, str):
|
||||
host_for_itemid[itemid] = host_name
|
||||
key_for_itemid[itemid] = key
|
||||
|
||||
point_maps: dict[str, dict[int, dict[str, Any]]] = {}
|
||||
bssid_timelines: dict[str, list[tuple[int, str]]] = {}
|
||||
rssi_timelines: dict[str, list[tuple[int, float]]] = {}
|
||||
|
||||
for event in float_events:
|
||||
itemid = event.get("itemid")
|
||||
host_name = host_for_itemid.get(itemid)
|
||||
key = key_for_itemid.get(itemid)
|
||||
if host_name is None or key is None:
|
||||
continue
|
||||
event_time = _history_event_time_ms(event)
|
||||
if event_time is None:
|
||||
continue
|
||||
value = _coerce_float(event.get("value"))
|
||||
if value is None:
|
||||
continue
|
||||
if key == _RSSI_KEY:
|
||||
rssi_timelines.setdefault(host_name, []).append((event_time, value))
|
||||
continue
|
||||
if key not in (_LOCATION_X_KEY, _LOCATION_Y_KEY):
|
||||
continue
|
||||
point = point_maps.setdefault(host_name, {}).setdefault(
|
||||
event_time,
|
||||
{
|
||||
"observed_at_unix_ms": event_time,
|
||||
"x": None,
|
||||
"y": None,
|
||||
},
|
||||
)
|
||||
if key == _LOCATION_X_KEY:
|
||||
point["x"] = value
|
||||
else:
|
||||
point["y"] = value
|
||||
|
||||
for event in string_events:
|
||||
itemid = event.get("itemid")
|
||||
host_name = host_for_itemid.get(itemid)
|
||||
key = key_for_itemid.get(itemid)
|
||||
if host_name is None or key != _BSSID_KEY:
|
||||
continue
|
||||
event_time = _history_event_time_ms(event)
|
||||
value = event.get("value")
|
||||
if event_time is None or not isinstance(value, str) or not value:
|
||||
continue
|
||||
bssid_timelines.setdefault(host_name, []).append((event_time, value))
|
||||
|
||||
history_by_host: dict[str, list[dict[str, Any]]] = {}
|
||||
for host_name, points_by_time in point_maps.items():
|
||||
points = []
|
||||
sorted_bssid = sorted(bssid_timelines.get(host_name, []), key=lambda item: item[0])
|
||||
sorted_rssi = sorted(rssi_timelines.get(host_name, []), key=lambda item: item[0])
|
||||
for event_time in sorted(points_by_time):
|
||||
point = points_by_time[event_time]
|
||||
if point["x"] is None or point["y"] is None:
|
||||
continue
|
||||
points.append(
|
||||
{
|
||||
"x": point["x"],
|
||||
"y": point["y"],
|
||||
"bssid": _latest_value_before(sorted_bssid, event_time),
|
||||
"rssi_dbm": _latest_value_before(sorted_rssi, event_time),
|
||||
"observed_at_unix_ms": event_time,
|
||||
}
|
||||
)
|
||||
if len(points) > tail_limit:
|
||||
points = points[-tail_limit:]
|
||||
history_by_host[host_name] = points
|
||||
return history_by_host
|
||||
|
||||
|
||||
def _latest_value_before(timeline: list[tuple[int, Any]], event_time: int) -> Any:
|
||||
latest_value = None
|
||||
for candidate_time, candidate_value in timeline:
|
||||
if candidate_time > event_time:
|
||||
break
|
||||
latest_value = candidate_value
|
||||
return latest_value
|
||||
|
||||
|
||||
def _derive_status(
|
||||
updated_at_unix_ms: int | None,
|
||||
stale_timeout_ms: int,
|
||||
offline_timeout_ms: int,
|
||||
server_time_unix_ms: int,
|
||||
) -> str:
|
||||
if updated_at_unix_ms is None:
|
||||
return "offline"
|
||||
age_ms = max(server_time_unix_ms - updated_at_unix_ms, 0)
|
||||
if age_ms > offline_timeout_ms:
|
||||
return "offline"
|
||||
if age_ms > stale_timeout_ms:
|
||||
return "stale"
|
||||
return "online"
|
||||
|
||||
|
||||
def _parse_numeric_item(item: dict[str, Any] | None) -> tuple[float | None, int | None]:
|
||||
if not isinstance(item, dict):
|
||||
return None, None
|
||||
return _coerce_float(item.get("lastvalue")), _coerce_clock_ms(item.get("lastclock"))
|
||||
|
||||
|
||||
def _parse_string_item(item: dict[str, Any] | None) -> tuple[str | None, int | None]:
|
||||
if not isinstance(item, dict):
|
||||
return None, None
|
||||
value = item.get("lastvalue")
|
||||
if not isinstance(value, str) or not value.strip():
|
||||
return None, _coerce_clock_ms(item.get("lastclock"))
|
||||
return value.strip(), _coerce_clock_ms(item.get("lastclock"))
|
||||
|
||||
|
||||
def _history_event_time_ms(event: dict[str, Any]) -> int | None:
|
||||
clock_ms = _coerce_clock_ms(event.get("clock"))
|
||||
if clock_ms is None:
|
||||
return None
|
||||
ns_raw = event.get("ns")
|
||||
ns_value = 0
|
||||
if isinstance(ns_raw, str) and ns_raw.isdigit():
|
||||
ns_value = int(ns_raw)
|
||||
elif isinstance(ns_raw, int):
|
||||
ns_value = ns_raw
|
||||
return clock_ms + int(ns_value / 1_000_000)
|
||||
|
||||
|
||||
def _coerce_clock_ms(value: Any) -> int | None:
|
||||
if isinstance(value, str) and value.isdigit():
|
||||
return int(value) * 1000
|
||||
if isinstance(value, int):
|
||||
return value * 1000
|
||||
return None
|
||||
|
||||
|
||||
def _coerce_float(value: Any) -> float | None:
|
||||
if isinstance(value, (int, float)):
|
||||
return float(value)
|
||||
if isinstance(value, str):
|
||||
try:
|
||||
return float(value)
|
||||
except ValueError:
|
||||
return None
|
||||
return None
|
||||
|
||||
|
||||
def _max_defined(*values: int | None) -> int | None:
|
||||
defined_values = [value for value in values if value is not None]
|
||||
return max(defined_values) if defined_values else None
|
||||
|
||||
|
||||
def _now_unix_ms() -> int:
|
||||
return int(time.time() * 1000)
|
||||
|
|
@ -3,7 +3,7 @@ from __future__ import annotations
|
|||
import asyncio
|
||||
import json
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
from aiohttp.test_utils import TestClient, TestServer
|
||||
|
||||
|
|
@ -16,7 +16,7 @@ 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.host == "0.0.0.0"
|
||||
assert config.api.port == 8080
|
||||
assert "h1500-09-01-00011" in config.api.objects
|
||||
|
||||
|
|
@ -233,6 +233,33 @@ def test_websocket_receives_initial_and_broadcast_snapshots() -> None:
|
|||
asyncio.run(_run())
|
||||
|
||||
|
||||
def test_floorplan_endpoint_returns_adapter_payload() -> None:
|
||||
async def _run() -> None:
|
||||
config = load_config("config/r2z-backend.yaml")
|
||||
store = ObjectStateStore(config.api)
|
||||
adapter = MagicMock()
|
||||
adapter.is_enabled.return_value = True
|
||||
adapter.build_floorplan_response.return_value = {
|
||||
"schema_version": "1.0",
|
||||
"server_time_unix_ms": 8_000,
|
||||
"coordinate_system": {"type": "local_relative", "unit": "meter", "origin": "site_origin"},
|
||||
"objects": [{"object_id": "h1500-09-01-00011"}],
|
||||
}
|
||||
api_server = NavigationApiServer(config.api, store, floorplan_adapter=adapter)
|
||||
client = TestClient(TestServer(api_server.app))
|
||||
await client.start_server()
|
||||
try:
|
||||
response = await client.get("/api/v1/floorplan")
|
||||
payload = await response.json()
|
||||
assert response.status == 200
|
||||
assert payload["objects"][0]["object_id"] == "h1500-09-01-00011"
|
||||
adapter.build_floorplan_response.assert_called_once()
|
||||
finally:
|
||||
await client.close()
|
||||
|
||||
asyncio.run(_run())
|
||||
|
||||
|
||||
def test_stale_object_suppresses_wifi_fields_in_api() -> None:
|
||||
async def _run() -> None:
|
||||
config = load_config("config/r2z-backend.yaml")
|
||||
|
|
|
|||
|
|
@ -16,6 +16,11 @@ def make_config() -> ZabbixConfig:
|
|||
server_port=10051,
|
||||
timeout_ms=3000,
|
||||
extra_args=[],
|
||||
api_url=None,
|
||||
api_token=None,
|
||||
verify_tls=True,
|
||||
history_window_sec=900,
|
||||
tail_limit=200,
|
||||
)
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -0,0 +1,98 @@
|
|||
from __future__ import annotations
|
||||
|
||||
from unittest.mock import patch
|
||||
|
||||
from robot2zabbix_backend.config import load_config
|
||||
from robot2zabbix_backend.zabbix_floorplan import ZabbixFloorplanAdapter
|
||||
|
||||
|
||||
class _FakeZabbixApiClient:
|
||||
def call(self, method: str, params: dict) -> list[dict]:
|
||||
if method == "host.get":
|
||||
return [
|
||||
{
|
||||
"hostid": "101",
|
||||
"host": "h1500-09-01-00011",
|
||||
"name": "Robot 31 host",
|
||||
}
|
||||
]
|
||||
if method == "item.get":
|
||||
return [
|
||||
{
|
||||
"itemid": "1001",
|
||||
"hostid": "101",
|
||||
"key_": "wifi.location.x",
|
||||
"lastvalue": "-55.1",
|
||||
"lastclock": "20",
|
||||
"value_type": "0",
|
||||
},
|
||||
{
|
||||
"itemid": "1002",
|
||||
"hostid": "101",
|
||||
"key_": "wifi.location.y",
|
||||
"lastvalue": "60.2",
|
||||
"lastclock": "20",
|
||||
"value_type": "0",
|
||||
},
|
||||
{
|
||||
"itemid": "1003",
|
||||
"hostid": "101",
|
||||
"key_": "wifi.state.bssid",
|
||||
"lastvalue": "11:22:33:44:55:66",
|
||||
"lastclock": "20",
|
||||
"value_type": "1",
|
||||
},
|
||||
{
|
||||
"itemid": "1004",
|
||||
"hostid": "101",
|
||||
"key_": "wifi.signal.rssi_dbm",
|
||||
"lastvalue": "-67",
|
||||
"lastclock": "20",
|
||||
"value_type": "0",
|
||||
},
|
||||
]
|
||||
if method == "history.get":
|
||||
history_type = params["history"]
|
||||
itemids = set(params["itemids"])
|
||||
if history_type == 0 and "1001" in itemids:
|
||||
return [
|
||||
{"itemid": "1001", "clock": "10", "ns": "0", "value": "-56.0"},
|
||||
{"itemid": "1002", "clock": "10", "ns": "0", "value": "59.0"},
|
||||
{"itemid": "1004", "clock": "10", "ns": "0", "value": "-71"},
|
||||
{"itemid": "1001", "clock": "20", "ns": "0", "value": "-55.1"},
|
||||
{"itemid": "1002", "clock": "20", "ns": "0", "value": "60.2"},
|
||||
{"itemid": "1004", "clock": "20", "ns": "0", "value": "-67"},
|
||||
]
|
||||
if history_type == 1 and "1003" in itemids:
|
||||
return [
|
||||
{"itemid": "1003", "clock": "9", "ns": "0", "value": "aa:aa:aa:aa:aa:aa"},
|
||||
{"itemid": "1003", "clock": "15", "ns": "0", "value": "11:22:33:44:55:66"},
|
||||
]
|
||||
raise AssertionError(f"Unexpected method {method}")
|
||||
|
||||
|
||||
def test_floorplan_adapter_builds_snapshot_from_zabbix_items() -> None:
|
||||
config = load_config("config/r2z-backend.yaml")
|
||||
config.zabbix.api_url = "http://zabbix.example/api_jsonrpc.php"
|
||||
config.zabbix.api_token = "demo-token"
|
||||
config.zabbix.tail_limit = 5
|
||||
adapter = ZabbixFloorplanAdapter(config.api, config.zabbix, api_client=_FakeZabbixApiClient())
|
||||
|
||||
with patch("robot2zabbix_backend.zabbix_floorplan._now_unix_ms", return_value=20_500), patch(
|
||||
"robot2zabbix_backend.zabbix_floorplan.time.time",
|
||||
return_value=20,
|
||||
):
|
||||
payload = adapter.build_floorplan_response()
|
||||
|
||||
assert payload["schema_version"] == "1.0"
|
||||
assert payload["coordinate_system"]["axis"]["x"] == "east"
|
||||
object_payload = payload["objects"][0]
|
||||
assert object_payload["object_id"] == "h1500-09-01-00011"
|
||||
assert object_payload["status"] == "online"
|
||||
assert object_payload["location"]["x"] == -55.1
|
||||
assert object_payload["location"]["y"] == 60.2
|
||||
assert object_payload["bssid"] == "11:22:33:44:55:66"
|
||||
assert object_payload["rssi_dbm"] == -67.0
|
||||
assert len(object_payload["tail_points"]) == 2
|
||||
assert object_payload["tail_points"][0]["bssid"] == "aa:aa:aa:aa:aa:aa"
|
||||
assert object_payload["tail_points"][1]["bssid"] == "11:22:33:44:55:66"
|
||||
Loading…
Reference in New Issue