Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
61 changes: 61 additions & 0 deletions docs/2026-11-21-oops-clear-power-on-analysis.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
# Machines powering on after an Oops is cleared: analysis (issue #201)

## Report

On 2026-10-08 staff told members that "once an Oops is cleared, any machine
that wasn't properly shut down will turn back on by itself", after a couple of
close calls. The intended behavior is that clearing an Oops never energizes a
machine; the relay closes only on an authorized RFID insert after the clear.

## Findings

**Server: no path closes the relay on an Oops clear for a normal machine.**
`MachineState.unoops()` sets `relay_desired_state = False` unless the machine is
`always_enabled`. A card left in the reader across the Oops and the clear does
not log in again, because `update()` only runs the login path when
`rfid_value` changes. This holds across a server restart (state reloaded from
the pickle cache) and across an MCU reboot. Regression tests now pin all of
these: `tests/views/test_oops_clear_safety.py`.

**Server: two `_handle_reboot()` defects, both fixed.**

1. An `always_enabled` machine that was Oopsed or locked out had its relay
turned back **on** by an MCU reboot, because `_handle_reboot()` restored the
always-on state without checking `is_oopsed` / `is_locked_out`. No machine
in the production `machines.json` sets `always_enabled`, so this could not
explain the reports, but it was a real energize-while-Oopsed path.
2. A reboot of an Oopsed or locked-out machine reset the display and status
LED to the idle defaults, so the reader stopped showing the Oops / lock-out
message (seen on Resaw on 2026-11-18). The relay stayed off.

`_handle_reboot()` now keeps the relay off and the Oops / lock-out display for
an Oopsed or locked-out machine, and restores always-on only otherwise.

**Firmware: relay follows the server only.** In
`esphome-configs/2025.11.2/no-current-input.yaml` the relay switch has no
`restore_mode`, so it uses the ESPHome default (`ALWAYS_OFF`) at boot, and
`relay_output.turn_on()` is called only when a 2xx response from
`/api/machine/update` carries `"relay": true`. A failed or non-2xx POST leaves
the relay as it was and never turns it on.

**Override sessions.** An `oops_override` user who badges in on an Oopsed
machine gets the relay, by design. If the Oops is cleared during that session,
the session continues until the card is removed; it does not start a new one.

## Most likely cause

The machine's own switch. MAC cuts power with its relay but cannot move the
machine's ON/OFF switch. If a machine is Oopsed (or the card is pulled) with
its switch left ON, the next authorized login closes the relay and the motor
starts at once. To the person badging in, it "turned on by itself" after the
clear. That is a hardware gap, not a server bug.

## Open items (need staff / hardware work)

