feat(k1): add USB networking, device management and acquisition recovery

This commit is contained in:
DCCONSTRUCTIONS
2026-11-04 00:42:57 +03:00
parent 14c3c7c2b6
commit 038337783f
78 changed files with 4612 additions and 384 deletions
@@ -67,6 +67,7 @@ ActiveAcquisitionRecoveryConnectionMode = Literal[
"bridge",
"quick-connect",
"direct-connect",
"usb",
]
ActiveAcquisitionRecoveryEvidencePolicy = Literal["required", "best-effort", "disabled"]
ActiveAcquisitionRecoveryMountType = Literal["handheld"]
@@ -120,7 +121,7 @@ ActiveAcquisitionRecoveryTransitionKind = Literal[
]
_CHECKPOINT_STATES = frozenset({"prepared", "active", "ceased"})
_CONNECTION_MODES = frozenset({"bridge", "quick-connect", "direct-connect"})
_CONNECTION_MODES = frozenset({"bridge", "quick-connect", "direct-connect", "usb"})
_EVIDENCE_POLICIES = frozenset({"required", "best-effort", "disabled"})
_MOUNT_TYPES = frozenset({"handheld"})
_GNSS_MODES = frozenset({"none"})
@@ -112,7 +112,7 @@ def _network_attempt_matches_live_control_authority(
and isinstance(transport_ref, str)
and transport_ref
and context.get("transport_ref") == transport_ref
and connection_mode in {"bridge", "quick-connect", "direct-connect"}
and connection_mode in {"bridge", "quick-connect", "direct-connect", "usb"}
and context.get("connection_mode") == connection_mode
and isinstance(target_ipv4, str)
and target_ipv4
@@ -187,7 +187,7 @@ def _owned_control_bootstrap_matches_network_attempt(
and network_result.get("parent_intent_id") == network_operation_id
and isinstance(transport_ref, str)
and transport_ref
and connection_mode in {"bridge", "quick-connect", "direct-connect"}
and connection_mode in {"bridge", "quick-connect", "direct-connect", "usb"}
and isinstance(target_ipv4, str)
and target_ipv4
and target_port == CONTROL_MQTT_PORT
@@ -252,7 +252,7 @@ def _recovery_verify_matches_network_attempt(
and network_result.get("parent_intent_id") == network_operation_id
and isinstance(transport_ref, str)
and transport_ref
and connection_mode in {"bridge", "quick-connect", "direct-connect"}
and connection_mode in {"bridge", "quick-connect", "direct-connect", "usb"}
and isinstance(target_ipv4, str)
and target_ipv4
and target_port == CONTROL_MQTT_PORT
@@ -16,7 +16,7 @@ from k1link.device_plugins.xgrids_k1.host_diagnostics import (
host_diagnostics_for_reasons,
)
ConnectionMode = Literal["bridge", "quick-connect", "direct-connect"]
ConnectionMode = Literal["bridge", "quick-connect", "direct-connect", "usb"]
RouteClass = Literal["direct", "default", "tunnel", "unavailable", "unknown"]
TcpState = Literal["unknown", "reachable", "unreachable"]
IdentityState = Literal["unverified", "verified", "stale", "mismatch"]
@@ -27,6 +27,7 @@ DeviceNetworkSource = Literal[
"ble-post-write-status",
"ble-read-only-status",
"durable-semantic-topology",
"usb-enumeration",
]
AllowedAction = Literal[
"select-connection-intent",
@@ -0,0 +1,68 @@
"""Plugin action boundary for explicit, idle-only XGRIDS maintenance."""
from __future__ import annotations
import hashlib
from typing import Any, Literal, Self, cast
from pydantic import BaseModel, ConfigDict, Field, model_validator
from k1link.web.device_lifecycle import TERMINAL_ACQUISITION_STATES
ACTION_DEVICE_MANAGE = "device.manage"
class DeviceManagementRequest(BaseModel):
model_config = ConfigDict(extra="forbid", strict=True)
operation_id: str = Field(pattern=r"^[A-Za-z0-9_-]{1,128}$")
operation: Literal["info", "projects", "delete-projects", "format-storage", "usb-storage",
"usb-data", "power-off", "reboot"]
expected_session_generation: int = Field(ge=0)
expected_state_revision: int = Field(ge=0)
operator_confirmed: bool = False
project_ids: list[str] = Field(default_factory=list, max_length=4096)
catalog_revision: str | None = None
@model_validator(mode="after")
def validate_operation(self) -> Self:
if self.operation not in {"info", "projects"} and not self.operator_confirmed:
raise ValueError("Подтвердите операцию с K1")
if (self.operation == "delete-projects") != bool(self.project_ids):
raise ValueError("Выберите проекты для удаления")
if len(set(self.project_ids)) != len(self.project_ids):
raise ValueError("Проекты повторяются в выборе")
return self
def manage_device(service: Any, request: DeviceManagementRequest) -> dict[str, object]:
with service._lock:
acquisition = service._acquisition
if acquisition is not None and acquisition.state not in TERMINAL_ACQUISITION_STATES:
raise ValueError("Сначала завершите съёмку K1")
device_id, session_id = service._device_id, service._device_session_id
fingerprint = hashlib.sha256(request.model_dump_json().encode()).hexdigest()
record, created = service._operations.begin(
ACTION_DEVICE_MANAGE, operation_id=request.operation_id,
idempotency_key=request.operation_id, device_id=device_id, device_session_id=session_id,
deadline_seconds=30, request_fingerprint=fingerprint,
)
if not created:
return cast(dict[str, object], record.result) if record.result else {
"status": "unknown", "message": "Операция уже была принята",
}
try:
result = service._application_control_session.manage_device(
operation=request.operation, identifier=request.operation_id,
project_ids=tuple(request.project_ids), catalog_revision=request.catalog_revision,
expected_session_generation=request.expected_session_generation,
expected_state_revision=request.expected_state_revision,
)
except ValueError as exc:
result = {"status": "blocked", "message": str(exc)}
except Exception:
result = {"status": "unknown", "message": "K1 не подтвердил результат операции"}
service._operations.transition(
record.operation_id, "succeeded" if result["status"] == "succeeded" else "failed",
stage_code="device-management", message_code="device.management." + result["status"],
result=result,
)
return cast(dict[str, object], result)
+282 -49
View File
@@ -19,14 +19,14 @@ import unicodedata
from collections.abc import Awaitable, Callable, Collection, Iterator, Mapping, Sequence
from concurrent.futures import Future as ConcurrentFuture
from concurrent.futures import TimeoutError as ConcurrentFutureTimeout
from contextlib import AbstractContextManager, ExitStack, contextmanager, suppress
from contextlib import AbstractContextManager, ExitStack, contextmanager, nullcontext, suppress
from dataclasses import dataclass
from dataclasses import replace as dataclass_replace
from datetime import UTC, datetime
from functools import wraps
from pathlib import Path
from typing import Any, Concatenate, Literal, Protocol, Self, cast
from uuid import uuid4
from uuid import NAMESPACE_URL, uuid4, uuid5
from bleak.exc import BleakDeviceNotFoundError, BleakError
from missioncore_plugin_sdk.v0alpha2 import (
@@ -144,6 +144,11 @@ from k1link.device_plugins.xgrids_k1.device_identity_pin_store import (
DeviceIdentityPinStoreCorrupt,
DeviceIdentityPinStoreError,
)
from k1link.device_plugins.xgrids_k1.device_management import (
ACTION_DEVICE_MANAGE,
DeviceManagementRequest,
manage_device,
)
from k1link.device_plugins.xgrids_k1.firmware_credential import (
K1_FW302_CREDENTIAL_PROVIDER_ID,
)
@@ -263,6 +268,8 @@ from k1link.web.plugin_runtime import (
PluginExecutionError,
)
from .usb_network import LinuxK1UsbProbe, UsbNetworkAttachment
XGRIDS_K1_PLUGIN_ID = "nodedc.device.xgrids-lixelkity-k1"
XGRIDS_K1_PLUGIN_VERSION = "0.7.5"
XGRIDS_K1_MODEL_ID = "xgrids.lixelkity-k1"
@@ -332,12 +339,13 @@ def _capture_network_intent_device(
return capture_discovered_device(macos_uuid)
ConnectionMode = Literal["bridge", "quick-connect", "direct-connect"]
ConnectionTopology = Literal["direct-lan", "device-ap", "controller-hotspot"]
ConnectionMode = Literal["bridge", "quick-connect", "direct-connect", "usb"]
ConnectionTopology = Literal["direct-lan", "device-ap", "controller-hotspot", "usb-ethernet"]
CONNECTION_TOPOLOGY_BY_MODE: dict[ConnectionMode, ConnectionTopology] = {
"bridge": "direct-lan",
"quick-connect": "device-ap",
"direct-connect": "controller-hotspot",
"usb": "usb-ethernet",
}
@@ -424,6 +432,7 @@ class ConfiguredEndpointProbeError(RuntimeError):
ACTION_STATE_READ = "state.read"
ACTION_DISCOVERY_SCAN = "discovery.scan"
ACTION_DEVICE_INSPECT = "device.inspect"
ACTION_SENSOR_CATALOG_READ = "sensor.catalog.read"
@@ -1030,7 +1039,7 @@ class ConnectRequest(StrictRequest):
device_id: str = Field(min_length=1, max_length=128)
ssid: str | None = Field(default=None, min_length=1, max_length=128)
password: SecretStr | None = Field(default=None, min_length=1, max_length=256)
connection_mode: ConnectionMode = "bridge"
connection_mode: Literal["bridge", "quick-connect", "direct-connect"] = "bridge"
compatibility_attestation: CompatibilityAttestationRequest
operation_id: str | None = Field(default=None, min_length=1, max_length=128)
idempotency_key: str = Field(min_length=16, max_length=160)
@@ -1077,9 +1086,9 @@ class ConnectionVerifyRequest(StrictRequest):
# the service resolves that form only from its current/durable exact
# target. New clients send the complete server-issued target contract.
device_id: str | None = Field(default=None, min_length=1, max_length=128)
source: Literal["fresh-scan", "retained-current-process", "durable-configured-state"] = (
"fresh-scan"
)
source: Literal[
"fresh-scan", "retained-current-process", "durable-configured-state", "usb-enumeration"
] = "fresh-scan"
compatibility_attestation: CompatibilityAttestationRequest | None = None
operation_id: str | None = Field(default=None, min_length=1, max_length=128)
# New clients bind Verify to the exact mode draft rendered at the click.
@@ -1239,12 +1248,13 @@ class _ProvisionalFreshBridgeTopology:
discovery_generation: int
device_session_id: str
transport_ref: str
connection_mode: Literal["bridge"]
connection_mode: Literal["bridge", "usb"]
ipv4: str
firmware_version: str
observed_at_utc: str
semantic_predecessor_revision: int
usb_generation: str | None = None
@dataclass(frozen=True, slots=True)
class _ScenarioResetRetiredTransportAuthority:
@@ -1395,7 +1405,7 @@ class ViewerSettingsRequest(StrictRequest):
color_mode: Literal["intensity", "height", "distance", "rgb", "class"] = "intensity"
palette: Literal["turbo", "viridis", "plasma", "grayscale", "custom"] = "turbo"
custom_color: str = Field(default="#f7f8f4", pattern=r"^#[0-9A-Fa-f]{6}$")
accumulation_seconds: float = Field(default=12.0, ge=0.0, le=120.0)
accumulation_seconds: float = Field(default=12.0, ge=0.0, allow_inf_nan=False)
show_points: bool = True
show_trajectory: bool = True
show_grid: bool = True
@@ -1476,6 +1486,7 @@ class XgridsK1CompatibilityService:
application_authority_loader: ApplicationAuthorityLoader | None = None,
calibration_snapshot_reader: DeviceCalibrationSnapshotReader | None = None,
host_wifi_association_probe: HostWifiAssociationProbe | None = None,
usb_network_probe: LinuxK1UsbProbe | None = None,
visualization_bridge_factory: Callable[..., Any] | None = None,
) -> None:
self.repository_root = repository_root.resolve()
@@ -1486,6 +1497,7 @@ class XgridsK1CompatibilityService:
# network/control lifecycle owner.
configure_ble_runtime_process_lease(self.repository_root)
self.evidence_root = resolve_missioncore_evidence_dir(self.repository_root)
self._usb_network_probe = usb_network_probe
self._host_wifi_association_probe = (
host_wifi_association_probe
or HostWifiAssociationIdentityProbe(
@@ -2163,7 +2175,9 @@ class XgridsK1CompatibilityService:
and topology_record is not None
and topology_record.transport_ref == transport_ref
and topology_record.connection_mode == connection_mode
and topology_record.source in {"ble-post-write-status", "ble-read-only-status"}
and topology_record.source in {
"ble-post-write-status", "ble-read-only-status", "usb-enumeration"
}
and ledger_record.last_observation.ipv4 == topology_record.ipv4
and topology_record.compatibility_profile_id == XGRIDS_K1_COMPATIBILITY_PROFILE_ID
):
@@ -2259,7 +2273,7 @@ class XgridsK1CompatibilityService:
ipv4: str,
compatibility_attestation: CompatibilityAttestationRequest,
captured_device: CapturedDiscoveredDevice | None,
source: Literal["ble-post-write-status", "ble-read-only-status"],
source: Literal["ble-post-write-status", "ble-read-only-status", "usb-enumeration"],
observed_at_utc: str,
) -> str | None:
"""Commit what the K1 reported, independently from the Mac route.
@@ -2311,6 +2325,7 @@ class XgridsK1CompatibilityService:
"ble-post-write-status",
"ble-read-only-status",
"durable-semantic-topology",
"usb-enumeration",
],
observed_at_utc: str,
force_new_session: bool,
@@ -2387,7 +2402,8 @@ class XgridsK1CompatibilityService:
self._connection_mode = connection_mode
self._device_id = self._device_ids_by_transport_ref.setdefault(
transport_ref,
new_device_id(),
(f"device-{uuid5(NAMESPACE_URL, 'xgrids-k1:' + transport_ref)}"
if connection_mode == "usb" else new_device_id()),
)
self._device_session_id = next_device_session_id
self._device_session_opened_at = observed_at_utc
@@ -2433,7 +2449,7 @@ class XgridsK1CompatibilityService:
connection_mode: ConnectionMode,
ipv4: str,
firmware_version: str,
source: Literal["ble-post-write-status", "ble-read-only-status"],
source: Literal["ble-post-write-status", "ble-read-only-status", "usb-enumeration"],
observed_at_utc: str,
predecessor_revision: int | None = None,
) -> None:
@@ -2557,6 +2573,27 @@ class XgridsK1CompatibilityService:
"""Bind one kernel route sample to this service's Wi-Fi association."""
path = _inspect_host_path(target)
with self._lock:
usb_transport = self._selected_device_id if self._connection_mode == "usb" else None
if usb_transport is not None:
try:
attachment = self._require_usb_attachment(usb_transport)
if (attachment.peer_ipv4 != target or attachment.interface != path.interface
or attachment.source_ipv4 != path.source_ipv4):
raise OSError("USB route changed")
except OSError:
return HostPathProbeResult(
available=False, fingerprint=None, interface=path.interface,
source_ipv4=path.source_ipv4, route_class="unavailable",
reason_code="usb-attachment-unavailable",
)
if path.available and path.fingerprint is not None:
return dataclass_replace(
path, fingerprint=hashlib.sha256(
(path.fingerprint + ":" + attachment.generation).encode()
).hexdigest(),
)
return path
association = self._host_wifi_association_probe.observe(
path.interface,
timeout_seconds=association_timeout_seconds,
@@ -2572,14 +2609,19 @@ class XgridsK1CompatibilityService:
if retained_unproven_path is not None:
return retained_unproven_path
if (
fail_closed_unproven_association
and not association["continuity_proven"]
# Missing BSSID is a documented macOS privacy condition. Its
# process-scoped fallback token still detects route/interface
# transitions. The monitor marks that result as unproven below so
# it cannot replace a verified association fingerprint merely
# because macOS changed what identity fields it disclosed.
and association_reason != "association-identity-unavailable"
not association["continuity_proven"]
and (
# Linux supplies no fallback token when NetworkManager cannot
# prove association. Report unavailable even during bootstrap;
# an empty token cannot be bound to a route fingerprint.
association["adapter"] == "linux-networkmanager"
or (
fail_closed_unproven_association
# macOS privacy-limited observations have a process-scoped
# fallback token. Preserve their existing continuity policy.
and association_reason != "association-identity-unavailable"
)
)
):
return HostPathProbeResult(
available=False,
@@ -3066,6 +3108,7 @@ class XgridsK1CompatibilityService:
semantic_predecessor_revision: int | None = None,
force_new_intent: bool = False,
persist_semantic_topology: bool = True,
source: Literal["ble-read-only-status", "usb-enumeration"] = "ble-read-only-status",
) -> str:
"""Bind an exact BLE status read to a fresh non-mutating intent."""
@@ -3081,7 +3124,7 @@ class XgridsK1CompatibilityService:
connection_mode=connection_mode,
ipv4=target.ipv4,
firmware_version=firmware_version,
source="ble-read-only-status",
source=source,
observed_at_utc=observed_at_utc,
predecessor_revision=semantic_predecessor_revision,
)
@@ -3110,7 +3153,7 @@ class XgridsK1CompatibilityService:
transport_ref=transport_ref,
connection_mode=connection_mode,
target=target,
source="ble-read-only-status",
source=source,
):
raise RuntimeError("read-only статус K1 потерял актуальность до admission")
return intent_id
@@ -3129,6 +3172,7 @@ class XgridsK1CompatibilityService:
force_new_intent: bool = False,
force_new_session: bool = False,
persist_semantic_topology: bool = True,
source: Literal["ble-read-only-status", "usb-enumeration"] = "ble-read-only-status",
retained_prepared_stop_owner: _PreparedStopRecoveryOwner | None = None,
) -> str:
"""Persist, supervise and project one exact non-mutating BLE status.
@@ -3168,6 +3212,7 @@ class XgridsK1CompatibilityService:
semantic_predecessor_revision=semantic_predecessor_revision,
force_new_intent=force_new_intent,
persist_semantic_topology=persist_semantic_topology,
source=source,
)
retired_ingress_session_id = self._project_applied_device_topology(
transport_ref=transport_ref,
@@ -3175,7 +3220,7 @@ class XgridsK1CompatibilityService:
target=target,
compatibility_attestation=attestation_snapshot,
captured_device=captured_device,
source="ble-read-only-status",
source=source,
observed_at_utc=observed_at_utc,
force_new_session=force_new_session,
retained_prepared_stop_owner=retained_prepared_stop_owner,
@@ -5731,7 +5776,7 @@ class XgridsK1CompatibilityService:
provisional.reconfiguration_intent_id
or f"fresh-verify-rejected-{provisional.device_session_id}"
),
requested_mode="bridge",
requested_mode=provisional.connection_mode,
expected_device_id=None,
)
with self._lock:
@@ -5817,12 +5862,21 @@ class XgridsK1CompatibilityService:
"DeviceInfo identity не закреплена за выбранным BLE transport",
reason_code="device-identity-pin-mismatch",
)
if provisional.connection_mode == "usb":
attachment = self._require_usb_attachment(provisional.transport_ref)
if (attachment.generation != provisional.usb_generation
or attachment.peer_ipv4 != provisional.ipv4):
raise ConnectionVerificationError(
"USB-подключение изменилось во время проверки",
reason_code="usb-attachment-changed",
)
self._persist_semantic_topology(
transport_ref=provisional.transport_ref,
connection_mode=provisional.connection_mode,
ipv4=provisional.ipv4,
firmware_version=provisional.firmware_version,
source="ble-read-only-status",
source=("usb-enumeration" if provisional.connection_mode == "usb"
else "ble-read-only-status"),
observed_at_utc=provisional.observed_at_utc,
predecessor_revision=provisional.semantic_predecessor_revision,
)
@@ -6385,7 +6439,9 @@ class XgridsK1CompatibilityService:
),
physical_recovery_mode=(
cast(ConnectionMode, recovery_connection_mode)
if recovery_connection_mode in {"bridge", "quick-connect", "direct-connect"}
if recovery_connection_mode in {
"bridge", "quick-connect", "direct-connect", "usb"
}
else None
),
)
@@ -10045,7 +10101,7 @@ class XgridsK1CompatibilityService:
and isinstance(scenario_reset_id, str)
and isinstance(scenario_reset_revision, int)
and scenario_reset_mode
in {"bridge", "quick-connect", "direct-connect"}
in {"bridge", "quick-connect", "direct-connect", "usb"}
and scenario_reset_revision == self._desired_connection_mode_revision
and scenario_reset_mode == self._desired_connection_mode
):
@@ -12642,6 +12698,25 @@ class XgridsK1CompatibilityService:
persisted = checkpoint.current_active_physical_proof
status = checkpoint.current_active_status_proof
# The physical READY commit may precede checkpoint cessation (including
# a process exit between fsyncs). Reconstruct only that immediate local
# predecessor for the existing exact reset/reopen ancestry predicate.
# This is an in-memory proof check, never a ledger rewrite or new edge.
reopened = record
if (
record.stage == "resolved"
and record.resolution == "start-active-observed"
and record.reconciliations
and record.reconciliations[-1].kind == "resolved-active-cessation"
and record.reconciliations[-1].resolution == "physical-standby-observed"
):
reopened = dataclass_replace(
record,
revision=record.revision - 1,
stage="observing",
resolution=None,
reconciliations=record.reconciliations[:-1],
)
if not (
persisted is not None
and status is not None
@@ -12653,12 +12728,11 @@ class XgridsK1CompatibilityService:
and record.operation_id == checkpoint.original_start_operation_id
and record.acquisition_id == checkpoint.acquisition_id
and record.action == "start"
and record.stage == "observing"
and record.resolution is None
and reopened.stage == "observing"
and reopened.resolution is None
and record.revision > persisted.ledger_revision
and record.payload_sha256 == checkpoint.start_payload_sha256
and record.reopened_resolved_start_requires_reconciliation
and record.reconciled_physical_state == "active"
and reopened.reopened_resolved_start_requires_reconciliation
):
return False
@@ -15913,6 +15987,7 @@ class XgridsK1CompatibilityService:
"direct-lan": "bridge",
"device-ap": "quick-connect",
"controller-hotspot": "direct-connect",
"usb-ethernet": "usb",
}[request.compatibility_attestation.topology]
if request.compatibility_attestation is not None
else None
@@ -15990,7 +16065,8 @@ class XgridsK1CompatibilityService:
reason_code="connection-verify-control-dispatch-active",
)
command_dispatch_gate_acquired = True
with self._borrow_network_ble_process_lease():
with (nullcontext() if requested_mode == "usb"
else self._borrow_network_ble_process_lease()):
(
verify_operation_id,
verify_created,
@@ -18152,7 +18228,7 @@ class XgridsK1CompatibilityService:
if (
not isinstance(transport_ref, str)
or not transport_ref.strip()
or connection_mode not in {"bridge", "quick-connect", "direct-connect"}
or connection_mode not in {"bridge", "quick-connect", "direct-connect", "usb"}
):
raise ConnectionVerificationError(
"Физическая recovery-цель K1 отсутствует в durable ledger",
@@ -18303,6 +18379,7 @@ class XgridsK1CompatibilityService:
"direct-lan": "bridge",
"device-ap": "quick-connect",
"controller-hotspot": "direct-connect",
"usb-ethernet": "usb",
}[request.compatibility_attestation.topology],
)
self._require_connection_mode_draft_for_verify(
@@ -18874,13 +18951,83 @@ class XgridsK1CompatibilityService:
)
return association, observation, supervisor_epoch_before
def _require_usb_attachment(self, transport_ref: str) -> UsbNetworkAttachment:
if self._usb_network_probe is None:
raise OSError("USB-подключение доступно только на подготовленном БК")
return self._usb_network_probe.require(transport_ref)
async def _adopt_usb_connection_owned(
self,
transport_ref: str,
attestation: CompatibilityAttestationRequest,
*,
retained_prepared_stop_owner: _PreparedStopRecoveryOwner | None,
) -> tuple[str, _ProvisionalFreshBridgeTopology]:
"""Supply topology to the existing Verify/DeviceInfo/recovery transaction.
Caller owns lifecycle, dispatch, provisioning and process gates and has
checked active receiver/STOP ownership. No BLE or network write occurs.
DHCP is provisional; the common commit still requires the identity pin.
"""
if self._network_mutation_ledger.snapshot().status in {"corrupt", "unresolved"}:
raise ConnectionVerificationError(
"Предыдущая настройка сети K1 требует завершения",
reason_code="usb-network-reconciliation-required",
)
self._require_semantic_topology_store_writable()
assert self._semantic_topology_store is not None
semantic = self._semantic_topology_store.snapshot()
attachment = await _run_blocking_operation_without_abandonment(
self._require_usb_attachment, transport_ref,
)
self._retire_application_control_for_network_change(allow_terminal_failure=True)
observed_at = _utc_now_iso()
intent_id = self._apply_read_only_device_topology(
transport_ref=transport_ref, connection_mode="usb",
ipv4=attachment.peer_ipv4, firmware_version=attestation.firmware_version,
compatibility_attestation=_attestation_snapshot(attestation),
observed_at_utc=observed_at, force_new_intent=True, force_new_session=True,
persist_semantic_topology=False, source="usb-enumeration",
retained_prepared_stop_owner=retained_prepared_stop_owner,
)
with self._lock:
assert self._device_session_id is not None
provisional = _ProvisionalFreshBridgeTopology(
reconfiguration_intent_id=None,
reconfiguration_revision=self._connection_reconfiguration_revision,
supervisor_intent_id=intent_id,
discovery_generation=self._ble_discovery_generation,
device_session_id=self._device_session_id,
transport_ref=transport_ref, connection_mode="usb",
ipv4=attachment.peer_ipv4, firmware_version=attestation.firmware_version,
observed_at_utc=observed_at,
semantic_predecessor_revision=semantic.record.revision if semantic.record else 0,
usb_generation=attachment.generation,
)
try:
observation = await _run_blocking_operation_without_abandonment(
self._probe_control_endpoint, attachment.peer_ipv4,
)
current = await _run_blocking_operation_without_abandonment(
self._require_usb_attachment, transport_ref,
)
if current != attachment or not observation.reachable:
raise ConnectionVerificationError(
"K1 найден по USB, но управляющий канал пока недоступен",
reason_code="usb-control-endpoint-unavailable",
)
except BaseException:
self._reset_provisional_fresh_bridge_topology(provisional)
raise
return attachment.peer_ipv4, provisional
async def _adopt_existing_lan_connection(
self,
device_id: str,
compatibility_attestation: CompatibilityAttestationRequest,
*,
verification_source: Literal[
"fresh-scan", "retained-current-process", "durable-configured-state"
"fresh-scan", "retained-current-process", "durable-configured-state", "usb-enumeration"
] = "fresh-scan",
expected_discovery_generation: int | None = None,
expected_mode_revision: int | None = None,
@@ -18895,6 +19042,8 @@ class XgridsK1CompatibilityService:
requested_mode = "quick-connect"
elif compatibility_attestation.topology == "controller-hotspot":
requested_mode = "direct-connect"
elif compatibility_attestation.topology == "usb-ethernet":
requested_mode = "usb"
else:
raise ValueError("read-only K1 adoption received an unsupported topology")
self._require_connection_mode_draft_for_verify(
@@ -18991,6 +19140,13 @@ class XgridsK1CompatibilityService:
verification_fence_active = False
provisional_topology: _ProvisionalFreshBridgeTopology | None = None
try:
if requested_mode == "usb":
return await self._adopt_usb_connection_owned(
actual_transport_ref, compatibility_attestation,
retained_prepared_stop_owner=(
retained_prepared_stop_owner if retained_stop_recovery else None
),
)
ledger_snapshot = self._network_mutation_ledger.snapshot()
if (
ledger_snapshot.status == "unresolved"
@@ -20155,6 +20311,14 @@ class XgridsK1CompatibilityService:
rediscover: bool,
) -> str:
selected_device_id, connection_mode, current_target = self._live_lan_address_context()
if connection_mode == "usb":
attachment = self._require_usb_attachment(selected_device_id)
if attachment.peer_ipv4 != current_target:
raise ConnectionVerificationError(
"Адрес USB изменился; подтвердите подключение K1",
reason_code="usb-attachment-changed",
)
return attachment.peer_ipv4
if connection_mode == "quick-connect":
return self._confirm_quick_connect_endpoint(
selected_device_id,
@@ -20216,6 +20380,14 @@ class XgridsK1CompatibilityService:
rediscover: bool,
) -> str:
selected_device_id, connection_mode, current_target = self._live_lan_address_context()
if connection_mode == "usb":
attachment = self._require_usb_attachment(selected_device_id)
if attachment.peer_ipv4 != current_target:
raise ConnectionVerificationError(
"Адрес USB изменился; подтвердите подключение K1",
reason_code="usb-attachment-changed",
)
return attachment.peer_ipv4
if connection_mode == "quick-connect":
return await _run_blocking_operation_without_abandonment(
self._confirm_quick_connect_endpoint,
@@ -21905,6 +22077,9 @@ class XgridsK1CompatibilityService:
runtime_state=runtime_state,
)
failure_stage = "evidence-lease-acquire"
# Match restart rehydration: a dead writer leaves only an unlocked
# marker. The canonical helper preserves live owners and all data.
recover_stale_active_session_marker(out_dir.parent)
lease = ActiveSessionLease.acquire(out_dir.parent, out_dir)
with self._lock:
if self._acquisition_session_lease is not None:
@@ -23915,7 +24090,7 @@ class XgridsK1CompatibilityService:
"control_session_id",
)
)
and connection_mode in {"bridge", "quick-connect", "direct-connect"}
and connection_mode in {"bridge", "quick-connect", "direct-connect", "usb"}
and all(
isinstance(values[field], int) and not isinstance(values[field], bool)
for field in (
@@ -24066,7 +24241,7 @@ class XgridsK1CompatibilityService:
and isinstance(selected_device_id, str)
and isinstance(device_id, str)
and isinstance(device_session_id, str)
and connection_mode in {"bridge", "quick-connect", "direct-connect"}
and connection_mode in {"bridge", "quick-connect", "direct-connect", "usb"}
and isinstance(target_ipv4, str)
and control.get("state") == "scanning"
):
@@ -24478,7 +24653,7 @@ class XgridsK1CompatibilityService:
and isinstance(selected_device_id, str)
and isinstance(device_id, str)
and isinstance(device_session_id, str)
and connection_mode in {"bridge", "quick-connect", "direct-connect"}
and connection_mode in {"bridge", "quick-connect", "direct-connect", "usb"}
and isinstance(target_ipv4, str)
and runtime_snapshot.get("source_mode") == "live"
and (
@@ -24552,7 +24727,7 @@ class XgridsK1CompatibilityService:
assert isinstance(runtime_generation, int)
assert intent is not None
assert isinstance(selected_device_id, str)
assert connection_mode in {"bridge", "quick-connect", "direct-connect"}
assert connection_mode in {"bridge", "quick-connect", "direct-connect", "usb"}
assert isinstance(target_ipv4, str)
if prepared_stop_owner_current:
assert prepared_stop_owner is not None
@@ -25035,11 +25210,14 @@ class XgridsK1CompatibilityService:
checkpoint_snapshot = store.snapshot()
checkpoint = checkpoint_snapshot.checkpoint
if checkpoint is not None and checkpoint.state == "ceased":
return bool(
owned = bool(
checkpoint.acquisition_id == expected_acquisition_id
and checkpoint.original_start_operation_id
== expected_start_operation_id
)
if owned:
self._set_active_acquisition_checkpoint_reason(None)
return owned
if not (
checkpoint_snapshot.status in {"prepared", "active"}
and checkpoint is not None
@@ -27881,6 +28059,33 @@ class XgridsK1CompatibilityService:
self._connection_loss_confirmation_count = 0
return
# A short association gap can revoke the control epoch while the
# data socket survives. Once the host path returns, negative probe
# streaks are already zero and no MQTT disconnect wakes the receiver.
# Hand that exact confirmed START to the existing read-only recovery;
# never promote the old control proof into the new host epoch.
returned_path = self._connection_supervisor.snapshot()
verified = application_control_session.get("verified_control")
verified_epoch = (
verified.get("host_path_epoch") if isinstance(verified, Mapping) else None
)
if (
application_control_session.get("state") == "scanning"
and returned_path.host_path.available
and returned_path.control_plane.reason_code == "host-path-epoch-changed"
and isinstance(verified_epoch, int)
and not isinstance(verified_epoch, bool)
and 0 < verified_epoch < returned_path.host_path.epoch
and self._request_active_stream_recovery_for_local_loss(
"host-path-epoch-changed"
)
):
with self._lock:
self._connection_loss_signature = None
self._connection_loss_evidence_token = None
self._connection_loss_confirmation_count = 0
return
# STOP PREPARE replaces the current successful START ledger row before
# the transport can acquire its dispatch fence. Preserve only this
# exact, bounded, still-undispatched owner; a terminal control state,
@@ -30508,10 +30713,27 @@ class XgridsK1CompatibilityService:
stop_operation_id=current_stop_operation_id,
)
checkpoint_snapshot_status: str | None = None
completed_checkpoint_owned = False
if self._active_acquisition_checkpoint is not None:
try:
checkpoint_snapshot_status = (
self._active_acquisition_checkpoint.snapshot().status
checkpoint_snapshot = self._active_acquisition_checkpoint.snapshot()
checkpoint_snapshot_status = checkpoint_snapshot.status
checkpoint = checkpoint_snapshot.checkpoint
# Completed local cleanup releases operation/evidence owners.
# A ceased journal for this same completed acquisition remains
# terminal proof; it grants no recovery or command authority.
completed_checkpoint_owned = bool(
current is not None
and current.state == "completed"
and checkpoint_snapshot_status == "ceased"
and checkpoint is not None
and checkpoint.acquisition_id == current.acquisition_id
and (
canonical_start_operation_id is None
or checkpoint.original_start_operation_id
== canonical_start_operation_id
)
and self._active_acquisition_checkpoint_trust == "trusted"
)
except (ActiveAcquisitionRecoveryCheckpointError, OSError, ValueError):
checkpoint_snapshot_status = None
@@ -30522,7 +30744,10 @@ class XgridsK1CompatibilityService:
# have no checkpoint to cease. Missing/corrupt storage does not
# enter this compatibility branch and remains fail closed.
or checkpoint_snapshot_status == "empty"
or completed_checkpoint_owned
)
if completed_checkpoint_owned:
self._set_active_acquisition_checkpoint_reason(None)
if (
current is not None
and current.control_mode == "plugin-commanded"
@@ -31922,6 +32147,7 @@ class XgridsK1ServicePort(Protocol):
_SNAPSHOT_RUNTIME_FENCED_MUTATING_ACTIONS = frozenset(
{
ACTION_DEVICE_MANAGE,
ACTION_DISCOVERY_SCAN,
ACTION_NETWORK_PROVISION,
ACTION_CONNECTION_MODE_SELECT,
@@ -31950,6 +32176,7 @@ class XgridsK1PluginFacade:
plugin_id = XGRIDS_K1_PLUGIN_ID
action_ids = frozenset(
{
ACTION_DEVICE_MANAGE,
ACTION_STATE_READ,
ACTION_DISCOVERY_SCAN,
ACTION_DEVICE_INSPECT,
@@ -32078,6 +32305,10 @@ class XgridsK1PluginFacade:
mode_request,
)
self.service.bind_runtime_event_loop(asyncio.get_running_loop())
if action_id == ACTION_DEVICE_MANAGE:
return await asyncio.to_thread(
manage_device, self.service, DeviceManagementRequest.model_validate(payload),
)
if action_id == ACTION_STATE_READ:
EmptyRequest.model_validate(payload)
return await self._read_state_single_flight()
@@ -33080,7 +33311,7 @@ def _physical_command_pending_reopened_reconciliation_mode(
if not (
isinstance(operation_id, str)
and isinstance(revision, int)
and connection_mode in {"bridge", "quick-connect", "direct-connect"}
and connection_mode in {"bridge", "quick-connect", "direct-connect", "usb"}
and isinstance(retirements, list)
and isinstance(reopens, list)
):
@@ -33322,7 +33553,9 @@ def _resolved_apply_durable_observation_target(
and isinstance(semantic_record, Mapping)
and semantic_record.get("schema_version") == "missioncore.xgrids-k1-semantic-topology/v1"
and semantic_record.get("compatibility_profile_id") == XGRIDS_K1_COMPATIBILITY_PROFILE_ID
and semantic_record.get("source") in {"ble-post-write-status", "ble-read-only-status"}
and semantic_record.get("source") in {
"ble-post-write-status", "ble-read-only-status", "usb-enumeration"
}
):
return None
@@ -33332,7 +33565,7 @@ def _resolved_apply_durable_observation_target(
if not (
isinstance(transport_ref, str)
and transport_ref
and connection_mode in {"bridge", "quick-connect", "direct-connect"}
and connection_mode in {"bridge", "quick-connect", "direct-connect", "usb"}
and isinstance(ipv4, str)
and ipv4
and physical_transport_ref_comparison_key(transport_ref)
@@ -33704,7 +33937,7 @@ def _connection_policy_projection(
)
recovery_mode = (
recovery_mode_raw
if recovery_mode_raw in {"bridge", "quick-connect", "direct-connect"}
if recovery_mode_raw in {"bridge", "quick-connect", "direct-connect", "usb"}
else None
)
recovery_advertised = bool(
@@ -33820,7 +34053,7 @@ def _connection_policy_projection(
semantic_topology_record.get("connection_mode")
if isinstance(semantic_topology_record, Mapping)
and semantic_topology_record.get("connection_mode")
in {"bridge", "quick-connect", "direct-connect"}
in {"bridge", "quick-connect", "direct-connect", "usb"}
else None
)
if transport_is_retired(semantic_recovery_ref):
@@ -33947,7 +34180,7 @@ def _connection_policy_projection(
and semantic_topology_record.get("transport_ref")
and not transport_is_retired(semantic_topology_record.get("transport_ref"))
and semantic_topology_record.get("connection_mode")
in {"bridge", "quick-connect", "direct-connect"}
in {"bridge", "quick-connect", "direct-connect", "usb"}
and isinstance(semantic_topology_record.get("ipv4"), str)
and semantic_topology_record.get("ipv4")
)
@@ -25,7 +25,12 @@ from k1link.device_plugins.xgrids_k1.protocol.application_bootstrap import (
def _run(args: list[str], timeout: float = 8) -> str:
result = subprocess.run(args, capture_output=True, text=True, timeout=timeout, check=False)
# nmcli localizes even terse ACTIVE values (for example yes/no -> да/нет).
# Pin machine output only for this child; keep UTF-8 SSIDs and host locale.
result = subprocess.run(
args, capture_output=True, text=True, encoding="utf-8", timeout=timeout,
check=False, env={**os.environ, "LC_ALL": "C", "LANG": "C"},
)
if result.returncode:
# Never forward subprocess diagnostics: SSIDs or other local data may occur.
raise OSError("Network observation unavailable")
@@ -24,6 +24,7 @@ NETWORK_MUTATION_LEDGER_LOCK_FILENAME = ".network-mutation.lock"
NETWORK_MUTATION_LEDGER_MAX_BYTES = 64 * 1024
NetworkConnectionMode = Literal["bridge", "quick-connect", "direct-connect"]
PreviousConnectionMode = Literal["bridge", "quick-connect", "direct-connect", "usb"]
NetworkMutationStage = Literal["prepared", "dispatching", "observing", "resolved"]
NetworkMutationWriteMode = Literal["with_response", "without_response"]
NetworkMutationResolution = Literal[
@@ -105,13 +106,14 @@ class PreviousConnectionEvidence:
"""Last admitted topology retained as evidence, never as live reachability."""
transport_ref: str
mode: NetworkConnectionMode
mode: PreviousConnectionMode
ipv4: str | None
device_session_id: str | None
def __post_init__(self) -> None:
_validate_identifier(self.transport_ref, field_name="transport_ref")
_validate_connection_mode(self.mode)
if self.mode != "usb":
_validate_connection_mode(self.mode)
if self.ipv4 is not None:
try:
parsed = ipaddress.ip_address(self.ipv4)
@@ -856,10 +858,11 @@ def _previous_connection_from_mapping(value: object) -> PreviousConnectionEviden
label="previous connection",
)
mode_raw = _required_string(document["mode"], field_name="mode")
_validate_connection_mode(mode_raw)
if mode_raw != "usb":
_validate_connection_mode(mode_raw)
return PreviousConnectionEvidence(
transport_ref=_required_string(document["transport_ref"], field_name="transport_ref"),
mode=cast(NetworkConnectionMode, mode_raw),
mode=cast(PreviousConnectionMode, mode_raw),
ipv4=_optional_string(document["ipv4"], field_name="ipv4"),
device_session_id=_optional_string(
document["device_session_id"], field_name="device_session_id"
@@ -10,6 +10,7 @@ import asyncio
import logging
import re
import traceback
from contextlib import suppress
from datetime import UTC, datetime
from pathlib import Path
from uuid import UUID, uuid5
@@ -30,6 +31,7 @@ from .facade import (
)
from .linux_host import LinuxApplicationAuthorityLoader, LinuxWifiAssociationProbe, wifi_networks
from .protocol.application_authority import ApplicationAuthorityLoadError
from .usb_network import LinuxK1UsbProbe
ATTESTATION = {
"firmware_version": "3.0.2",
@@ -42,25 +44,48 @@ def verification_parameters(state, operation_id, *, requested_device_id=None):
"""Use the admitted persisted Bridge target before asking for BLE again.
The facade still checks its ledger, exact identity, route, DeviceInfo and
physical reconciliation fences. A saved address alone never grants START.
physical reconciliation fences, including any required live GATT read.
A saved address alone never grants START.
"""
parameters = {
"expected_snapshot_runtime_id": state["snapshot_runtime_id"],
"operation_id": operation_id,
}
if state.get("active_connection_mode") == "usb" or (
state.get("active_connection_mode") is None
and state.get("desired_connection_mode") == "usb"
):
target = state.get("selected_device_id")
if isinstance(target, str) and target.startswith("usb:"):
parameters.update(
device_id=target, source="usb-enumeration",
compatibility_attestation={**ATTESTATION, "topology": "usb-ethernet"},
expected_mode_revision=state.get("desired_connection_mode_revision"),
)
return parameters
policy = (state.get("connection_policy") or {}).get("actions", {})
fresh = policy.get("observe-fresh-device-network") or {}
if requested_device_id is not None and fresh.get("allowed") is True and any(
item.get("likely_k1") is True
and str(item.get("device_id", "")).casefold() == requested_device_id.casefold()
for item in state.get("devices", [])
):
# The caller already carries the current discovery generation. Preserve
# the explicitly selected scan result instead of replacing it with the
# durable target, whose BlueZ device reference may belong to an old scan.
return parameters
decision = policy.get("observe-configured-device-network") or {}
target = decision.get("required_transport_ref")
selected = state.get("selected_device_id")
if (decision.get("allowed") is True
and decision.get("requires_live_gatt_validation") is False
and decision.get("required_connection_mode") == "bridge"
and isinstance(target, str) and isinstance(selected, str)
and target.casefold() == selected.casefold()
and (requested_device_id is None
or target.casefold() == requested_device_id.casefold())):
if (
decision.get("allowed") is True
and decision.get("required_connection_mode") == "bridge"
and isinstance(target, str)
and bool(target.strip())
and (requested_device_id is None or target.casefold() == requested_device_id.casefold())
):
parameters.update(
device_id=target, source="durable-configured-state",
device_id=target,
source="durable-configured-state",
compatibility_attestation=ATTESTATION,
expected_mode_revision=state.get("desired_connection_mode_revision"),
)
@@ -99,15 +124,24 @@ def failure_transport_facts(error: BaseException) -> str:
seen.add(id(current))
stage = getattr(current, "operation_stage", None)
if isinstance(stage, str) and stage in {
"resolution", "exact-uuid-scan", "connect", "gatt-contract",
"baseline-read", "gatt-write", "status-poll", "status-read",
"resolution",
"exact-uuid-scan",
"connect",
"gatt-contract",
"baseline-read",
"gatt-write",
"status-poll",
"status-read",
}:
facts["stage"] = stage
bluez = getattr(current, "dbus_error", None)
if isinstance(bluez, str) and bluez in {
"org.bluez.Error.InProgress", "org.bluez.Error.NotReady",
"org.bluez.Error.Failed", "org.bluez.Error.NotAuthorized",
"org.bluez.Error.NotSupported", "org.bluez.Error.DoesNotExist",
"org.bluez.Error.InProgress",
"org.bluez.Error.NotReady",
"org.bluez.Error.Failed",
"org.bluez.Error.NotAuthorized",
"org.bluez.Error.NotSupported",
"org.bluez.Error.DoesNotExist",
"org.freedesktop.DBus.Error.UnknownObject",
}:
facts["bluez"] = bluez
@@ -156,6 +190,7 @@ class NodeBridge:
def __init__(self, repository_root: Path, *, service=None):
self.rerun = NodeRerunHub()
self.application_authority_available = None
self.usb_probe = LinuxK1UsbProbe() if service is None else None
if service is None:
_validate_installed_compatibility_profile(repository_root)
loader = LinuxApplicationAuthorityLoader()
@@ -170,6 +205,7 @@ class NodeBridge:
repository_root,
application_authority_loader=loader,
host_wifi_association_probe=LinuxWifiAssociationProbe(),
usb_network_probe=self.usb_probe,
visualization_bridge_factory=self.rerun.create,
)
self.service = service
@@ -191,8 +227,56 @@ class NodeBridge:
for key in ("attempt_id", "recovery_operation_id"):
if key in attempt:
attempt[key] = node_operation_id(attempt[key])
target = verification_parameters(snapshot, "projection")
checkpoint = snapshot.get("active_acquisition_recovery_checkpoint") or {}
reset = snapshot.get("connection_scenario_reset") or {}
reset_completed = (reset.get("timing") or {}).get("completed_at_utc")
verification = next(
(
operation
for operation in reversed(snapshot.get("operations", []))
if operation.get("action") == "connection.verify"
and (operation.get("context") or {}).get("snapshot_runtime_id")
== snapshot["snapshot_runtime_id"]
and (
not reset_completed
or (
operation.get("accepted_at")
and datetime.fromisoformat(operation["accepted_at"])
> datetime.fromisoformat(reset_completed)
)
)
),
None,
)
return {
"reconnect_target": (
{"device_id": target["device_id"], "source": target["source"]}
if "source" in target
else None
),
"acquisition_recovery": {
key: checkpoint[key]
for key in (
"status",
"state",
"gap_open",
"restart_rehydration_phase",
"reason_code",
)
if key in checkpoint
},
"verification": (
{
"operation_id": node_operation_id(verification.get("operation_id")),
"status": verification.get("status"),
"error_code": (verification.get("error") or {}).get("code"),
}
if verification
else None
),
"available": True,
"can_reset": True,
"model": "XGRIDS K1",
"mode": "bridge",
"runtime_id": snapshot["snapshot_runtime_id"],
@@ -292,6 +376,44 @@ class NodeBridge:
action, identifier = command["action"], command["operation_id"]
plugin_identifier = plugin_operation_id(identifier)
parameters = command.get("parameters", {})
if action == "reset":
# The existing reset owns cancellation, quiescence and local retirement.
# Never queue it behind this adapter's network-operation lock or bind
# the old monitor through state.read before the canonical reset runs.
if datetime.fromisoformat(command["deadline_at"]) <= datetime.now(UTC):
raise NodeEnrollmentRejected("command-expired")
if (
set(parameters) != {"mode_revision"}
or type(parameters["mode_revision"]) is not int
or parameters["mode_revision"] < 0
):
raise NodeEnrollmentRejected("device-selection-changed")
result = await self.invoke(
"connection.mode.select",
{
"connection_mode": "bridge",
"expected_revision": parameters["mode_revision"],
"expected_snapshot_runtime_id": command.get("runtime_id"),
"reset_scenario": True,
"reset_id": plugin_identifier,
},
identifier,
)
marker = result.get("connection_scenario_reset") or {}
committed = (
marker.get("reset_id") == plugin_identifier
and marker.get("revision") == parameters["mode_revision"] + 1
and marker.get("local_session_closed") is True
)
return {
**self.project(result),
"command_result": {
"operation_id": identifier,
"action": action,
"status": "succeeded" if committed else "failed",
"error_code": None if committed else "connection-scenario-reset-unconfirmed",
},
}
if action not in {"scan", "networks", "connect", "verify"}:
raise NodeEnrollmentRejected("unsupported-action")
async with self.lock:
@@ -316,10 +438,21 @@ class NodeBridge:
else:
# Do not derive fences at dispatch: they are the exact version
# shown to the operator before credentials were submitted.
recovery = (
verification_parameters(
snapshot, plugin_identifier, requested_device_id=parameters.get("device_id")
)
if action == "verify"
else {}
)
if (
parameters.get("discovery_generation") != state["discovery_generation"]
or parameters.get("mode_revision") != state["mode_revision"]
or parameters.get("device_id") not in {v["id"] for v in state["candidates"]}
or (
"source" not in recovery
and parameters.get("device_id")
not in {v["id"] for v in state["candidates"]}
)
):
raise NodeEnrollmentRejected("device-selection-changed")
payload = {
@@ -339,9 +472,11 @@ class NodeBridge:
password=parameters.get("password"),
)
else:
payload.update(verification_parameters(
snapshot, plugin_identifier, requested_device_id=parameters["device_id"],
))
payload.update(recovery)
if "source" in recovery:
# The adapter already fenced the displayed discovery generation.
# The canonical durable Verify contract has no fresh-scan token.
payload.pop("expected_discovery_generation", None)
try:
result = await self.invoke_journalled(
"network.provision" if action == "connect" else "connection.verify",
@@ -383,7 +518,8 @@ def create_app(repository_root: Path):
sensor = NodeK1Sensor(bridge, peers)
from fastapi.responses import Response
from k1link.viewer.node_local_media import start_local, read_local
from k1link.viewer.node_local_media import read_local, start_local
async def preview_request(request):
data = await request.body()
@@ -393,9 +529,18 @@ def create_app(repository_root: Path):
@asynccontextmanager
async def lifespan(_app):
yield
await peers.close_all()
await asyncio.to_thread(bridge.service.close)
from .node_usb import NodeK1UsbObserver
observer = NodeK1UsbObserver(bridge, bridge.usb_probe)
task = asyncio.create_task(observer.run(), name="k1-usb-observer")
try:
yield
finally:
task.cancel()
with suppress(asyncio.CancelledError):
await task
await peers.close_all()
await asyncio.to_thread(bridge.service.close)
app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None, lifespan=lifespan)
@@ -403,6 +548,10 @@ def create_app(repository_root: Path):
async def status():
return await bridge.state()
@app.get("/preview-health")
async def preview_health():
return peers.snapshot()
@app.get("/inventory")
async def inventory(request: Request):
return await sensor.inventory(request.headers["X-Node-Id"])
@@ -414,10 +563,13 @@ def create_app(repository_root: Path):
if datetime.fromisoformat(command["deadline_at"]) <= datetime.now(UTC):
raise ValueError("Preview request expired")
await sensor.admit_preview(command, request.headers["X-Node-Id"])
identifier = await start_local(peers, command['parameters'])
data = await read_local(peers, identifier, command['parameters'].get('after', 0))
return Response(data, media_type="application/vnd.missioncore.preview",
headers={"Cache-Control": "no-store"})
identifier = await start_local(peers, command["parameters"])
data = await read_local(peers, identifier, command["parameters"].get("after", 0))
return Response(
data,
media_type="application/vnd.missioncore.preview",
headers={"Cache-Control": "no-store"},
)
except (ValueError, KeyError, TypeError):
return JSONResponse({"error": "Preview unavailable"}, status_code=409)
@@ -425,9 +577,12 @@ def create_app(repository_root: Path):
async def preview_read(request: Request):
try:
data = await preview_request(request)
payload = await read_local(peers, data['peer_id'], data['after'])
return Response(payload, media_type="application/vnd.missioncore.preview",
headers={"Cache-Control": "no-store"})
payload = await read_local(peers, data["peer_id"], data["after"])
return Response(
payload,
media_type="application/vnd.missioncore.preview",
headers={"Cache-Control": "no-store"},
)
except (ValueError, KeyError, TypeError):
return JSONResponse({"error": "Preview expired"}, status_code=409)
@@ -460,7 +615,8 @@ def create_app(repository_root: Path):
except Exception as error:
logging.getLogger(__name__).warning(
"K1 sensor operation failed: exception=%s chain=%s",
type(error).__name__, failure_locations(error),
type(error).__name__,
failure_locations(error),
)
return {
"state": "unknown",
@@ -1,10 +1,16 @@
"""SDK projection and explicit acquisition actions for the Node-owned K1."""
import asyncio
import base64
import hashlib
import math
import re
import time
from datetime import UTC, datetime
from k1link.viewer.recorded import recorded_blueprint_rrd, recorded_blueprint_sessions
from k1link.viewer.rerun_bridge import RerunSceneSettings
from .facade import (
XGRIDS_K1_MODEL_ID,
XGRIDS_K1_PLUGIN_ID,
@@ -23,6 +29,20 @@ PHYSICAL_ACCEPTANCE_KEYS = (
)
def _storage_status(control, connected):
value = (control.get("transport") or {}).get("storage_status")
if not connected or not isinstance(value, dict):
return None
used, observed = value.get("used_percent"), value.get("observed_at")
if type(used) not in {int, float} or not math.isfinite(used) or not 0 <= used <= 100:
return None
try:
age = (datetime.now(UTC) - datetime.fromisoformat(observed)).total_seconds()
except (ValueError, TypeError):
return None
return {"used_percent": used, "observed_at": observed} if 0 <= age <= 5 else None
def project_sensor(snapshot, node_id):
session = snapshot.get("device_session")
if not session:
@@ -31,7 +51,7 @@ def project_sensor(snapshot, node_id):
lifecycle = snapshot.get("connection_lifecycle", {})
connected = (
lifecycle.get("connection_ready") is True
and snapshot.get("active_connection_mode") == "bridge"
and snapshot.get("active_connection_mode") in {"bridge", "usb"}
)
acquisition = snapshot.get("acquisition") or {}
acquisition_state = {
@@ -66,6 +86,15 @@ def project_sensor(snapshot, node_id):
}
control = snapshot.get("application_control_session") or {}
attempt = snapshot.get("connection_attempt") or {}
connection_mode = snapshot.get("active_connection_mode")
if (
connection_mode is None
and snapshot.get("desired_connection_mode") == "usb"
and str(snapshot.get("selected_device_id") or "").startswith("usb:")
):
# Transport identity survives a retired control socket; it does not
# imply that the device is online or that START is admitted.
connection_mode = "usb"
return {
"id": identifier,
"name": "XGRIDS K1",
@@ -76,7 +105,10 @@ def project_sensor(snapshot, node_id):
"verified": connected,
"online": connected,
"usb": "",
"connection_label": "Wi-Fi · " + (snapshot.get("k1_ip") or "—"),
"connection_label": (
"USB · " if connection_mode == "usb" else "Wi-Fi · "
) + (snapshot.get("k1_ip") or "—"),
"connection_mode": connection_mode,
"layers": ["points", "camera"],
"snapshot": {
"context": context,
@@ -92,15 +124,21 @@ def project_sensor(snapshot, node_id):
"phase": control.get("state"),
"can_start": lifecycle.get("ready_to_start", False),
"can_stop": control.get("state") in {"start-requested", "initializing", "scanning"},
"can_verify": any(action in lifecycle.get("allowed_actions", []) for action in (
"verify-control-read-only", "observe-current-device-network",
"observe-configured-device-network", "observe-fresh-device-network",
)),
"can_verify": any(
action in lifecycle.get("allowed_actions", [])
for action in (
"verify-control-read-only",
"observe-current-device-network",
"observe-configured-device-network",
"observe-fresh-device-network",
)
),
"network_applied": connected or attempt.get("phase") == "network_applied",
"reason_code": None if connected else attempt.get("public_error_code"),
"acquisition_id": acquisition.get("acquisition_id"),
"acquisition_phase": acquisition.get("state"),
},
"storage_status": _storage_status(control, connected),
"live_settings": snapshot.get("viewer_settings", {}),
"frames": snapshot.get("metrics", {}),
"recordings": [],
@@ -134,12 +172,16 @@ class NodeK1Sensor:
async def admit_preview(self, command, node_id):
item = project_sensor(await self.raw_state(), node_id)
if (not item or command.get("action_id") != "offer"
or command.get("session", {}).get("device_id") != item["id"]
or command["session"].get("session_id") != item["snapshot"]["context"]["session_id"]
or item["snapshot"]["acquisition"] != "streaming"
or not item["control"]["acquisition_id"]
or command.get("parameters", {}).get("acquisition_id") != item["control"]["acquisition_id"]):
if (
not item
or command.get("action_id") != "offer"
or command.get("session", {}).get("device_id") != item["id"]
or command["session"].get("session_id") != item["snapshot"]["context"]["session_id"]
or item["snapshot"]["acquisition"] != "streaming"
or not item["control"]["acquisition_id"]
or command.get("parameters", {}).get("acquisition_id")
!= item["control"]["acquisition_id"]
):
raise ValueError("Acquisition is not active or changed")
return item
@@ -159,7 +201,70 @@ class NodeK1Sensor:
)
plugin_identifier = plugin_operation_id(identifier)
if action == "details":
return item
if "preview_blueprint" not in params:
return item
request = params["preview_blueprint"]
if not isinstance(request, dict):
raise ValueError("Invalid preview blueprint")
recording, owner = request.get("recording_id"), request.get("owner")
if (
not isinstance(recording, str)
or not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9._:-]{0,127}", recording)
or not isinstance(owner, str)
or not re.fullmatch(r"[a-f0-9]{32}", owner)
):
raise ValueError("Invalid preview identity")
if request.get("release") is True:
recorded_blueprint_sessions.release(
("nodedc_mission_core_spatial", recording, owner)
)
return {"released": True}
if request.get("view") not in {"3d", "plan"}:
raise ValueError("Invalid spatial view")
settings = ViewerSettingsRequest.model_validate(
request.get("settings", state.get("viewer_settings", {}))
)
follow = request.get("follow_trajectory", False)
if not isinstance(follow, bool):
raise ValueError("Invalid follow state")
host_playback = request.get("host_playback", False)
if not isinstance(host_playback, bool):
raise ValueError("Invalid playback owner")
eye = request.get("eye")
eye_fields = {}
if eye is not None:
import math
if not isinstance(eye, dict) or set(eye) != {"position", "lookTarget", "eyeUp"}:
raise ValueError("Invalid spatial eye")
for key, target in (
("position", "eye_position"),
("lookTarget", "eye_look_target"),
("eyeUp", "eye_up"),
):
value = eye[key]
if (
not isinstance(value, list)
or len(value) != 3
or any(type(v) not in {int, float} or not math.isfinite(v) for v in value)
):
raise ValueError("Invalid spatial eye")
eye_fields[target] = tuple(value)
payload = await asyncio.to_thread(
recorded_blueprint_rrd,
RerunSceneSettings(**settings.model_dump()),
application_id="nodedc_mission_core_spatial",
recording_id=recording,
blueprint_session_id=owner,
timeline="stream_time",
plan_view=request["view"] == "plan",
follow_trajectory=follow,
reactivate_updates=True,
initialize_playback=not host_playback,
**eye_fields,
)
return {"rrd": base64.b64encode(payload).decode("ascii")}
if action == "close-peer":
await self.peers.close(params.get("peer_id"))
if params.get("retire_view") is True:
@@ -167,17 +272,22 @@ class NodeK1Sensor:
return {"ok": True}
if action == "offer":
acquisition_id = item["control"]["acquisition_id"]
if (item["snapshot"]["acquisition"] != "streaming" or not acquisition_id
or params.get("acquisition_id") != acquisition_id):
if (
item["snapshot"]["acquisition"] != "streaming"
or not acquisition_id
or params.get("acquisition_id") != acquisition_id
):
raise ValueError("Acquisition is not active or changed")
answer = await self.peers.offer(params)
# Signalling may outlive STOP or a replacement acquisition. Retire
# that disposable preview instead of attaching it to another run.
current = project_sensor(await self.raw_state(), node_id)
if (current is None or current["snapshot"]["acquisition"] != "streaming"
or current["snapshot"]["context"]["session_id"]
!= command["session"]["session_id"]
or current["control"]["acquisition_id"] != acquisition_id):
if (
current is None
or current["snapshot"]["acquisition"] != "streaming"
or current["snapshot"]["context"]["session_id"] != command["session"]["session_id"]
or current["control"]["acquisition_id"] != acquisition_id
):
await self.peers.close(answer["peer_id"])
raise ValueError("Acquisition changed during preview signalling")
return answer
@@ -192,6 +302,17 @@ class NodeK1Sensor:
):
raise ValueError("Device session changed")
runtime = state["snapshot_runtime_id"]
if action == "management":
if (params.get("control_generation") != current["control"]["generation"]
or params.get("control_revision") != current["control"]["revision"]):
raise ValueError("Состояние K1 изменилось. Обновите окно")
return await self.bridge.invoke("device.manage", {
**{key: value for key, value in params.items()
if key not in {"control_generation", "control_revision"}},
"operation_id": plugin_identifier,
"expected_snapshot_runtime_id": runtime,
**self.cas(state, acquisition=False),
}, identifier)
if action == "option":
if (
set(params) != {"profile", "settings"}
@@ -252,8 +373,11 @@ class NodeK1Sensor:
control = state.get("application_control_session") or {}
phase = control.get("state")
physical = control.get("physical_command") or state.get("physical_command") or {}
if ("acquisition.start" in dispatched
and phase in {"start-requested", "initializing", "scanning"}):
if "acquisition.start" in dispatched and phase in {
"start-requested",
"initializing",
"scanning",
}:
# The just-admitted START owns its pending physical edge.
# Returning its state does not dispatch or reconcile it again.
return project_sensor(state, node_id)
@@ -277,8 +401,15 @@ class NodeK1Sensor:
operation_id=prepare_identifier,
idempotency_key=prepare_identifier,
project_name=project_name,
mount_type=params["mount_type"], gnss_mode=params["gnss_mode"],
compatibility_attestation=ATTESTATION,
mount_type=params["mount_type"],
gnss_mode=params["gnss_mode"],
compatibility_attestation={
**ATTESTATION,
"topology": (
"usb-ethernet"
if state.get("active_connection_mode") == "usb" else "direct-lan"
),
},
)
elif phase == "project-ready" and acquisition.get("state") == "prepared":
if acquisition.get("project_name") != project_name:
@@ -0,0 +1,89 @@
"""Node-owned USB hotplug observation feeding the existing K1 Verify pipeline."""
import asyncio
import logging
from typing import TYPE_CHECKING
from .usb_network import LinuxK1UsbProbe
if TYPE_CHECKING:
from .node_bridge import NodeBridge
from .facade import (
CompatibilityAttestationRequest,
ConnectionVerifyRequest,
DesiredConnectionModeRequest,
)
logger = logging.getLogger(__name__)
class NodeK1UsbObserver:
def __init__(self, bridge: "NodeBridge", probe: LinuxK1UsbProbe) -> None:
self.bridge, self.probe = bridge, probe
self.accepted_generation: str | None = None
async def observe_once(self) -> None:
candidates = await asyncio.to_thread(self.probe.discover)
if len(candidates) != 1:
self.accepted_generation = None
return
attachment = candidates[0]
# Observe-only hotplug never steals a live wireless dialogue. The
# facade repeats all physical/receiver/lease checks under its gates.
async with self.bridge.lock:
state = await self.bridge.invoke("state.read", {}, "usb-observe")
mode = state.get("active_connection_mode")
if self.accepted_generation == attachment.generation:
lifecycle = state.get("connection_lifecycle") or {}
acquisition = state.get("acquisition") or {}
# A terminal STOP timeout can retire local control without a
# USB hotplug. Re-enter the same read-only Verify transaction;
# the physical ledger, not enumeration, decides its outcome.
# A live receiver remains owned by the connection monitor.
if (
lifecycle.get("connection_ready") is True
or state.get("source_mode") != "idle"
or acquisition.get("state") not in {None, "completed", "failed", "aborted"}
):
return
if mode not in {None, "usb"} and (
state.get("connection_lifecycle", {}).get("connection_ready") is True
or state.get("source_mode") != "idle"
):
return
if (state.get("connection_reconfiguration") or {}).get("intent"):
return
if state.get("desired_connection_mode") != "usb":
state = await asyncio.to_thread(
self.bridge.service.select_connection_mode, DesiredConnectionModeRequest(
connection_mode="usb",
expected_revision=state["desired_connection_mode_revision"],
)
)
# DeviceInfo-only, then the already implemented physical START
# reconciliation. This path never creates or reissues START.
await self.bridge.service.verify_connection(ConnectionVerifyRequest(
device_id=attachment.transport_ref, source="usb-enumeration",
compatibility_attestation=CompatibilityAttestationRequest(
firmware_version="3.0.2", topology="usb-ethernet",
verification="live-device-info",
),
expected_mode_revision=state["desired_connection_mode_revision"],
))
self.accepted_generation = attachment.generation
async def run(self) -> None:
while True:
try:
await self.observe_once()
except asyncio.CancelledError:
raise
except Exception as error:
# Bound retries of topology observation only. Never log native
# USB details/credentials or issue a device command here.
logger.info("K1 USB observation pending", extra={
"event_code": "k1_usb_observation_pending",
"reason_code": getattr(error, "reason_code", type(error).__name__),
})
await asyncio.sleep(5)
@@ -57,7 +57,7 @@ class PhysicalCommandRuntimeBinding:
compatibility_profile_id: str
intent_id: str
transport_ref: str
connection_mode: Literal["bridge", "quick-connect", "direct-connect"]
connection_mode: Literal["bridge", "quick-connect", "direct-connect", "usb"]
target_ipv4: str
target_port: int
host_path_epoch: int
@@ -45,7 +45,7 @@ _PHYSICAL_COMMAND_ARCHIVE_AFTER_LINK_FSYNC_FAILPOINT: Callable[[], None] | None
PHYSICAL_COMMAND_APPLICATION_SUCCESS_CODE = 302252033
PhysicalCommandAction = Literal["start", "stop"]
PhysicalCommandConnectionMode = Literal["bridge", "quick-connect", "direct-connect"]
PhysicalCommandConnectionMode = Literal["bridge", "quick-connect", "direct-connect", "usb"]
PhysicalCommandStage = Literal["prepared", "dispatching", "observing", "resolved"]
PhysicalCommandResolution = Literal[
"not-dispatched",
@@ -120,7 +120,7 @@ PhysicalSessionState = Literal[
]
_ACTIONS = frozenset({"start", "stop"})
_CONNECTION_MODES = frozenset({"bridge", "quick-connect", "direct-connect"})
_CONNECTION_MODES = frozenset({"bridge", "quick-connect", "direct-connect", "usb"})
_STAGES = frozenset({"prepared", "dispatching", "observing", "resolved"})
_RESOLUTIONS = frozenset(
{
@@ -2483,6 +2483,7 @@ class PhysicalCommandLedger:
if (
current.reconciled_physical_state != "active"
and not current.reopened_physical_state_requires_reconciliation
and reopened_resolved_start is None
):
raise PhysicalCommandTransitionError(
"active rebind requires a resolved active physical state"
@@ -2573,6 +2574,8 @@ class PhysicalCommandLedger:
prior_active_observation = (
latest_recovery.observation
if latest_recovery is not None
else reopened_resolved_start.last_status
if reopened_resolved_start is not None
else current.last_status
if current.resolution == "start-active-observed"
else _latest_reconciliation_for_operation(current).observation
@@ -2692,6 +2695,7 @@ class PhysicalCommandLedger:
if (
current.reconciled_physical_state != "active"
and not reopened_physical_state_requires_reconciliation
and reopened_resolved_start is None
and not awaiting_ready_after_scan_over
):
raise PhysicalCommandTransitionError(
@@ -361,6 +361,7 @@ class PhysicalAcceptanceDialogueExecutor:
event_observed: Callable[[], bool],
*,
reconciled_active_observed: Callable[[], bool] | None = None,
standby_work: Callable[[], None] | None = None,
) -> OperatorDialogueCheckpoint | None:
"""Service the original socket until one exact operator UI event occurs."""
@@ -382,6 +383,8 @@ class PhysicalAcceptanceDialogueExecutor:
"active recovery may replace only the workspace-entry checkpoint"
)
while True:
if standby_work is not None:
standby_work()
if reconciled_active_observed is not None and reconciled_active_observed():
if not self._transport.scan_initialization_complete(binding):
raise ApplicationAcceptanceError(
@@ -806,11 +809,15 @@ class PhysicalAcceptanceDialogueExecutor:
self._active_authority = None
self._active_binding = None
def maintain_standby_until_next_acquisition(self, requested: Callable[[], bool]) -> None:
def maintain_standby_until_next_acquisition(
self, requested: Callable[[], bool], *, standby_work: Callable[[], None] | None = None,
) -> None:
"""Pump the retained socket after READY; issue no device commands."""
if self._dialogue_stage != "standby-confirmed" or self._standby_binding is None:
raise ApplicationAcceptanceError("next acquisition requires confirmed standby")
while True:
if standby_work is not None:
standby_work()
self._transport.maintain_open_for(
CONTROL_NETWORK_PUMP_QUANTUM_SECONDS,
allowed_response_topics={MODELING_STATUS_RESPONSE_TOPIC},
@@ -53,6 +53,16 @@ from k1link.device_plugins.xgrids_k1.protocol.modeling_safety import (
MODELING_REQUEST_TOPIC,
)
from .device_management import (
CONTROL_REQUEST,
CONTROL_RESPONSE,
MAX_PROJECT_RESPONSE_BYTES,
PROJECT_REQUEST,
PROJECT_RESPONSE,
management_action,
management_identity,
)
MODELING_RESPONSE_TOPIC = "lixel/application/response/modeling"
CONTROL_KEEPALIVE_SECONDS = 60
CONTROL_CONNECT_TIMEOUT_SECONDS = 10.0
@@ -61,6 +71,10 @@ CONTROL_LOOP_INTERVAL_SECONDS = 0.05
MAX_CONTROL_MAINTAIN_SECONDS = 30.0
MAX_CONTROL_RESPONSE_BYTES = 64 * 1024
SYSTEM_ERROR_TOPIC = "lixel/application/report/system_error"
# Exact non-terminating report observed on FW 3.0.2, with LixelGO's
# severity-1 handling independently reviewed. Do not generalize by bit prefix:
# unknown reports and known session faults remain blocking. See MQTT profile.
_NON_TERMINATING_SYSTEM_REPORTS = frozenset({0x12041002})
CONTROL_HEARTBEAT_TOPIC = "lixel/application/report/heartbeat"
# DeviceInfo proves identity only at one instant. Thereafter the unchanged
# control socket must keep producing reviewed MQTT evidence. Ninety seconds
@@ -71,6 +85,8 @@ CONTROL_HEARTBEAT_TOPIC = "lixel/application/report/heartbeat"
CONTROL_PROOF_TTL_SECONDS = 90.0
APPLICATION_RESPONSE_TOPIC_BY_REQUEST_TOPIC = {
CONTROL_REQUEST: CONTROL_RESPONSE,
PROJECT_REQUEST: PROJECT_RESPONSE,
DEVICE_INFO_REQUEST_TOPIC: DEVICE_INFO_RESPONSE_TOPIC,
MODELING_STATUS_REQUEST_TOPIC: MODELING_STATUS_RESPONSE_TOPIC,
GET_RTK_ADVANCE_REQUEST_TOPIC: GET_RTK_ADVANCE_RESPONSE_TOPIC,
@@ -149,6 +165,7 @@ CONTROL_SUBSCRIPTION_GROUPS: tuple[tuple[tuple[str, int], ...], ...] = (
APPLICATION_RESPONSE_TOPICS = frozenset(
{
CONTROL_RESPONSE, PROJECT_RESPONSE,
DEVICE_INFO_RESPONSE_TOPIC,
MODELING_STATUS_RESPONSE_TOPIC,
GET_RTK_ADVANCE_RESPONSE_TOPIC,
@@ -168,6 +185,7 @@ CONTROL_REPORT_TOPICS = frozenset(
APPLICATION_REQUEST_ALLOWLIST = frozenset(
{
CONTROL_REQUEST, PROJECT_REQUEST,
"lixel/application/request/device_info",
"lixel/application/request/modeling_status",
"lixel/application/request/get_rtk_advance",
@@ -287,6 +305,7 @@ class _ApplicationResponseExpectation:
topic: str
identity: ApplicationMessageIdentity
modeling_action: ModelingAction | None = None
management_action: int | None = None
@property
def correlation_key(self) -> tuple[str, str, ModelingAction | None]:
@@ -296,9 +315,12 @@ class _ApplicationResponseExpectation:
self,
observed: ApplicationMessageIdentity,
observed_modeling_action: ModelingAction | None,
observed_management_action: int | None = None,
) -> bool:
if self.modeling_action is not observed_modeling_action:
return False
if self.management_action != observed_management_action:
return False
if not hmac.compare_digest(self.identity.session_id, observed.session_id):
return False
if not hmac.compare_digest(self.identity.openapi_key, observed.openapi_key):
@@ -338,6 +360,7 @@ class ApplicationMqttTransportSnapshot:
control_proof_source: str | None
control_proof_fresh: bool
control_proof_age_seconds: float | None
storage_status: dict[str, object] | None = None
clean_session: bool = False
keepalive_seconds: int = CONTROL_KEEPALIVE_SECONDS
automatic_reconnect: bool = False
@@ -374,6 +397,7 @@ class ApplicationMqttTransportSnapshot:
"control_proof_source": self.control_proof_source,
"control_proof_fresh": self.control_proof_fresh,
"control_proof_age_seconds": self.control_proof_age_seconds,
"storage_status": dict(self.storage_status) if self.storage_status else None,
"clean_session": self.clean_session,
"keepalive_seconds": self.keepalive_seconds,
"automatic_reconnect": self.automatic_reconnect,
@@ -460,11 +484,14 @@ class ReviewedApplicationMqttTransport:
self._late_known_responses = 0
self._device_status_reports = 0
self._system_error_reports = 0
self._blocking_system_error = False
self._report_decode_errors = 0
self._retained_control_reports_ignored = 0
self._retained_application_responses_rejected = 0
self._latest_device_session_state: str | None = None
self._latest_device_project_bound: bool | None = None
self._validated_status_identity: tuple[str, str] | None = None
self._latest_storage_status: dict[str, object] | None = None
self._latest_device_init_ready: bool | None = None
self._latest_device_id: str | None = None
self._latest_device_serial: str | None = None
@@ -1006,6 +1033,14 @@ class ReviewedApplicationMqttTransport:
and proof_age <= self._control_proof_ttl_seconds
),
control_proof_age_seconds=proof_age,
storage_status=(
dict(self._latest_storage_status)
if self._latest_storage_status
and self._validated_status_identity is not None
and (self._latest_device_id, self._latest_device_serial)
== self._validated_status_identity
else None
),
)
def _new_client(self) -> mqtt.Client:
@@ -1108,7 +1143,9 @@ class ReviewedApplicationMqttTransport:
self._set_callback_error("control MQTT received an unreviewed subscribed topic")
return
payload = bytes(message.payload)
if len(payload) > MAX_CONTROL_RESPONSE_BYTES:
response_limit = (MAX_PROJECT_RESPONSE_BYTES if message.topic == PROJECT_RESPONSE
else MAX_CONTROL_RESPONSE_BYTES)
if len(payload) > response_limit:
self._set_callback_error("control MQTT response exceeds the reviewed bound")
return
mqtt_retained = bool(getattr(message, "retain", False))
@@ -1210,6 +1247,11 @@ class ReviewedApplicationMqttTransport:
)
self._latest_device_project_bound = bool(device_report.project_id)
self._latest_device_init_ready = device_report.init_ready
self._latest_storage_status = (
{"used_percent": device_report.storage_used_percent,
"observed_at": evidence.observed_at_utc}
if device_report.storage_used_percent is not None else None
)
self._latest_device_id = (
device_report.header.device_id if device_report.header is not None else None
)
@@ -1239,6 +1281,9 @@ class ReviewedApplicationMqttTransport:
return
with self._lock:
self._system_error_reports += 1
self._blocking_system_error |= (
system_error_report.error_code not in _NON_TERMINATING_SYSTEM_REPORTS
)
self._latest_system_error_code = system_error_report.error_code
self._latest_system_error_state = (
system_error_report.session_state.name.casefold()
@@ -1254,7 +1299,7 @@ class ReviewedApplicationMqttTransport:
raise ApplicationControlDeviceFault(
"K1 control report decoding failed; no further automatic action is admissible"
)
if self._system_error_reports or self._latest_device_fault:
if self._blocking_system_error or self._latest_device_fault:
state = self._latest_system_error_state or self._latest_device_session_state
raise ApplicationControlDeviceFault(
f"K1 reported a control fault state: {state or 'unknown'}"
@@ -1288,6 +1333,10 @@ class ReviewedApplicationMqttTransport:
raise ApplicationControlProofStale(
"K1 control proof expired without fresh MQTT evidence"
)
# Bind display telemetry to the proven DeviceInfo identity. Subsequent
# reports need not be promoted to command authority just to display
# their storage value; each still has to match this exact identity.
self._validated_status_identity = (binding.vendor_device_id, binding.device_serial)
def _mark_control_proof_locked(
self,
@@ -1496,14 +1545,24 @@ class ReviewedApplicationMqttTransport:
ambiguous_reason_code = "retained_application_response"
break
try:
observed = decode_application_message_identity(payload)
except ApplicationBootstrapError:
observed = (management_identity(payload) if topic == PROJECT_RESPONSE
else decode_application_message_identity(payload))
except (ApplicationBootstrapError, ValueError):
self._poison_locked("response identity decoding failed")
ambiguous_message = "control response identity could not be decoded safely"
ambiguous_reason_code = "response_identity_decode_failed"
break
observed_modeling_action: ModelingAction | None = None
observed_management_action: int | None = None
observed_result_code: int | None = None
if topic in {CONTROL_RESPONSE, PROJECT_RESPONSE}:
try:
observed_management_action = management_action(payload)
except ValueError:
self._poison_locked("management response action decoding failed")
ambiguous_message = "control management response has no exact action"
ambiguous_reason_code = "management_response_decode_failed"
break
if topic == MODELING_RESPONSE_TOPIC:
try:
modeling_response = decode_modeling_response(payload)
@@ -1523,6 +1582,7 @@ class ReviewedApplicationMqttTransport:
if self._known_response_expectations[operation_key].matches(
observed,
observed_modeling_action,
observed_management_action,
)
]
next_unobserved = next(
@@ -1604,7 +1664,8 @@ class ReviewedApplicationMqttTransport:
if response_topic is None:
raise ValueError("control request has no reviewed response topic")
try:
identity = decode_application_message_identity(envelope.payload)
identity = (management_identity(envelope.payload) if envelope.topic == PROJECT_REQUEST
else decode_application_message_identity(envelope.payload))
except ApplicationBootstrapError as exc:
raise ValueError("control request identity is not decodable") from exc
modeling_action: ModelingAction | None = None
@@ -1620,6 +1681,8 @@ class ReviewedApplicationMqttTransport:
topic=response_topic,
identity=identity,
modeling_action=modeling_action,
management_action=(management_action(envelope.payload)
if envelope.topic in {CONTROL_REQUEST, PROJECT_REQUEST} else None),
)
@staticmethod
@@ -1671,6 +1734,14 @@ class ReviewedApplicationMqttTransport:
dispatch_admission_commit: Callable[[], None] | None,
) -> None:
observer = self._evidence_observer_snapshot()
if evidence.operation_key.startswith(("management:", "management-info:")):
# The physical START/STOP coordinator deliberately ignores these
# explicit idle-only operations. Own their final no-retry admission
# here, even when that observer is installed on the shared socket.
self._require_dispatch_deadline_open(dispatch_admission_deadline_reached)
if dispatch_admission_commit is not None:
dispatch_admission_commit()
return
if observer is not None:
observer.publish_dispatching(
evidence,
@@ -6,6 +6,7 @@ import threading
import time
from collections.abc import Callable, Mapping
from dataclasses import dataclass
from functools import partial
from typing import Literal
from k1link.device_plugins.xgrids_k1.physical_command_coordinator import (
@@ -39,6 +40,10 @@ from k1link.device_plugins.xgrids_k1.protocol.application_mqtt import (
from k1link.device_plugins.xgrids_k1.protocol.application_publish import (
OneShotPublishEnvelope,
)
from k1link.device_plugins.xgrids_k1.protocol.management_mailbox import (
MaintenanceJob,
ManagementMailbox,
)
from k1link.device_plugins.xgrids_k1.protocol.modeling_control import (
CommandHeaderIdentity,
ModelingAction,
@@ -126,7 +131,7 @@ class ApplicationConnectionBinding:
host_path_epoch: int
target_ipv4: str
target_port: int
connection_mode: Literal["bridge", "quick-connect", "direct-connect"]
connection_mode: Literal["bridge", "quick-connect", "direct-connect", "usb"]
def __post_init__(self) -> None:
if not self.intent_id.strip():
@@ -264,6 +269,40 @@ class InteractiveApplicationControlSession:
# browser response cannot advance a later session that happens to be
# in the same named phase.
self._state_revision = 0
self._management = ManagementMailbox()
def manage_device(
self, *, operation: str, identifier: str, project_ids: tuple[str, ...],
expected_session_generation: int, expected_state_revision: int,
catalog_revision: str | None = None,
) -> dict[str, object]:
job = MaintenanceJob(operation, identifier, project_ids, expected_session_generation,
expected_state_revision, time.monotonic() + 25, catalog_revision)
self._validate_management_job(job)
return self._management.submit(job)
def _validate_management_job(self, job: MaintenanceJob) -> None:
coordinator = self._physical_command_coordinator
if coordinator is not None:
physical = coordinator.snapshot()
if physical.get("recovery_requirement") or physical.get("requires_reconciliation"):
raise ValueError("Сначала подтвердите состояние предыдущей съёмки K1")
with self._lock:
self._require_checkpoint_locked(expected_session_generation=job.generation,
expected_state_revision=job.revision)
if (self._phase not in {"connection-ready", "completed"} or self._cancel_requested
or self._workspace_requested.is_set()
or self._active_recovery_requested.is_set()):
raise ValueError("Обслуживание доступно только после завершения съёмки K1")
if job.operation == "usb-storage" and (
self._connection_binding is None
or self._connection_binding.connection_mode != "bridge"
):
raise ValueError(
"Режим носителя отключает USB-связь. Подключите K1 через Bridge "
"для переключения и возврата. Проекты доступны и без смены режима."
)
self._validate_connection_binding_snapshot("device-management-dispatch")
def open(
self,
@@ -389,6 +428,8 @@ class InteractiveApplicationControlSession:
return self.snapshot()
def _require_workspace_entry_locked(self) -> None:
if self._management.pending is not None or self._management.block_start:
raise ValueError("Завершите обслуживание K1 и подтвердите режим передачи данных")
if (self._phase == "completed" and self._transport is not None
and not self._cancel_requested):
return
@@ -968,6 +1009,9 @@ class InteractiveApplicationControlSession:
"workspace-entered",
self._workspace_requested.is_set,
reconciled_active_observed=self._active_recovery_requested.is_set,
standby_work=partial(self._management.pump,
transport, authority, binding, self._validate_management_job,
),
)
if workspace is None:
self._validate_connection_binding("active-recovery-adoption")
@@ -1159,7 +1203,12 @@ class InteractiveApplicationControlSession:
self._scanning_observer_confirmed = self._scanning_observer is None
completed_acquisition = True
self._set_phase_locked("completed")
executor.maintain_standby_until_next_acquisition(self._workspace_requested.is_set)
executor.maintain_standby_until_next_acquisition(
self._workspace_requested.is_set,
standby_work=partial(self._management.pump,
transport, authority, binding, self._validate_management_job,
),
)
self._validate_connection_binding_snapshot("next-acquisition-preflight")
# Operation keys and response correlations are one-shot per MQTT
# dialogue. A new explicit scan gets a fresh socket, never reset
@@ -1488,6 +1537,7 @@ class InteractiveApplicationControlSession:
},
)
finally:
self._management.cancel_queued()
final_dialogue_snapshot: dict[str, object] | None = None
final_transport_snapshot: dict[str, object] | None = None
if executor is not None:
@@ -0,0 +1,177 @@
"""Bounded vendor device/storage messages; no SDK client or new authentication.
Wire reference: XGRIDS Lixel_OpenAPI aiot_msgs.proto at
a60a73773b0c2da3e582607ff71b32baa1238d4e. Execution belongs to the existing
interactive control worker, exclusively at its confirmed standby checkpoint.
"""
from __future__ import annotations
import hashlib
from enum import IntEnum
from .application_bootstrap import (
ApplicationControlAuthority,
ApplicationMessageIdentity,
ApplicationRequestHeader,
LiveDeviceControlBinding,
_bytes_field,
_encode_header,
_text_field,
_varint_field,
decode_application_message_identity,
)
from .application_publish import OneShotPublishEnvelope
from .modeling_control import OPENAPI_SUCCESS
from .protobuf_wire import ProtoField, iter_fields
PROJECT_REQUEST = "lixel/application/request/project_list"
PROJECT_RESPONSE = "lixel/application/response/project_list"
CONTROL_REQUEST = "lixel/application/request/device_control"
CONTROL_RESPONSE = "lixel/application/response/device_control"
MAX_PROJECT_RESPONSE_BYTES = 4 * 1024 * 1024
MAX_PROJECTS = 4096
class ManagementAction(IntEnum):
USB_MASS = 15
USB_ETHER = 16
DISK_FORMAT = 17
POWER_OFF = 20
SYSTEM_REBOOT = 22
LIST_PROJECTS = 23
DELETE_PROJECTS = 25
OPERATIONS = {
"projects": ManagementAction.LIST_PROJECTS,
"delete-projects": ManagementAction.DELETE_PROJECTS,
"format-storage": ManagementAction.DISK_FORMAT,
"usb-storage": ManagementAction.USB_MASS,
"usb-data": ManagementAction.USB_ETHER,
"power-off": ManagementAction.POWER_OFF,
"reboot": ManagementAction.SYSTEM_REBOOT,
}
def management_envelope(
operation: str, operation_id: str, authority: ApplicationControlAuthority,
binding: LiveDeviceControlBinding, project_ids: tuple[str, ...] = (),
) -> OneShotPublishEnvelope:
action = OPERATIONS[operation]
if len(project_ids) > MAX_PROJECTS or len(set(project_ids)) != len(project_ids):
raise ValueError("Invalid project selection")
if (action == ManagementAction.DELETE_PROJECTS) != bool(project_ids):
raise ValueError("Only project deletion accepts a nonempty project selection")
if any(not value or len(value.encode("utf-8")) > 256 for value in project_ids):
raise ValueError("Invalid project identifier")
project_request = action in {ManagementAction.LIST_PROJECTS, ManagementAction.DELETE_PROJECTS}
header = ApplicationRequestHeader(
"ProjectListRequest" if project_request else "DeviceControlRequest",
authority, binding, context=operation_id,
)
payload = _bytes_field(1, _encode_header(header)) + _varint_field(2, int(action))
payload += b"".join(_text_field(3 if len(project_ids) == 1 else 5, value)
for value in project_ids)
return OneShotPublishEnvelope(
operation_key=f"management:{operation_id}",
topic=PROJECT_REQUEST if project_request else CONTROL_REQUEST,
payload=payload, payload_sha256=hashlib.sha256(payload).hexdigest(),
payload_bytes=len(payload), qos=2, retain=False,
)
def unique_fields(payload: bytes, *, maximum: int = 64) -> dict[int, ProtoField]:
result: dict[int, ProtoField] = {}
for item in iter_fields(payload, max_fields=maximum):
if item.number in result:
raise ValueError("Duplicate singular vendor field")
result[item.number] = item
return result
def management_identity(payload: bytes) -> ApplicationMessageIdentity:
"""Bound repeated project fields without widening ordinary control decoding."""
if len(payload) > MAX_PROJECT_RESPONSE_BYTES:
raise ValueError("Project response exceeds the bounded catalog")
header = None
for item in iter_fields(payload, max_fields=MAX_PROJECTS + 32):
if item.number == 1:
if header is not None or item.wire_type != 2 or not isinstance(item.value, bytes):
raise ValueError("Invalid project response header")
header = item.value
if header is None:
raise ValueError("Project response header is missing")
return decode_application_message_identity(_bytes_field(1, header))
def uint(fields: dict[int, ProtoField], key: int, default: int | None = None) -> int:
value = fields.get(key)
if value is None and default is not None:
return default
if value is None or value.wire_type != 0 or not isinstance(value.value, int):
raise ValueError("Missing vendor integer")
return value.value
def management_action(payload: bytes) -> int:
"""Read the exact action without interpreting repeated project entries."""
actions = [item for item in iter_fields(payload, max_fields=MAX_PROJECTS + 32)
if item.number == 2]
if len(actions) != 1:
raise ValueError("Missing or repeated management action")
return uint({2: actions[0]}, 2)
def data(fields: dict[int, ProtoField], key: int) -> bytes:
value = fields.get(key)
if value is None or value.wire_type != 2 or not isinstance(value.value, bytes):
raise ValueError("Missing vendor message")
return value.value
def decode_management_response(payload: bytes, operation: str) -> dict[str, object]:
if len(payload) > MAX_PROJECT_RESPONSE_BYTES:
raise ValueError("Project response exceeds the bounded catalog")
fields: dict[int, ProtoField] = {}
projects: list[dict[str, object]] = []
seen: set[str] = set()
for item in iter_fields(payload, max_fields=MAX_PROJECTS + 32):
if item.number == 4 and operation in {"projects", "delete-projects"}:
if not isinstance(item.value, bytes) or item.wire_type != 2:
raise ValueError("Invalid project entry")
project = unique_fields(item.value)
identifier = data(project, 1).decode("utf-8")
name = data(project, 2).decode("utf-8")
if (not identifier or len(identifier.encode()) > 256 or len(name.encode()) > 1024
or identifier in seen or len(projects) >= MAX_PROJECTS):
raise ValueError("Invalid or duplicate project identity")
seen.add(identifier)
# URLs, directory JSON and file paths never cross the product boundary.
projects.append({"id": identifier, "name": name})
else:
if item.number in fields:
raise ValueError("Duplicate management response field")
fields[item.number] = item
if uint(fields, 2) != int(OPERATIONS[operation]):
raise ValueError("Vendor response belongs to another command")
code = uint(unique_fields(data(fields, 15)), 1)
return {"status": "succeeded" if code == OPENAPI_SUCCESS else "rejected",
"result_code": code, **({"projects": projects} if operation == "projects" else {})}
def decode_storage_mode(payload: bytes) -> dict[str, object]:
"""DeviceInfo owns observed mode; an accepted mode command is not evidence."""
top = unique_fields(payload)
if uint(unique_fields(data(top, 15)), 1) != OPENAPI_SUCCESS:
raise ValueError("DeviceInfo rejected")
device = unique_fields(data(top, 2))
working = unique_fields(data(device, 7))
mass = uint(working, 4, 0)
if mass not in {0, 1}:
raise ValueError("Invalid USB mode")
storage = unique_fields(data(device, 10)) if 10 in device else {}
storage_code = uint(storage, 1, 0)
storage_type = (storage_code >> 1) ^ -(storage_code & 1)
return {"usb_mode": "storage" if mass else "data",
"storage_type": {0: "internal", 1: "microSD", 2: "external-usb"}.get(
storage_type, "unknown") if 10 in device else "unknown"}
@@ -0,0 +1,171 @@
"""Explicit maintenance work on the existing control worker, never a second client."""
from __future__ import annotations
import hashlib
import json
import threading
import time
from collections.abc import Callable
from dataclasses import dataclass, field
from typing import TYPE_CHECKING, Any, cast
from .application_bootstrap import (
DEVICE_INFO_REQUEST_TOPIC,
ApplicationControlAuthority,
ApplicationRequestHeader,
LiveDeviceControlBinding,
_bytes_field,
_encode_header,
)
from .application_publish import OneShotPublishEnvelope
from .device_management import decode_management_response, decode_storage_mode, management_envelope
if TYPE_CHECKING:
from .application_mqtt import ReviewedApplicationMqttTransport
@dataclass
class MaintenanceJob:
operation: str
identifier: str
project_ids: tuple[str, ...]
generation: int
revision: int
deadline: float
catalog_revision: str | None = None
finished: threading.Event = field(default_factory=threading.Event)
result: dict[str, Any] | None = None
class ManagementMailbox:
def __init__(self) -> None:
self.lock = threading.Lock()
self.pending: MaintenanceJob | None = None
self.block_start = False
self.mode: dict[str, object] = {}
self.generation = -1
self.catalog_revision: str | None = None
self.project_ids: set[str] = set()
def submit(self, job: MaintenanceJob) -> dict[str, Any]:
with self.lock:
if self.pending is not None:
raise ValueError("Другая операция K1 ещё выполняется")
self.pending = job
if not job.finished.wait(max(0.0, job.deadline - time.monotonic()) + 1):
# An expired queued job can never be published later. A dispatch
# already on the wire stays unknown and is never retried here.
return {"status": "unknown", "message": "K1 не подтвердил результат операции"}
return job.result or {"status": "unknown"}
def cancel_queued(self) -> None:
"""Called by the sole worker only after any in-flight pump has ended."""
with self.lock:
job, self.pending = self.pending, None
if job is not None:
job.result = {"status": "blocked", "message": "Управляющее соединение K1 закрыто"}
job.finished.set()
def pump(
self, transport: ReviewedApplicationMqttTransport,
authority: ApplicationControlAuthority, binding: LiveDeviceControlBinding,
validate: Callable[[MaintenanceJob], None],
) -> None:
with self.lock:
job = self.pending
if job is None:
return
dispatched = False
deleted: list[str] = []
try:
validate(job)
if time.monotonic() >= job.deadline:
raise ValueError("Время ожидания операции истекло до отправки")
if not transport.standby_complete(binding):
raise ValueError("K1 не подтвердил завершение съёмки. Остановите запись")
if job.operation == "delete-projects" and (
job.generation != self.generation or not self.catalog_revision
or job.catalog_revision != self.catalog_revision
or not set(job.project_ids) <= self.project_ids
):
raise ValueError("Список проектов изменился. Обновите его перед удалением")
def expired() -> bool:
validate(job)
return time.monotonic() >= job.deadline
def mark_dispatched() -> None:
nonlocal dispatched
dispatched = True
def exchange(envelope: OneShotPublishEnvelope) -> bytes:
return transport.exchange_batch_once(
(envelope,), required_response_operation_keys=(envelope.operation_key,),
dispatch_admission_deadline_reached=expired,
dispatch_admission_commit=mark_dispatched,
)[envelope.operation_key]
result: dict[str, Any]
if job.operation == "info":
result = {"status": "succeeded"}
else:
if job.operation in {"delete-projects", "format-storage"}:
self.catalog_revision = None
# The qualified K1 firmware accepts the singular project ID but
# rejects the newer repeated-ID request. Keep group selection in
# this same fenced worker and await each ordinary vendor reply.
selections = [(value,) for value in job.project_ids] if (
job.operation == "delete-projects"
) else [job.project_ids]
for index, selection in enumerate(selections):
envelope = management_envelope(
job.operation, f"{job.identifier}-{index}", authority, binding, selection,
)
result = decode_management_response(exchange(envelope), job.operation)
if result["status"] != "succeeded":
if job.operation == "delete-projects":
result["message"] = (
f"Удалено {len(deleted)} из {len(job.project_ids)}. "
"K1 отклонил следующее удаление. Обновите список проектов."
)
break
if job.operation == "delete-projects":
deleted.extend(selection)
if job.operation == "delete-projects":
result["deleted_project_ids"] = deleted
if result["status"] == "succeeded" and job.operation == "projects":
projects = cast(list[dict[str, str]], result["projects"])
self.project_ids = {item["id"] for item in projects}
self.catalog_revision = hashlib.sha256(
json.dumps([job.generation, result["projects"]], sort_keys=True).encode()
).hexdigest()
result["catalog_revision"] = self.catalog_revision
if result["status"] == "succeeded" and job.operation not in {"power-off", "reboot"}:
header = ApplicationRequestHeader("DeviceInfoRequest", authority, binding,
context=job.identifier + "-info")
payload = _bytes_field(1, _encode_header(header))
envelope = OneShotPublishEnvelope(
"management-info:" + job.identifier, DEVICE_INFO_REQUEST_TOPIC,
payload, hashlib.sha256(payload).hexdigest(), len(payload), 2, False,
)
mode = decode_storage_mode(exchange(envelope))
self.mode, self.generation = mode, job.generation
self.block_start = mode["usb_mode"] == "storage"
result.update(mode)
elif result["status"] == "succeeded":
self.block_start = True
job.result = result
except Exception as exc:
if dispatched and job.operation not in {"info", "projects"}:
self.block_start = True
# A lost reply is not a rejected command. Never retry a write.
job.result = {
"status": "unknown" if dispatched else "blocked",
"message": ("K1 не подтвердил результат. Проверьте состояние устройства."
if dispatched else str(exc)),
**({"deleted_project_ids": deleted} if job.operation == "delete-projects" else {}),
}
finally:
with self.lock:
self.pending = None
job.finished.set()
@@ -188,8 +188,8 @@ class DeviceStatusReport:
"""Recovered acquisition subset of ``DeviceStatusReport``.
Vendor identity and project strings are intentionally redacted from repr.
Nested system/RTK messages are bounded by the outer parser but are not
interpreted by this modeling state machine.
Storage occupancy is optional display telemetry; nested system/RTK messages
never decide this modeling state machine.
"""
header: ObservedHeader | None = field(repr=False)
@@ -201,6 +201,7 @@ class DeviceStatusReport:
init_ready: bool
system_status_present: bool
rtk_status_present: bool
storage_used_percent: float | None = None
@dataclass(frozen=True, slots=True)
@@ -338,6 +339,7 @@ def decode_device_status_report(
init_ready = False
system_status_present = False
rtk_status_present = False
storage_used_percent = None
seen: set[int] = set()
try:
for proto_field in iter_fields(payload, max_fields=64):
@@ -366,7 +368,8 @@ def decode_device_status_report(
init_ready = bool(raw_ready)
elif proto_field.number == 7:
_mark_once(seen, 7, "device_status.system_status")
_bytes_value(proto_field, "device_status.system_status")
system = _bytes_value(proto_field, "device_status.system_status")
storage_used_percent = _storage_used_percent(system)
system_status_present = True
elif proto_field.number == 8:
_mark_once(seen, 8, "device_status.rtk_status")
@@ -387,9 +390,32 @@ def decode_device_status_report(
init_ready=init_ready,
system_status_present=system_status_present,
rtk_status_present=rtk_status_present,
storage_used_percent=storage_used_percent,
)
def _storage_used_percent(payload: bytes) -> float | None:
"""Optional display telemetry from reviewed SystemStatus fields 4/5.
Units are not inferred; only the dimensionless ratio is exposed. Invalid
auxiliary telemetry must not change the existing acquisition state machine.
Proto3 may omit DiskUsed when it is zero.
"""
values: dict[int, int] = {}
try:
for field in iter_fields(payload, max_fields=64):
if field.number in {4, 5}:
if field.number in values:
return None
values[field.number] = _uint_value(
field, "system_status.storage", max_value=(1 << 63) - 1
)
except ValueError:
return None
total, used = values.get(4, 0), values.get(5, 0)
return 100.0 * used / total if total > 0 and used <= total else None
def session_state_from_code(code: int) -> SessionState | None:
"""Map the captured base-offset status code, preserving unknown values."""
@@ -23,12 +23,12 @@ SEMANTIC_TOPOLOGY_LOCK_FILENAME = ".semantic-topology.lock"
SEMANTIC_TOPOLOGY_MAX_BYTES = 16 * 1024
SEMANTIC_TOPOLOGY_MAX_REVISION = (1 << 63) - 1
TopologyConnectionMode = Literal["bridge", "quick-connect", "direct-connect"]
TopologyEvidenceSource = Literal["ble-post-write-status", "ble-read-only-status"]
TopologyConnectionMode = Literal["bridge", "quick-connect", "direct-connect", "usb"]
TopologyEvidenceSource = Literal["ble-post-write-status", "ble-read-only-status", "usb-enumeration"]
SemanticTopologyStoreStatus = Literal["empty", "available", "corrupt"]
_CONNECTION_MODES = frozenset({"bridge", "quick-connect", "direct-connect"})
_EVIDENCE_SOURCES = frozenset({"ble-post-write-status", "ble-read-only-status"})
_CONNECTION_MODES = frozenset({"bridge", "quick-connect", "direct-connect", "usb"})
_EVIDENCE_SOURCES = frozenset({"ble-post-write-status", "ble-read-only-status", "usb-enumeration"})
_SAFE_IDENTIFIER = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._:+-]{0,159}$")
_SAFE_FIRMWARE_VERSION = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._+() -]{0,63}$")
@@ -0,0 +1,121 @@
"""Read-only Linux USB Ethernet discovery for the physically qualified K1.
Addresses come from the device's DHCP lease, never from a product default.
Enumeration is only a candidate: the existing DeviceInfo/identity admission
must still succeed before any acquisition command can be sent.
"""
from __future__ import annotations
import hashlib
import ipaddress
import json
import re
import subprocess
from dataclasses import dataclass
from pathlib import Path
from typing import Protocol
from .linux_host import _run, nm_fields
class NetworkObservationRunner(Protocol):
def __call__(self, args: list[str], *, timeout: float) -> str: ...
@dataclass(frozen=True, slots=True)
class UsbNetworkAttachment:
transport_ref: str
interface: str
peer_ipv4: str
source_ipv4: str
generation: str
speed: str
class LinuxK1UsbProbe:
"""Observe an already enumerated RNDIS interface; never configure the OS."""
def __init__(
self, sys_net: Path = Path("/sys/class/net"),
runner: NetworkObservationRunner | None = None,
) -> None:
self.sys_net = sys_net
self.run = runner or _run
def discover(self) -> tuple[UsbNetworkAttachment, ...]:
found = []
for interface in sorted(self.sys_net.iterdir()):
if not re.fullmatch(r"[A-Za-z0-9_.:-]{1,64}", interface.name):
continue
try:
attachment = self._read(interface)
except (OSError, ValueError, KeyError, TypeError, subprocess.SubprocessError):
continue
if attachment is not None:
found.append(attachment)
# Same serial or same peer on multiple links is not an exact route.
# Supporting those devices requires explicit routing isolation first.
return tuple(
item for item in found
if sum(other.transport_ref == item.transport_ref for other in found) == 1
and sum(other.peer_ipv4 == item.peer_ipv4 for other in found) == 1
)
def require(self, transport_ref: str) -> UsbNetworkAttachment:
matches = [item for item in self.discover() if item.transport_ref == transport_ref]
if len(matches) != 1:
raise OSError("USB K1 не найден. Проверьте питание и USB-кабель.")
return matches[0]
def _read(self, interface: Path) -> UsbNetworkAttachment | None:
device = (interface / "device").resolve(strict=True)
usb = next((parent for parent in (device, *device.parents)
if (parent / "idVendor").is_file()), None)
if usb is None or (usb / "idVendor").read_text().strip().lower() != "2207":
return None
if (usb / "idProduct").read_text().strip().lower() != "0019":
return None
if (usb / "product").read_text().strip() != "XGRIDS Device":
return None
if (device / "driver").resolve(strict=True).name != "rndis_host":
return None
serial = (usb / "serial").read_text().strip()
if not serial or len(serial) > 128 or (interface / "carrier").read_text().strip() != "1":
return None
options = self.run([
"nmcli", "-t", "--escape", "yes", "-f", "DHCP4.OPTION",
"device", "show", interface.name,
], timeout=2)
peers = set()
for line in options.splitlines():
fields = nm_fields(line)
if len(fields) != 2:
continue
key, separator, value = fields[1].partition(" = ")
if separator and key.strip() == "dhcp_server_identifier":
peer = ipaddress.IPv4Address(value.strip())
if peer.is_private and not (peer.is_loopback or peer.is_link_local
or peer.is_multicast or peer.is_unspecified):
peers.add(str(peer))
if len(peers) != 1:
return None
peer_ipv4 = peers.pop()
routes = json.loads(self.run(["ip", "-j", "route", "get", peer_ipv4], timeout=2))
if not isinstance(routes, list) or len(routes) != 1:
return None
route = routes[0]
if (route.get("dev") != interface.name or route.get("gateway")
or route.get("type", "unicast") != "unicast"):
return None
source = str(ipaddress.IPv4Address(route["prefsrc"]))
generation = hashlib.sha256(json.dumps([
serial, str(usb), (usb / "busnum").read_text().strip(),
(usb / "devnum").read_text().strip(), (interface / "ifindex").read_text().strip(),
usb.stat().st_ino, source, peer_ipv4,
]).encode()).hexdigest()
return UsbNetworkAttachment(
transport_ref="usb:" + hashlib.sha256(serial.encode()).hexdigest(),
interface=interface.name, peer_ipv4=peer_ipv4, source_ipv4=source,
generation=generation, speed=(usb / "speed").read_text().strip(),
)
+7 -1
View File
@@ -13,7 +13,7 @@ from datetime import UTC, datetime
from .trust import PairingError
ACTIONS = {"scan", "networks", "connect", "verify"}
ACTIONS = {"scan", "networks", "connect", "verify", "reset"}
def validate(value):
@@ -45,10 +45,16 @@ def validate(value):
expected = {"device_id", "discovery_generation", "mode_revision"}
if value["action"] == "connect":
expected |= {"ssid", "password"}
elif value["action"] == "reset":
expected = {"mode_revision"}
elif value["action"] in {"scan", "networks"}:
expected = set()
if not isinstance(parameters, dict) or set(parameters) != expected:
raise PairingError("Неверные параметры подключения.")
if value["action"] == "reset" and (
type(parameters["mode_revision"]) is not int or parameters["mode_revision"] < 0
):
raise PairingError("Обновите состояние подключения.")
if "device_id" in expected and (
not isinstance(parameters["device_id"], str)
or not 1 <= len(parameters["device_id"]) <= 128
+1
View File
@@ -15,6 +15,7 @@ ACTIONS = {
"details",
"rename",
"verify",
"management",
"start",
"replay",
"stop",
+242
View File
@@ -0,0 +1,242 @@
"""Adaptive disposable camera preview from the acquisition's existing MP4 lease.
The archive and RTSP producer remain owned by acquisition. Only decoded latest
frames cross the preview budget; network stalls cannot queue encoded capture.
"""
import asyncio
import io
import logging
import queue
import threading
import time
from fractions import Fraction
from uuid import uuid4
import av
from aiortc import (
RTCConfiguration,
RTCPeerConnection,
RTCRtpSender,
RTCSessionDescription,
VideoStreamTrack,
)
from aiortc.mediastreams import MediaStreamError
from missioncore_plugin_sdk.link_budget import budget_peer
from missioncore_plugin_sdk.media_budget import adapt_peer, cap_video_sender
logger = logging.getLogger(__name__)
def open_live_camera(reader):
# The MP4 initialization already declares the codec. Bound stream analysis
# so avformat does not wait for seconds of future live samples.
return av.open(reader, format="mp4", mode="r",
options={"probesize": "32", "analyzeduration": "1"})
class LeaseReader(io.RawIOBase):
def __init__(self, lease, stopped):
self.lease, self.stopped, self.pending = lease, stopped, b""
self.ended = False
def readable(self):
return True
def read(self, size=-1):
if self.ended:
return b""
if size < 0:
size = 32768
# A pipe read may be short. Waiting to fill FFmpeg's requested buffer
# holds a complete live fragment until future frames arrive.
while len(self.pending) < size and not self.stopped.is_set():
try:
segment = self.lease.segments.get(timeout=0 if self.pending else 0.25)
except queue.Empty:
if self.pending:
break
continue
if segment is None:
self.ended = True
break
self.pending += segment[1]
result, self.pending = self.pending[:size], self.pending[size:]
return result
class CameraSource:
def __init__(self, camera):
self.camera = camera
self.closed = threading.Event()
self.lock = threading.Lock()
self.frame = None
self.sequence = 0
self.observed = 0.0
self.started = time.monotonic()
self.thread = threading.Thread(target=self.pump, name="k1-camera-preview", daemon=True)
self.thread.start()
def current(self):
with self.lock:
return self.sequence, self.frame, self.observed
def pump(self):
while not self.closed.is_set():
lease = None
try:
state = self.camera.snapshot()
recording = state.get("recording") or {}
if recording.get("source_end_expected"):
break
if not (
recording.get("active")
and recording.get("producer_alive")
and recording.get("media_ready")
and recording.get("active_epoch") == state.get("generation")
):
self.closed.wait(0.25)
continue
lease = self.camera.open_delivery(state["generation"], require_recording=True)
with open_live_camera(LeaseReader(lease, self.closed)) as container:
stream = container.streams.video[0]
stream.codec_context.thread_count = 1
for packet in container.demux(stream):
if self.closed.is_set():
break
try:
frames = packet.decode()
except av.error.InvalidDataError:
continue # A late observer awaits the next capture keyframe.
for frame in frames:
now = time.monotonic()
if not (0 < frame.width <= 4096 and 0 < frame.height <= 2160):
raise ValueError("Camera preview dimensions exceed bound")
if now - self.observed < 1 / 15:
continue
width = min(1280, frame.width) // 2 * 2
height = max(2, round(frame.height * width / frame.width) // 2 * 2)
frame = frame.reformat(width=width, height=height, format="yuv420p")
frame.pts, frame.time_base = (
round((now - self.started) * 90000),
Fraction(1, 90000),
)
with self.lock:
self.sequence += 1
self.frame, self.observed = frame, now
self.camera.mark_streaming(lease)
except (OSError, ValueError, RuntimeError, IndexError) as error:
logger.debug("K1 camera observer awaiting producer (%s)", type(error).__name__)
finally:
if lease is not None:
self.camera.release_delivery(lease, client_closed=True)
self.closed.wait(0.25)
self.closed.set()
with self.lock:
self.frame = None
def close(self):
self.closed.set()
class CameraTrack(VideoStreamTrack):
def __init__(self, source, budget):
super().__init__()
self.source, self.budget, self.sequence, self.next_at = source, budget, 0, 0.0
async def recv(self):
while self.readyState == "live" and not self.source.closed.is_set():
await asyncio.sleep(max(0, self.next_at - time.monotonic()))
width, fps = self.budget.video()
sequence, frame, observed = self.source.current()
if (
fps
and frame is not None
and sequence > self.sequence
and time.monotonic() - observed < 2
):
self.sequence, self.next_at = sequence, time.monotonic() + 1 / fps
width = min(frame.width, width)
height = max(2, round(frame.height * width / frame.width) // 2 * 2)
resized = frame.reformat(width=width, height=height, format="yuv420p")
# Encoder keyframe requests must not mutate a shared source frame.
result = av.VideoFrame.from_ndarray(
resized.to_ndarray(format="yuv420p"), format="yuv420p"
)
result.pts, result.time_base = frame.pts, frame.time_base
return result
await asyncio.sleep(0.025)
raise MediaStreamError
async def camera_offer(peers, parameters):
from .node_media import admit_sdp
admit_sdp(parameters.get("sdp"), camera=True)
if sum(entry.get("media") == "camera" for entry in peers.items.values()) >= 2:
raise ValueError("Close another camera viewer")
pc = RTCPeerConnection(RTCConfiguration(iceServers=[]))
identifier = "peer_" + uuid4().hex
entry = {
"pc": pc,
"seen": time.monotonic(),
"tasks": [],
"media": "camera",
"view_id": parameters.get("view_id"),
}
peers.items[identifier] = entry
source = getattr(peers, "camera_source", None)
if source is None or source.closed.is_set():
source = peers.camera_source = CameraSource(peers.camera)
entry["source"] = source
@pc.on("datachannel")
def channel_open(channel):
if channel.label != "sensor":
channel.close()
return
@channel.on("message")
def message(value):
if value == "keepalive":
entry["seen"] = time.monotonic()
@pc.on("connectionstatechange")
async def changed():
if pc.connectionState in {"closed", "failed"}:
await peers.close(identifier)
async def watchdog():
while identifier in peers.items:
if source.closed.is_set() or time.monotonic() - entry["seen"] > 30:
await peers.close(identifier)
return
await asyncio.sleep(1)
try:
budget = await adapt_peer(pc, "video")
entry["budget"] = budget
track = CameraTrack(source, budget)
entry["track"] = track
sender = pc.addTrack(track)
cap_video_sender(sender, budget)
pc.getTransceivers()[0].setCodecPreferences(
[
codec
for codec in RTCRtpSender.getCapabilities("video").codecs
if codec.mimeType.lower() in {"video/h264", "video/rtx"}
]
)
await pc.setRemoteDescription(RTCSessionDescription(sdp=parameters["sdp"], type="offer"))
budget_peer(pc, "video", producer_id=budget.id)
await pc.setLocalDescription(await pc.createAnswer())
entry["tasks"].append(asyncio.create_task(watchdog()))
return {
"peer_id": identifier,
"sdp": pc.localDescription.sdp,
"type": "answer",
"transport": "webrtc-video",
}
except BaseException:
await peers.close(identifier)
raise