Home Assistant Unofficial Reference 2024.12.1
switch.py
Go to the documentation of this file.
1 """Support for customised Kankun SP3 Wifi switch."""
2 
3 from __future__ import annotations
4 
5 import logging
6 from typing import Any
7 
8 import requests
9 import voluptuous as vol
10 
12  PLATFORM_SCHEMA as SWITCH_PLATFORM_SCHEMA,
13  SwitchEntity,
14 )
15 from homeassistant.const import (
16  CONF_HOST,
17  CONF_NAME,
18  CONF_PASSWORD,
19  CONF_PATH,
20  CONF_PORT,
21  CONF_SWITCHES,
22  CONF_USERNAME,
23 )
24 from homeassistant.core import HomeAssistant
26 from homeassistant.helpers.entity_platform import AddEntitiesCallback
27 from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType
28 
29 _LOGGER = logging.getLogger(__name__)
30 
31 DEFAULT_PORT = 80
32 DEFAULT_PATH = "/cgi-bin/json.cgi"
33 
34 SWITCH_SCHEMA = vol.Schema(
35  {
36  vol.Required(CONF_HOST): cv.string,
37  vol.Optional(CONF_NAME): cv.string,
38  vol.Optional(CONF_PORT, default=DEFAULT_PORT): cv.port,
39  vol.Optional(CONF_PATH, default=DEFAULT_PATH): cv.string,
40  vol.Optional(CONF_USERNAME): cv.string,
41  vol.Optional(CONF_PASSWORD): cv.string,
42  }
43 )
44 
45 PLATFORM_SCHEMA = SWITCH_PLATFORM_SCHEMA.extend(
46  {vol.Required(CONF_SWITCHES): cv.schema_with_slug_keys(SWITCH_SCHEMA)}
47 )
48 
49 
51  hass: HomeAssistant,
52  config: ConfigType,
53  add_entities_callback: AddEntitiesCallback,
54  discovery_info: DiscoveryInfoType | None = None,
55 ) -> None:
56  """Set up Kankun Wifi switches."""
57  switches = config.get("switches", {})
58  devices = []
59 
60  for dev_name, properties in switches.items():
61  devices.append(
63  hass,
64  properties.get(CONF_NAME, dev_name),
65  properties.get(CONF_HOST),
66  properties.get(CONF_PORT, DEFAULT_PORT),
67  properties.get(CONF_PATH, DEFAULT_PATH),
68  properties.get(CONF_USERNAME),
69  properties.get(CONF_PASSWORD),
70  )
71  )
72 
73  add_entities_callback(devices)
74 
75 
77  """Representation of a Kankun Wifi switch."""
78 
79  def __init__(self, hass, name, host, port, path, user, passwd):
80  """Initialize the device."""
81  self._hass_hass = hass
82  self._name_name = name
83  self._state_state = False
84  self._url_url = f"http://{host}:{port}{path}"
85  if user is not None:
86  self._auth_auth = (user, passwd)
87  else:
88  self._auth_auth = None
89 
90  def _switch(self, newstate):
91  """Switch on or off."""
92  _LOGGER.debug("Switching to state: %s", newstate)
93 
94  try:
95  req = requests.get(
96  f"{self._url}?set={newstate}", auth=self._auth_auth, timeout=5
97  )
98  return req.json()["ok"]
99  except requests.RequestException:
100  _LOGGER.error("Switching failed")
101 
102  def _query_state(self):
103  """Query switch state."""
104  _LOGGER.debug("Querying state from: %s", self._url_url)
105 
106  try:
107  req = requests.get(f"{self._url}?get=state", auth=self._auth_auth, timeout=5)
108  return req.json()["state"] == "on"
109  except requests.RequestException:
110  _LOGGER.error("State query failed")
111 
112  @property
113  def name(self):
114  """Return the name of the switch."""
115  return self._name_name
116 
117  @property
118  def is_on(self):
119  """Return true if device is on."""
120  return self._state_state
121 
122  def update(self) -> None:
123  """Update device state."""
124  self._state_state = self._query_state_query_state()
125 
126  def turn_on(self, **kwargs: Any) -> None:
127  """Turn the device on."""
128  if self._switch_switch("on"):
129  self._state_state = True
130 
131  def turn_off(self, **kwargs: Any) -> None:
132  """Turn the device off."""
133  if self._switch_switch("off"):
134  self._state_state = False
def __init__(self, hass, name, host, port, path, user, passwd)
Definition: switch.py:79
None setup_platform(HomeAssistant hass, ConfigType config, AddEntitiesCallback add_entities_callback, DiscoveryInfoType|None discovery_info=None)
Definition: switch.py:55