deb04c9315
Sprint 0 completo del producto VMS-Sailor (Vessel Management System integrado para buques 30-40m). Brief de referencia en VMS_Sailor_v2_Parte_*.md (intacto). Core (vmssailor.core, 95.17% coverage, 99 tests verde): - ShipCoord: sistema naval x_pp/y_cl/z_bl frozen - Vessel, Deck, Bulkhead - Equipment, EquipmentModel, Sensor, EquipmentSpec - Tag, AlarmConfig, TagBinding, Scaling - CardInstance, Bus, Topology con validacion 21 puntos I/O AR-NMEA-IO-v1.0 - Alarm, PermissiveRule, Condition - Project agregado raiz con validacion cross-entity - Persistencia portable .vmsproj (SQLite) con roundtrip verificable Biblioteca curada seed (vmssailor.library): - systems_catalog.json completo (catalogo maestro Parte 1 sec 7) - 2 vessels: Sunseeker 76, Ferretti 850 - 2 motores: MTU 12V 2000 M96, Volvo D13-900 - 1 genset: Northern Lights M65C13 - yacht_motor_planeo.yaml (reglas heuristicas) - TODO marcado data_source=seed_estimate - requiere validacion datasheets Tools: - vms-validate-library: CLI valida biblioteca completa - vms-generate-test-project: CLI demo + verificacion roundtrip persistencia Design System + 8 mockups HTML estaticos: - docs/design_system.md (paleta Deep Ocean, gradientes, typography, motion) - docs/brand/ (logo + variantes SVG) - docs/mockups/splash, studio_main, runtime_overview, runtime_mimic_fuel (P&ID animado), runtime_alarms, runtime_trim (panel estrella con horizonte artificial), mobile_overview, mobile_trim - docs/mockups/index.html (galeria) Firmware (Sprint 12+ implementacion): - firmware/ar_nmea_io_v1/src/config/pinout.h con macros GPIO Decisiones autonomas documentadas en docs/decisions_sprint0.md. Stack: Python 3.11 + uv + Pydantic v2 + SQLite stdlib + hatchling + pytest 9 + ruff + mypy. Sin PySide6, FastAPI, Flutter ni firmware funcional (entran en sprints siguientes). Criterio de aceptacion Sprint 0: cumplido. - uv sync: OK - pytest: 99/99 verde - cov vmssailor.core: 95.17% (objetivo >=80%) - ruff: clean - vms-validate-library: OK - vms-generate-test-project: INTEGRIDAD OK Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
106 lines
3.6 KiB
Python
106 lines
3.6 KiB
Python
"""Permissive Engine — pre-condiciones declarativas para acciones de control.
|
|
|
|
Cada acción de control crítica (arrancar motor, abrir válvula de mar, etc.)
|
|
debe pasar TODAS sus pre-condiciones antes de ejecutarse. Las pre-condiciones
|
|
se evalúan en el **servidor** del Runtime, no en la UI — única fuente de
|
|
verdad (Parte 1 sec 9).
|
|
|
|
Estados posibles de cada permissive:
|
|
|
|
- **OK**: condición cumplida.
|
|
- **FAIL**: condición no cumplida, BLOQUEA acción.
|
|
- **WARNING**: el sensor que debería verificar la condición no existe o está
|
|
en estado inválido. Requiere override consciente del Admin del buque.
|
|
- **N/A**: la pre-condición no aplica a este buque.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
from typing import Literal
|
|
|
|
from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
|
|
|
|
OperatorStr = Literal["==", "!=", ">", "<", ">=", "<=", "between", "is_true", "is_false"]
|
|
|
|
|
|
class Condition(BaseModel):
|
|
"""Una pre-condición evaluable contra el valor de un tag."""
|
|
|
|
model_config = ConfigDict(extra="forbid")
|
|
|
|
tag_ref: str = Field(
|
|
...,
|
|
min_length=1,
|
|
max_length=128,
|
|
description="Tag.id a evaluar.",
|
|
)
|
|
operator: OperatorStr = Field(
|
|
...,
|
|
description="Operador de comparación. 'between' usa threshold_low + threshold_high.",
|
|
)
|
|
threshold: float | None = Field(
|
|
default=None,
|
|
description="Para operadores escalares (==, !=, >, <, >=, <=).",
|
|
)
|
|
threshold_low: float | None = Field(
|
|
default=None, description="Para 'between' (límite inferior)."
|
|
)
|
|
threshold_high: float | None = Field(
|
|
default=None, description="Para 'between' (límite superior)."
|
|
)
|
|
severity: Literal["fail", "warning"] = Field(
|
|
default="fail",
|
|
description=(
|
|
"'fail' bloquea la acción. 'warning' permite pero exige override "
|
|
"consciente del Admin del buque."
|
|
),
|
|
)
|
|
message_on_fail: str = Field(
|
|
default="", max_length=512, description="Mensaje al operador si falla."
|
|
)
|
|
|
|
@model_validator(mode="after")
|
|
def _between_requires_both(self) -> Condition:
|
|
if self.operator == "between" and (
|
|
self.threshold_low is None or self.threshold_high is None
|
|
):
|
|
raise ValueError(
|
|
"Operator 'between' requiere threshold_low y threshold_high."
|
|
)
|
|
if self.operator in ("==", "!=", ">", "<", ">=", "<=") and self.threshold is None:
|
|
raise ValueError(
|
|
f"Operator '{self.operator}' requiere threshold."
|
|
)
|
|
return self
|
|
|
|
|
|
class PermissiveRule(BaseModel):
|
|
"""Conjunto de pre-condiciones que rigen una acción de control."""
|
|
|
|
model_config = ConfigDict(extra="forbid")
|
|
|
|
id: str = Field(..., min_length=1, max_length=128)
|
|
action_id: str = Field(
|
|
...,
|
|
min_length=1,
|
|
max_length=128,
|
|
description="ID de la acción que protege, ej: 'START_ME_PORT'.",
|
|
)
|
|
description: str = Field(default="", max_length=512)
|
|
conditions: list[Condition] = Field(default_factory=list)
|
|
on_fail_message: str = Field(
|
|
default="",
|
|
max_length=512,
|
|
description="Mensaje agregado al operador cuando el conjunto falla.",
|
|
)
|
|
|
|
@field_validator("conditions")
|
|
@classmethod
|
|
def _at_least_one_condition(cls, v: list[Condition]) -> list[Condition]:
|
|
if not v:
|
|
raise ValueError(
|
|
"PermissiveRule requiere al menos 1 condition (use lista vacía solo si "
|
|
"la acción no tiene permissives, en cuyo caso no debería existir esta regla)."
|
|
)
|
|
return v
|