- Ask staff which machines had the close calls, when, and whether a card was
in the reader at the moment the machine started.
- Correlate with the `OOPS` and `AUTH` logs in Loki: an `un-Oopsed` line
followed by a relay-on with **no** `RFID login` / `session start` between
them would contradict the analysis above. Older logs may have aged out.
- List the machines that lack no-volt-release (magnetic) switches and decide
on NVR switches, a switch-position interlock, or a documented procedure.
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ requires = [

[tool.poetry]
name = "machine_access_control"
version = "0.15.1"
version = "0.15.2"
description = "Decatur Makers Machine Access Control package"
license = "MIT"
authors = [ "Jason Antman <jason@jasonantman.com>" ]
Expand Down
21 changes: 18 additions & 3 deletions src/dm_mac/models/machine.py
Original file line number Diff line number Diff line change
Expand Up @@ -823,7 +823,9 @@ async def _handle_reboot(self) -> None:
"""Handle when the ESP32 (MCU) has rebooted since last checkin.

This logs out the current user if logged in and resets the machine state.
For always-enabled machines, restores the always-on state.
An Oopsed or locked-out machine keeps its relay off and its Oops /
lock-out display; otherwise, always-enabled machines restore the
always-on state.
"""
logging.getLogger("AUTH").warning(
"Machine %s rebooted; resetting relay and RFID state",
Expand All @@ -837,8 +839,21 @@ async def _handle_reboot(self) -> None:
prior_user: Optional[User] = self.current_user
self.current_user = None
self.is_override_login = False
# Restore always-enabled state if applicable
if self.machine.always_enabled:
# An Oops or lock-out survives a reboot: keep the relay off and keep
# showing the Oops / lock-out display. Only a machine that is neither
# Oopsed nor locked out may restore its always-enabled state; doing
# so while Oopsed or locked out would energize the relay.
if self.is_oopsed:
self.relay_desired_state = False
self.display_text = self.OOPS_DISPLAY_TEXT
self.status_led_rgb = (1.0, 0.0, 0.0)
self.status_led_brightness = self.STATUS_LED_BRIGHTNESS
elif self.is_locked_out:
self.relay_desired_state = False
self.display_text = self.LOCKOUT_DISPLAY_TEXT
self.status_led_rgb = (1.0, 0.5, 0.0)
self.status_led_brightness = self.STATUS_LED_BRIGHTNESS
elif self.machine.always_enabled:
self.relay_desired_state = True
self.display_text = self.ALWAYS_ON_DISPLAY_TEXT
self.status_led_rgb = (0.0, 1.0, 0.0)
Expand Down
229 changes: 229 additions & 0 deletions tests/views/test_oops_clear_safety.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,229 @@
"""Safety regression tests: clearing an Oops must never energize a machine.

See issue #201. After an Oops is cleared, the relay may only close on a fresh
authorized RFID insert. A card left in the reader across the Oops, the clear,
a server restart or an MCU reboot must not re-energize the machine.
"""

from pathlib import Path
from typing import Any
from typing import Dict

from freezegun import freeze_time
from quart import Quart
from quart.typing import TestClientProtocol

from dm_mac.models.machine import MachineState

from .quart_test_helpers import app_and_client

#: Strict machine (no warn-only, not always-enabled).
MNAME: str = "metal-mill"
#: Fob of a user authorized for metal-mill; no oops_override.
FOB: str = "8114346998"


async def mcu_update(
client: TestClientProtocol,
mname: str = MNAME,
rfid_value: str = FOB,
uptime: float = 100.0,
oops: bool = False,
) -> Dict[str, Any]:
"""POST an MCU update and return the JSON response."""
response = await client.post(
"/api/machine/update",
json={
"machine_name": mname,
"oops": oops,
"rfid_value": rfid_value,
"uptime": uptime,
"wifi_signal_db": -54,
"wifi_signal_percent": 92,
"internal_temperature_c": 53.89,
},
)
assert response.status_code == 200
result: Dict[str, Any] = await response.json
return result


async def oops_and_clear(
client: TestClientProtocol,
mname: str = MNAME,
uptime: float = 101.0,
rfid_value: str = FOB,
) -> None:
"""Oops via the MCU button with the card present, then clear it via API."""
resp = await mcu_update(
client, mname=mname, rfid_value=rfid_value, uptime=uptime, oops=True
)
assert resp["relay"] is False
assert resp["display"] == MachineState.OOPS_DISPLAY_TEXT
response = await client.delete(f"/api/machine/oops/{mname}")
assert response.status_code == 200


async def login(client: TestClientProtocol) -> None:
"""Establish a baseline with no card, then log in (relay on)."""
resp = await mcu_update(client, rfid_value="", uptime=99.0)
assert resp["relay"] is False
resp = await mcu_update(client, uptime=100.0)
assert resp["relay"] is True


@freeze_time("2023-07-16 03:14:08", tz_offset=0)
class TestOopsClearWithCardPresent:
"""Card stays in the reader through Oops and clear."""

async def test_same_card_after_clear(self, tmp_path: Path) -> None:
"""Relay stays off on heartbeats after clear; fresh insert turns it on."""
app: Quart
client: TestClientProtocol
app, client = app_and_client(tmp_path)
await login(client)
await oops_and_clear(client)
for uptime in (102.0, 103.0, 104.0):
resp = await mcu_update(client, uptime=uptime)
assert resp["relay"] is False
assert resp["display"] == MachineState.DEFAULT_DISPLAY_TEXT
state = app.config["MACHINES"].machines_by_name[MNAME].state
assert state.relay_desired_state is False
assert state.current_user is None
# positive control: remove and re-insert the card -> login
resp = await mcu_update(client, rfid_value="", uptime=105.0)
assert resp["relay"] is False
resp = await mcu_update(client, uptime=106.0)
assert resp["relay"] is True

async def test_same_card_after_clear_and_server_restart(
self, tmp_path: Path
) -> None:
"""Relay stays off after clear across a server restart (cache reload)."""
client: TestClientProtocol
_, client = app_and_client(tmp_path)
await login(client)
await oops_and_clear(client)
# new app instance loads state from the same on-disk cache
app2: Quart
client2: TestClientProtocol
app2, client2 = app_and_client(tmp_path)
state = app2.config["MACHINES"].machines_by_name[MNAME].state
assert state.is_oopsed is False
assert state.relay_desired_state is False
for uptime in (102.0, 103.0):
resp = await mcu_update(client2, uptime=uptime)
assert resp["relay"] is False

async def test_server_restart_while_oopsed_then_clear(self, tmp_path: Path) -> None:
"""Restart while Oopsed, clear on the new instance, card still present."""
client: TestClientProtocol
_, client = app_and_client(tmp_path)
await login(client)
resp = await mcu_update(client, uptime=101.0, oops=True)
assert resp["relay"] is False
client2: TestClientProtocol
_, client2 = app_and_client(tmp_path)
resp = await mcu_update(client2, uptime=102.0)
assert resp["relay"] is False
assert resp["display"] == MachineState.OOPS_DISPLAY_TEXT
response = await client2.delete(f"/api/machine/oops/{MNAME}")
assert response.status_code == 200
resp = await mcu_update(client2, uptime=103.0)
assert resp["relay"] is False

async def test_same_card_after_clear_and_mcu_reboot(self, tmp_path: Path) -> None:
"""Relay stays off when the MCU reboots after clear with card present."""
client: TestClientProtocol
_, client = app_and_client(tmp_path)
await login(client)
await oops_and_clear(client)
# lower uptime = MCU reboot
resp = await mcu_update(client, uptime=2.0)
assert resp["relay"] is False
resp = await mcu_update(client, uptime=7.0)
assert resp["relay"] is False

async def test_mcu_reboot_while_oopsed_then_clear(self, tmp_path: Path) -> None:
"""MCU reboots while Oopsed with card present; clear; relay stays off."""
client: TestClientProtocol
_, client = app_and_client(tmp_path)
await login(client)
resp = await mcu_update(client, uptime=101.0, oops=True)
assert resp["relay"] is False
resp = await mcu_update(client, uptime=2.0)
assert resp["relay"] is False
response = await client.delete(f"/api/machine/oops/{MNAME}")
assert response.status_code == 200
resp = await mcu_update(client, uptime=7.0)
assert resp["relay"] is False


@freeze_time("2023-07-16 03:14:08", tz_offset=0)
class TestRebootKeepsOopsAndLockout:
"""An MCU reboot must not drop the Oops / lock-out display or state."""

@staticmethod
async def _reboot(
client: TestClientProtocol, mname: str, rfid_value: str = ""
) -> Dict[str, Any]:
await mcu_update(client, mname=mname, rfid_value=rfid_value, uptime=100.0)
return await mcu_update(client, mname=mname, rfid_value=rfid_value, uptime=1.0)

async def test_reboot_while_oopsed(self, tmp_path: Path) -> None:
"""Reboot of an Oopsed machine keeps the Oops display."""
app: Quart
client: TestClientProtocol
app, client = app_and_client(tmp_path)
app.config["MACHINES"].machines_by_name[MNAME].state.oops()
resp = await self._reboot(client, MNAME)
assert resp == {
"relay": False,
"display": MachineState.OOPS_DISPLAY_TEXT,
"oops_led": True,
"status_led_rgb": [1.0, 0.0, 0.0],
"status_led_brightness": MachineState.STATUS_LED_BRIGHTNESS,
"second_relay": False,
}

async def test_reboot_while_locked_out(self, tmp_path: Path) -> None:
"""Reboot of a locked-out machine keeps the lock-out display."""
app: Quart
client: TestClientProtocol
app, client = app_and_client(tmp_path)
app.config["MACHINES"].machines_by_name[MNAME].state.lockout()
resp = await self._reboot(client, MNAME)
assert resp["relay"] is False
assert resp["display"] == MachineState.LOCKOUT_DISPLAY_TEXT
assert resp["status_led_rgb"] == [1.0, 0.5, 0.0]

async def test_always_enabled_reboot_while_oopsed(self, tmp_path: Path) -> None:
"""Always-enabled machine must not energize on reboot while Oopsed."""
mname: str = "always-on-machine"
app: Quart
client: TestClientProtocol
app, client = app_and_client(tmp_path)
resp = await mcu_update(client, mname=mname, rfid_value="", uptime=100.0)
assert resp["relay"] is True
resp = await mcu_update(
client, mname=mname, rfid_value="", uptime=101.0, oops=True
)
assert resp["relay"] is False
resp = await mcu_update(client, mname=mname, rfid_value="", uptime=1.0)
assert resp["relay"] is False
assert resp["display"] == MachineState.OOPS_DISPLAY_TEXT
resp = await mcu_update(client, mname=mname, rfid_value="", uptime=6.0)
assert resp["relay"] is False
state = app.config["MACHINES"].machines_by_name[mname].state
assert state.relay_desired_state is False

async def test_always_enabled_reboot_while_locked_out(self, tmp_path: Path) -> None:
"""Always-enabled machine must not energize on reboot while locked out."""
mname: str = "always-on-machine"
app: Quart
client: TestClientProtocol
app, client = app_and_client(tmp_path)
app.config["MACHINES"].machines_by_name[mname].state.lockout()
resp = await self._reboot(client, mname)
assert resp["relay"] is False
assert resp["display"] == MachineState.LOCKOUT_DISPLAY_TEXT
Loading