Add direct E1 material name signals

This commit is contained in:
admin committed 2026-10-07 19:08:39 +02:00
1 parent 824b1caca7
commit 1b060377aa
6 files changed
+341 -30

No files matched your search

+203 -1
View File
@@ -54,6 +54,10 @@ def test_e1_config_dry_run_resolves_every_signal_through_gateway_without_samplin
}
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(
@@ -65,7 +69,13 @@ def test_e1_config_dry_run_resolves_every_signal_through_gateway_without_samplin
assert len(config.channels) == 14
assert len(origins) == 44
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.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))
assert result is not None
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)
]