1 """The Netio switch component."""
3 from __future__
import annotations
5 from collections
import namedtuple
6 from datetime
import timedelta
10 from pynetio
import Netio
11 import voluptuous
as vol
13 from homeassistant
import util
16 PLATFORM_SCHEMA
as SWITCH_PLATFORM_SCHEMA,
24 EVENT_HOMEASSISTANT_STOP,
32 _LOGGER = logging.getLogger(__name__)
34 ATTR_START_DATE =
"start_date"
35 ATTR_TOTAL_CONSUMPTION_KWH =
"total_energy_kwh"
37 CONF_OUTLETS =
"outlets"
40 DEFAULT_USERNAME =
"admin"
41 Device = namedtuple(
"Device", [
"netio",
"entities"])
42 DEVICES: dict[str, Device] = {}
46 REQ_CONF = [CONF_HOST, CONF_OUTLETS]
48 URL_API_NETIO_EP =
"/api/netio/{host}"
50 PLATFORM_SCHEMA = SWITCH_PLATFORM_SCHEMA.extend(
52 vol.Required(CONF_HOST): cv.string,
53 vol.Required(CONF_PORT, default=DEFAULT_PORT): cv.port,
54 vol.Required(CONF_USERNAME, default=DEFAULT_USERNAME): cv.string,
55 vol.Required(CONF_PASSWORD): cv.string,
56 vol.Optional(CONF_OUTLETS): {cv.string: cv.string},
64 add_entities: AddEntitiesCallback,
65 discovery_info: DiscoveryInfoType |
None =
None,
67 """Set up the Netio platform."""
69 host = config[CONF_HOST]
70 username = config[CONF_USERNAME]
71 password = config[CONF_PASSWORD]
72 port = config[CONF_PORT]
75 hass.http.register_view(NetioApiView)
77 dev = Netio(host, port, username, password)
79 DEVICES[host] =
Device(dev, [])
82 dev.update =
util.Throttle(MIN_TIME_BETWEEN_SCANS)(dev.update)
84 for key
in config[CONF_OUTLETS]:
85 switch =
NetioSwitch(DEVICES[host].netio, key, config[CONF_OUTLETS][key])
86 DEVICES[host].entities.append(switch)
90 hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, dispose)
94 """Close connections to Netio Devices."""
95 for value
in DEVICES.values():
100 """WSGI handler class."""
102 url = URL_API_NETIO_EP
106 def get(self, request, host):
107 """Request handler."""
109 states, consumptions, cumulated_consumptions, start_dates = [], [], [], []
111 for i
in range(1, 5):
113 states.append(data.get(f
"{out}_state") == STATE_ON)
114 consumptions.append(
float(data.get(f
"{out}_consumption", 0)))
115 cumulated_consumptions.append(
116 float(data.get(f
"{out}_cumulatedConsumption", 0)) / 1000
118 start_dates.append(data.get(f
"{out}_consumptionStart",
""))
121 "%s: %s, %s, %s since %s",
125 cumulated_consumptions,
129 ndev = DEVICES[host].netio
130 ndev.consumptions = consumptions
131 ndev.cumulated_consumptions = cumulated_consumptions
133 ndev.start_dates = start_dates
135 for dev
in DEVICES[host].entities:
136 dev.async_write_ha_state()
138 return self.json(
True)
142 """Provide a Netio linked switch."""
145 """Initialize the Netio switch."""
152 """Return the device's name."""
153 return self.
_name_name
157 """Return true if entity is available."""
158 return not hasattr(self,
"telnet")
161 """Turn switch on."""
165 """Turn switch off."""
170 val[
int(self.
outletoutlet) - 1] =
"1" if value
else "0"
172 self.
netionetio.
get(f
"port list {val}")
178 """Return the switch's status."""
182 """Update the state."""
def get(self, request, host)
None turn_on(self, **Any kwargs)
def __init__(self, netio, outlet, name)
None turn_off(self, **Any kwargs)
None schedule_update_ha_state(self, bool force_refresh=False)
None add_entities(AsusWrtRouter router, AddEntitiesCallback async_add_entities, set[str] tracked)
web.Response get(self, web.Request request, str config_key)
None setup_platform(HomeAssistant hass, ConfigType config, AddEntitiesCallback add_entities, DiscoveryInfoType|None discovery_info=None)