Home Assistant Unofficial Reference 2024.12.1
switch.py
Go to the documentation of this file.
1 """Support for X10 switch over Mochad."""
2 
3 from __future__ import annotations
4 
5 import logging
6 from typing import Any
7 
8 from pymochad import controller, device
9 from pymochad.exceptions import MochadException
10 import voluptuous as vol
11 
12 from homeassistant.components.switch import SwitchEntity
13 from homeassistant.const import CONF_ADDRESS, CONF_DEVICES, CONF_NAME, CONF_PLATFORM
14 from homeassistant.core import HomeAssistant
15 from homeassistant.helpers import config_validation as cv
16 from homeassistant.helpers.entity_platform import AddEntitiesCallback
17 from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType
18 
19 from . import CONF_COMM_TYPE, DOMAIN, REQ_LOCK, MochadCtrl
20 
21 _LOGGER = logging.getLogger(__name__)
22 
23 
24 PLATFORM_SCHEMA = vol.Schema(
25  {
26  vol.Required(CONF_PLATFORM): DOMAIN,
27  CONF_DEVICES: [
28  {
29  vol.Optional(CONF_NAME): cv.string,
30  vol.Required(CONF_ADDRESS): cv.x10_address,
31  vol.Optional(CONF_COMM_TYPE): cv.string,
32  }
33  ],
34  }
35 )
36 
37 
39  hass: HomeAssistant,
40  config: ConfigType,
41  add_entities: AddEntitiesCallback,
42  discovery_info: DiscoveryInfoType | None = None,
43 ) -> None:
44  """Set up X10 switches over a mochad controller."""
45  mochad_controller: MochadCtrl = hass.data[DOMAIN]
46  devs: list[dict[str, str]] = config[CONF_DEVICES]
47  add_entities([MochadSwitch(hass, mochad_controller.ctrl, dev) for dev in devs])
48 
49 
51  """Representation of a X10 switch over Mochad."""
52 
53  def __init__(
54  self, hass: HomeAssistant, ctrl: controller.PyMochad, dev: dict[str, str]
55  ) -> None:
56  """Initialize a Mochad Switch Device."""
57 
58  self._controller_controller = ctrl
59  self._address: str = dev[CONF_ADDRESS]
60  self._attr_name: str = dev.get(CONF_NAME, f"x10_switch_dev_{self._address}")
61  self._comm_type_comm_type: str = dev.get(CONF_COMM_TYPE, "pl")
62  self.switchswitch = device.Device(ctrl, self._address, comm_type=self._comm_type_comm_type)
63  # Init with false to avoid locking HA for long on CM19A (goes from rf
64  # to pl via TM751, but not other way around)
65  if self._comm_type_comm_type == "pl":
66  self._attr_is_on_attr_is_on = self._get_device_status_get_device_status()
67  else:
68  self._attr_is_on_attr_is_on = False
69 
70  def turn_on(self, **kwargs: Any) -> None:
71  """Turn the switch on."""
72 
73  _LOGGER.debug("Reconnect %s:%s", self._controller_controller.server, self._controller_controller.port)
74  with REQ_LOCK:
75  try:
76  # Recycle socket on new command to recover mochad connection
77  self._controller_controller.reconnect()
78  self.switchswitch.send_cmd("on")
79  # No read data on CM19A which is rf only
80  if self._comm_type_comm_type == "pl":
81  self._controller_controller.read_data()
82  self._attr_is_on_attr_is_on = True
83  except (MochadException, OSError) as exc:
84  _LOGGER.error("Error with mochad communication: %s", exc)
85 
86  def turn_off(self, **kwargs: Any) -> None:
87  """Turn the switch off."""
88 
89  _LOGGER.debug("Reconnect %s:%s", self._controller_controller.server, self._controller_controller.port)
90  with REQ_LOCK:
91  try:
92  # Recycle socket on new command to recover mochad connection
93  self._controller_controller.reconnect()
94  self.switchswitch.send_cmd("off")
95  # No read data on CM19A which is rf only
96  if self._comm_type_comm_type == "pl":
97  self._controller_controller.read_data()
98  self._attr_is_on_attr_is_on = False
99  except (MochadException, OSError) as exc:
100  _LOGGER.error("Error with mochad communication: %s", exc)
101 
102  def _get_device_status(self) -> bool:
103  """Get the status of the switch from mochad."""
104  with REQ_LOCK:
105  status = self.switchswitch.get_status().rstrip()
106  return status == "on"
None __init__(self, HomeAssistant hass, controller.PyMochad ctrl, dict[str, str] dev)
Definition: switch.py:55
None add_entities(AsusWrtRouter router, AddEntitiesCallback async_add_entities, set[str] tracked)
def get_status(hass, host, port)
Definition: panel.py:387
None setup_platform(HomeAssistant hass, ConfigType config, AddEntitiesCallback add_entities, DiscoveryInfoType|None discovery_info=None)
Definition: switch.py:43