Consolidate all platforms that have no tests (#22096)

* Consolidate

* Fix tests

* Update imports

* Fix import

* Use importlib because integration and package share name

* Fix more tests

* Update .coveragerc and CODEOWNERS
This commit is contained in:
Paulus Schoutsen authored and GitHub committed 2019-03-16 20:44:05 -07:00
1 parent d33cad0b24
commit f5076188ef
742 files changed
+1145 -795

No files matched your search

@@ -1,168 +0,0 @@
"""
Use serial protocol of Acer projector to obtain state of the projector.
For more details about this component, please refer to the documentation
at https://home-assistant.io/components/switch.acer_projector/
"""
import logging
import re
import voluptuous as vol
from homeassistant.components.switch import (SwitchDevice, PLATFORM_SCHEMA)
from homeassistant.const import (
STATE_ON, STATE_OFF, STATE_UNKNOWN, CONF_NAME, CONF_FILENAME)
import homeassistant.helpers.config_validation as cv
REQUIREMENTS = ['pyserial==3.1.1']
_LOGGER = logging.getLogger(__name__)
CONF_TIMEOUT = 'timeout'
CONF_WRITE_TIMEOUT = 'write_timeout'
DEFAULT_NAME = 'Acer Projector'
DEFAULT_TIMEOUT = 1
DEFAULT_WRITE_TIMEOUT = 1
ECO_MODE = 'ECO Mode'
ICON = 'mdi:projector'
INPUT_SOURCE = 'Input Source'
LAMP = 'Lamp'
LAMP_HOURS = 'Lamp Hours'
MODEL = 'Model'
# Commands known to the projector
CMD_DICT = {
LAMP: '* 0 Lamp ?\r',
LAMP_HOURS: '* 0 Lamp\r',
INPUT_SOURCE: '* 0 Src ?\r',
ECO_MODE: '* 0 IR 052\r',
MODEL: '* 0 IR 035\r',
STATE_ON: '* 0 IR 001\r',
STATE_OFF: '* 0 IR 002\r',
}
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Required(CONF_FILENAME): cv.isdevice,
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
vol.Optional(CONF_TIMEOUT, default=DEFAULT_TIMEOUT): cv.positive_int,
vol.Optional(CONF_WRITE_TIMEOUT, default=DEFAULT_WRITE_TIMEOUT):
cv.positive_int,
})
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Connect with serial port and return Acer Projector."""
serial_port = config.get(CONF_FILENAME)
name = config.get(CONF_NAME)
timeout = config.get(CONF_TIMEOUT)
write_timeout = config.get(CONF_WRITE_TIMEOUT)
add_entities([AcerSwitch(serial_port, name, timeout, write_timeout)], True)
class AcerSwitch(SwitchDevice):
"""Represents an Acer Projector as a switch."""
def __init__(self, serial_port, name, timeout, write_timeout, **kwargs):
"""Init of the Acer projector."""
import serial
self.ser = serial.Serial(
port=serial_port, timeout=timeout, write_timeout=write_timeout,
**kwargs)
self._serial_port = serial_port
self._name = name
self._state = False
self._available = False
self._attributes = {
LAMP_HOURS: STATE_UNKNOWN,
INPUT_SOURCE: STATE_UNKNOWN,
ECO_MODE: STATE_UNKNOWN,
}
def _write_read(self, msg):
"""Write to the projector and read the return."""
import serial
ret = ""
# Sometimes the projector won't answer for no reason or the projector
# was disconnected during runtime.
# This way the projector can be reconnected and will still work
try:
if not self.ser.is_open:
self.ser.open()
msg = msg.encode('utf-8')
self.ser.write(msg)
# Size is an experience value there is no real limit.
# AFAIK there is no limit and no end character so we will usually
# need to wait for timeout
ret = self.ser.read_until(size=20).decode('utf-8')
except serial.SerialException:
_LOGGER.error('Problem communicating with %s', self._serial_port)
self.ser.close()
return ret
def _write_read_format(self, msg):
"""Write msg, obtain answer and format output."""
# answers are formatted as ***\answer\r***
awns = self._write_read(msg)
match = re.search(r'\r(.+)\r', awns)
if match:
return match.group(1)
return STATE_UNKNOWN
@property
def available(self):
"""Return if projector is available."""
return self._available
@property
def name(self):
"""Return name of the projector."""
return self._name
@property
def is_on(self):
"""Return if the projector is turned on."""
return self._state
@property
def state_attributes(self):
"""Return state attributes."""
return self._attributes
def update(self):
"""Get the latest state from the projector."""
msg = CMD_DICT[LAMP]
awns = self._write_read_format(msg)
if awns == 'Lamp 1':
self._state = True
self._available = True
elif awns == 'Lamp 0':
self._state = False
self._available = True
else:
self._available = False
for key in self._attributes:
msg = CMD_DICT.get(key, None)
if msg:
awns = self._write_read_format(msg)
self._attributes[key] = awns
def turn_on(self, **kwargs):
"""Turn the projector on."""
msg = CMD_DICT[STATE_ON]
self._write_read(msg)
self._state = STATE_ON
def turn_off(self, **kwargs):
"""Turn the projector off."""
msg = CMD_DICT[STATE_OFF]
self._write_read(msg)
self._state = STATE_OFF
@@ -1,120 +0,0 @@
"""
Support for ANEL PwrCtrl switches.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/switch.pwrctrl/
"""
import logging
import socket
from datetime import timedelta
import voluptuous as vol
import homeassistant.helpers.config_validation as cv
from homeassistant.components.switch import (SwitchDevice, PLATFORM_SCHEMA)
from homeassistant.const import (CONF_HOST, CONF_PASSWORD, CONF_USERNAME)
from homeassistant.util import Throttle
REQUIREMENTS = ['anel_pwrctrl-homeassistant==0.0.1.dev2']
_LOGGER = logging.getLogger(__name__)
CONF_PORT_RECV = 'port_recv'
CONF_PORT_SEND = 'port_send'
MIN_TIME_BETWEEN_UPDATES = timedelta(seconds=5)
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Required(CONF_PORT_RECV): cv.port,
vol.Required(CONF_PORT_SEND): cv.port,
vol.Required(CONF_USERNAME): cv.string,
vol.Required(CONF_PASSWORD): cv.string,
vol.Optional(CONF_HOST): cv.string,
})
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up PwrCtrl devices/switches."""
host = config.get(CONF_HOST, None)
username = config.get(CONF_USERNAME)
password = config.get(CONF_PASSWORD)
port_recv = config.get(CONF_PORT_RECV)
port_send = config.get(CONF_PORT_SEND)
from anel_pwrctrl import DeviceMaster
try:
master = DeviceMaster(
username=username, password=password, read_port=port_send,
write_port=port_recv)
master.query(ip_addr=host)
except socket.error as ex:
_LOGGER.error("Unable to discover PwrCtrl device: %s", str(ex))
return False
devices = []
for device in master.devices.values():
parent_device = PwrCtrlDevice(device)
devices.extend(
PwrCtrlSwitch(switch, parent_device)
for switch in device.switches.values()
)
add_entities(devices)
class PwrCtrlSwitch(SwitchDevice):
"""Representation of a PwrCtrl switch."""
def __init__(self, port, parent_device):
"""Initialize the PwrCtrl switch."""
self._port = port
self._parent_device = parent_device
@property
def should_poll(self):
"""Return the polling state."""
return True
@property
def unique_id(self):
"""Return the unique ID of the device."""
return '{device}-{switch_idx}'.format(
device=self._port.device.host,
switch_idx=self._port.get_index()
)
@property
def name(self):
"""Return the name of the device."""
return self._port.label
@property
def is_on(self):
"""Return true if the device is on."""
return self._port.get_state()
def update(self):
"""Trigger update for all switches on the parent device."""
self._parent_device.update()
def turn_on(self, **kwargs):
"""Turn the switch on."""
self._port.on()
def turn_off(self, **kwargs):
"""Turn the switch off."""
self._port.off()
class PwrCtrlDevice:
"""Device representation for per device throttling."""
def __init__(self, device):
"""Initialize the PwrCtrl device."""
self._device = device
@Throttle(MIN_TIME_BETWEEN_UPDATES)
def update(self):
"""Update the device and all its switches."""
self._device.update()
-205
View File
@@ -1,205 +0,0 @@
"""
Support for an exposed aREST RESTful API of a device.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/switch.arest/
"""
import logging
import requests
import voluptuous as vol
from homeassistant.components.switch import (SwitchDevice, PLATFORM_SCHEMA)
from homeassistant.const import (CONF_NAME, CONF_RESOURCE)
import homeassistant.helpers.config_validation as cv
_LOGGER = logging.getLogger(__name__)
CONF_FUNCTIONS = 'functions'
CONF_PINS = 'pins'
CONF_INVERT = 'invert'
DEFAULT_NAME = 'aREST switch'
PIN_FUNCTION_SCHEMA = vol.Schema({
vol.Optional(CONF_NAME): cv.string,
vol.Optional(CONF_INVERT, default=False): cv.boolean,
})
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Required(CONF_RESOURCE): cv.url,
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
vol.Optional(CONF_PINS, default={}):
vol.Schema({cv.string: PIN_FUNCTION_SCHEMA}),
vol.Optional(CONF_FUNCTIONS, default={}):
vol.Schema({cv.string: PIN_FUNCTION_SCHEMA}),
})
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the aREST switches."""
resource = config.get(CONF_RESOURCE)
try:
response = requests.get(resource, timeout=10)
except requests.exceptions.MissingSchema:
_LOGGER.error("Missing resource or schema in configuration. "
"Add http:// to your URL")
return False
except requests.exceptions.ConnectionError:
_LOGGER.error("No route to device at %s", resource)
return False
dev = []
pins = config.get(CONF_PINS)
for pinnum, pin in pins.items():
dev.append(ArestSwitchPin(
resource, config.get(CONF_NAME, response.json()[CONF_NAME]),
pin.get(CONF_NAME), pinnum, pin.get(CONF_INVERT)))
functions = config.get(CONF_FUNCTIONS)
for funcname, func in functions.items():
dev.append(ArestSwitchFunction(
resource, config.get(CONF_NAME, response.json()[CONF_NAME]),
func.get(CONF_NAME), funcname))
add_entities(dev)
class ArestSwitchBase(SwitchDevice):
"""Representation of an aREST switch."""
def __init__(self, resource, location, name):
"""Initialize the switch."""
self._resource = resource
self._name = '{} {}'.format(location.title(), name.title())
self._state = None
self._available = True
@property
def name(self):
"""Return the name of the switch."""
return self._name
@property
def is_on(self):
"""Return true if device is on."""
return self._state
@property
def available(self):
"""Could the device be accessed during the last update call."""
return self._available
class ArestSwitchFunction(ArestSwitchBase):
"""Representation of an aREST switch."""
def __init__(self, resource, location, name, func):
"""Initialize the switch."""
super().__init__(resource, location, name)
self._func = func
request = requests.get(
'{}/{}'.format(self._resource, self._func), timeout=10)
if request.status_code != 200:
_LOGGER.error("Can't find function")
return
try:
request.json()['return_value']
except KeyError:
_LOGGER.error("No return_value received")
except ValueError:
_LOGGER.error("Response invalid")
def turn_on(self, **kwargs):
"""Turn the device on."""
request = requests.get(
'{}/{}'.format(self._resource, self._func), timeout=10,
params={'params': '1'})
if request.status_code == 200:
self._state = True
else:
_LOGGER.error(
"Can't turn on function %s at %s", self._func, self._resource)
def turn_off(self, **kwargs):
"""Turn the device off."""
request = requests.get(
'{}/{}'.format(self._resource, self._func), timeout=10,
params={'params': '0'})
if request.status_code == 200:
self._state = False
else:
_LOGGER.error(
"Can't turn off function %s at %s", self._func, self._resource)
def update(self):
"""Get the latest data from aREST API and update the state."""
try:
request = requests.get(
'{}/{}'.format(self._resource, self._func), timeout=10)
self._state = request.json()['return_value'] != 0
self._available = True
except requests.exceptions.ConnectionError:
_LOGGER.warning("No route to device %s", self._resource)
self._available = False
class ArestSwitchPin(ArestSwitchBase):
"""Representation of an aREST switch. Based on digital I/O."""
def __init__(self, resource, location, name, pin, invert):
"""Initialize the switch."""
super().__init__(resource, location, name)
self._pin = pin
self.invert = invert
request = requests.get(
'{}/mode/{}/o'.format(self._resource, self._pin), timeout=10)
if request.status_code != 200:
_LOGGER.error("Can't set mode")
self._available = False
def turn_on(self, **kwargs):
"""Turn the device on."""
turn_on_payload = int(not self.invert)
request = requests.get(
'{}/digital/{}/{}'.format(self._resource, self._pin,
turn_on_payload),
timeout=10)
if request.status_code == 200:
self._state = True
else:
_LOGGER.error(
"Can't turn on pin %s at %s", self._pin, self._resource)
def turn_off(self, **kwargs):
"""Turn the device off."""
turn_off_payload = int(self.invert)
request = requests.get(
'{}/digital/{}/{}'.format(self._resource, self._pin,
turn_off_payload),
timeout=10)
if request.status_code == 200:
self._state = False
else:
_LOGGER.error(
"Can't turn off pin %s at %s", self._pin, self._resource)
def update(self):
"""Get the latest data from aREST API and update the state."""
try:
request = requests.get(
'{}/digital/{}'.format(self._resource, self._pin), timeout=10)
status_value = int(self.invert)
self._state = request.json()['return_value'] != status_value
self._available = True
except requests.exceptions.ConnectionError:
_LOGGER.warning("No route to device %s", self._resource)
self._available = False
@@ -1,404 +0,0 @@
"""
Support for Broadlink RM devices.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/switch.broadlink/
"""
import asyncio
from base64 import b64decode, b64encode
import binascii
from datetime import timedelta
import logging
import socket
import voluptuous as vol
from homeassistant.components.switch import (
DOMAIN, PLATFORM_SCHEMA, SwitchDevice, ENTITY_ID_FORMAT)
from homeassistant.const import (
CONF_COMMAND_OFF, CONF_COMMAND_ON, CONF_FRIENDLY_NAME, CONF_HOST, CONF_MAC,
CONF_SWITCHES, CONF_TIMEOUT, CONF_TYPE)
import homeassistant.helpers.config_validation as cv
from homeassistant.util import Throttle, slugify
from homeassistant.util.dt import utcnow
REQUIREMENTS = ['broadlink==0.9.0']
_LOGGER = logging.getLogger(__name__)
TIME_BETWEEN_UPDATES = timedelta(seconds=5)
DEFAULT_NAME = 'Broadlink switch'
DEFAULT_TIMEOUT = 10
DEFAULT_RETRY = 3
SERVICE_LEARN = 'broadlink_learn_command'
SERVICE_SEND = 'broadlink_send_packet'
CONF_SLOTS = 'slots'
RM_TYPES = ['rm', 'rm2', 'rm_mini', 'rm_pro_phicomm', 'rm2_home_plus',
'rm2_home_plus_gdt', 'rm2_pro_plus', 'rm2_pro_plus2',
'rm2_pro_plus_bl', 'rm_mini_shate']
SP1_TYPES = ['sp1']
SP2_TYPES = ['sp2', 'honeywell_sp2', 'sp3', 'spmini2', 'spminiplus']
MP1_TYPES = ['mp1']
SWITCH_TYPES = RM_TYPES + SP1_TYPES + SP2_TYPES + MP1_TYPES
SWITCH_SCHEMA = vol.Schema({
vol.Optional(CONF_COMMAND_OFF): cv.string,
vol.Optional(CONF_COMMAND_ON): cv.string,
vol.Optional(CONF_FRIENDLY_NAME): cv.string,
})
MP1_SWITCH_SLOT_SCHEMA = vol.Schema({
vol.Optional('slot_1'): cv.string,
vol.Optional('slot_2'): cv.string,
vol.Optional('slot_3'): cv.string,
vol.Optional('slot_4'): cv.string
})
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Optional(CONF_SWITCHES, default={}):
cv.schema_with_slug_keys(SWITCH_SCHEMA),
vol.Optional(CONF_SLOTS, default={}): MP1_SWITCH_SLOT_SCHEMA,
vol.Required(CONF_HOST): cv.string,
vol.Required(CONF_MAC): cv.string,
vol.Optional(CONF_FRIENDLY_NAME, default=DEFAULT_NAME): cv.string,
vol.Optional(CONF_TYPE, default=SWITCH_TYPES[0]): vol.In(SWITCH_TYPES),
vol.Optional(CONF_TIMEOUT, default=DEFAULT_TIMEOUT): cv.positive_int
})
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the Broadlink switches."""
import broadlink
devices = config.get(CONF_SWITCHES)
slots = config.get('slots', {})
ip_addr = config.get(CONF_HOST)
friendly_name = config.get(CONF_FRIENDLY_NAME)
mac_addr = binascii.unhexlify(
config.get(CONF_MAC).encode().replace(b':', b''))
switch_type = config.get(CONF_TYPE)
async def _learn_command(call):
"""Handle a learn command."""
try:
auth = await hass.async_add_job(broadlink_device.auth)
except socket.timeout:
_LOGGER.error("Failed to connect to device, timeout")
return
if not auth:
_LOGGER.error("Failed to connect to device")
return
await hass.async_add_job(broadlink_device.enter_learning)
_LOGGER.info("Press the key you want Home Assistant to learn")
start_time = utcnow()
while (utcnow() - start_time) < timedelta(seconds=20):
packet = await hass.async_add_job(
broadlink_device.check_data)
if packet:
log_msg = "Received packet is: {}".\
format(b64encode(packet).decode('utf8'))
_LOGGER.info(log_msg)
hass.components.persistent_notification.async_create(
log_msg, title='Broadlink switch')
return
await asyncio.sleep(1, loop=hass.loop)
_LOGGER.error("Did not received any signal")
hass.components.persistent_notification.async_create(
"Did not received any signal", title='Broadlink switch')
async def _send_packet(call):
"""Send a packet."""
packets = call.data.get('packet', [])
for packet in packets:
for retry in range(DEFAULT_RETRY):
try:
extra = len(packet) % 4
if extra > 0:
packet = packet + ('=' * (4 - extra))
payload = b64decode(packet)
await hass.async_add_job(
broadlink_device.send_data, payload)
break
except (socket.timeout, ValueError):
try:
await hass.async_add_job(
broadlink_device.auth)
except socket.timeout:
if retry == DEFAULT_RETRY-1:
_LOGGER.error("Failed to send packet to device")
def _get_mp1_slot_name(switch_friendly_name, slot):
"""Get slot name."""
if not slots['slot_{}'.format(slot)]:
return '{} slot {}'.format(switch_friendly_name, slot)
return slots['slot_{}'.format(slot)]
if switch_type in RM_TYPES:
broadlink_device = broadlink.rm((ip_addr, 80), mac_addr, None)
hass.services.register(DOMAIN, SERVICE_LEARN + '_' +
slugify(ip_addr.replace('.', '_')),
_learn_command)
hass.services.register(DOMAIN, SERVICE_SEND + '_' +
slugify(ip_addr.replace('.', '_')),
_send_packet,
vol.Schema({'packet': cv.ensure_list}))
switches = []
for object_id, device_config in devices.items():
switches.append(
BroadlinkRMSwitch(
object_id,
device_config.get(CONF_FRIENDLY_NAME, object_id),
broadlink_device,
device_config.get(CONF_COMMAND_ON),
device_config.get(CONF_COMMAND_OFF)
)
)
elif switch_type in SP1_TYPES:
broadlink_device = broadlink.sp1((ip_addr, 80), mac_addr, None)
switches = [BroadlinkSP1Switch(friendly_name, broadlink_device)]
elif switch_type in SP2_TYPES:
broadlink_device = broadlink.sp2((ip_addr, 80), mac_addr, None)
switches = [BroadlinkSP2Switch(friendly_name, broadlink_device)]
elif switch_type in MP1_TYPES:
switches = []
broadlink_device = broadlink.mp1((ip_addr, 80), mac_addr, None)
parent_device = BroadlinkMP1Switch(broadlink_device)
for i in range(1, 5):
slot = BroadlinkMP1Slot(
_get_mp1_slot_name(friendly_name, i),
broadlink_device, i, parent_device)
switches.append(slot)
broadlink_device.timeout = config.get(CONF_TIMEOUT)
try:
broadlink_device.auth()
except socket.timeout:
_LOGGER.error("Failed to connect to device")
add_entities(switches)
class BroadlinkRMSwitch(SwitchDevice):
"""Representation of an Broadlink switch."""
def __init__(self, name, friendly_name, device, command_on, command_off):
"""Initialize the switch."""
self.entity_id = ENTITY_ID_FORMAT.format(slugify(name))
self._name = friendly_name
self._state = False
self._command_on = b64decode(command_on) if command_on else None
self._command_off = b64decode(command_off) if command_off else None
self._device = device
@property
def name(self):
"""Return the name of the switch."""
return self._name
@property
def assumed_state(self):
"""Return true if unable to access real state of entity."""
return True
@property
def should_poll(self):
"""Return the polling state."""
return False
@property
def is_on(self):
"""Return true if device is on."""
return self._state
def turn_on(self, **kwargs):
"""Turn the device on."""
if self._sendpacket(self._command_on):
self._state = True
self.schedule_update_ha_state()
def turn_off(self, **kwargs):
"""Turn the device off."""
if self._sendpacket(self._command_off):
self._state = False
self.schedule_update_ha_state()
def _sendpacket(self, packet, retry=2):
"""Send packet to device."""
if packet is None:
_LOGGER.debug("Empty packet")
return True
try:
self._device.send_data(packet)
except (socket.timeout, ValueError) as error:
if retry < 1:
_LOGGER.error("Error during sending a packet: %s", error)
return False
if not self._auth():
return False
return self._sendpacket(packet, retry-1)
return True
def _auth(self, retry=2):
try:
auth = self._device.auth()
except socket.timeout:
auth = False
if retry < 1:
_LOGGER.error("Timeout during authorization")
if not auth and retry > 0:
return self._auth(retry-1)
return auth
class BroadlinkSP1Switch(BroadlinkRMSwitch):
"""Representation of an Broadlink switch."""
def __init__(self, friendly_name, device):
"""Initialize the switch."""
super().__init__(friendly_name, friendly_name, device, None, None)
self._command_on = 1
self._command_off = 0
self._load_power = None
def _sendpacket(self, packet, retry=2):
"""Send packet to device."""
try:
self._device.set_power(packet)
except (socket.timeout, ValueError) as error:
if retry < 1:
_LOGGER.error("Error during sending a packet: %s", error)
return False
if not self._auth():
return False
return self._sendpacket(packet, retry-1)
return True
class BroadlinkSP2Switch(BroadlinkSP1Switch):
"""Representation of an Broadlink switch."""
@property
def assumed_state(self):
"""Return true if unable to access real state of entity."""
return False
@property
def should_poll(self):
"""Return the polling state."""
return True
@property
def current_power_w(self):
"""Return the current power usage in Watt."""
try:
return round(self._load_power, 2)
except (ValueError, TypeError):
return None
def update(self):
"""Synchronize state with switch."""
self._update()
def _update(self, retry=2):
"""Update the state of the device."""
try:
state = self._device.check_power()
load_power = self._device.get_energy()
except (socket.timeout, ValueError) as error:
if retry < 1:
_LOGGER.error("Error during updating the state: %s", error)
return
if not self._auth():
return
return self._update(retry-1)
if state is None and retry > 0:
return self._update(retry-1)
self._state = state
self._load_power = load_power
class BroadlinkMP1Slot(BroadlinkRMSwitch):
"""Representation of a slot of Broadlink switch."""
def __init__(self, friendly_name, device, slot, parent_device):
"""Initialize the slot of switch."""
super().__init__(friendly_name, friendly_name, device, None, None)
self._command_on = 1
self._command_off = 0
self._slot = slot
self._parent_device = parent_device
@property
def assumed_state(self):
"""Return true if unable to access real state of entity."""
return False
def _sendpacket(self, packet, retry=2):
"""Send packet to device."""
try:
self._device.set_power(self._slot, packet)
except (socket.timeout, ValueError) as error:
if retry < 1:
_LOGGER.error("Error during sending a packet: %s", error)
return False
if not self._auth():
return False
return self._sendpacket(packet, max(0, retry-1))
return True
@property
def should_poll(self):
"""Return the polling state."""
return True
def update(self):
"""Trigger update for all switches on the parent device."""
self._parent_device.update()
self._state = self._parent_device.get_outlet_status(self._slot)
class BroadlinkMP1Switch:
"""Representation of a Broadlink switch - To fetch states of all slots."""
def __init__(self, device):
"""Initialize the switch."""
self._device = device
self._states = None
def get_outlet_status(self, slot):
"""Get status of outlet from cached status list."""
return self._states['s{}'.format(slot)]
@Throttle(TIME_BETWEEN_UPDATES)
def update(self):
"""Fetch new state data for this device."""
self._update()
def _update(self, retry=2):
"""Update the state of the device."""
try:
states = self._device.check_power()
except (socket.timeout, ValueError) as error:
if retry < 1:
_LOGGER.error("Error during updating the state: %s", error)
return
if not self._auth():
return
return self._update(max(0, retry-1))
if states is None and retry > 0:
return self._update(max(0, retry-1))
self._states = states
def _auth(self, retry=2):
"""Authenticate the device."""
try:
auth = self._device.auth()
except socket.timeout:
auth = False
if not auth and retry > 0:
return self._auth(retry-1)
return auth
-112
View File
@@ -1,112 +0,0 @@
"""
Support for setting the Deluge BitTorrent client in Pause.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/switch.deluge/
"""
import logging
import voluptuous as vol
from homeassistant.components.switch import PLATFORM_SCHEMA
from homeassistant.exceptions import PlatformNotReady
from homeassistant.const import (
CONF_HOST, CONF_NAME, CONF_PORT, CONF_PASSWORD, CONF_USERNAME, STATE_OFF,
STATE_ON)
from homeassistant.helpers.entity import ToggleEntity
import homeassistant.helpers.config_validation as cv
REQUIREMENTS = ['deluge-client==1.4.0']
_LOGGER = logging.getLogger(__name__)
DEFAULT_NAME = 'Deluge Switch'
DEFAULT_PORT = 58846
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Required(CONF_HOST): cv.string,
vol.Required(CONF_PASSWORD): cv.string,
vol.Optional(CONF_PORT, default=DEFAULT_PORT): cv.port,
vol.Required(CONF_USERNAME): cv.string,
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
})
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the Deluge switch."""
from deluge_client import DelugeRPCClient
name = config.get(CONF_NAME)
host = config.get(CONF_HOST)
username = config.get(CONF_USERNAME)
password = config.get(CONF_PASSWORD)
port = config.get(CONF_PORT)
deluge_api = DelugeRPCClient(host, port, username, password)
try:
deluge_api.connect()
except ConnectionRefusedError:
_LOGGER.error("Connection to Deluge Daemon failed")
raise PlatformNotReady
add_entities([DelugeSwitch(deluge_api, name)])
class DelugeSwitch(ToggleEntity):
"""Representation of a Deluge switch."""
def __init__(self, deluge_client, name):
"""Initialize the Deluge switch."""
self._name = name
self.deluge_client = deluge_client
self._state = STATE_OFF
self._available = False
@property
def name(self):
"""Return the name of the switch."""
return self._name
@property
def state(self):
"""Return the state of the device."""
return self._state
@property
def is_on(self):
"""Return true if device is on."""
return self._state == STATE_ON
@property
def available(self):
"""Return true if device is available."""
return self._available
def turn_on(self, **kwargs):
"""Turn the device on."""
torrent_ids = self.deluge_client.call('core.get_session_state')
self.deluge_client.call('core.resume_torrent', torrent_ids)
def turn_off(self, **kwargs):
"""Turn the device off."""
torrent_ids = self.deluge_client.call('core.get_session_state')
self.deluge_client.call('core.pause_torrent', torrent_ids)
def update(self):
"""Get the latest data from deluge and updates the state."""
from deluge_client import FailedToReconnectException
try:
torrent_list = self.deluge_client.call('core.get_torrents_status',
{}, ['paused'])
self._available = True
except FailedToReconnectException:
_LOGGER.error("Connection to Deluge Daemon Lost")
self._available = False
return
for torrent in torrent_list.values():
item = torrent.popitem()
if not item[1]:
self._state = STATE_ON
return
self._state = STATE_OFF
-73
View File
@@ -1,73 +0,0 @@
"""
Demo platform that has two fake switches.
For more details about this platform, please refer to the documentation
https://home-assistant.io/components/demo/
"""
from homeassistant.components.switch import SwitchDevice
from homeassistant.const import DEVICE_DEFAULT_NAME
def setup_platform(hass, config, add_entities_callback, discovery_info=None):
"""Set up the demo switches."""
add_entities_callback([
DemoSwitch('Decorative Lights', True, None, True),
DemoSwitch('AC', False, 'mdi:air-conditioner', False)
])
class DemoSwitch(SwitchDevice):
"""Representation of a demo switch."""
def __init__(self, name, state, icon, assumed):
"""Initialize the Demo switch."""
self._name = name or DEVICE_DEFAULT_NAME
self._state = state
self._icon = icon
self._assumed = assumed
@property
def should_poll(self):
"""No polling needed for a demo switch."""
return False
@property
def name(self):
"""Return the name of the device if any."""
return self._name
@property
def icon(self):
"""Return the icon to use for device if any."""
return self._icon
@property
def assumed_state(self):
"""Return if the state is based on assumptions."""
return self._assumed
@property
def current_power_w(self):
"""Return the current power usage in W."""
if self._state:
return 100
@property
def today_energy_kwh(self):
"""Return the today total energy usage in kWh."""
return 15
@property
def is_on(self):
"""Return true if switch is on."""
return self._state
def turn_on(self, **kwargs):
"""Turn the switch on."""
self._state = True
self.schedule_update_ha_state()
def turn_off(self, **kwargs):
"""Turn the device off."""
self._state = False
self.schedule_update_ha_state()
@@ -1,140 +0,0 @@
"""
Support for Digital Loggers DIN III Relays.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/switch.digitalloggers/
"""
import logging
from datetime import timedelta
import voluptuous as vol
from homeassistant.components.switch import (SwitchDevice, PLATFORM_SCHEMA)
from homeassistant.const import (
CONF_HOST, CONF_NAME, CONF_USERNAME, CONF_PASSWORD, CONF_TIMEOUT)
import homeassistant.helpers.config_validation as cv
from homeassistant.util import Throttle
REQUIREMENTS = ['dlipower==0.7.165']
_LOGGER = logging.getLogger(__name__)
CONF_CYCLETIME = 'cycletime'
DEFAULT_NAME = 'DINRelay'
DEFAULT_USERNAME = 'admin'
DEFAULT_PASSWORD = 'admin'
DEFAULT_TIMEOUT = 20
DEFAULT_CYCLETIME = 2
MIN_TIME_BETWEEN_UPDATES = timedelta(seconds=5)
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Required(CONF_HOST): cv.string,
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
vol.Optional(CONF_USERNAME, default=DEFAULT_USERNAME): cv.string,
vol.Optional(CONF_PASSWORD, default=DEFAULT_PASSWORD): cv.string,
vol.Optional(CONF_TIMEOUT, default=DEFAULT_TIMEOUT):
vol.All(vol.Coerce(int), vol.Range(min=1, max=600)),
vol.Optional(CONF_CYCLETIME, default=DEFAULT_CYCLETIME):
vol.All(vol.Coerce(int), vol.Range(min=1, max=600)),
})
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Find and return DIN III Relay switch."""
import dlipower
host = config.get(CONF_HOST)
controller_name = config.get(CONF_NAME)
user = config.get(CONF_USERNAME)
pswd = config.get(CONF_PASSWORD)
tout = config.get(CONF_TIMEOUT)
cycl = config.get(CONF_CYCLETIME)
power_switch = dlipower.PowerSwitch(
hostname=host, userid=user, password=pswd,
timeout=tout, cycletime=cycl
)
if not power_switch.verify():
_LOGGER.error("Could not connect to DIN III Relay")
return False
outlets = []
parent_device = DINRelayDevice(power_switch)
outlets.extend(
DINRelay(controller_name, parent_device, outlet)
for outlet in power_switch[0:]
)
add_entities(outlets)
class DINRelay(SwitchDevice):
"""Representation of an individual DIN III relay port."""
def __init__(self, controller_name, parent_device, outlet):
"""Initialize the DIN III Relay switch."""
self._controller_name = controller_name
self._parent_device = parent_device
self._outlet = outlet
self._outlet_number = self._outlet.outlet_number
self._name = self._outlet.description
self._state = self._outlet.state == 'ON'
@property
def name(self):
"""Return the display name of this relay."""
return '{}_{}'.format(
self._controller_name,
self._name
)
@property
def is_on(self):
"""Return true if relay is on."""
return self._state
@property
def should_poll(self):
"""Return the polling state."""
return True
def turn_on(self, **kwargs):
"""Instruct the relay to turn on."""
self._outlet.on()
def turn_off(self, **kwargs):
"""Instruct the relay to turn off."""
self._outlet.off()
def update(self):
"""Trigger update for all switches on the parent device."""
self._parent_device.update()
outlet_status = self._parent_device.get_outlet_status(
self._outlet_number)
self._name = outlet_status[1]
self._state = outlet_status[2] == 'ON'
class DINRelayDevice:
"""Device representation for per device throttling."""
def __init__(self, power_switch):
"""Initialize the DINRelay device."""
self._power_switch = power_switch
self._statuslist = None
def get_outlet_status(self, outlet_number):
"""Get status of outlet from cached status list."""
return self._statuslist[outlet_number - 1]
@Throttle(MIN_TIME_BETWEEN_UPDATES)
def update(self):
"""Fetch new state data for this device."""
self._statuslist = self._power_switch.statuslist()
-168
View File
@@ -1,168 +0,0 @@
"""
Support for D-Link W215 smart switch.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/switch.dlink/
"""
from datetime import timedelta
import logging
import urllib
import voluptuous as vol
from homeassistant.components.switch import PLATFORM_SCHEMA, SwitchDevice
from homeassistant.const import (
ATTR_TEMPERATURE, CONF_HOST, CONF_NAME, CONF_PASSWORD, CONF_USERNAME,
TEMP_CELSIUS)
import homeassistant.helpers.config_validation as cv
from homeassistant.util import dt as dt_util
REQUIREMENTS = ['pyW215==0.6.0']
_LOGGER = logging.getLogger(__name__)
ATTR_TOTAL_CONSUMPTION = 'total_consumption'
CONF_USE_LEGACY_PROTOCOL = 'use_legacy_protocol'
DEFAULT_NAME = "D-Link Smart Plug W215"
DEFAULT_PASSWORD = ''
DEFAULT_USERNAME = 'admin'
SCAN_INTERVAL = timedelta(minutes=2)
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Required(CONF_HOST): cv.string,
vol.Required(CONF_PASSWORD, default=DEFAULT_PASSWORD): cv.string,
vol.Required(CONF_USERNAME, default=DEFAULT_USERNAME): cv.string,
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
vol.Optional(CONF_USE_LEGACY_PROTOCOL, default=False): cv.boolean,
})
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up a D-Link Smart Plug."""
from pyW215.pyW215 import SmartPlug
host = config.get(CONF_HOST)
username = config.get(CONF_USERNAME)
password = config.get(CONF_PASSWORD)
use_legacy_protocol = config.get(CONF_USE_LEGACY_PROTOCOL)
name = config.get(CONF_NAME)
smartplug = SmartPlug(host, password, username, use_legacy_protocol)
data = SmartPlugData(smartplug)
add_entities([SmartPlugSwitch(hass, data, name)], True)
class SmartPlugSwitch(SwitchDevice):
"""Representation of a D-Link Smart Plug switch."""
def __init__(self, hass, data, name):
"""Initialize the switch."""
self.units = hass.config.units
self.data = data
self._name = name
@property
def name(self):
"""Return the name of the Smart Plug."""
return self._name
@property
def device_state_attributes(self):
"""Return the state attributes of the device."""
try:
ui_temp = self.units.temperature(
int(self.data.temperature), TEMP_CELSIUS)
temperature = ui_temp
except (ValueError, TypeError):
temperature = None
try:
total_consumption = float(self.data.total_consumption)
except (ValueError, TypeError):
total_consumption = None
attrs = {
ATTR_TOTAL_CONSUMPTION: total_consumption,
ATTR_TEMPERATURE: temperature,
}
return attrs
@property
def current_power_w(self):
"""Return the current power usage in Watt."""
try:
return float(self.data.current_consumption)
except (ValueError, TypeError):
return None
@property
def is_on(self):
"""Return true if switch is on."""
return self.data.state == 'ON'
def turn_on(self, **kwargs):
"""Turn the switch on."""
self.data.smartplug.state = 'ON'
def turn_off(self, **kwargs):
"""Turn the switch off."""
self.data.smartplug.state = 'OFF'
def update(self):
"""Get the latest data from the smart plug and updates the states."""
self.data.update()
@property
def available(self) -> bool:
"""Return True if entity is available."""
return self.data.available
class SmartPlugData:
"""Get the latest data from smart plug."""
def __init__(self, smartplug):
"""Initialize the data object."""
self.smartplug = smartplug
self.state = None
self.temperature = None
self.current_consumption = None
self.total_consumption = None
self.available = False
self._n_tried = 0
self._last_tried = None
def update(self):
"""Get the latest data from the smart plug."""
if self._last_tried is not None:
last_try_s = (dt_util.now() - self._last_tried).total_seconds()/60
retry_seconds = min(self._n_tried*2, 10) - last_try_s
if self._n_tried > 0 and retry_seconds > 0:
_LOGGER.warning("Waiting %s s to retry", retry_seconds)
return
_state = 'unknown'
try:
self._last_tried = dt_util.now()
_state = self.smartplug.state
except urllib.error.HTTPError:
_LOGGER.error("D-Link connection problem")
if _state == 'unknown':
self._n_tried += 1
self.available = False
_LOGGER.warning("Failed to connect to D-Link switch")
return
self.state = _state
self.available = True
self.temperature = self.smartplug.temperature
self.current_consumption = self.smartplug.current_consumption
self.total_consumption = self.smartplug.total_consumption
self._n_tried = 0
-94
View File
@@ -1,94 +0,0 @@
"""
Support for Edimax switches.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/switch.edimax/
"""
import logging
import voluptuous as vol
from homeassistant.components.switch import (SwitchDevice, PLATFORM_SCHEMA)
from homeassistant.const import (
CONF_HOST, CONF_NAME, CONF_PASSWORD, CONF_USERNAME)
import homeassistant.helpers.config_validation as cv
REQUIREMENTS = ['pyedimax==0.1']
_LOGGER = logging.getLogger(__name__)
DEFAULT_NAME = 'Edimax Smart Plug'
DEFAULT_PASSWORD = '1234'
DEFAULT_USERNAME = 'admin'
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Required(CONF_HOST): cv.string,
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
vol.Optional(CONF_PASSWORD, default=DEFAULT_PASSWORD): cv.string,
vol.Optional(CONF_USERNAME, default=DEFAULT_USERNAME): cv.string,
})
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Find and return Edimax Smart Plugs."""
from pyedimax.smartplug import SmartPlug
host = config.get(CONF_HOST)
auth = (config.get(CONF_USERNAME), config.get(CONF_PASSWORD))
name = config.get(CONF_NAME)
add_entities([SmartPlugSwitch(SmartPlug(host, auth), name)])
class SmartPlugSwitch(SwitchDevice):
"""Representation an Edimax Smart Plug switch."""
def __init__(self, smartplug, name):
"""Initialize the switch."""
self.smartplug = smartplug
self._name = name
self._now_power = None
self._now_energy_day = None
self._state = False
@property
def name(self):
"""Return the name of the Smart Plug, if any."""
return self._name
@property
def current_power_w(self):
"""Return the current power usage in W."""
return self._now_power
@property
def today_energy_kwh(self):
"""Return the today total energy usage in kWh."""
return self._now_energy_day
@property
def is_on(self):
"""Return true if switch is on."""
return self._state
def turn_on(self, **kwargs):
"""Turn the switch on."""
self.smartplug.state = 'ON'
def turn_off(self, **kwargs):
"""Turn the switch off."""
self.smartplug.state = 'OFF'
def update(self):
"""Update edimax switch."""
try:
self._now_power = float(self.smartplug.now_power)
except (TypeError, ValueError):
self._now_power = None
try:
self._now_energy_day = float(self.smartplug.now_energy_day)
except (TypeError, ValueError):
self._now_energy_day = None
self._state = self.smartplug.state == 'ON'
@@ -1,221 +0,0 @@
"""
Support for FRITZ!DECT Switches.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/switch.fritzdect/
"""
import logging
from requests.exceptions import RequestException, HTTPError
import voluptuous as vol
from homeassistant.components.switch import (SwitchDevice, PLATFORM_SCHEMA)
from homeassistant.const import (
CONF_HOST, CONF_PASSWORD, CONF_USERNAME, POWER_WATT, ENERGY_KILO_WATT_HOUR)
import homeassistant.helpers.config_validation as cv
from homeassistant.const import TEMP_CELSIUS, ATTR_TEMPERATURE
REQUIREMENTS = ['fritzhome==1.0.4']
_LOGGER = logging.getLogger(__name__)
# Standard Fritz Box IP
DEFAULT_HOST = 'fritz.box'
ATTR_CURRENT_CONSUMPTION = 'current_consumption'
ATTR_CURRENT_CONSUMPTION_UNIT = 'current_consumption_unit'
ATTR_CURRENT_CONSUMPTION_UNIT_VALUE = POWER_WATT
ATTR_TOTAL_CONSUMPTION = 'total_consumption'
ATTR_TOTAL_CONSUMPTION_UNIT = 'total_consumption_unit'
ATTR_TOTAL_CONSUMPTION_UNIT_VALUE = ENERGY_KILO_WATT_HOUR
ATTR_TEMPERATURE_UNIT = 'temperature_unit'
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Optional(CONF_HOST, default=DEFAULT_HOST): cv.string,
vol.Required(CONF_USERNAME): cv.string,
vol.Required(CONF_PASSWORD): cv.string,
})
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Add all switches connected to Fritz Box."""
from fritzhome.fritz import FritzBox
host = config.get(CONF_HOST)
username = config.get(CONF_USERNAME)
password = config.get(CONF_PASSWORD)
# Log into Fritz Box
fritz = FritzBox(host, username, password)
try:
fritz.login()
except Exception: # pylint: disable=broad-except
_LOGGER.error("Login to Fritz!Box failed")
return
# Add all actors to hass
for actor in fritz.get_actors():
# Only add devices that support switching
if actor.has_switch:
data = FritzDectSwitchData(fritz, actor.actor_id)
data.is_online = True
add_entities([FritzDectSwitch(hass, data, actor.name)], True)
class FritzDectSwitch(SwitchDevice):
"""Representation of a FRITZ!DECT switch."""
def __init__(self, hass, data, name):
"""Initialize the switch."""
self.units = hass.config.units
self.data = data
self._name = name
@property
def name(self):
"""Return the name of the FRITZ!DECT switch, if any."""
return self._name
@property
def device_state_attributes(self):
"""Return the state attributes of the device."""
attrs = {}
if self.data.has_powermeter and \
self.data.current_consumption is not None and \
self.data.total_consumption is not None:
attrs[ATTR_CURRENT_CONSUMPTION] = "{:.1f}".format(
self.data.current_consumption)
attrs[ATTR_CURRENT_CONSUMPTION_UNIT] = "{}".format(
ATTR_CURRENT_CONSUMPTION_UNIT_VALUE)
attrs[ATTR_TOTAL_CONSUMPTION] = "{:.3f}".format(
self.data.total_consumption)
attrs[ATTR_TOTAL_CONSUMPTION_UNIT] = "{}".format(
ATTR_TOTAL_CONSUMPTION_UNIT_VALUE)
if self.data.has_temperature and \
self.data.temperature is not None:
attrs[ATTR_TEMPERATURE] = "{}".format(
self.units.temperature(self.data.temperature, TEMP_CELSIUS))
attrs[ATTR_TEMPERATURE_UNIT] = "{}".format(
self.units.temperature_unit)
return attrs
@property
def current_power_w(self):
"""Return the current power usage in Watt."""
try:
return float(self.data.current_consumption)
except ValueError:
return None
@property
def is_on(self):
"""Return true if switch is on."""
return self.data.state
def turn_on(self, **kwargs):
"""Turn the switch on."""
if not self.data.is_online:
_LOGGER.error("turn_on: Not online skipping request")
return
try:
actor = self.data.fritz.get_actor_by_ain(self.data.ain)
actor.switch_on()
except (RequestException, HTTPError):
_LOGGER.error("Fritz!Box query failed, triggering relogin")
self.data.is_online = False
def turn_off(self, **kwargs):
"""Turn the switch off."""
if not self.data.is_online:
_LOGGER.error("turn_off: Not online skipping request")
return
try:
actor = self.data.fritz.get_actor_by_ain(self.data.ain)
actor.switch_off()
except (RequestException, HTTPError):
_LOGGER.error("Fritz!Box query failed, triggering relogin")
self.data.is_online = False
def update(self):
"""Get the latest data from the fritz box and updates the states."""
if not self.data.is_online:
_LOGGER.error("update: Not online, logging back in")
try:
self.data.fritz.login()
except Exception: # pylint: disable=broad-except
_LOGGER.error("Login to Fritz!Box failed")
return
self.data.is_online = True
try:
self.data.update()
except Exception: # pylint: disable=broad-except
_LOGGER.error("Fritz!Box query failed, triggering relogin")
self.data.is_online = False
class FritzDectSwitchData:
"""Get the latest data from the fritz box."""
def __init__(self, fritz, ain):
"""Initialize the data object."""
self.fritz = fritz
self.ain = ain
self.state = None
self.temperature = None
self.current_consumption = None
self.total_consumption = None
self.has_switch = False
self.has_temperature = False
self.has_powermeter = False
self.is_online = False
def update(self):
"""Get the latest data from the fritz box."""
if not self.is_online:
_LOGGER.error("Not online skipping request")
return
try:
actor = self.fritz.get_actor_by_ain(self.ain)
except (RequestException, HTTPError):
_LOGGER.error("Request to actor registry failed")
self.state = None
self.temperature = None
self.current_consumption = None
self.total_consumption = None
raise Exception('Request to actor registry failed')
if actor is None:
_LOGGER.error("Actor could not be found")
self.state = None
self.temperature = None
self.current_consumption = None
self.total_consumption = None
raise Exception('Actor could not be found')
try:
self.state = actor.get_state()
self.current_consumption = (actor.get_power() or 0.0) / 1000
self.total_consumption = (actor.get_energy() or 0.0) / 100000
except (RequestException, HTTPError):
_LOGGER.error("Request to actor failed")
self.state = None
self.temperature = None
self.current_consumption = None
self.total_consumption = None
raise Exception('Request to actor failed')
self.temperature = actor.temperature
self.has_switch = actor.has_switch
self.has_temperature = actor.has_temperature
self.has_powermeter = actor.has_powermeter
@@ -1,106 +0,0 @@
"""
Support turning on/off motion detection on Hikvision cameras.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/switch.hikvision/
"""
import logging
import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.const import (
CONF_NAME, CONF_HOST, CONF_PASSWORD, CONF_USERNAME, CONF_PORT, STATE_OFF,
STATE_ON)
from homeassistant.helpers.entity import ToggleEntity
import homeassistant.helpers.config_validation as cv
REQUIREMENTS = ['hikvision==0.4']
# This is the last working version, please test before updating
_LOGGING = logging.getLogger(__name__)
DEFAULT_NAME = 'Hikvision Camera Motion Detection'
DEFAULT_PASSWORD = '12345'
DEFAULT_PORT = 80
DEFAULT_USERNAME = 'admin'
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Required(CONF_HOST): cv.string,
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
vol.Optional(CONF_PASSWORD, default=DEFAULT_PASSWORD): cv.string,
vol.Optional(CONF_PORT): cv.port,
vol.Optional(CONF_USERNAME, default=DEFAULT_USERNAME): cv.string,
})
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up Hikvision camera."""
import hikvision.api
from hikvision.error import HikvisionError, MissingParamError
host = config.get(CONF_HOST)
port = config.get(CONF_PORT)
name = config.get(CONF_NAME)
username = config.get(CONF_USERNAME)
password = config.get(CONF_PASSWORD)
try:
hikvision_cam = hikvision.api.CreateDevice(
host, port=port, username=username, password=password,
is_https=False)
except MissingParamError as param_err:
_LOGGING.error("Missing required param: %s", param_err)
return False
except HikvisionError as conn_err:
_LOGGING.error("Unable to connect: %s", conn_err)
return False
add_entities([HikvisionMotionSwitch(name, hikvision_cam)])
class HikvisionMotionSwitch(ToggleEntity):
"""Representation of a switch to toggle on/off motion detection."""
def __init__(self, name, hikvision_cam):
"""Initialize the switch."""
self._name = name
self._hikvision_cam = hikvision_cam
self._state = STATE_OFF
@property
def should_poll(self):
"""Poll for status regularly."""
return True
@property
def name(self):
"""Return the name of the device if any."""
return self._name
@property
def state(self):
"""Return the state of the device if any."""
return self._state
@property
def is_on(self):
"""Return true if device is on."""
return self._state == STATE_ON
def turn_on(self, **kwargs):
"""Turn the device on."""
_LOGGING.info("Turning on Motion Detection ")
self._hikvision_cam.enable_motion_detection()
def turn_off(self, **kwargs):
"""Turn the device off."""
_LOGGING.info("Turning off Motion Detection ")
self._hikvision_cam.disable_motion_detection()
def update(self):
"""Update Motion Detection state."""
enabled = self._hikvision_cam.is_motion_detection_enabled()
_LOGGING.info("enabled: %s", enabled)
self._state = STATE_ON if enabled else STATE_OFF
-138
View File
@@ -1,138 +0,0 @@
"""
Support Hook, available at hooksmarthome.com.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/switch.hook/
"""
import logging
import asyncio
import voluptuous as vol
import async_timeout
import aiohttp
from homeassistant.components.switch import (SwitchDevice, PLATFORM_SCHEMA)
from homeassistant.const import CONF_PASSWORD, CONF_USERNAME, CONF_TOKEN
from homeassistant.helpers.aiohttp_client import async_get_clientsession
import homeassistant.helpers.config_validation as cv
_LOGGER = logging.getLogger(__name__)
HOOK_ENDPOINT = 'https://api.gethook.io/v1/'
TIMEOUT = 10
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Exclusive(CONF_PASSWORD, 'hook_secret', msg='hook: provide ' +
'username/password OR token'): cv.string,
vol.Exclusive(CONF_TOKEN, 'hook_secret', msg='hook: provide ' +
'username/password OR token'): cv.string,
vol.Inclusive(CONF_USERNAME, 'hook_auth'): cv.string,
vol.Inclusive(CONF_PASSWORD, 'hook_auth'): cv.string,
})
async def async_setup_platform(hass, config, async_add_entities,
discovery_info=None):
"""Set up Hook by getting the access token and list of actions."""
username = config.get(CONF_USERNAME)
password = config.get(CONF_PASSWORD)
token = config.get(CONF_TOKEN)
websession = async_get_clientsession(hass)
# If password is set in config, prefer it over token
if username is not None and password is not None:
try:
with async_timeout.timeout(TIMEOUT, loop=hass.loop):
response = await websession.post(
'{}{}'.format(HOOK_ENDPOINT, 'user/login'),
data={
'username': username,
'password': password})
# The Hook API returns JSON but calls it 'text/html'. Setting
# content_type=None disables aiohttp's content-type validation.
data = await response.json(content_type=None)
except (asyncio.TimeoutError, aiohttp.ClientError) as error:
_LOGGER.error("Failed authentication API call: %s", error)
return False
try:
token = data['data']['token']
except KeyError:
_LOGGER.error("No token. Check username and password")
return False
try:
with async_timeout.timeout(TIMEOUT, loop=hass.loop):
response = await websession.get(
'{}{}'.format(HOOK_ENDPOINT, 'device'),
params={"token": token})
data = await response.json(content_type=None)
except (asyncio.TimeoutError, aiohttp.ClientError) as error:
_LOGGER.error("Failed getting devices: %s", error)
return False
async_add_entities(
HookSmartHome(
hass,
token,
d['device_id'],
d['device_name'])
for lst in data['data']
for d in lst)
class HookSmartHome(SwitchDevice):
"""Representation of a Hook device, allowing on and off commands."""
def __init__(self, hass, token, device_id, device_name):
"""Initialize the switch."""
self.hass = hass
self._token = token
self._state = False
self._id = device_id
self._name = device_name
_LOGGER.debug(
"Creating Hook object: ID: %s Name: %s", self._id, self._name)
@property
def name(self):
"""Return the name of the switch."""
return self._name
@property
def is_on(self):
"""Return true if device is on."""
return self._state
async def _send(self, url):
"""Send the url to the Hook API."""
try:
_LOGGER.debug("Sending: %s", url)
websession = async_get_clientsession(self.hass)
with async_timeout.timeout(TIMEOUT, loop=self.hass.loop):
response = await websession.get(
url, params={"token": self._token})
data = await response.json(content_type=None)
except (asyncio.TimeoutError, aiohttp.ClientError) as error:
_LOGGER.error("Failed setting state: %s", error)
return False
_LOGGER.debug("Got: %s", data)
return data['return_value'] == '1'
async def async_turn_on(self, **kwargs):
"""Turn the device on asynchronously."""
_LOGGER.debug("Turning on: %s", self._name)
url = '{}{}{}{}'.format(
HOOK_ENDPOINT, 'device/trigger/', self._id, '/On')
success = await self._send(url)
self._state = success
async def async_turn_off(self, **kwargs):
"""Turn the device off asynchronously."""
_LOGGER.debug("Turning off: %s", self._name)
url = '{}{}{}{}'.format(
HOOK_ENDPOINT, 'device/trigger/', self._id, '/Off')
success = await self._send(url)
# If it wasn't successful, keep state as true
self._state = not success
-119
View File
@@ -1,119 +0,0 @@
"""
Support for customised Kankun SP3 Wifi switch.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/switch.kankun/
"""
import logging
import requests
import voluptuous as vol
from homeassistant.components.switch import SwitchDevice, PLATFORM_SCHEMA
from homeassistant.const import (
CONF_HOST, CONF_NAME, CONF_PORT, CONF_PATH, CONF_USERNAME, CONF_PASSWORD,
CONF_SWITCHES)
import homeassistant.helpers.config_validation as cv
_LOGGER = logging.getLogger(__name__)
DEFAULT_PORT = 80
DEFAULT_PATH = "/cgi-bin/json.cgi"
SWITCH_SCHEMA = vol.Schema({
vol.Required(CONF_HOST): cv.string,
vol.Optional(CONF_NAME): cv.string,
vol.Optional(CONF_PORT, default=DEFAULT_PORT): cv.port,
vol.Optional(CONF_PATH, default=DEFAULT_PATH): cv.string,
vol.Optional(CONF_USERNAME): cv.string,
vol.Optional(CONF_PASSWORD): cv.string,
})
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Required(CONF_SWITCHES): cv.schema_with_slug_keys(SWITCH_SCHEMA),
})
def setup_platform(hass, config, add_entities_callback, discovery_info=None):
"""Set up Kankun Wifi switches."""
switches = config.get('switches', {})
devices = []
for dev_name, properties in switches.items():
devices.append(
KankunSwitch(
hass,
properties.get(CONF_NAME, dev_name),
properties.get(CONF_HOST, None),
properties.get(CONF_PORT, DEFAULT_PORT),
properties.get(CONF_PATH, DEFAULT_PATH),
properties.get(CONF_USERNAME, None),
properties.get(CONF_PASSWORD)))
add_entities_callback(devices)
class KankunSwitch(SwitchDevice):
"""Representation of a Kankun Wifi switch."""
def __init__(self, hass, name, host, port, path, user, passwd):
"""Initialize the device."""
self._hass = hass
self._name = name
self._state = False
self._url = 'http://{}:{}{}'.format(host, port, path)
if user is not None:
self._auth = (user, passwd)
else:
self._auth = None
def _switch(self, newstate):
"""Switch on or off."""
_LOGGER.info("Switching to state: %s", newstate)
try:
req = requests.get('{}?set={}'.format(self._url, newstate),
auth=self._auth, timeout=5)
return req.json()['ok']
except requests.RequestException:
_LOGGER.error("Switching failed")
def _query_state(self):
"""Query switch state."""
_LOGGER.info("Querying state from: %s", self._url)
try:
req = requests.get('{}?get=state'.format(self._url),
auth=self._auth, timeout=5)
return req.json()['state'] == "on"
except requests.RequestException:
_LOGGER.error("State query failed")
@property
def should_poll(self):
"""Return the polling state."""
return True
@property
def name(self):
"""Return the name of the switch."""
return self._name
@property
def is_on(self):
"""Return true if device is on."""
return self._state
def update(self):
"""Update device state."""
self._state = self._query_state()
def turn_on(self, **kwargs):
"""Turn the device on."""
if self._switch('on'):
self._state = True
def turn_off(self, **kwargs):
"""Turn the device off."""
if self._switch('off'):
self._state = False
@@ -1,89 +0,0 @@
"""Support for myStrom switches."""
import logging
import voluptuous as vol
from homeassistant.components.switch import (SwitchDevice, PLATFORM_SCHEMA)
from homeassistant.const import (CONF_NAME, CONF_HOST)
import homeassistant.helpers.config_validation as cv
REQUIREMENTS = ['python-mystrom==0.5.0']
DEFAULT_NAME = 'myStrom Switch'
_LOGGER = logging.getLogger(__name__)
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Required(CONF_HOST): cv.string,
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
})
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Find and return myStrom switch."""
from pymystrom.switch import MyStromPlug, exceptions
name = config.get(CONF_NAME)
host = config.get(CONF_HOST)
try:
MyStromPlug(host).get_status()
except exceptions.MyStromConnectionError:
_LOGGER.error("No route to device: %s", host)
return
add_entities([MyStromSwitch(name, host)])
class MyStromSwitch(SwitchDevice):
"""Representation of a myStrom switch."""
def __init__(self, name, resource):
"""Initialize the myStrom switch."""
from pymystrom.switch import MyStromPlug
self._name = name
self._resource = resource
self.data = {}
self.plug = MyStromPlug(self._resource)
self.update()
@property
def name(self):
"""Return the name of the switch."""
return self._name
@property
def is_on(self):
"""Return true if switch is on."""
return bool(self.data['relay'])
@property
def current_power_w(self):
"""Return the current power consumption in W."""
return round(self.data['power'], 2)
def turn_on(self, **kwargs):
"""Turn the switch on."""
from pymystrom import exceptions
try:
self.plug.set_relay_on()
except exceptions.MyStromConnectionError:
_LOGGER.error("No route to device: %s", self._resource)
def turn_off(self, **kwargs):
"""Turn the switch off."""
from pymystrom import exceptions
try:
self.plug.set_relay_off()
except exceptions.MyStromConnectionError:
_LOGGER.error("No route to device: %s", self._resource)
def update(self):
"""Get the latest data from the device and update the data."""
from pymystrom import exceptions
try:
self.data = self.plug.get_status()
except exceptions.MyStromConnectionError:
self.data = {'power': 0, 'relay': False}
_LOGGER.error("No route to device: %s", self._resource)
-189
View File
@@ -1,189 +0,0 @@
"""
The Netio switch component.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/switch.netio/
"""
import logging
from collections import namedtuple
from datetime import timedelta
import voluptuous as vol
from homeassistant.core import callback
from homeassistant import util
from homeassistant.components.http import HomeAssistantView
from homeassistant.const import (
CONF_HOST, CONF_PORT, CONF_USERNAME, CONF_PASSWORD,
EVENT_HOMEASSISTANT_STOP, STATE_ON)
from homeassistant.components.switch import (SwitchDevice, PLATFORM_SCHEMA)
import homeassistant.helpers.config_validation as cv
REQUIREMENTS = ['pynetio==0.1.9.1']
_LOGGER = logging.getLogger(__name__)
ATTR_START_DATE = 'start_date'
ATTR_TOTAL_CONSUMPTION_KWH = 'total_energy_kwh'
CONF_OUTLETS = 'outlets'
DEFAULT_PORT = 1234
DEFAULT_USERNAME = 'admin'
DEPENDENCIES = ['http']
Device = namedtuple('device', ['netio', 'entities'])
DEVICES = {}
MIN_TIME_BETWEEN_SCANS = timedelta(seconds=10)
REQ_CONF = [CONF_HOST, CONF_OUTLETS]
URL_API_NETIO_EP = '/api/netio/{host}'
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Required(CONF_HOST): cv.string,
vol.Required(CONF_PORT, default=DEFAULT_PORT): cv.port,
vol.Required(CONF_USERNAME, default=DEFAULT_USERNAME): cv.string,
vol.Required(CONF_PASSWORD): cv.string,
vol.Optional(CONF_OUTLETS): {cv.string: cv.string},
})
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the Netio platform."""
from pynetio import Netio
host = config.get(CONF_HOST)
username = config.get(CONF_USERNAME)
password = config.get(CONF_PASSWORD)
port = config.get(CONF_PORT)
if not DEVICES:
hass.http.register_view(NetioApiView)
dev = Netio(host, port, username, password)
DEVICES[host] = Device(dev, [])
# Throttle the update for all Netio switches of one Netio
dev.update = util.Throttle(MIN_TIME_BETWEEN_SCANS)(dev.update)
for key in config[CONF_OUTLETS]:
switch = NetioSwitch(
DEVICES[host].netio, key, config[CONF_OUTLETS][key])
DEVICES[host].entities.append(switch)
add_entities(DEVICES[host].entities)
hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, dispose)
return True
def dispose(event):
"""Close connections to Netio Devices."""
for _, value in DEVICES.items():
value.netio.stop()
class NetioApiView(HomeAssistantView):
"""WSGI handler class."""
url = URL_API_NETIO_EP
name = 'api:netio'
@callback
def get(self, request, host):
"""Request handler."""
hass = request.app['hass']
data = request.query
states, consumptions, cumulated_consumptions, start_dates = \
[], [], [], []
for i in range(1, 5):
out = 'output%d' % i
states.append(data.get('%s_state' % out) == STATE_ON)
consumptions.append(float(data.get('%s_consumption' % out, 0)))
cumulated_consumptions.append(
float(data.get('%s_cumulatedConsumption' % out, 0)) / 1000)
start_dates.append(data.get('%s_consumptionStart' % out, ""))
_LOGGER.debug('%s: %s, %s, %s since %s', host, states,
consumptions, cumulated_consumptions, start_dates)
ndev = DEVICES[host].netio
ndev.consumptions = consumptions
ndev.cumulated_consumptions = cumulated_consumptions
ndev.states = states
ndev.start_dates = start_dates
for dev in DEVICES[host].entities:
hass.async_create_task(dev.async_update_ha_state())
return self.json(True)
class NetioSwitch(SwitchDevice):
"""Provide a Netio linked switch."""
def __init__(self, netio, outlet, name):
"""Initialize the Netio switch."""
self._name = name
self.outlet = outlet
self.netio = netio
@property
def name(self):
"""Return the device's name."""
return self._name
@property
def available(self):
"""Return true if entity is available."""
return not hasattr(self, 'telnet')
def turn_on(self, **kwargs):
"""Turn switch on."""
self._set(True)
def turn_off(self, **kwargs):
"""Turn switch off."""
self._set(False)
def _set(self, value):
val = list('uuuu')
val[int(self.outlet) - 1] = '1' if value else '0'
self.netio.get('port list %s' % ''.join(val))
self.netio.states[int(self.outlet) - 1] = value
self.schedule_update_ha_state()
@property
def is_on(self):
"""Return the switch's status."""
return self.netio.states[int(self.outlet) - 1]
def update(self):
"""Update the state."""
self.netio.update()
@property
def state_attributes(self):
"""Return optional state attributes."""
return {
ATTR_TOTAL_CONSUMPTION_KWH: self.cumulated_consumption_kwh,
ATTR_START_DATE: self.start_date.split('|')[0]
}
@property
def current_power_w(self):
"""Return actual power."""
return self.netio.consumptions[int(self.outlet) - 1]
@property
def cumulated_consumption_kwh(self):
"""Return the total enerygy consumption since start_date."""
return self.netio.cumulated_consumptions[int(self.outlet) - 1]
@property
def start_date(self):
"""Point in time when the energy accumulation started."""
return self.netio.start_dates[int(self.outlet) - 1]
-106
View File
@@ -1,106 +0,0 @@
"""
Support for Orvibo S20 Wifi Smart Switches.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/switch.orvibo/
"""
import logging
import voluptuous as vol
from homeassistant.components.switch import (SwitchDevice, PLATFORM_SCHEMA)
from homeassistant.const import (
CONF_HOST, CONF_NAME, CONF_SWITCHES, CONF_MAC, CONF_DISCOVERY)
import homeassistant.helpers.config_validation as cv
REQUIREMENTS = ['orvibo==1.1.1']
_LOGGER = logging.getLogger(__name__)
DEFAULT_NAME = 'Orvibo S20 Switch'
DEFAULT_DISCOVERY = True
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Required(CONF_SWITCHES, default=[]):
vol.All(cv.ensure_list, [{
vol.Required(CONF_HOST): cv.string,
vol.Optional(CONF_MAC): cv.string,
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string
}]),
vol.Optional(CONF_DISCOVERY, default=DEFAULT_DISCOVERY): cv.boolean,
})
def setup_platform(hass, config, add_entities_callback, discovery_info=None):
"""Set up S20 switches."""
from orvibo.s20 import discover, S20, S20Exception
switch_data = {}
switches = []
switch_conf = config.get(CONF_SWITCHES, [config])
if config.get(CONF_DISCOVERY):
_LOGGER.info("Discovering S20 switches ...")
switch_data.update(discover())
for switch in switch_conf:
switch_data[switch.get(CONF_HOST)] = switch
for host, data in switch_data.items():
try:
switches.append(S20Switch(data.get(CONF_NAME),
S20(host, mac=data.get(CONF_MAC))))
_LOGGER.info("Initialized S20 at %s", host)
except S20Exception:
_LOGGER.error("S20 at %s couldn't be initialized", host)
add_entities_callback(switches)
class S20Switch(SwitchDevice):
"""Representation of an S20 switch."""
def __init__(self, name, s20):
"""Initialize the S20 device."""
from orvibo.s20 import S20Exception
self._name = name
self._s20 = s20
self._state = False
self._exc = S20Exception
@property
def should_poll(self):
"""Return the polling state."""
return True
@property
def name(self):
"""Return the name of the switch."""
return self._name
@property
def is_on(self):
"""Return true if device is on."""
return self._state
def update(self):
"""Update device state."""
try:
self._state = self._s20.on
except self._exc:
_LOGGER.exception("Error while fetching S20 state")
def turn_on(self, **kwargs):
"""Turn the device on."""
try:
self._s20.on = True
except self._exc:
_LOGGER.exception("Error while turning on S20")
def turn_off(self, **kwargs):
"""Turn the device off."""
try:
self._s20.on = False
except self._exc:
_LOGGER.exception("Error while turning off S20")
-101
View File
@@ -1,101 +0,0 @@
"""Pencom relay control.
For more details about this component, please refer to the documentation at
http://home-assistant.io/components/switch.pencom
"""
import logging
import voluptuous as vol
from homeassistant.components.switch import SwitchDevice, PLATFORM_SCHEMA
from homeassistant.const import CONF_HOST, CONF_PORT, CONF_NAME
from homeassistant.exceptions import PlatformNotReady
import homeassistant.helpers.config_validation as cv
REQUIREMENTS = ['pencompy==0.0.3']
_LOGGER = logging.getLogger(__name__)
CONF_BOARDS = 'boards'
CONF_BOARD = 'board'
CONF_ADDR = 'addr'
CONF_RELAYS = 'relays'
RELAY_SCHEMA = vol.Schema({
vol.Required(CONF_NAME): cv.string,
vol.Required(CONF_ADDR): cv.positive_int,
vol.Optional(CONF_BOARD, default=0): cv.positive_int,
})
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Required(CONF_HOST): cv.string,
vol.Required(CONF_PORT): cv.port,
vol.Optional(CONF_BOARDS, default=1): cv.positive_int,
vol.Required(CONF_RELAYS): vol.All(cv.ensure_list, [RELAY_SCHEMA]),
})
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Pencom relay platform (pencompy)."""
from pencompy.pencompy import Pencompy
# Assign configuration variables.
host = config[CONF_HOST]
port = config[CONF_PORT]
boards = config[CONF_BOARDS]
# Setup connection
try:
hub = Pencompy(host, port, boards=boards)
except OSError as error:
_LOGGER.error("Could not connect to pencompy: %s", error)
raise PlatformNotReady
# Add devices.
devs = []
for relay in config[CONF_RELAYS]:
name = relay[CONF_NAME]
board = relay[CONF_BOARD]
addr = relay[CONF_ADDR]
devs.append(PencomRelay(hub, board, addr, name))
add_entities(devs, True)
class PencomRelay(SwitchDevice):
"""Representation of a pencom relay."""
def __init__(self, hub, board, addr, name):
"""Create a relay."""
self._hub = hub
self._board = board
self._addr = addr
self._name = name
self._state = None
@property
def name(self):
"""Relay name."""
return self._name
@property
def is_on(self):
"""Return a relay's state."""
return self._state
def turn_on(self, **kwargs):
"""Turn a relay on."""
self._hub.set(self._board, self._addr, True)
def turn_off(self, **kwargs):
"""Turn a relay off."""
self._hub.set(self._board, self._addr, False)
def update(self):
"""Refresh a relay's state."""
self._state = self._hub.get(self._board, self._addr)
@property
def device_state_attributes(self):
"""Return supported attributes."""
return {"board": self._board,
"addr": self._addr}
@@ -1,191 +0,0 @@
"""
Switch logic for loading/unloading pulseaudio loopback modules.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/switch.pulseaudio_loopback/
"""
import logging
import re
import socket
from datetime import timedelta
import voluptuous as vol
from homeassistant import util
from homeassistant.components.switch import (SwitchDevice, PLATFORM_SCHEMA)
from homeassistant.const import (CONF_NAME, CONF_HOST, CONF_PORT)
import homeassistant.helpers.config_validation as cv
_LOGGER = logging.getLogger(__name__)
_PULSEAUDIO_SERVERS = {}
CONF_BUFFER_SIZE = 'buffer_size'
CONF_SINK_NAME = 'sink_name'
CONF_SOURCE_NAME = 'source_name'
CONF_TCP_TIMEOUT = 'tcp_timeout'
DEFAULT_BUFFER_SIZE = 1024
DEFAULT_HOST = 'localhost'
DEFAULT_NAME = 'paloopback'
DEFAULT_PORT = 4712
DEFAULT_TCP_TIMEOUT = 3
IGNORED_SWITCH_WARN = "Switch is already in the desired state. Ignoring."
LOAD_CMD = "load-module module-loopback sink={0} source={1}"
MIN_TIME_BETWEEN_FORCED_SCANS = timedelta(milliseconds=100)
MIN_TIME_BETWEEN_SCANS = timedelta(seconds=10)
MOD_REGEX = r"index: ([0-9]+)\s+name: <module-loopback>" \
r"\s+argument: (?=<.*sink={0}.*>)(?=<.*source={1}.*>)"
UNLOAD_CMD = "unload-module {0}"
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Required(CONF_SINK_NAME): cv.string,
vol.Required(CONF_SOURCE_NAME): cv.string,
vol.Optional(CONF_BUFFER_SIZE, default=DEFAULT_BUFFER_SIZE):
cv.positive_int,
vol.Optional(CONF_HOST, default=DEFAULT_HOST): cv.string,
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
vol.Optional(CONF_PORT, default=DEFAULT_PORT): cv.port,
vol.Optional(CONF_TCP_TIMEOUT, default=DEFAULT_TCP_TIMEOUT):
cv.positive_int,
})
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Read in all of our configuration, and initialize the loopback switch."""
name = config.get(CONF_NAME)
sink_name = config.get(CONF_SINK_NAME)
source_name = config.get(CONF_SOURCE_NAME)
host = config.get(CONF_HOST)
port = config.get(CONF_PORT)
buffer_size = config.get(CONF_BUFFER_SIZE)
tcp_timeout = config.get(CONF_TCP_TIMEOUT)
server_id = str.format("{0}:{1}", host, port)
if server_id in _PULSEAUDIO_SERVERS:
server = _PULSEAUDIO_SERVERS[server_id]
else:
server = PAServer(host, port, buffer_size, tcp_timeout)
_PULSEAUDIO_SERVERS[server_id] = server
add_entities([
PALoopbackSwitch(hass, name, server, sink_name, source_name)])
class PAServer():
"""Representation of a Pulseaudio server."""
_current_module_state = ""
def __init__(self, host, port, buff_sz, tcp_timeout):
"""Initialize PulseAudio server."""
self._pa_host = host
self._pa_port = int(port)
self._buffer_size = int(buff_sz)
self._tcp_timeout = int(tcp_timeout)
def _send_command(self, cmd, response_expected):
"""Send a command to the pa server using a socket."""
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(self._tcp_timeout)
try:
sock.connect((self._pa_host, self._pa_port))
_LOGGER.info("Calling pulseaudio: %s", cmd)
sock.send((cmd + "\n").encode("utf-8"))
if response_expected:
return_data = self._get_full_response(sock)
_LOGGER.debug("Data received from pulseaudio: %s", return_data)
else:
return_data = ""
finally:
sock.close()
return return_data
def _get_full_response(self, sock):
"""Get the full response back from pulseaudio."""
result = ""
rcv_buffer = sock.recv(self._buffer_size)
result += rcv_buffer.decode('utf-8')
while len(rcv_buffer) == self._buffer_size:
rcv_buffer = sock.recv(self._buffer_size)
result += rcv_buffer.decode('utf-8')
return result
@util.Throttle(MIN_TIME_BETWEEN_SCANS, MIN_TIME_BETWEEN_FORCED_SCANS)
def update_module_state(self):
"""Refresh state in case an alternate process modified this data."""
self._current_module_state = self._send_command("list-modules", True)
def turn_on(self, sink_name, source_name):
"""Send a command to pulseaudio to turn on the loopback."""
self._send_command(str.format(LOAD_CMD, sink_name, source_name), False)
def turn_off(self, module_idx):
"""Send a command to pulseaudio to turn off the loopback."""
self._send_command(str.format(UNLOAD_CMD, module_idx), False)
def get_module_idx(self, sink_name, source_name):
"""For a sink/source, return its module id in our cache, if found."""
result = re.search(str.format(MOD_REGEX, re.escape(sink_name),
re.escape(source_name)),
self._current_module_state)
if result and result.group(1).isdigit():
return int(result.group(1))
return -1
class PALoopbackSwitch(SwitchDevice):
"""Representation the presence or absence of a PA loopback module."""
def __init__(self, hass, name, pa_server, sink_name, source_name):
"""Initialize the Pulseaudio switch."""
self._module_idx = -1
self._hass = hass
self._name = name
self._sink_name = sink_name
self._source_name = source_name
self._pa_svr = pa_server
@property
def name(self):
"""Return the name of the switch."""
return self._name
@property
def is_on(self):
"""Return true if device is on."""
return self._module_idx > 0
def turn_on(self, **kwargs):
"""Turn the device on."""
if not self.is_on:
self._pa_svr.turn_on(self._sink_name, self._source_name)
self._pa_svr.update_module_state(no_throttle=True)
self._module_idx = self._pa_svr.get_module_idx(
self._sink_name, self._source_name)
self.schedule_update_ha_state()
else:
_LOGGER.warning(IGNORED_SWITCH_WARN)
def turn_off(self, **kwargs):
"""Turn the device off."""
if self.is_on:
self._pa_svr.turn_off(self._module_idx)
self._pa_svr.update_module_state(no_throttle=True)
self._module_idx = self._pa_svr.get_module_idx(
self._sink_name, self._source_name)
self.schedule_update_ha_state()
else:
_LOGGER.warning(IGNORED_SWITCH_WARN)
def update(self):
"""Refresh state in case an alternate process modified this data."""
self._pa_svr.update_module_state()
self._module_idx = self._pa_svr.get_module_idx(
self._sink_name, self._source_name)
@@ -1,92 +0,0 @@
"""
Support for Rain Bird Irrigation system LNK WiFi Module.
For more details about this component, please refer to the documentation at
https://home-assistant.io/components/switch.rainbird/
"""
import logging
import voluptuous as vol
from homeassistant.components.rainbird import DATA_RAINBIRD
from homeassistant.components.switch import (SwitchDevice, PLATFORM_SCHEMA)
from homeassistant.const import (CONF_SWITCHES, CONF_ZONE,
CONF_FRIENDLY_NAME, CONF_TRIGGER_TIME,
CONF_SCAN_INTERVAL)
from homeassistant.helpers import config_validation as cv
DEPENDENCIES = ['rainbird']
DOMAIN = 'rainbird'
_LOGGER = logging.getLogger(__name__)
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Required(CONF_SWITCHES, default={}): vol.Schema({
cv.string: {
vol.Optional(CONF_FRIENDLY_NAME): cv.string,
vol.Required(CONF_ZONE): cv.string,
vol.Required(CONF_TRIGGER_TIME): cv.string,
vol.Optional(CONF_SCAN_INTERVAL): cv.string,
},
}),
})
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up Rain Bird switches over a Rain Bird controller."""
controller = hass.data[DATA_RAINBIRD]
devices = []
for dev_id, switch in config.get(CONF_SWITCHES).items():
devices.append(RainBirdSwitch(controller, switch, dev_id))
add_entities(devices, True)
class RainBirdSwitch(SwitchDevice):
"""Representation of a Rain Bird switch."""
def __init__(self, rb, dev, dev_id):
"""Initialize a Rain Bird Switch Device."""
self._rainbird = rb
self._devid = dev_id
self._zone = int(dev.get(CONF_ZONE))
self._name = dev.get(CONF_FRIENDLY_NAME,
"Sprinkler {}".format(self._zone))
self._state = None
self._duration = dev.get(CONF_TRIGGER_TIME)
self._attributes = {
"duration": self._duration,
"zone": self._zone
}
@property
def device_state_attributes(self):
"""Return state attributes."""
return self._attributes
@property
def name(self):
"""Get the name of the switch."""
return self._name
def turn_on(self, **kwargs):
"""Turn the switch on."""
self._rainbird.startIrrigation(int(self._zone), int(self._duration))
def turn_off(self, **kwargs):
"""Turn the switch off."""
self._rainbird.stopIrrigation()
def get_device_status(self):
"""Get the status of the switch from Rain Bird Controller."""
return self._rainbird.currentIrrigation() == self._zone
def update(self):
"""Update switch status."""
self._state = self.get_device_status()
@property
def is_on(self):
"""Return true if switch is on."""
return self._state
-137
View File
@@ -1,137 +0,0 @@
"""
Support for switch devices that can be controlled using the RaspyRFM rc module.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/switch.raspyrfm/
"""
import logging
import voluptuous as vol
from homeassistant.components.switch import PLATFORM_SCHEMA, SwitchDevice
from homeassistant.const import (
CONF_HOST, CONF_NAME, CONF_PORT, CONF_SWITCHES,
DEVICE_DEFAULT_NAME)
import homeassistant.helpers.config_validation as cv
REQUIREMENTS = ['raspyrfm-client==1.2.8']
_LOGGER = logging.getLogger(__name__)
CONF_GATEWAY_MANUFACTURER = 'gateway_manufacturer'
CONF_GATEWAY_MODEL = 'gateway_model'
CONF_CONTROLUNIT_MANUFACTURER = 'controlunit_manufacturer'
CONF_CONTROLUNIT_MODEL = 'controlunit_model'
CONF_CHANNEL_CONFIG = 'channel_config'
DEFAULT_HOST = '127.0.0.1'
# define configuration parameters
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Optional(CONF_HOST, default=DEFAULT_HOST): cv.string,
vol.Optional(CONF_PORT): cv.port,
vol.Optional(CONF_GATEWAY_MANUFACTURER): cv.string,
vol.Optional(CONF_GATEWAY_MODEL): cv.string,
vol.Required(CONF_SWITCHES): vol.Schema([{
vol.Optional(CONF_NAME, default=DEVICE_DEFAULT_NAME): cv.string,
vol.Required(CONF_CONTROLUNIT_MANUFACTURER): cv.string,
vol.Required(CONF_CONTROLUNIT_MODEL): cv.string,
vol.Required(CONF_CHANNEL_CONFIG): {cv.string: cv.match_all},
}])
}, extra=vol.ALLOW_EXTRA)
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the RaspyRFM switch."""
from raspyrfm_client import RaspyRFMClient
from raspyrfm_client.device_implementations.controlunit. \
controlunit_constants import ControlUnitModel
from raspyrfm_client.device_implementations.gateway.manufacturer. \
gateway_constants import GatewayModel
from raspyrfm_client.device_implementations.manufacturer_constants \
import Manufacturer
gateway_manufacturer = config.get(CONF_GATEWAY_MANUFACTURER,
Manufacturer.SEEGEL_SYSTEME.value)
gateway_model = config.get(CONF_GATEWAY_MODEL, GatewayModel.RASPYRFM.value)
host = config[CONF_HOST]
port = config.get(CONF_PORT)
switches = config[CONF_SWITCHES]
raspyrfm_client = RaspyRFMClient()
gateway = raspyrfm_client.get_gateway(Manufacturer(gateway_manufacturer),
GatewayModel(gateway_model), host,
port)
switch_entities = []
for switch in switches:
name = switch[CONF_NAME]
controlunit_manufacturer = switch[CONF_CONTROLUNIT_MANUFACTURER]
controlunit_model = switch[CONF_CONTROLUNIT_MODEL]
channel_config = switch[CONF_CHANNEL_CONFIG]
controlunit = raspyrfm_client.get_controlunit(
Manufacturer(controlunit_manufacturer),
ControlUnitModel(controlunit_model))
controlunit.set_channel_config(**channel_config)
switch = RaspyRFMSwitch(raspyrfm_client, name, gateway, controlunit)
switch_entities.append(switch)
add_entities(switch_entities)
class RaspyRFMSwitch(SwitchDevice):
"""Representation of a RaspyRFM switch."""
def __init__(self, raspyrfm_client, name: str, gateway, controlunit):
"""Initialize the switch."""
self._raspyrfm_client = raspyrfm_client
self._name = name
self._gateway = gateway
self._controlunit = controlunit
self._state = None
@property
def name(self):
"""Return the name of the device if any."""
return self._name
@property
def should_poll(self):
"""Return True if polling should be used."""
return False
@property
def assumed_state(self):
"""Return True when the current state can not be queried."""
return True
@property
def is_on(self):
"""Return true if switch is on."""
return self._state
def turn_on(self, **kwargs):
"""Turn the switch on."""
from raspyrfm_client.device_implementations.controlunit.actions \
import Action
self._raspyrfm_client.send(self._gateway, self._controlunit, Action.ON)
self._state = True
self.schedule_update_ha_state()
def turn_off(self, **kwargs):
"""Turn the switch off."""
from raspyrfm_client.device_implementations.controlunit.actions \
import Action
if Action.OFF in self._controlunit.get_supported_actions():
self._raspyrfm_client.send(
self._gateway, self._controlunit, Action.OFF)
else:
self._raspyrfm_client.send(
self._gateway, self._controlunit, Action.ON)
self._state = False
self.schedule_update_ha_state()
@@ -1,101 +0,0 @@
"""
Support for Ankuoo RecSwitch MS6126 devices.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/switch.recswitch/
"""
import logging
import voluptuous as vol
from homeassistant.components.switch import PLATFORM_SCHEMA, SwitchDevice
from homeassistant.const import CONF_HOST, CONF_MAC, CONF_NAME
import homeassistant.helpers.config_validation as cv
_LOGGER = logging.getLogger(__name__)
REQUIREMENTS = ['pyrecswitch==1.0.2']
DEFAULT_NAME = 'RecSwitch {0}'
DATA_RSN = 'RSN'
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Required(CONF_HOST): cv.string,
vol.Required(CONF_MAC): vol.All(cv.string, vol.Upper),
vol.Optional(CONF_NAME): cv.string,
})
async def async_setup_platform(hass, config, async_add_entities,
discovery_info=None):
"""Set up the device."""
from pyrecswitch import RSNetwork
host = config[CONF_HOST]
mac_address = config[CONF_MAC]
device_name = config.get(CONF_NAME)
if not hass.data.get(DATA_RSN):
hass.data[DATA_RSN] = RSNetwork()
job = hass.data[DATA_RSN].create_datagram_endpoint(loop=hass.loop)
hass.async_create_task(job)
device = hass.data[DATA_RSN].register_device(mac_address, host)
async_add_entities([RecSwitchSwitch(device, device_name, mac_address)])
class RecSwitchSwitch(SwitchDevice):
"""Representation of a recswitch device."""
def __init__(self, device, device_name, mac_address):
"""Initialize a recswitch device."""
self.gpio_state = False
self.device = device
self.device_name = device_name
self.mac_address = mac_address
if not self.device_name:
self.device_name = DEFAULT_NAME.format(self.mac_address)
@property
def unique_id(self):
"""Return the switch unique ID."""
return self.mac_address
@property
def name(self):
"""Return the switch name."""
return self.device_name
@property
def is_on(self):
"""Return true if switch is on."""
return self.gpio_state
async def async_turn_on(self, **kwargs):
"""Turn on the switch."""
await self.async_set_gpio_status(True)
async def async_turn_off(self, **kwargs):
"""Turn off the switch."""
await self.async_set_gpio_status(False)
async def async_set_gpio_status(self, status):
"""Set the switch status."""
from pyrecswitch import RSNetworkError
try:
ret = await self.device.set_gpio_status(status)
self.gpio_state = ret.state
except RSNetworkError as error:
_LOGGER.error('Setting status to %s: %r', self.name, error)
async def async_update(self):
"""Update the current switch status."""
from pyrecswitch import RSNetworkError
try:
ret = await self.device.get_gpio_status()
self.gpio_state = ret.state
except RSNetworkError as error:
_LOGGER.error('Reading status from %s: %r', self.name, error)
-130
View File
@@ -1,130 +0,0 @@
"""
Allows to configure a switch using a 433MHz module via GPIO on a Raspberry Pi.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/switch.rpi_rf/
"""
import logging
import voluptuous as vol
from homeassistant.components.switch import SwitchDevice, PLATFORM_SCHEMA
from homeassistant.const import (
CONF_NAME, CONF_SWITCHES, EVENT_HOMEASSISTANT_STOP)
import homeassistant.helpers.config_validation as cv
REQUIREMENTS = ['rpi-rf==0.9.7']
_LOGGER = logging.getLogger(__name__)
CONF_CODE_OFF = 'code_off'
CONF_CODE_ON = 'code_on'
CONF_GPIO = 'gpio'
CONF_PROTOCOL = 'protocol'
CONF_PULSELENGTH = 'pulselength'
CONF_SIGNAL_REPETITIONS = 'signal_repetitions'
DEFAULT_PROTOCOL = 1
DEFAULT_SIGNAL_REPETITIONS = 10
SWITCH_SCHEMA = vol.Schema({
vol.Required(CONF_CODE_OFF):
vol.All(cv.ensure_list_csv, [cv.positive_int]),
vol.Required(CONF_CODE_ON):
vol.All(cv.ensure_list_csv, [cv.positive_int]),
vol.Optional(CONF_PULSELENGTH): cv.positive_int,
vol.Optional(CONF_SIGNAL_REPETITIONS,
default=DEFAULT_SIGNAL_REPETITIONS): cv.positive_int,
vol.Optional(CONF_PROTOCOL, default=DEFAULT_PROTOCOL): cv.positive_int,
})
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Required(CONF_GPIO): cv.positive_int,
vol.Required(CONF_SWITCHES): vol.Schema({cv.string: SWITCH_SCHEMA}),
})
# pylint: disable=no-member
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Find and return switches controlled by a generic RF device via GPIO."""
import rpi_rf
from threading import RLock
gpio = config.get(CONF_GPIO)
rfdevice = rpi_rf.RFDevice(gpio)
rfdevice_lock = RLock()
switches = config.get(CONF_SWITCHES)
devices = []
for dev_name, properties in switches.items():
devices.append(
RPiRFSwitch(
properties.get(CONF_NAME, dev_name),
rfdevice,
rfdevice_lock,
properties.get(CONF_PROTOCOL),
properties.get(CONF_PULSELENGTH),
properties.get(CONF_SIGNAL_REPETITIONS),
properties.get(CONF_CODE_ON),
properties.get(CONF_CODE_OFF)
)
)
if devices:
rfdevice.enable_tx()
add_entities(devices)
hass.bus.listen_once(
EVENT_HOMEASSISTANT_STOP, lambda event: rfdevice.cleanup())
class RPiRFSwitch(SwitchDevice):
"""Representation of a GPIO RF switch."""
def __init__(self, name, rfdevice, lock, protocol, pulselength,
signal_repetitions, code_on, code_off):
"""Initialize the switch."""
self._name = name
self._state = False
self._rfdevice = rfdevice
self._lock = lock
self._protocol = protocol
self._pulselength = pulselength
self._code_on = code_on
self._code_off = code_off
self._rfdevice.tx_repeat = signal_repetitions
@property
def should_poll(self):
"""No polling needed."""
return False
@property
def name(self):
"""Return the name of the switch."""
return self._name
@property
def is_on(self):
"""Return true if device is on."""
return self._state
def _send_code(self, code_list, protocol, pulselength):
"""Send the code(s) with a specified pulselength."""
with self._lock:
_LOGGER.info("Sending code(s): %s", code_list)
for code in code_list:
self._rfdevice.tx_code(code, protocol, pulselength)
return True
def turn_on(self, **kwargs):
"""Turn the switch on."""
if self._send_code(self._code_on, self._protocol, self._pulselength):
self._state = True
self.schedule_update_ha_state()
def turn_off(self, **kwargs):
"""Turn the switch off."""
if self._send_code(self._code_off, self._protocol, self._pulselength):
self._state = False
self.schedule_update_ha_state()
-218
View File
@@ -1,218 +0,0 @@
"""
Support for SNMP enabled switch.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/switch.snmp/
"""
import logging
import voluptuous as vol
from homeassistant.components.switch import (SwitchDevice, PLATFORM_SCHEMA)
from homeassistant.const import (
CONF_HOST, CONF_NAME, CONF_PORT, CONF_PAYLOAD_ON, CONF_PAYLOAD_OFF,
CONF_USERNAME)
import homeassistant.helpers.config_validation as cv
REQUIREMENTS = ['pysnmp==4.4.8']
_LOGGER = logging.getLogger(__name__)
CONF_BASEOID = 'baseoid'
CONF_COMMAND_OID = 'command_oid'
CONF_COMMAND_PAYLOAD_ON = 'command_payload_on'
CONF_COMMAND_PAYLOAD_OFF = 'command_payload_off'
CONF_COMMUNITY = 'community'
CONF_VERSION = 'version'
CONF_AUTH_KEY = 'auth_key'
CONF_AUTH_PROTOCOL = 'auth_protocol'
CONF_PRIV_KEY = 'priv_key'
CONF_PRIV_PROTOCOL = 'priv_protocol'
DEFAULT_NAME = 'SNMP Switch'
DEFAULT_HOST = 'localhost'
DEFAULT_PORT = '161'
DEFAULT_COMMUNITY = 'private'
DEFAULT_VERSION = '1'
DEFAULT_AUTH_PROTOCOL = 'none'
DEFAULT_PRIV_PROTOCOL = 'none'
DEFAULT_PAYLOAD_ON = 1
DEFAULT_PAYLOAD_OFF = 0
SNMP_VERSIONS = {
'1': 0,
'2c': 1,
'3': None
}
MAP_AUTH_PROTOCOLS = {
'none': 'usmNoAuthProtocol',
'hmac-md5': 'usmHMACMD5AuthProtocol',
'hmac-sha': 'usmHMACSHAAuthProtocol',
'hmac128-sha224': 'usmHMAC128SHA224AuthProtocol',
'hmac192-sha256': 'usmHMAC192SHA256AuthProtocol',
'hmac256-sha384': 'usmHMAC256SHA384AuthProtocol',
'hmac384-sha512': 'usmHMAC384SHA512AuthProtocol',
}
MAP_PRIV_PROTOCOLS = {
'none': 'usmNoPrivProtocol',
'des': 'usmDESPrivProtocol',
'3des-ede': 'usm3DESEDEPrivProtocol',
'aes-cfb-128': 'usmAesCfb128Protocol',
'aes-cfb-192': 'usmAesCfb192Protocol',
'aes-cfb-256': 'usmAesCfb256Protocol',
}
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Required(CONF_BASEOID): cv.string,
vol.Optional(CONF_COMMAND_OID): cv.string,
vol.Optional(CONF_COMMAND_PAYLOAD_ON): cv.string,
vol.Optional(CONF_COMMAND_PAYLOAD_OFF): cv.string,
vol.Optional(CONF_COMMUNITY, default=DEFAULT_COMMUNITY): cv.string,
vol.Optional(CONF_HOST, default=DEFAULT_HOST): cv.string,
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
vol.Optional(CONF_PAYLOAD_OFF, default=DEFAULT_PAYLOAD_OFF): cv.string,
vol.Optional(CONF_PAYLOAD_ON, default=DEFAULT_PAYLOAD_ON): cv.string,
vol.Optional(CONF_PORT, default=DEFAULT_PORT): cv.port,
vol.Optional(CONF_VERSION, default=DEFAULT_VERSION): vol.In(SNMP_VERSIONS),
vol.Optional(CONF_USERNAME): cv.string,
vol.Optional(CONF_AUTH_KEY): cv.string,
vol.Optional(CONF_AUTH_PROTOCOL, default=DEFAULT_AUTH_PROTOCOL):
vol.In(MAP_AUTH_PROTOCOLS),
vol.Optional(CONF_PRIV_KEY): cv.string,
vol.Optional(CONF_PRIV_PROTOCOL, default=DEFAULT_PRIV_PROTOCOL):
vol.In(MAP_PRIV_PROTOCOLS),
})
async def async_setup_platform(
hass, config, async_add_entities, discovery_info=None):
"""Set up the SNMP switch."""
name = config.get(CONF_NAME)
host = config.get(CONF_HOST)
port = config.get(CONF_PORT)
community = config.get(CONF_COMMUNITY)
baseoid = config.get(CONF_BASEOID)
command_oid = config.get(CONF_COMMAND_OID)
command_payload_on = config.get(CONF_COMMAND_PAYLOAD_ON)
command_payload_off = config.get(CONF_COMMAND_PAYLOAD_OFF)
version = config.get(CONF_VERSION)
username = config.get(CONF_USERNAME)
authkey = config.get(CONF_AUTH_KEY)
authproto = config.get(CONF_AUTH_PROTOCOL)
privkey = config.get(CONF_PRIV_KEY)
privproto = config.get(CONF_PRIV_PROTOCOL)
payload_on = config.get(CONF_PAYLOAD_ON)
payload_off = config.get(CONF_PAYLOAD_OFF)
async_add_entities(
[SnmpSwitch(
name, host, port, community, baseoid, command_oid, version,
username, authkey, authproto, privkey, privproto, payload_on,
payload_off, command_payload_on, command_payload_off)], True)
class SnmpSwitch(SwitchDevice):
"""Representation of a SNMP switch."""
def __init__(self, name, host, port, community, baseoid, commandoid,
version, username, authkey, authproto, privkey, privproto,
payload_on, payload_off, command_payload_on,
command_payload_off):
"""Initialize the switch."""
from pysnmp.hlapi.asyncio import (
CommunityData, ContextData, SnmpEngine,
UdpTransportTarget, UsmUserData)
self._name = name
self._baseoid = baseoid
# Set the command OID to the base OID if command OID is unset
self._commandoid = commandoid or baseoid
self._command_payload_on = command_payload_on or payload_on
self._command_payload_off = command_payload_off or payload_off
self._state = None
self._payload_on = payload_on
self._payload_off = payload_off
if version == '3':
import pysnmp.hlapi.asyncio as hlapi
if not authkey:
authproto = 'none'
if not privkey:
privproto = 'none'
self._request_args = [
SnmpEngine(),
UsmUserData(
username,
authKey=authkey or None,
privKey=privkey or None,
authProtocol=getattr(hlapi, MAP_AUTH_PROTOCOLS[authproto]),
privProtocol=getattr(hlapi, MAP_PRIV_PROTOCOLS[privproto]),
),
UdpTransportTarget((host, port)),
ContextData(),
]
else:
self._request_args = [
SnmpEngine(),
CommunityData(community, mpModel=SNMP_VERSIONS[version]),
UdpTransportTarget((host, port)),
ContextData(),
]
async def async_turn_on(self, **kwargs):
"""Turn on the switch."""
from pyasn1.type.univ import (Integer)
await self._set(Integer(self._command_payload_on))
async def async_turn_off(self, **kwargs):
"""Turn off the switch."""
from pyasn1.type.univ import (Integer)
await self._set(Integer(self._command_payload_off))
async def async_update(self):
"""Update the state."""
from pysnmp.hlapi.asyncio import (getCmd, ObjectType, ObjectIdentity)
from pyasn1.type.univ import (Integer)
errindication, errstatus, errindex, restable = await getCmd(
*self._request_args, ObjectType(ObjectIdentity(self._baseoid)))
if errindication:
_LOGGER.error("SNMP error: %s", errindication)
elif errstatus:
_LOGGER.error("SNMP error: %s at %s", errstatus.prettyPrint(),
errindex and restable[-1][int(errindex) - 1] or '?')
else:
for resrow in restable:
if resrow[-1] == Integer(self._payload_on):
self._state = True
elif resrow[-1] == Integer(self._payload_off):
self._state = False
else:
self._state = None
@property
def name(self):
"""Return the switch's name."""
return self._name
@property
def is_on(self):
"""Return true if switch is on; False if off. None if unknown."""
return self._state
async def _set(self, value):
from pysnmp.hlapi.asyncio import (setCmd, ObjectType, ObjectIdentity)
await setCmd(
*self._request_args,
ObjectType(ObjectIdentity(self._commandoid), value)
)
@@ -1,97 +0,0 @@
"""Support for Sony projectors via SDCP network control."""
import logging
import voluptuous as vol
from homeassistant.components.switch import (SwitchDevice, PLATFORM_SCHEMA)
from homeassistant.const import (
STATE_ON, STATE_OFF, CONF_NAME, CONF_HOST)
import homeassistant.helpers.config_validation as cv
REQUIREMENTS = ['pysdcp==1']
_LOGGER = logging.getLogger(__name__)
DEFAULT_NAME = 'Sony Projector'
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Required(CONF_HOST): cv.string,
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string
})
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Connect to Sony projector using network."""
import pysdcp
host = config[CONF_HOST]
name = config[CONF_NAME]
sdcp_connection = pysdcp.Projector(host)
# Sanity check the connection
try:
sdcp_connection.get_power()
except ConnectionError:
_LOGGER.error("Failed to connect to projector '%s'", host)
return False
_LOGGER.debug("Validated projector '%s' OK", host)
add_entities([SonyProjector(sdcp_connection, name)], True)
return True
class SonyProjector(SwitchDevice):
"""Represents a Sony Projector as a switch."""
def __init__(self, sdcp_connection, name):
"""Init of the Sony projector."""
self._sdcp = sdcp_connection
self._name = name
self._state = None
self._available = False
self._attributes = {}
@property
def available(self):
"""Return if projector is available."""
return self._available
@property
def name(self):
"""Return name of the projector."""
return self._name
@property
def is_on(self):
"""Return if the projector is turned on."""
return self._state
@property
def state_attributes(self):
"""Return state attributes."""
return self._attributes
def update(self):
"""Get the latest state from the projector."""
try:
self._state = self._sdcp.get_power()
self._available = True
except ConnectionRefusedError:
_LOGGER.error("Projector connection refused")
self._available = False
def turn_on(self, **kwargs):
"""Turn the projector on."""
_LOGGER.debug("Powering on projector '%s'...", self.name)
if self._sdcp.set_power(True):
_LOGGER.debug("Powered on successfully.")
self._state = STATE_ON
else:
_LOGGER.error("Power on command was not successful")
def turn_off(self, **kwargs):
"""Turn the projector off."""
_LOGGER.debug("Powering off projector '%s'...", self.name)
if self._sdcp.set_power(False):
_LOGGER.debug("Powered off successfully.")
self._state = STATE_OFF
else:
_LOGGER.error("Power off command was not successful")
@@ -1,74 +0,0 @@
"""
Support for Switchbot.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/switch.switchbot
"""
import logging
import voluptuous as vol
import homeassistant.helpers.config_validation as cv
from homeassistant.components.switch import SwitchDevice, PLATFORM_SCHEMA
from homeassistant.const import CONF_NAME, CONF_MAC
REQUIREMENTS = ['PySwitchbot==0.5']
_LOGGER = logging.getLogger(__name__)
DEFAULT_NAME = 'Switchbot'
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Required(CONF_MAC): cv.string,
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
})
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Perform the setup for Switchbot devices."""
name = config.get(CONF_NAME)
mac_addr = config[CONF_MAC]
add_entities([SwitchBot(mac_addr, name)])
class SwitchBot(SwitchDevice):
"""Representation of a Switchbot."""
def __init__(self, mac, name) -> None:
"""Initialize the Switchbot."""
# pylint: disable=import-error, no-member
import switchbot
self._state = False
self._name = name
self._mac = mac
self._device = switchbot.Switchbot(mac=mac)
def turn_on(self, **kwargs) -> None:
"""Turn device on."""
if self._device.turn_on():
self._state = True
def turn_off(self, **kwargs) -> None:
"""Turn device off."""
if self._device.turn_off():
self._state = False
@property
def assumed_state(self) -> bool:
"""Return true if unable to access real state of entity."""
return True
@property
def is_on(self) -> bool:
"""Return true if device is on."""
return self._state
@property
def unique_id(self) -> str:
"""Return a unique, HASS-friendly identifier for this entity."""
return self._mac.replace(':', '')
@property
def name(self) -> str:
"""Return the name of the switch."""
return self._name
@@ -1,81 +0,0 @@
"""
Support for Switchmate.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/switch.switchmate/
"""
import logging
from datetime import timedelta
import voluptuous as vol
import homeassistant.helpers.config_validation as cv
from homeassistant.components.switch import SwitchDevice, PLATFORM_SCHEMA
from homeassistant.const import CONF_NAME, CONF_MAC
REQUIREMENTS = ['pySwitchmate==0.4.5']
_LOGGER = logging.getLogger(__name__)
CONF_FLIP_ON_OFF = 'flip_on_off'
DEFAULT_NAME = 'Switchmate'
SCAN_INTERVAL = timedelta(minutes=30)
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Required(CONF_MAC): cv.string,
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
vol.Optional(CONF_FLIP_ON_OFF, default=False): cv.boolean,
})
def setup_platform(hass, config, add_entities, discovery_info=None) -> None:
"""Perform the setup for Switchmate devices."""
name = config.get(CONF_NAME)
mac_addr = config[CONF_MAC]
flip_on_off = config[CONF_FLIP_ON_OFF]
add_entities([SwitchmateEntity(mac_addr, name, flip_on_off)], True)
class SwitchmateEntity(SwitchDevice):
"""Representation of a Switchmate."""
def __init__(self, mac, name, flip_on_off) -> None:
"""Initialize the Switchmate."""
# pylint: disable=import-error, no-member, no-value-for-parameter
import switchmate
self._mac = mac
self._name = name
self._device = switchmate.Switchmate(mac=mac, flip_on_off=flip_on_off)
@property
def unique_id(self) -> str:
"""Return a unique, HASS-friendly identifier for this entity."""
return self._mac.replace(':', '')
@property
def available(self) -> bool:
"""Return True if entity is available."""
return self._device.available
@property
def name(self) -> str:
"""Return the name of the switch."""
return self._name
def update(self) -> None:
"""Synchronize state with switch."""
self._device.update()
@property
def is_on(self) -> bool:
"""Return true if it is on."""
return self._device.state
def turn_on(self, **kwargs) -> None:
"""Turn the switch on."""
self._device.turn_on()
def turn_off(self, **kwargs) -> None:
"""Turn the switch off."""
self._device.turn_off()
-143
View File
@@ -1,143 +0,0 @@
"""
Support for switch controlled using a telnet connection.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/switch.telnet/
"""
from datetime import timedelta
import logging
import telnetlib
import voluptuous as vol
from homeassistant.components.switch import (
ENTITY_ID_FORMAT, PLATFORM_SCHEMA, SwitchDevice)
from homeassistant.const import (
CONF_COMMAND_OFF, CONF_COMMAND_ON, CONF_COMMAND_STATE, CONF_NAME,
CONF_PORT, CONF_RESOURCE, CONF_SWITCHES, CONF_VALUE_TEMPLATE)
import homeassistant.helpers.config_validation as cv
_LOGGER = logging.getLogger(__name__)
DEFAULT_PORT = 23
SWITCH_SCHEMA = vol.Schema({
vol.Required(CONF_COMMAND_OFF): cv.string,
vol.Required(CONF_COMMAND_ON): cv.string,
vol.Required(CONF_RESOURCE): cv.string,
vol.Optional(CONF_VALUE_TEMPLATE): cv.template,
vol.Optional(CONF_COMMAND_STATE): cv.string,
vol.Optional(CONF_NAME): cv.string,
vol.Optional(CONF_PORT, default=DEFAULT_PORT): cv.port,
})
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Required(CONF_SWITCHES): cv.schema_with_slug_keys(SWITCH_SCHEMA),
})
SCAN_INTERVAL = timedelta(seconds=10)
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Find and return switches controlled by telnet commands."""
devices = config.get(CONF_SWITCHES, {})
switches = []
for object_id, device_config in devices.items():
value_template = device_config.get(CONF_VALUE_TEMPLATE)
if value_template is not None:
value_template.hass = hass
switches.append(
TelnetSwitch(
hass,
object_id,
device_config.get(CONF_RESOURCE),
device_config.get(CONF_PORT),
device_config.get(CONF_NAME, object_id),
device_config.get(CONF_COMMAND_ON),
device_config.get(CONF_COMMAND_OFF),
device_config.get(CONF_COMMAND_STATE),
value_template
)
)
if not switches:
_LOGGER.error("No switches added")
return
add_entities(switches)
class TelnetSwitch(SwitchDevice):
"""Representation of a switch that can be toggled using telnet commands."""
def __init__(self, hass, object_id, resource, port, friendly_name,
command_on, command_off, command_state, value_template):
"""Initialize the switch."""
self._hass = hass
self.entity_id = ENTITY_ID_FORMAT.format(object_id)
self._resource = resource
self._port = port
self._name = friendly_name
self._state = False
self._command_on = command_on
self._command_off = command_off
self._command_state = command_state
self._value_template = value_template
def _telnet_command(self, command):
try:
telnet = telnetlib.Telnet(self._resource, self._port)
telnet.write(command.encode('ASCII') + b'\r')
response = telnet.read_until(b'\r', timeout=0.2)
return response.decode('ASCII').strip()
except IOError as error:
_LOGGER.error(
'Command "%s" failed with exception: %s',
command, repr(error))
return None
@property
def name(self):
"""Return the name of the switch."""
return self._name
@property
def should_poll(self):
"""Only poll if we have state command."""
return self._command_state is not None
@property
def is_on(self):
"""Return true if device is on."""
return self._state
@property
def assumed_state(self):
"""Return true if no state command is defined, false otherwise."""
return self._command_state is None
def update(self):
"""Update device state."""
response = self._telnet_command(self._command_state)
if response:
rendered = self._value_template \
.render_with_possible_json_value(response)
self._state = rendered == "True"
else:
_LOGGER.warning(
"Empty response for command: %s", self._command_state)
def turn_on(self, **kwargs):
"""Turn the device on."""
self._telnet_command(self._command_on)
if self.assumed_state:
self._state = True
def turn_off(self, **kwargs):
"""Turn the device off."""
self._telnet_command(self._command_off)
if self.assumed_state:
self._state = False
-109
View File
@@ -1,109 +0,0 @@
"""
Support for Etekcity VeSync switches.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/switch.vesync/
"""
import logging
import voluptuous as vol
from homeassistant.components.switch import (SwitchDevice, PLATFORM_SCHEMA)
from homeassistant.const import (CONF_USERNAME, CONF_PASSWORD)
import homeassistant.helpers.config_validation as cv
REQUIREMENTS = ['pyvesync_v2==0.9.6']
_LOGGER = logging.getLogger(__name__)
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Required(CONF_USERNAME): cv.string,
vol.Required(CONF_PASSWORD): cv.string,
})
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the VeSync switch platform."""
from pyvesync_v2.vesync import VeSync
switches = []
manager = VeSync(config.get(CONF_USERNAME), config.get(CONF_PASSWORD))
if not manager.login():
_LOGGER.error("Unable to login to VeSync")
return
manager.update()
if manager.devices is not None and manager.devices:
if len(manager.devices) == 1:
count_string = 'switch'
else:
count_string = 'switches'
_LOGGER.info("Discovered %d VeSync %s",
len(manager.devices), count_string)
for switch in manager.devices:
switches.append(VeSyncSwitchHA(switch))
_LOGGER.info("Added a VeSync switch named '%s'",
switch.device_name)
else:
_LOGGER.info("No VeSync devices found")
add_entities(switches)
class VeSyncSwitchHA(SwitchDevice):
"""Representation of a VeSync switch."""
def __init__(self, plug):
"""Initialize the VeSync switch device."""
self.smartplug = plug
self._current_power_w = None
self._today_energy_kwh = None
@property
def unique_id(self):
"""Return the ID of this switch."""
return self.smartplug.cid
@property
def name(self):
"""Return the name of the switch."""
return self.smartplug.device_name
@property
def current_power_w(self):
"""Return the current power usage in W."""
return self._current_power_w
@property
def today_energy_kwh(self):
"""Return the today total energy usage in kWh."""
return self._today_energy_kwh
@property
def available(self) -> bool:
"""Return True if switch is available."""
return self.smartplug.connection_status == "online"
@property
def is_on(self):
"""Return True if switch is on."""
return self.smartplug.device_status == "on"
def turn_on(self, **kwargs):
"""Turn the switch on."""
self.smartplug.turn_on()
def turn_off(self, **kwargs):
"""Turn the switch off."""
self.smartplug.turn_off()
def update(self):
"""Handle data changes for node values."""
self.smartplug.update()
if self.smartplug.devtype == 'outlet':
self._current_power_w = self.smartplug.get_power()
self._today_energy_kwh = self.smartplug.get_kwh_today()