diff --git a/CHANGELOG.md b/CHANGELOG.md index 2f8a11f..c5bcaaf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,22 @@ adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ## [Unreleased] +## [0.8.0] - 2026-10-21 + +### Added +- **Chamber conditions on weigh-ins.** A weigh-in can carry the chamber + temperature (°C) and relative humidity (%) observed when it was taken, for + chambers with no sensor where the values are read off a thermo-hygrometer by + hand: new optional `temperature` / `humidity` fields on the `record_weight` + action and the `weigh_in` websocket command, two inputs in the panel's + weigh-in form, two columns in the history table and in the CSV export. On a + weigh-in taken now with the fields left blank, the current (filtered) + sensor readings are snapshotted instead, so a batch keeps the context of + its drying curve long after the recorder has purged the history; a + backdated weigh-in is never filled from live sensors. These values are + context only and never feed the regulation. Stored batches and + `export_batch` / `import_batch` payloads without the fields load unchanged. + ## [0.7.1] - 2026-10-21 ### Security @@ -248,7 +264,8 @@ adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). - FR/EN translations, HACS metadata, and CI (ruff, mypy, pytest+coverage, hassfest, HACS validation) on Python 3.13. -[Unreleased]: https://github.com/ttiot/curingChamber/compare/v0.7.1...HEAD +[Unreleased]: https://github.com/ttiot/curingChamber/compare/v0.8.0...HEAD +[0.8.0]: https://github.com/ttiot/curingChamber/compare/v0.7.1...v0.8.0 [0.7.1]: https://github.com/ttiot/curingChamber/compare/v0.7.0...v0.7.1 [0.7.0]: https://github.com/ttiot/curingChamber/compare/v0.6.0...v0.7.0 [0.6.0]: https://github.com/ttiot/curingChamber/compare/v0.5.0...v0.6.0 diff --git a/README.md b/README.md index f565e4c..50014be 100644 --- a/README.md +++ b/README.md @@ -304,9 +304,19 @@ the same as **Export** / **Import** buttons working on `.json` files. A **batch** is one product curing in the chamber, with its own reference weight, target weight loss and a **history of weigh-ins**. Weigh-ins can come from a -scale or be entered by hand — **no scale required** — optionally with a note and -a photo. From the weigh-in history the integration derives each batch's current -weight loss, drying rate and a **predicted completion date (ETA)**. +scale or be entered by hand — **no scale required** — optionally with a note, a +photo and the **chamber conditions** (temperature and humidity) at that moment. +From the weigh-in history the integration derives each batch's current weight +loss, drying rate and a **predicted completion date (ETA)**. + +**Conditions without sensors.** A chamber with no temperature / humidity sensor +(a passive cellar, a fridge with a dial thermo-hygrometer) can still keep track +of its conditions: type them in with each weigh-in (`temperature` in °C, +`humidity` in %). With sensors, leaving the fields blank on a weigh-in taken +now records the current readings, so the drying curve keeps its context well +after the recorder's retention has expired. A backdated weigh-in is never filled +from live sensors. These values are context for the batch only — they never +drive the regulation. **ETA model.** With two weigh-ins the ETA is a straight-line extrapolation of the drying rate. From three weigh-ins on, an exponential drying model @@ -366,6 +376,8 @@ data: batch_id: coppa_1 weight: 1080 note: "day 12" + temperature: 12.5 # optional, °C — read off a thermo-hygrometer + humidity: 80 # optional, % RH — omitted: current sensor values photo: "/config/www/photos/coppa_day12.jpg" # data: URL, base64 or a local file ``` diff --git a/custom_components/curing_chamber/batch/types.py b/custom_components/curing_chamber/batch/types.py index 51a29b0..01b0ef7 100644 --- a/custom_components/curing_chamber/batch/types.py +++ b/custom_components/curing_chamber/batch/types.py @@ -23,12 +23,20 @@ class BatchStatus(StrEnum): @dataclass(frozen=True) class WeightSample: - """A single weigh-in: a weight at a point in time, plus optional context.""" + """A single weigh-in: a weight at a point in time, plus optional context. + + ``temperature`` (°C) and ``humidity`` (% RH) are the chamber conditions + observed at the weigh-in: read off a thermo-hygrometer by hand when the + chamber has no sensor, or snapshotted from the sensors otherwise. They are + context for the drying curve only and never feed the regulation. + """ timestamp: float weight: float note: str | None = None photo_url: str | None = None + temperature: float | None = None + humidity: float | None = None def to_dict(self) -> dict[str, object]: return { @@ -36,6 +44,8 @@ def to_dict(self) -> dict[str, object]: "weight": self.weight, "note": self.note, "photo_url": self.photo_url, + "temperature": self.temperature, + "humidity": self.humidity, } @classmethod @@ -45,6 +55,8 @@ def from_dict(cls, data: dict[str, object]) -> WeightSample: weight=float(_req_float(data.get("weight"))), note=_opt_str(data.get("note")), photo_url=_opt_str(data.get("photo_url")), + temperature=_opt_float(data.get("temperature")), + humidity=_opt_float(data.get("humidity")), ) diff --git a/custom_components/curing_chamber/coordinator.py b/custom_components/curing_chamber/coordinator.py index ffb5198..6882ff0 100644 --- a/custom_components/curing_chamber/coordinator.py +++ b/custom_components/curing_chamber/coordinator.py @@ -1188,14 +1188,38 @@ async def async_record_weight( timestamp: float | None = None, note: str | None = None, photo: str | None = None, + temperature: float | None = None, + humidity: float | None = None, ) -> None: - """Append a weigh-in (with optional note/photo) to a batch.""" + """Append a weigh-in (with optional note/photo/conditions) to a batch. + + ``temperature`` / ``humidity`` are the chamber conditions at the + weigh-in. When they are not given and the weigh-in is taken now, the + current (filtered) sensor readings are snapshotted instead, so the + drying curve keeps its context long after the recorder has purged the + history. A backdated weigh-in is never filled from live sensors. + """ batch = self.batches.get(batch_id) if batch is None: raise ValueError(f"Unknown batch '{batch_id}'") ts = timestamp if timestamp is not None else dt_util.utcnow().timestamp() + if timestamp is None: + data = self.data or {} + if temperature is None: + temperature = data.get("temp") + if humidity is None: + humidity = data.get("humidity") photo_url = await self._save_photo(batch_id, ts, photo) if photo else None - batch.add_sample(WeightSample(timestamp=ts, weight=weight, note=note, photo_url=photo_url)) + batch.add_sample( + WeightSample( + timestamp=ts, + weight=weight, + note=note, + photo_url=photo_url, + temperature=temperature, + humidity=humidity, + ) + ) self._last_weight = None self._persist_batches() await self.async_refresh() diff --git a/custom_components/curing_chamber/frontend/curing-chamber-panel.js b/custom_components/curing_chamber/frontend/curing-chamber-panel.js index 4dfce5a..54aecf4 100644 --- a/custom_components/curing_chamber/frontend/curing-chamber-panel.js +++ b/custom_components/curing_chamber/frontend/curing-chamber-panel.js @@ -154,6 +154,7 @@ const STR = { record: "Record", recorded: "Weigh-in recorded.", enter_weight: "Enter a weight.", + conditions_hint: "Chamber conditions at the weigh-in. Left blank, the current sensor readings are recorded.", make_reference: "Make reference", complete: "Complete", archive: "Archive", @@ -359,6 +360,7 @@ const STR = { record: "Enregistrer", recorded: "Pesée enregistrée.", enter_weight: "Saisissez un poids.", + conditions_hint: "Conditions de la cave au moment de la pesée. Laissées vides, les valeurs des capteurs sont enregistrées.", make_reference: "Définir référence", complete: "Terminer", archive: "Archiver", @@ -1853,11 +1855,13 @@ class CuringChamberPanel extends HTMLElement { if (!samples.length) histCard.appendChild(h("div", { class: "muted small" }, "—")); else { histCard.appendChild(h("div", { class: "table-wrap" }, h("table", null, [ - h("thead", null, h("tr", null, [h("th", null, t("date")), h("th", null, t("weight")), h("th", null, t("loss")), h("th", null, t("note")), h("th", null, t("photo")), h("th")])), + h("thead", null, h("tr", null, [h("th", null, t("date")), h("th", null, t("weight")), h("th", null, t("loss")), h("th", null, "T°"), h("th", null, "RH"), h("th", null, t("note")), h("th", null, t("photo")), h("th")])), h("tbody", null, samples.map((x) => h("tr", null, [ h("td", null, fmtDateTime(x.timestamp, this._locale)), h("td", null, fmtNum(x.weight, 0)), h("td", null, ref ? fmtNum(((ref - x.weight) / ref) * 100, 1, " %") : "—"), + h("td", { class: "muted" }, x.temperature != null ? fmtNum(x.temperature, 1, " °C") : ""), + h("td", { class: "muted" }, x.humidity != null ? fmtNum(x.humidity, 0, " %") : ""), h("td", { class: "muted" }, x.note || ""), h("td", null, x.photo_url ? this._photoImg(x.photo_url, "thumb") : ""), h("td", null, h("button", { class: "ghost sm", title: t("delete"), onclick: async () => { @@ -1962,14 +1966,14 @@ class CuringChamberPanel extends HTMLElement { if (format === "json") { downloadJson(`${base}.json`, data); return; } const batch = data.batch || {}; const ref = data.summary && data.summary.reference_weight; - const rows = [["timestamp", "type", "kind", "weight", "loss_pct", "note", "photo_url"]]; + const rows = [["timestamp", "type", "kind", "weight", "loss_pct", "temperature", "humidity", "note", "photo_url"]]; const iso = (ts) => new Date(ts * 1000).toISOString(); const lines = []; for (const x of batch.samples || []) { - lines.push({ ts: x.timestamp, row: [iso(x.timestamp), "weigh_in", "", x.weight, ref ? (((ref - x.weight) / ref) * 100).toFixed(2) : "", x.note || "", x.photo_url || ""] }); + lines.push({ ts: x.timestamp, row: [iso(x.timestamp), "weigh_in", "", x.weight, ref ? (((ref - x.weight) / ref) * 100).toFixed(2) : "", x.temperature ?? "", x.humidity ?? "", x.note || "", x.photo_url || ""] }); } for (const e of batch.events || []) { - lines.push({ ts: e.timestamp, row: [iso(e.timestamp), "event", e.kind, "", "", e.note || "", ""] }); + lines.push({ ts: e.timestamp, row: [iso(e.timestamp), "event", e.kind, "", "", "", "", e.note || "", ""] }); } lines.sort((a, c) => a.ts - c.ts); for (const l of lines) rows.push(l.row); @@ -1988,6 +1992,8 @@ class CuringChamberPanel extends HTMLElement { _weighInForm(b) { const t = (k) => this._t(k); const weight = h("input", { type: "number", step: "0.1", min: "0", inputmode: "decimal" }); + const temperature = h("input", { type: "number", step: "0.1", inputmode: "decimal", placeholder: "°C", style: "width:80px", title: t("conditions_hint") }); + const humidity = h("input", { type: "number", step: "1", min: "0", max: "100", inputmode: "numeric", placeholder: "%", style: "width:80px", title: t("conditions_hint") }); const note = h("input", { type: "text", placeholder: t("note_placeholder") }); const photo = h("input", { type: "file", accept: "image/*", capture: "environment" }); const nowBox = h("input", { type: "checkbox", checked: true }); @@ -2000,6 +2006,10 @@ class CuringChamberPanel extends HTMLElement { if (Number.isNaN(w)) { status.textContent = t("enter_weight"); weight.focus(); return; } const params = { batch_id: b.id, weight: w }; if (note.value.trim()) params.note = note.value.trim(); + const tv = parseFloat(temperature.value); + if (!Number.isNaN(tv)) params.temperature = tv; + const hv = parseFloat(humidity.value); + if (!Number.isNaN(hv)) params.humidity = hv; if (!nowBox.checked) { const ts = fromLocalInputValue(when.value); if (ts != null) params.timestamp = ts; @@ -2024,6 +2034,8 @@ class CuringChamberPanel extends HTMLElement { h("h2", null, t("record_weigh_in")), h("div", { class: "form" }, [ h("label", null, [t("weight"), weight]), + h("label", null, [t("temperature"), temperature]), + h("label", null, [t("humidity"), humidity]), h("label", { style: "flex:1;min-width:160px" }, [t("note"), note]), h("label", null, [t("photo"), photo]), h("label", { class: "inline" }, [nowBox, t("now")]), diff --git a/custom_components/curing_chamber/manifest.json b/custom_components/curing_chamber/manifest.json index 31974e3..723ac84 100644 --- a/custom_components/curing_chamber/manifest.json +++ b/custom_components/curing_chamber/manifest.json @@ -16,5 +16,5 @@ "iot_class": "calculated", "issue_tracker": "https://github.com/ttiot/curingchamber/issues", "requirements": [], - "version": "0.7.1" + "version": "0.8.0" } diff --git a/custom_components/curing_chamber/services.py b/custom_components/curing_chamber/services.py index aa1a34c..279674c 100644 --- a/custom_components/curing_chamber/services.py +++ b/custom_components/curing_chamber/services.py @@ -144,6 +144,8 @@ vol.Optional(_ATTR_TIMESTAMP): cv.datetime, vol.Optional(_ATTR_NOTE): cv.string, vol.Optional(_ATTR_PHOTO): cv.string, + vol.Optional(_ATTR_TEMPERATURE): vol.Coerce(float), + vol.Optional(_ATTR_HUMIDITY): vol.All(vol.Coerce(float), vol.Range(min=0, max=100)), } ) _BATCH_ID_SCHEMA = vol.Schema({**_TARGET, vol.Required(_ATTR_BATCH_ID): cv.string}) @@ -381,6 +383,8 @@ async def record_weight(call: ServiceCall) -> None: timestamp=timestamp, note=call.data.get(_ATTR_NOTE), photo=photo, + temperature=call.data.get(_ATTR_TEMPERATURE), + humidity=call.data.get(_ATTR_HUMIDITY), ) except ValueError as err: raise HomeAssistantError(str(err)) from err diff --git a/custom_components/curing_chamber/services.yaml b/custom_components/curing_chamber/services.yaml index d858592..8c3331b 100644 --- a/custom_components/curing_chamber/services.yaml +++ b/custom_components/curing_chamber/services.yaml @@ -355,7 +355,8 @@ record_weight: name: Record weigh-in description: >- Add a weigh-in to a batch (works without a scale). Optionally attach a - timestamp, a note and a photo. + timestamp, a note, a photo and the chamber conditions (temperature and + humidity) read at the weigh-in. fields: device_id: name: Chamber @@ -398,6 +399,30 @@ record_weight: users at /api/curing_chamber/photo/... selector: text: + temperature: + name: Temperature + description: >- + Chamber temperature at the weigh-in (°C), for chambers without a + sensor. Omitted on a weigh-in taken now, the current sensor reading is + recorded instead when one is available. + selector: + number: + min: -10 + max: 40 + step: 0.1 + unit_of_measurement: "°C" + humidity: + name: Humidity + description: >- + Chamber relative humidity at the weigh-in (%), for chambers without a + sensor. Omitted on a weigh-in taken now, the current sensor reading is + recorded instead when one is available. + selector: + number: + min: 0 + max: 100 + step: 1 + unit_of_measurement: "%" set_reference_batch: name: Set reference batch diff --git a/custom_components/curing_chamber/websocket.py b/custom_components/curing_chamber/websocket.py index d18296a..1722cd0 100644 --- a/custom_components/curing_chamber/websocket.py +++ b/custom_components/curing_chamber/websocket.py @@ -334,6 +334,10 @@ async def ws_batch_delete( vol.Optional("note"): vol.Any(None, str), # Inline data only (data URL / base64); a file path is never read here. vol.Optional("photo"): vol.Any(None, str), + vol.Optional("temperature"): vol.Any(None, vol.Coerce(float)), + vol.Optional("humidity"): vol.Any( + None, vol.All(vol.Coerce(float), vol.Range(min=0, max=100)) + ), } ) @websocket_api.async_response @@ -349,6 +353,8 @@ async def ws_weigh_in( timestamp=msg.get("timestamp"), note=msg.get("note") or None, photo=msg.get("photo") or None, + temperature=msg.get("temperature"), + humidity=msg.get("humidity"), ) except ValueError as err: connection.send_error(msg["id"], websocket_api.ERR_NOT_FOUND, str(err)) diff --git a/pyproject.toml b/pyproject.toml index 2d98f53..bc96024 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "curing_chamber" -version = "0.7.1" +version = "0.8.0" description = "Home Assistant custom integration to drive a charcuterie curing chamber." readme = "README.md" requires-python = ">=3.11" diff --git a/tests/batch/test_restore.py b/tests/batch/test_restore.py index eb93d86..42d1f1b 100644 --- a/tests/batch/test_restore.py +++ b/tests/batch/test_restore.py @@ -20,16 +20,29 @@ def test_roundtrip_preserves_batch() -> None: ) photo = "/local/curing_chamber/c/1.jpg" b.add_sample(WeightSample(timestamp=0.0, weight=1200.0, note="start")) - b.add_sample(WeightSample(timestamp=DAY, weight=1150.0, photo_url=photo)) + b.add_sample( + WeightSample(timestamp=DAY, weight=1150.0, photo_url=photo, temperature=12.5, humidity=78.0) + ) restored = Batch.from_dict(b.to_dict()) assert restored == b assert restored.status is BatchStatus.ACTIVE assert restored.samples[1].photo_url == photo + assert restored.samples[1].temperature == 12.5 + assert restored.samples[1].humidity == 78.0 assert restored.latest_weight == 1150.0 +def test_from_dict_without_conditions_is_backward_compatible() -> None: + """Stores written before weigh-in conditions existed still load.""" + sample = WeightSample.from_dict({"timestamp": 0.0, "weight": 1000.0, "note": None}) + assert sample.temperature is None + assert sample.humidity is None + junk = WeightSample.from_dict({"timestamp": 0.0, "weight": 1.0, "humidity": "x"}) + assert junk.humidity is None + + def test_from_dict_sorts_samples_by_time() -> None: data = { "id": "b", diff --git a/tests/ha/test_services.py b/tests/ha/test_services.py index 92c0b54..1a1c85e 100644 --- a/tests/ha/test_services.py +++ b/tests/ha/test_services.py @@ -117,6 +117,29 @@ async def test_create_batch_and_record_weight( assert summary["last_weight"] == 900.0 +async def test_record_weight_conditions(hass: HomeAssistant, config_entry, seed_states) -> None: + """Explicit conditions win; omitted ones on a weigh-in taken now come from the sensors.""" + coordinator = await _setup(hass, config_entry, seed_states) + await _create_batch(hass) + batch_id = next(iter(coordinator.batches)) + + await hass.services.async_call( + DOMAIN, + SERVICE_RECORD_WEIGHT, + {"batch_id": batch_id, "weight": 950.0, "temperature": 11.5, "humidity": 82}, + blocking=True, + ) + await hass.services.async_call( + DOMAIN, SERVICE_RECORD_WEIGHT, {"batch_id": batch_id, "weight": 940.0}, blocking=True + ) + await hass.async_block_till_done() + + manual, auto = coordinator.batches[batch_id].samples + assert (manual.temperature, manual.humidity) == (11.5, 82.0) + # seed_states seeds 13.0 °C / 75 % on the chamber sensors. + assert (auto.temperature, auto.humidity) == (13.0, 75.0) + + async def test_record_weight_with_photo(hass: HomeAssistant, config_entry, seed_states) -> None: coordinator = await _setup(hass, config_entry, seed_states) await _create_batch(hass) diff --git a/tests/ha/test_websocket.py b/tests/ha/test_websocket.py index d1562b0..900d156 100644 --- a/tests/ha/test_websocket.py +++ b/tests/ha/test_websocket.py @@ -115,6 +115,49 @@ async def test_subscribe_pushes_live_state( assert "samples" not in pushed[-1]["batches"][0] +async def test_weigh_in_conditions( + hass: HomeAssistant, config_entry, seed_states, hass_ws_client +) -> None: + await _setup(hass, config_entry, seed_states) + client = await hass_ws_client(hass) + entry_id = config_entry.entry_id + batch = await _create_batch(client, entry_id) + + # Backdated weigh-in: nothing is guessed from the live sensors. + msg = await _call( + client, "weigh_in", entry_id=entry_id, batch_id=batch["id"], weight=990.0, timestamp=1.0 + ) + assert msg["success"], msg + assert msg["result"]["samples"][0]["temperature"] is None + assert msg["result"]["samples"][0]["humidity"] is None + + # Hand-entered conditions are kept as given. + msg = await _call( + client, + "weigh_in", + entry_id=entry_id, + batch_id=batch["id"], + weight=980.0, + temperature=10.2, + humidity=88, + ) + assert msg["success"], msg + assert msg["result"]["samples"][1]["temperature"] == 10.2 + assert msg["result"]["samples"][1]["humidity"] == 88.0 + + # Taken now with nothing given: snapshot of the chamber sensors. + msg = await _call(client, "weigh_in", entry_id=entry_id, batch_id=batch["id"], weight=970.0) + assert msg["success"], msg + assert msg["result"]["samples"][2]["temperature"] == 13.0 + assert msg["result"]["samples"][2]["humidity"] == 75.0 + + # Out-of-range humidity is rejected by the schema. + msg = await _call( + client, "weigh_in", entry_id=entry_id, batch_id=batch["id"], weight=960.0, humidity=140 + ) + assert not msg["success"] + + async def test_subscribe_chambers_pushes_on_load_and_unload( hass: HomeAssistant, config_entry, seed_states, hass_ws_client ) -> None: