Newer
Older
smart-home-server / tools / virtual_devices / device / relay.py
from __future__ import annotations

from typing import Any, Dict

from device.base import BaseDevice
from state import save


class RelayDevice(BaseDevice):
    def __init__(self, state):
        super().__init__(state)
        self._ensure_channels(self._channel_count())

    def _channel_count(self) -> int:
        # Default to 4 if not specified, but schema implies 8 max
        # We use active channels based on schema or default to 4
        return 4

    def status(self) -> Dict[str, Any]:
        return {"channels": self.state.channels}

    def action(self, action_name: str, params: Dict[str, Any]) -> Dict[str, Any]:
        if action_name == "set_state":
            channel = params.get("channel", 0)
            new_state = params.get("state", "off")
            if channel < 0 or channel >= len(self.state.channels):
                return {
                    "status": "error",
                    "error": "IllegalActionOrParams",
                    "message": "Invalid channel index",
                }
            if new_state not in ("on", "off"):
                return {
                    "status": "error",
                    "error": "IllegalActionOrParams",
                    "message": "State must be 'on' or 'off'",
                }
            self.state.channels[channel]["state"] = new_state
            save(self.state)
            return {"status": "ok", "message": "State changed"}

        return {
            "status": "error",
            "error": "IllegalActionOrParams",
            "message": "Device does not support this action or params",
        }