1 """Support for switch controlled using a telnet connection."""
3 from __future__
import annotations
5 from datetime
import timedelta
10 import voluptuous
as vol
14 PLATFORM_SCHEMA
as SWITCH_PLATFORM_SCHEMA,
34 _LOGGER = logging.getLogger(__name__)
39 SWITCH_SCHEMA = vol.Schema(
41 vol.Required(CONF_COMMAND_OFF): cv.string,
42 vol.Required(CONF_COMMAND_ON): cv.string,
43 vol.Required(CONF_RESOURCE): cv.string,
44 vol.Optional(CONF_VALUE_TEMPLATE): cv.template,
45 vol.Optional(CONF_COMMAND_STATE): cv.string,
46 vol.Optional(CONF_NAME): cv.string,
47 vol.Optional(CONF_PORT, default=DEFAULT_PORT): cv.port,
48 vol.Optional(CONF_TIMEOUT, default=DEFAULT_TIMEOUT): vol.Coerce(float),
52 PLATFORM_SCHEMA = SWITCH_PLATFORM_SCHEMA.extend(
53 {vol.Required(CONF_SWITCHES): cv.schema_with_slug_keys(SWITCH_SCHEMA)}
62 add_entities: AddEntitiesCallback,
63 discovery_info: DiscoveryInfoType |
None =
None,
65 """Find and return switches controlled by telnet commands."""
66 devices: dict[str, Any] = config[CONF_SWITCHES]
69 for object_id, device_config
in devices.items():
73 device_config[CONF_RESOURCE],
74 device_config[CONF_PORT],
75 device_config.get(CONF_NAME, object_id),
76 device_config[CONF_COMMAND_ON],
77 device_config[CONF_COMMAND_OFF],
78 device_config.get(CONF_COMMAND_STATE),
79 device_config.get(CONF_VALUE_TEMPLATE),
80 device_config[CONF_TIMEOUT],
85 _LOGGER.error(
"No switches added")
92 """Representation of a switch that can be toggled using telnet commands."""
102 command_state: str |
None,
103 value_template: Template |
None,
106 """Initialize the switch."""
122 telnet = telnetlib.Telnet(self.
_resource_resource, self.
_port_port)
123 telnet.write(command.encode(
"ASCII") + b
"\r")
124 response = telnet.read_until(b
"\r", timeout=self.
_timeout_timeout)
125 except OSError
as error:
127 'Command "%s" failed with exception: %s', command, repr(error)
130 _LOGGER.debug(
"telnet response: %s", response.decode(
"ASCII").strip())
131 return response.decode(
"ASCII").strip()
134 """Update device state."""
139 rendered = self.
_value_template_value_template.render_with_possible_json_value(response)
141 _LOGGER.warning(
"Empty response for command: %s", self.
_command_state_command_state)
146 """Turn the device on."""
153 """Turn the device off."""
None turn_off(self, **Any kwargs)
None __init__(self, str object_id, str resource, int port, str friendly_name, str command_on, str command_off, str|None command_state, Template|None value_template, float timeout)
None turn_on(self, **Any kwargs)
str|None _telnet_command(self, str command)
None schedule_update_ha_state(self, bool force_refresh=False)
None add_entities(AsusWrtRouter router, AddEntitiesCallback async_add_entities, set[str] tracked)
None setup_platform(HomeAssistant hass, ConfigType config, AddEntitiesCallback add_entities, DiscoveryInfoType|None discovery_info=None)