Home Assistant Unofficial Reference 2024.12.1
__init__.py
Go to the documentation of this file.
1 """Support for CM15A/CM19A X10 Controller using mochad daemon."""
2 
3 import logging
4 import threading
5 
6 from pymochad import controller, exceptions
7 import voluptuous as vol
8 
9 from homeassistant.const import (
10  CONF_HOST,
11  CONF_PORT,
12  EVENT_HOMEASSISTANT_START,
13  EVENT_HOMEASSISTANT_STOP,
14 )
15 from homeassistant.core import HomeAssistant
17 from homeassistant.helpers.typing import ConfigType
18 
19 _LOGGER = logging.getLogger(__name__)
20 
21 CONF_COMM_TYPE = "comm_type"
22 
23 DOMAIN = "mochad"
24 
25 REQ_LOCK = threading.Lock()
26 
27 CONFIG_SCHEMA = vol.Schema(
28  {
29  DOMAIN: vol.Schema(
30  {
31  vol.Optional(CONF_HOST, default="localhost"): cv.string,
32  vol.Optional(CONF_PORT, default=1099): cv.port,
33  }
34  )
35  },
36  extra=vol.ALLOW_EXTRA,
37 )
38 
39 
40 def setup(hass: HomeAssistant, config: ConfigType) -> bool:
41  """Set up the mochad component."""
42  conf = config[DOMAIN]
43  host = conf.get(CONF_HOST)
44  port = conf.get(CONF_PORT)
45 
46  try:
47  mochad_controller = MochadCtrl(host, port)
48  except exceptions.ConfigurationError:
49  _LOGGER.exception("Unexpected exception")
50  return False
51 
52  def stop_mochad(event):
53  """Stop the Mochad service."""
54  mochad_controller.disconnect()
55 
56  def start_mochad(event):
57  """Start the Mochad service."""
58  hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, stop_mochad)
59 
60  hass.bus.listen_once(EVENT_HOMEASSISTANT_START, start_mochad)
61  hass.data[DOMAIN] = mochad_controller
62 
63  return True
64 
65 
66 class MochadCtrl:
67  """Mochad controller."""
68 
69  def __init__(self, host, port):
70  """Initialize a PyMochad controller."""
71  super().__init__()
72  self._host_host = host
73  self._port_port = port
74 
75  self.ctrlctrl = controller.PyMochad(server=self._host_host, port=self._port_port)
76 
77  @property
78  def host(self):
79  """Return the server where mochad is running."""
80  return self._host_host
81 
82  @property
83  def port(self):
84  """Return the port mochad is running on."""
85  return self._port_port
86 
87  def disconnect(self):
88  """Close the connection to the mochad socket."""
89  self.ctrlctrl.socket.close()
bool setup(HomeAssistant hass, ConfigType config)
Definition: __init__.py:40