Add direct E1 material name signals
This commit is contained in:
1 parent
824b1caca7
commit
1b060377aa
6 files changed
+341
-30
No files matched your search
@@ -1,5 +1,5 @@
|
|||||||
# Supply E1's ENLYZE machine UUID before operating. Signal references are PLC
|
# Process signals use unique PLC origins. Direct material names use explicit
|
||||||
# origins, resolved uniquely by the ENLYZE gateway at poll time.
|
# ENLYZE variable UUIDs (uuid:<UUID>); null current values remain unavailable.
|
||||||
calculations:
|
calculations:
|
||||||
- id: e1-channel-material-consumption
|
- id: e1-channel-material-consumption
|
||||||
type: channel_material_consumption
|
type: channel_material_consumption
|
||||||
@@ -11,20 +11,76 @@ calculations:
|
|||||||
- id: Ex1
|
- id: Ex1
|
||||||
total_rate_signal_ref: DB107:18
|
total_rate_signal_ref: DB107:18
|
||||||
channels:
|
channels:
|
||||||
- {id: C1, status_signal_ref: DB107:122.0, percentage_signal_ref: DB107:126, screw_speed_signal_ref: DB107:170}
|
- id: C1
|
||||||
- {id: C2, status_signal_ref: DB107:222.0, percentage_signal_ref: DB107:226, screw_speed_signal_ref: DB107:270}
|
status_signal_ref: DB107:122.0
|
||||||
- {id: C3, status_signal_ref: DB107:322.0, percentage_signal_ref: DB107:326, screw_speed_signal_ref: DB107:370}
|
percentage_signal_ref: DB107:126
|
||||||
- {id: C4, status_signal_ref: DB107:422.0, percentage_signal_ref: DB107:426, screw_speed_signal_ref: DB107:470}
|
screw_speed_signal_ref: DB107:170
|
||||||
- {id: C5, status_signal_ref: DB107:522.0, percentage_signal_ref: DB107:526, screw_speed_signal_ref: DB107:570}
|
material_name_signal_ref: "uuid:d3129cf5-3b6e-486c-99e3-8ee6b6fbd7aa"
|
||||||
- {id: C6, status_signal_ref: DB107:622.0, percentage_signal_ref: DB107:626, screw_speed_signal_ref: DB107:670}
|
- id: C2
|
||||||
- {id: C7, status_signal_ref: DB107:722.0, percentage_signal_ref: DB107:726, screw_speed_signal_ref: DB107:770}
|
status_signal_ref: DB107:222.0
|
||||||
|
percentage_signal_ref: DB107:226
|
||||||
|
screw_speed_signal_ref: DB107:270
|
||||||
|
material_name_signal_ref: "uuid:b8be6b5a-0ce7-40ed-9754-107175468c8d"
|
||||||
|
- id: C3
|
||||||
|
status_signal_ref: DB107:322.0
|
||||||
|
percentage_signal_ref: DB107:326
|
||||||
|
screw_speed_signal_ref: DB107:370
|
||||||
|
material_name_signal_ref: "uuid:08e0e7e5-574a-487e-8a73-329d9cd9c2f7"
|
||||||
|
- id: C4
|
||||||
|
status_signal_ref: DB107:422.0
|
||||||
|
percentage_signal_ref: DB107:426
|
||||||
|
screw_speed_signal_ref: DB107:470
|
||||||
|
material_name_signal_ref: "uuid:de3ea4b4-9f60-4ff7-9c7f-c04a5348a8ae"
|
||||||
|
- id: C5
|
||||||
|
status_signal_ref: DB107:522.0
|
||||||
|
percentage_signal_ref: DB107:526
|
||||||
|
screw_speed_signal_ref: DB107:570
|
||||||
|
material_name_signal_ref: "uuid:fd774a7a-ff76-449a-82a6-8b7a8c9aa8af"
|
||||||
|
- id: C6
|
||||||
|
status_signal_ref: DB107:622.0
|
||||||
|
percentage_signal_ref: DB107:626
|
||||||
|
screw_speed_signal_ref: DB107:670
|
||||||
|
material_name_signal_ref: "uuid:16b8d94e-2b7f-48a4-bb46-a212554837b1"
|
||||||
|
- id: C7
|
||||||
|
status_signal_ref: DB107:722.0
|
||||||
|
percentage_signal_ref: DB107:726
|
||||||
|
screw_speed_signal_ref: DB107:770
|
||||||
|
material_name_signal_ref: "uuid:35bc651a-9e47-4a4d-bb9b-6505e08cb056"
|
||||||
- id: Ex2
|
- id: Ex2
|
||||||
total_rate_signal_ref: DB207:18
|
total_rate_signal_ref: DB207:18
|
||||||
channels:
|
channels:
|
||||||
- {id: C1, status_signal_ref: DB207:122.0, percentage_signal_ref: DB207:126, screw_speed_signal_ref: DB207:170}
|
- id: C1
|
||||||
- {id: C2, status_signal_ref: DB207:222.0, percentage_signal_ref: DB207:226, screw_speed_signal_ref: DB207:270}
|
status_signal_ref: DB207:122.0
|
||||||
- {id: C3, status_signal_ref: DB207:322.0, percentage_signal_ref: DB207:326, screw_speed_signal_ref: DB207:370}
|
percentage_signal_ref: DB207:126
|
||||||
- {id: C4, status_signal_ref: DB207:422.0, percentage_signal_ref: DB207:426, screw_speed_signal_ref: DB207:470}
|
screw_speed_signal_ref: DB207:170
|
||||||
- {id: C5, status_signal_ref: DB207:522.0, percentage_signal_ref: DB207:526, screw_speed_signal_ref: DB207:570}
|
material_name_signal_ref: "uuid:7e0b7ea0-1564-467b-aa74-d6ea48ee4a1c"
|
||||||
- {id: C6, status_signal_ref: DB207:622.0, percentage_signal_ref: DB207:626, screw_speed_signal_ref: DB207:670}
|
- id: C2
|
||||||
- {id: C7, status_signal_ref: DB207:722.0, percentage_signal_ref: DB207:726, screw_speed_signal_ref: DB207:770}
|
status_signal_ref: DB207:222.0
|
||||||
|
percentage_signal_ref: DB207:226
|
||||||
|
screw_speed_signal_ref: DB207:270
|
||||||
|
material_name_signal_ref: "uuid:25aeaf2f-cc77-4af0-8109-adf51fb86735"
|
||||||
|
- id: C3
|
||||||
|
status_signal_ref: DB207:322.0
|
||||||
|
percentage_signal_ref: DB207:326
|
||||||
|
screw_speed_signal_ref: DB207:370
|
||||||
|
material_name_signal_ref: "uuid:ed1eaa2f-31c4-4237-9b6d-8d47f74a3c83"
|
||||||
|
- id: C4
|
||||||
|
status_signal_ref: DB207:422.0
|
||||||
|
percentage_signal_ref: DB207:426
|
||||||
|
screw_speed_signal_ref: DB207:470
|
||||||
|
material_name_signal_ref: "uuid:eb6a77b6-db1a-4826-9633-9bb38fbc7720"
|
||||||
|
- id: C5
|
||||||
|
status_signal_ref: DB207:522.0
|
||||||
|
percentage_signal_ref: DB207:526
|
||||||
|
screw_speed_signal_ref: DB207:570
|
||||||
|
material_name_signal_ref: "uuid:68672e9b-aff8-47c8-980a-aa71bc6f2b2d"
|
||||||
|
- id: C6
|
||||||
|
status_signal_ref: DB207:622.0
|
||||||
|
percentage_signal_ref: DB207:626
|
||||||
|
screw_speed_signal_ref: DB207:670
|
||||||
|
material_name_signal_ref: "uuid:0955ce3e-658f-47e4-8d60-3a331ab428d1"
|
||||||
|
- id: C7
|
||||||
|
status_signal_ref: DB207:722.0
|
||||||
|
percentage_signal_ref: DB207:726
|
||||||
|
screw_speed_signal_ref: DB207:770
|
||||||
|
material_name_signal_ref: "uuid:bd833c03-3323-41f3-81cd-b624d3af555b"
|
||||||
@@ -2,6 +2,7 @@
|
|||||||
|
|
||||||
from dataclasses import dataclass
|
from dataclasses import dataclass
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
from uuid import UUID
|
||||||
|
|
||||||
import yaml
|
import yaml
|
||||||
|
|
||||||
@@ -78,6 +79,7 @@ def load_channel_material_calculation(path: str | Path) -> ChannelMaterialCalcul
|
|||||||
"percentage_signal_ref",
|
"percentage_signal_ref",
|
||||||
"screw_speed_signal_ref",
|
"screw_speed_signal_ref",
|
||||||
"material_number_signal_ref",
|
"material_number_signal_ref",
|
||||||
|
"material_name_signal_ref",
|
||||||
}
|
}
|
||||||
if (
|
if (
|
||||||
not isinstance(row, dict)
|
not isinstance(row, dict)
|
||||||
@@ -99,6 +101,20 @@ def load_channel_material_calculation(path: str | Path) -> ChannelMaterialCalcul
|
|||||||
material = row.get("material_number_signal_ref")
|
material = row.get("material_number_signal_ref")
|
||||||
if material is not None and (not isinstance(material, str) or not material.strip()):
|
if material is not None and (not isinstance(material, str) or not material.strip()):
|
||||||
raise CalculationConfigError("material signal must be a string or null")
|
raise CalculationConfigError("material signal must be a string or null")
|
||||||
|
material_name = row.get("material_name_signal_ref")
|
||||||
|
if material_name is not None:
|
||||||
|
try:
|
||||||
|
if not isinstance(material_name, str) or not material_name.startswith("uuid:"):
|
||||||
|
raise ValueError("expected uuid:<UUID>")
|
||||||
|
UUID(material_name[5:])
|
||||||
|
except ValueError as exc:
|
||||||
|
raise CalculationConfigError(
|
||||||
|
"material_name_signal_ref must be uuid:<UUID> or null"
|
||||||
|
) from exc
|
||||||
|
if material is not None and material_name is not None:
|
||||||
|
raise CalculationConfigError(
|
||||||
|
"Material number and name signals are mutually exclusive"
|
||||||
|
)
|
||||||
channels.append(
|
channels.append(
|
||||||
ChannelDefinition(
|
ChannelDefinition(
|
||||||
extruder["id"],
|
extruder["id"],
|
||||||
@@ -108,6 +124,7 @@ def load_channel_material_calculation(path: str | Path) -> ChannelMaterialCalcul
|
|||||||
row["percentage_signal_ref"],
|
row["percentage_signal_ref"],
|
||||||
row["screw_speed_signal_ref"],
|
row["screw_speed_signal_ref"],
|
||||||
material,
|
material,
|
||||||
|
material_name,
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
if len({(c.extruder, c.channel) for c in channels}) != len(channels):
|
if len({(c.extruder, c.channel) for c in channels}) != len(channels):
|
||||||
|
|||||||
@@ -21,6 +21,7 @@ class DosingChannelSample:
|
|||||||
dosing_percentage: float
|
dosing_percentage: float
|
||||||
screw_speed: float
|
screw_speed: float
|
||||||
material_number: str | None = None
|
material_number: str | None = None
|
||||||
|
material_name: str | None = None
|
||||||
|
|
||||||
|
|
||||||
@dataclass(frozen=True, slots=True)
|
@dataclass(frozen=True, slots=True)
|
||||||
@@ -55,9 +56,10 @@ def channel_rates(
|
|||||||
) -> tuple[ChannelRate, ...]:
|
) -> tuple[ChannelRate, ...]:
|
||||||
"""Derive rates and conservative material identity for one aligned timestamp.
|
"""Derive rates and conservative material identity for one aligned timestamp.
|
||||||
|
|
||||||
A material value which occurs on more than one channel is deliberately not
|
A material number which occurs on more than one channel is deliberately not
|
||||||
attributed to either channel: PLC assignments are not reliable enough to
|
attributed to either channel: PLC assignments are not reliable enough to
|
||||||
resolve that ambiguity from a previous sample.
|
resolve that ambiguity from a previous sample. Direct per-channel names are
|
||||||
|
already assigned and may be shared by multiple channels.
|
||||||
"""
|
"""
|
||||||
values = tuple(samples)
|
values = tuple(samples)
|
||||||
validate_active_percentage_sum(values, tolerance=percentage_tolerance)
|
validate_active_percentage_sum(values, tolerance=percentage_tolerance)
|
||||||
@@ -71,7 +73,9 @@ def channel_rates(
|
|||||||
for value in values:
|
for value in values:
|
||||||
if not isfinite(value.total_rate_kg_per_hour) or not isfinite(value.screw_speed):
|
if not isfinite(value.total_rate_kg_per_hour) or not isfinite(value.screw_speed):
|
||||||
raise ValueError("total rate and screw speed must be finite")
|
raise ValueError("total rate and screw speed must be finite")
|
||||||
if value.material_number is None:
|
if value.material_name is not None and value.material_name.strip():
|
||||||
|
number, name, status = None, value.material_name, MATERIAL_ASSIGNED
|
||||||
|
elif value.material_number is None:
|
||||||
number, name, status = None, None, MATERIAL_UNAVAILABLE
|
number, name, status = None, None, MATERIAL_UNAVAILABLE
|
||||||
elif counts[value.material_number] > 1:
|
elif counts[value.material_number] > 1:
|
||||||
number, name, status = None, None, MATERIAL_AMBIGUOUS
|
number, name, status = None, None, MATERIAL_AMBIGUOUS
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ from dataclasses import dataclass
|
|||||||
from datetime import UTC, datetime
|
from datetime import UTC, datetime
|
||||||
from math import isfinite
|
from math import isfinite
|
||||||
from typing import TYPE_CHECKING
|
from typing import TYPE_CHECKING
|
||||||
|
from uuid import UUID
|
||||||
|
|
||||||
from production_analytics.calculations.channel_material import DosingChannelSample
|
from production_analytics.calculations.channel_material import DosingChannelSample
|
||||||
from production_analytics.calculations.material_consumption import (
|
from production_analytics.calculations.material_consumption import (
|
||||||
@@ -308,8 +309,8 @@ class EnlyzeApiGateway:
|
|||||||
) -> dict[str, list[DosingChannelSample]]:
|
) -> dict[str, list[DosingChannelSample]]:
|
||||||
"""Read configured dosing channels through the gateway only.
|
"""Read configured dosing channels through the gateway only.
|
||||||
|
|
||||||
Configurations name stable PLC origins; ENLYZE UUIDs are resolved at poll
|
Process and material-number refs name stable PLC origins resolved uniquely
|
||||||
time and must be unique, preventing a silently stale variable mapping.
|
at poll time. Direct material-name refs explicitly name machine variable UUIDs.
|
||||||
"""
|
"""
|
||||||
if (
|
if (
|
||||||
start.tzinfo is None
|
start.tzinfo is None
|
||||||
@@ -355,9 +356,17 @@ class EnlyzeApiGateway:
|
|||||||
if not isinstance(row, list) or len(row) != len(columns):
|
if not isinstance(row, list) or len(row) != len(columns):
|
||||||
raise ValueError("record must match columns")
|
raise ValueError("record must match columns")
|
||||||
timestamp = _parse_timestamp(row[columns.index("time")])
|
timestamp = _parse_timestamp(row[columns.index("time")])
|
||||||
for key, (total, status, percentage, screw, material) in resolved.items():
|
for key, (total, status, percentage, screw, material, name) in resolved.items():
|
||||||
sample = self._dosing_sample(
|
sample = self._dosing_sample(
|
||||||
row, columns, timestamp, total, status, percentage, screw, material
|
row,
|
||||||
|
columns,
|
||||||
|
timestamp,
|
||||||
|
total,
|
||||||
|
status,
|
||||||
|
percentage,
|
||||||
|
screw,
|
||||||
|
material,
|
||||||
|
name,
|
||||||
)
|
)
|
||||||
if sample is not None:
|
if sample is not None:
|
||||||
result[key].append(sample)
|
result[key].append(sample)
|
||||||
@@ -376,10 +385,11 @@ class EnlyzeApiGateway:
|
|||||||
*,
|
*,
|
||||||
machine_id: str,
|
machine_id: str,
|
||||||
channels: tuple["ChannelDefinition", ...],
|
channels: tuple["ChannelDefinition", ...],
|
||||||
) -> dict[str, tuple[str, str, str, str, str | None]]:
|
) -> dict[str, tuple[str, str, str, str, str | None, str | None]]:
|
||||||
"""Resolve configured PLC origins without reading samples or writing state."""
|
"""Resolve unique PLC origins and explicit machine variable UUID references."""
|
||||||
origins = self._variables_by_origin(machine_id)
|
variable_ids: set[str] = set()
|
||||||
resolved: dict[str, tuple[str, str, str, str, str | None]] = {}
|
origins = self._variables_by_origin(machine_id, variable_ids=variable_ids)
|
||||||
|
resolved: dict[str, tuple[str, str, str, str, str | None, str | None]] = {}
|
||||||
for channel in channels:
|
for channel in channels:
|
||||||
refs = (
|
refs = (
|
||||||
channel.total_rate_signal_ref,
|
channel.total_rate_signal_ref,
|
||||||
@@ -394,7 +404,17 @@ class EnlyzeApiGateway:
|
|||||||
else None
|
else None
|
||||||
)
|
)
|
||||||
key = channel.channel + "\0" + channel.extruder
|
key = channel.channel + "\0" + channel.extruder
|
||||||
resolved[key] = (*ids, material)
|
name = None
|
||||||
|
if channel.material_name_signal_ref is not None:
|
||||||
|
if material is not None:
|
||||||
|
raise ValueError("Material number and name signals are mutually exclusive")
|
||||||
|
ref = channel.material_name_signal_ref
|
||||||
|
if not ref.startswith("uuid:"):
|
||||||
|
raise ValueError("material_name_signal_ref must be uuid:<UUID>")
|
||||||
|
name = str(UUID(ref[5:]))
|
||||||
|
if name not in variable_ids:
|
||||||
|
raise ValueError(f"Configured material-name UUID {name!r} is unavailable")
|
||||||
|
resolved[key] = (*ids, material, name)
|
||||||
return resolved
|
return resolved
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
@@ -407,6 +427,7 @@ class EnlyzeApiGateway:
|
|||||||
percentage: str,
|
percentage: str,
|
||||||
screw: str,
|
screw: str,
|
||||||
material: str | None,
|
material: str | None,
|
||||||
|
name: str | None = None,
|
||||||
) -> DosingChannelSample | None:
|
) -> DosingChannelSample | None:
|
||||||
def numeric(variable: str) -> float:
|
def numeric(variable: str) -> float:
|
||||||
value = row[columns.index(variable)]
|
value = row[columns.index(variable)]
|
||||||
@@ -438,6 +459,9 @@ class EnlyzeApiGateway:
|
|||||||
material_value = None if material is None else row[columns.index(material)]
|
material_value = None if material is None else row[columns.index(material)]
|
||||||
if material_value is not None and not isinstance(material_value, (str, int, float)):
|
if material_value is not None and not isinstance(material_value, (str, int, float)):
|
||||||
raise ValueError("material assignment must be scalar or null")
|
raise ValueError("material assignment must be scalar or null")
|
||||||
|
name_value = None if name is None else row[columns.index(name)]
|
||||||
|
if name_value is not None and not isinstance(name_value, str):
|
||||||
|
raise ValueError("material name must be a string or null")
|
||||||
return DosingChannelSample(
|
return DosingChannelSample(
|
||||||
timestamp,
|
timestamp,
|
||||||
numeric(total),
|
numeric(total),
|
||||||
@@ -445,9 +469,12 @@ class EnlyzeApiGateway:
|
|||||||
numeric(percentage),
|
numeric(percentage),
|
||||||
numeric(screw),
|
numeric(screw),
|
||||||
None if material_value is None else str(material_value),
|
None if material_value is None else str(material_value),
|
||||||
|
name_value if name_value is not None and name_value.strip() else None,
|
||||||
)
|
)
|
||||||
|
|
||||||
def _variables_by_origin(self, machine_id: str) -> dict[str, list[str]]:
|
def _variables_by_origin(
|
||||||
|
self, machine_id: str, *, variable_ids: set[str] | None = None
|
||||||
|
) -> dict[str, list[str]]:
|
||||||
params = {"machine": machine_id}
|
params = {"machine": machine_id}
|
||||||
result: dict[str, list[str]] = {}
|
result: dict[str, list[str]] = {}
|
||||||
cursors: set[str] = set()
|
cursors: set[str] = set()
|
||||||
@@ -461,6 +488,10 @@ class EnlyzeApiGateway:
|
|||||||
uuid = item["uuid"]
|
uuid = item["uuid"]
|
||||||
if not isinstance(uuid, str):
|
if not isinstance(uuid, str):
|
||||||
raise ValueError("variable uuid must be a string")
|
raise ValueError("variable uuid must be a string")
|
||||||
|
if variable_ids is not None:
|
||||||
|
if uuid in variable_ids:
|
||||||
|
raise ValueError("variable UUID must be unique")
|
||||||
|
variable_ids.add(uuid)
|
||||||
details = item.get("details")
|
details = item.get("details")
|
||||||
if not isinstance(details, dict):
|
if not isinstance(details, dict):
|
||||||
raise ValueError("variable details must be an object")
|
raise ValueError("variable details must be an object")
|
||||||
|
|||||||
@@ -28,6 +28,7 @@ class ChannelDefinition:
|
|||||||
percentage_signal_ref: str
|
percentage_signal_ref: str
|
||||||
screw_speed_signal_ref: str
|
screw_speed_signal_ref: str
|
||||||
material_number_signal_ref: str | None = None
|
material_number_signal_ref: str | None = None
|
||||||
|
material_name_signal_ref: str | None = None
|
||||||
|
|
||||||
|
|
||||||
@dataclass(frozen=True, slots=True)
|
@dataclass(frozen=True, slots=True)
|
||||||
|
|||||||
@@ -54,6 +54,10 @@ def test_e1_config_dry_run_resolves_every_signal_through_gateway_without_samplin
|
|||||||
}
|
}
|
||||||
for index, origin in enumerate(sorted(origins))
|
for index, origin in enumerate(sorted(origins))
|
||||||
]
|
]
|
||||||
|
+ [
|
||||||
|
{"uuid": channel.material_name_signal_ref[5:], "details": {"origin_identifier": None}}
|
||||||
|
for channel in config.channels
|
||||||
|
]
|
||||||
}
|
}
|
||||||
|
|
||||||
resolved = EnlyzeApiGateway(client).resolve_dosing_channel_signal_refs(
|
resolved = EnlyzeApiGateway(client).resolve_dosing_channel_signal_refs(
|
||||||
@@ -65,7 +69,13 @@ def test_e1_config_dry_run_resolves_every_signal_through_gateway_without_samplin
|
|||||||
assert len(config.channels) == 14
|
assert len(config.channels) == 14
|
||||||
assert len(origins) == 44
|
assert len(origins) == 44
|
||||||
assert len(resolved) == 14
|
assert len(resolved) == 14
|
||||||
assert all(len(refs) == 5 and refs[-1] is None for refs in resolved.values())
|
for channel in config.channels:
|
||||||
|
refs = resolved[channel.channel + "\0" + channel.extruder]
|
||||||
|
assert len(refs) == 6 and refs[-2] is None
|
||||||
|
assert refs[-1] == channel.material_name_signal_ref[5:]
|
||||||
|
assert config.channels[1].material_name_signal_ref == (
|
||||||
|
"uuid:b8be6b5a-0ce7-40ed-9754-107175468c8d"
|
||||||
|
)
|
||||||
client.get.assert_called_once_with("/v2/variables", {"machine": config.machine_ref})
|
client.get.assert_called_once_with("/v2/variables", {"machine": config.machine_ref})
|
||||||
client.post_json.assert_not_called()
|
client.post_json.assert_not_called()
|
||||||
|
|
||||||
@@ -156,3 +166,195 @@ def test_bootstrap_replays_closed_runs_without_integrating_the_inter_run_gap(tmp
|
|||||||
).poll_once(now=NOW + timedelta(seconds=30))
|
).poll_once(now=NOW + timedelta(seconds=30))
|
||||||
assert result is not None
|
assert result is not None
|
||||||
assert result[0].state.cumulative_consumption_kg == pytest.approx(20 / 30)
|
assert result[0].state.cumulative_consumption_kg == pytest.approx(20 / 30)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("name", ["TR 131", None, "", " "])
|
||||||
|
def test_direct_name_samples_and_assignment(name):
|
||||||
|
columns = ["rate", "on", "pct", "rpm", "name"]
|
||||||
|
value = EnlyzeApiGateway._dosing_sample(
|
||||||
|
[120, True, 100, 10, name], columns, NOW, "rate", "on", "pct", "rpm", None, "name"
|
||||||
|
)
|
||||||
|
assert value is not None
|
||||||
|
expected = name if name and name.strip() else None
|
||||||
|
assert value.material_name == expected
|
||||||
|
assert value.material_number is None
|
||||||
|
rate = channel_rates((value,), material_names={"123": "Other"})[0]
|
||||||
|
assert rate.material_name == expected
|
||||||
|
assert rate.material_number is None
|
||||||
|
assert rate.material_mapping_status == ("ASSIGNED" if expected else "UNAVAILABLE")
|
||||||
|
|
||||||
|
|
||||||
|
def test_duplicate_direct_names_remain_assigned():
|
||||||
|
value = DosingChannelSample(NOW, 120, True, 50, 10, material_name="TR 131")
|
||||||
|
assert all(rate.material_mapping_status == "ASSIGNED" for rate in channel_rates((value, value)))
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("value", [123, True, [], {}])
|
||||||
|
def test_direct_name_rejects_non_string(value):
|
||||||
|
with pytest.raises(ValueError, match="material name must be a string or null"):
|
||||||
|
EnlyzeApiGateway._dosing_sample(
|
||||||
|
[120, True, 100, 10, value],
|
||||||
|
["rate", "on", "pct", "rpm", "name"],
|
||||||
|
NOW,
|
||||||
|
"rate",
|
||||||
|
"on",
|
||||||
|
"pct",
|
||||||
|
"rpm",
|
||||||
|
None,
|
||||||
|
"name",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_numeric_material_mapping_is_unchanged():
|
||||||
|
value = EnlyzeApiGateway._dosing_sample(
|
||||||
|
[120, True, 100, 10, 123],
|
||||||
|
["rate", "on", "pct", "rpm", "number"],
|
||||||
|
NOW,
|
||||||
|
"rate",
|
||||||
|
"on",
|
||||||
|
"pct",
|
||||||
|
"rpm",
|
||||||
|
"number",
|
||||||
|
)
|
||||||
|
assert value.material_number == "123"
|
||||||
|
mapped = channel_rates((value,), material_names={"123": "Mapped"})[0]
|
||||||
|
assert (mapped.material_number, mapped.material_name, mapped.material_mapping_status) == (
|
||||||
|
"123",
|
||||||
|
"Mapped",
|
||||||
|
"ASSIGNED",
|
||||||
|
)
|
||||||
|
assert channel_rates((value,), material_names={"456": "Other"})[0].material_mapping_status == (
|
||||||
|
"UNMAPPED"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("ref", ["exa_c1_material", "uuid:bad", "", 123])
|
||||||
|
def test_config_rejects_invalid_direct_name_ref(tmp_path, ref):
|
||||||
|
import yaml
|
||||||
|
|
||||||
|
from production_analytics.calculations.config import CalculationConfigError
|
||||||
|
|
||||||
|
document = yaml.safe_load(E1_CONFIG.read_text())
|
||||||
|
document["calculations"][0]["extruders"][0]["channels"][0]["material_name_signal_ref"] = ref
|
||||||
|
path = tmp_path / "config.yaml"
|
||||||
|
path.write_text(yaml.safe_dump(document))
|
||||||
|
with pytest.raises(CalculationConfigError, match="material_name_signal_ref"):
|
||||||
|
load_channel_material_calculation(path)
|
||||||
|
|
||||||
|
|
||||||
|
def test_config_preserves_number_mode_and_rejects_both_modes(tmp_path):
|
||||||
|
import yaml
|
||||||
|
|
||||||
|
from production_analytics.calculations.config import CalculationConfigError
|
||||||
|
|
||||||
|
document = yaml.safe_load(E1_CONFIG.read_text())
|
||||||
|
row = document["calculations"][0]["extruders"][0]["channels"][0]
|
||||||
|
row["material_number_signal_ref"] = "DB107:100"
|
||||||
|
path = tmp_path / "config.yaml"
|
||||||
|
path.write_text(yaml.safe_dump(document))
|
||||||
|
with pytest.raises(CalculationConfigError, match="mutually exclusive"):
|
||||||
|
load_channel_material_calculation(path)
|
||||||
|
del row["material_name_signal_ref"]
|
||||||
|
path.write_text(yaml.safe_dump(document))
|
||||||
|
channel = load_channel_material_calculation(path).channels[0]
|
||||||
|
assert channel.material_number_signal_ref == "DB107:100"
|
||||||
|
assert channel.material_name_signal_ref is None
|
||||||
|
|
||||||
|
|
||||||
|
def dosing_client(*, include_name=True):
|
||||||
|
name_id = "b8be6b5a-0ce7-40ed-9754-107175468c8d"
|
||||||
|
client = Mock()
|
||||||
|
client.get.return_value.body = {
|
||||||
|
"data": [
|
||||||
|
{"uuid": ref, "details": {"origin_identifier": {"code": ref}}}
|
||||||
|
for ref in ("rate", "on", "pct", "rpm", "number")
|
||||||
|
]
|
||||||
|
+ ([{"uuid": name_id, "details": {"origin_identifier": None}}] if include_name else [])
|
||||||
|
}
|
||||||
|
return client, name_id
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("problem", ["missing_name", "missing_origin", "duplicate_origin"])
|
||||||
|
def test_resolver_preserves_availability_and_origin_uniqueness(problem):
|
||||||
|
client, name_id = dosing_client(include_name=problem != "missing_name")
|
||||||
|
items = client.get.return_value.body["data"]
|
||||||
|
if problem == "missing_origin":
|
||||||
|
items.pop(0)
|
||||||
|
elif problem == "duplicate_origin":
|
||||||
|
items.append({"uuid": "duplicate", "details": {"origin_identifier": {"code": "rate"}}})
|
||||||
|
channel = ChannelDefinition(
|
||||||
|
"Ex1", "C2", "rate", "on", "pct", "rpm", material_name_signal_ref=f"uuid:{name_id}"
|
||||||
|
)
|
||||||
|
with pytest.raises(ValueError, match="unavailable|ambiguous"):
|
||||||
|
EnlyzeApiGateway(client).resolve_dosing_channel_signal_refs(
|
||||||
|
machine_id="m", channels=(channel,)
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_number_signal_still_resolves_by_origin():
|
||||||
|
client, _ = dosing_client()
|
||||||
|
channel = ChannelDefinition("Ex1", "C1", "rate", "on", "pct", "rpm", "number")
|
||||||
|
refs = EnlyzeApiGateway(client).resolve_dosing_channel_signal_refs(
|
||||||
|
machine_id="m", channels=(channel,)
|
||||||
|
)
|
||||||
|
assert refs["C1\0Ex1"] == ("rate", "on", "pct", "rpm", "number", None)
|
||||||
|
|
||||||
|
|
||||||
|
def test_direct_name_changes_and_null_reach_postgres_without_carry_forward(tmp_path):
|
||||||
|
import io
|
||||||
|
from unittest.mock import patch
|
||||||
|
|
||||||
|
from production_analytics.service.channel_material_runner import ChannelMaterialPollingRunner
|
||||||
|
from production_analytics.service.postgres_channel_material import (
|
||||||
|
PostgresChannelMaterialSnapshotWriter,
|
||||||
|
)
|
||||||
|
from production_analytics.service.postgres_material import PostgresSettings
|
||||||
|
|
||||||
|
client, name_id = dosing_client()
|
||||||
|
gateway = EnlyzeApiGateway(client)
|
||||||
|
gateway.get_open_production_run = Mock(
|
||||||
|
return_value=EnlyzeProductionRun("run", "m", None, "order", NOW, None)
|
||||||
|
)
|
||||||
|
gateway.get_production_runs = Mock(return_value=[])
|
||||||
|
channel = ChannelDefinition(
|
||||||
|
"Ex1", "C2", "rate", "on", "pct", "rpm", material_name_signal_ref=f"uuid:{name_id}"
|
||||||
|
)
|
||||||
|
service = ChannelMaterialPollingService(
|
||||||
|
gateway=gateway,
|
||||||
|
state_store=JsonChannelMaterialStateStore(tmp_path),
|
||||||
|
machine_id="m",
|
||||||
|
channels=(channel,),
|
||||||
|
max_sample_gap_seconds=20,
|
||||||
|
)
|
||||||
|
writer = PostgresChannelMaterialSnapshotWriter(
|
||||||
|
PostgresSettings("localhost", 5432, "db", "user", "pw")
|
||||||
|
)
|
||||||
|
runner = ChannelMaterialPollingRunner(
|
||||||
|
service,
|
||||||
|
machine_id="m",
|
||||||
|
calculation_id="calc",
|
||||||
|
snapshot_writer=writer,
|
||||||
|
poll_interval_seconds=10,
|
||||||
|
stdout=io.StringIO(),
|
||||||
|
clock=lambda: NOW,
|
||||||
|
)
|
||||||
|
with patch("psycopg.connect") as connect:
|
||||||
|
connection = connect.return_value.__enter__.return_value
|
||||||
|
for index, name in enumerate(("TR 131", "New material", None)):
|
||||||
|
timestamp = NOW + timedelta(seconds=index * 10)
|
||||||
|
client.post_json.return_value.body = {
|
||||||
|
"data": {
|
||||||
|
"columns": ["time", "rate", "on", "pct", "rpm", name_id],
|
||||||
|
"records": [[timestamp.isoformat(), 120, True, 100, 10, name]],
|
||||||
|
}
|
||||||
|
}
|
||||||
|
runner.clock = lambda: timestamp
|
||||||
|
assert runner.run_once()
|
||||||
|
parameters = connection.execute.call_args.args[1]
|
||||||
|
assert parameters[8:11] == (None, name, "ASSIGNED" if name else "UNAVAILABLE")
|
||||||
|
assert parameters[7] == pytest.approx(index / 3)
|
||||||
|
request = client.post_json.call_args.args
|
||||||
|
assert request[0] == "/v2/timeseries"
|
||||||
|
assert request[1]["variables"] == [
|
||||||
|
{"uuid": ref} for ref in ("rate", "on", "pct", "rpm", name_id)
|
||||||
|
]
|
||||||
Reference in new issue
Block a user