commit
c95c8a04ef
409 files changed
+17583
-4105
No files matched your search
@@ -0,0 +1,80 @@
|
||||
"""
|
||||
This component provides HA switch support for Abode Security System.
|
||||
|
||||
For more details about this platform, please refer to the documentation at
|
||||
https://home-assistant.io/components/switch.abode/
|
||||
"""
|
||||
import logging
|
||||
|
||||
from homeassistant.components.abode import (AbodeDevice, AbodeAutomation,
|
||||
DOMAIN as ABODE_DOMAIN)
|
||||
from homeassistant.components.switch import SwitchDevice
|
||||
|
||||
|
||||
DEPENDENCIES = ['abode']
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def setup_platform(hass, config, add_devices, discovery_info=None):
|
||||
"""Set up Abode switch devices."""
|
||||
import abodepy.helpers.constants as CONST
|
||||
import abodepy.helpers.timeline as TIMELINE
|
||||
|
||||
data = hass.data[ABODE_DOMAIN]
|
||||
|
||||
devices = []
|
||||
|
||||
# Get all regular switches that are not excluded or marked as lights
|
||||
for device in data.abode.get_devices(generic_type=CONST.TYPE_SWITCH):
|
||||
if data.is_excluded(device) or data.is_light(device):
|
||||
continue
|
||||
|
||||
devices.append(AbodeSwitch(data, device))
|
||||
|
||||
# Get all Abode automations that can be enabled/disabled
|
||||
for automation in data.abode.get_automations(
|
||||
generic_type=CONST.TYPE_AUTOMATION):
|
||||
if data.is_automation_excluded(automation):
|
||||
continue
|
||||
|
||||
devices.append(AbodeAutomationSwitch(
|
||||
data, automation, TIMELINE.AUTOMATION_EDIT_GROUP))
|
||||
|
||||
data.devices.extend(devices)
|
||||
|
||||
add_devices(devices)
|
||||
|
||||
|
||||
class AbodeSwitch(AbodeDevice, SwitchDevice):
|
||||
"""Representation of an Abode switch."""
|
||||
|
||||
def turn_on(self, **kwargs):
|
||||
"""Turn on the device."""
|
||||
self._device.switch_on()
|
||||
|
||||
def turn_off(self, **kwargs):
|
||||
"""Turn off the device."""
|
||||
self._device.switch_off()
|
||||
|
||||
@property
|
||||
def is_on(self):
|
||||
"""Return true if device is on."""
|
||||
return self._device.is_on
|
||||
|
||||
|
||||
class AbodeAutomationSwitch(AbodeAutomation, SwitchDevice):
|
||||
"""A switch implementation for Abode automations."""
|
||||
|
||||
def turn_on(self, **kwargs):
|
||||
"""Turn on the device."""
|
||||
self._automation.set_active(True)
|
||||
|
||||
def turn_off(self, **kwargs):
|
||||
"""Turn off the device."""
|
||||
self._automation.set_active(False)
|
||||
|
||||
@property
|
||||
def is_on(self):
|
||||
"""Return True if the binary sensor is on."""
|
||||
return self._automation.is_active
|
||||
@@ -109,7 +109,7 @@ class AcerSwitch(SwitchDevice):
|
||||
|
||||
def _write_read_format(self, msg):
|
||||
"""Write msg, obtain awnser and format output."""
|
||||
# awnsers are formated as ***\rawnser\r***
|
||||
# awnsers are formatted as ***\rawnser\r***
|
||||
awns = self._write_read(msg)
|
||||
match = re.search(r'\r(.+)\r', awns)
|
||||
if match:
|
||||
|
||||
@@ -47,7 +47,7 @@ class IPWebcamSettingsSwitch(AndroidIPCamEntity, SwitchDevice):
|
||||
|
||||
@property
|
||||
def name(self):
|
||||
"""Return the the name of the node."""
|
||||
"""Return the name of the node."""
|
||||
return self._name
|
||||
|
||||
@asyncio.coroutine
|
||||
@@ -72,7 +72,7 @@ class IPWebcamSettingsSwitch(AndroidIPCamEntity, SwitchDevice):
|
||||
else:
|
||||
yield from self._ipcam.change_setting(self._setting, True)
|
||||
self._state = True
|
||||
self.hass.async_add_job(self.async_update_ha_state())
|
||||
self.async_schedule_update_ha_state()
|
||||
|
||||
@asyncio.coroutine
|
||||
def async_turn_off(self, **kwargs):
|
||||
@@ -86,7 +86,7 @@ class IPWebcamSettingsSwitch(AndroidIPCamEntity, SwitchDevice):
|
||||
else:
|
||||
yield from self._ipcam.change_setting(self._setting, False)
|
||||
self._state = False
|
||||
self.hass.async_add_job(self.async_update_ha_state())
|
||||
self.async_schedule_update_ha_state()
|
||||
|
||||
@property
|
||||
def icon(self):
|
||||
|
||||
@@ -14,9 +14,11 @@ import socket
|
||||
import voluptuous as vol
|
||||
|
||||
from homeassistant.util.dt import utcnow
|
||||
from homeassistant.util import Throttle
|
||||
from homeassistant.components.switch import (SwitchDevice, PLATFORM_SCHEMA)
|
||||
from homeassistant.const import (
|
||||
CONF_FRIENDLY_NAME, CONF_SWITCHES, CONF_COMMAND_OFF, CONF_COMMAND_ON,
|
||||
CONF_FRIENDLY_NAME, CONF_SWITCHES,
|
||||
CONF_COMMAND_OFF, CONF_COMMAND_ON,
|
||||
CONF_TIMEOUT, CONF_HOST, CONF_MAC, CONF_TYPE)
|
||||
import homeassistant.helpers.config_validation as cv
|
||||
|
||||
@@ -24,20 +26,24 @@ REQUIREMENTS = ['broadlink==0.5']
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
TIME_BETWEEN_UPDATES = timedelta(seconds=5)
|
||||
|
||||
DOMAIN = 'broadlink'
|
||||
DEFAULT_NAME = 'Broadlink switch'
|
||||
DEFAULT_TIMEOUT = 10
|
||||
DEFAULT_RETRY = 3
|
||||
SERVICE_LEARN = 'learn_command'
|
||||
SERVICE_SEND = '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
|
||||
SWITCH_TYPES = RM_TYPES + SP1_TYPES + SP2_TYPES + MP1_TYPES
|
||||
|
||||
SWITCH_SCHEMA = vol.Schema({
|
||||
vol.Optional(CONF_COMMAND_OFF, default=None): cv.string,
|
||||
@@ -45,9 +51,17 @@ SWITCH_SCHEMA = vol.Schema({
|
||||
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={}):
|
||||
vol.Schema({cv.slug: 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,
|
||||
@@ -59,7 +73,8 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
|
||||
def setup_platform(hass, config, add_devices, discovery_info=None):
|
||||
"""Set up Broadlink switches."""
|
||||
import broadlink
|
||||
devices = config.get(CONF_SWITCHES, {})
|
||||
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(
|
||||
@@ -114,6 +129,11 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
|
||||
if retry == DEFAULT_RETRY-1:
|
||||
_LOGGER.error("Failed to send packet to device")
|
||||
|
||||
def _get_mp1_slot_name(switch_friendly_name, slot):
|
||||
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)
|
||||
hass.services.register(DOMAIN, SERVICE_LEARN + '_' +
|
||||
@@ -136,6 +156,15 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
|
||||
elif switch_type in SP2_TYPES:
|
||||
broadlink_device = broadlink.sp2((ip_addr, 80), mac_addr)
|
||||
switches = [BroadlinkSP2Switch(friendly_name, broadlink_device)]
|
||||
elif switch_type in MP1_TYPES:
|
||||
switches = []
|
||||
broadlink_device = broadlink.mp1((ip_addr, 80), mac_addr)
|
||||
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:
|
||||
@@ -268,3 +297,84 @@ class BroadlinkSP2Switch(BroadlinkSP1Switch):
|
||||
if state is None and retry > 0:
|
||||
return self._update(retry-1)
|
||||
self._state = state
|
||||
|
||||
|
||||
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, 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)
|
||||
return False
|
||||
if not self._auth():
|
||||
return False
|
||||
return self._sendpacket(packet, max(0, retry-1))
|
||||
return True
|
||||
|
||||
@property
|
||||
def should_poll(self):
|
||||
"""Polling needed."""
|
||||
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(object):
|
||||
"""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):
|
||||
try:
|
||||
states = self._device.check_power()
|
||||
except (socket.timeout, ValueError) as error:
|
||||
if retry < 1:
|
||||
_LOGGER.error(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):
|
||||
try:
|
||||
auth = self._device.auth()
|
||||
except socket.timeout:
|
||||
auth = False
|
||||
if not auth and retry > 0:
|
||||
return self._auth(retry-1)
|
||||
return auth
|
||||
@@ -46,7 +46,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
|
||||
import dlipower
|
||||
|
||||
host = config.get(CONF_HOST)
|
||||
controllername = config.get(CONF_NAME)
|
||||
controller_name = config.get(CONF_NAME)
|
||||
user = config.get(CONF_USERNAME)
|
||||
pswd = config.get(CONF_PASSWORD)
|
||||
tout = config.get(CONF_TIMEOUT)
|
||||
@@ -61,37 +61,42 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
|
||||
_LOGGER.error("Could not connect to DIN III Relay")
|
||||
return False
|
||||
|
||||
devices = []
|
||||
outlets = []
|
||||
parent_device = DINRelayDevice(power_switch)
|
||||
|
||||
devices.extend(
|
||||
DINRelay(controllername, device.outlet_number, parent_device)
|
||||
for device in power_switch
|
||||
outlets.extend(
|
||||
DINRelay(controller_name, parent_device, outlet)
|
||||
for outlet in power_switch[0:]
|
||||
)
|
||||
|
||||
add_devices(devices, True)
|
||||
add_devices(outlets)
|
||||
|
||||
|
||||
class DINRelay(SwitchDevice):
|
||||
"""Representation of a individual DIN III relay port."""
|
||||
|
||||
def __init__(self, name, outletnumber, parent_device):
|
||||
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.controllername = name
|
||||
self.outletnumber = outletnumber
|
||||
self._outletname = ''
|
||||
self._is_on = False
|
||||
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 self._outletname
|
||||
return '{}_{}'.format(
|
||||
self._controller_name,
|
||||
self._name
|
||||
)
|
||||
|
||||
@property
|
||||
def is_on(self):
|
||||
"""Return true if relay is on."""
|
||||
return self._is_on
|
||||
return self._state
|
||||
|
||||
@property
|
||||
def should_poll(self):
|
||||
@@ -100,41 +105,36 @@ class DINRelay(SwitchDevice):
|
||||
|
||||
def turn_on(self, **kwargs):
|
||||
"""Instruct the relay to turn on."""
|
||||
self._parent_device.turn_on(outlet=self.outletnumber)
|
||||
self._outlet.on()
|
||||
|
||||
def turn_off(self, **kwargs):
|
||||
"""Instruct the relay to turn off."""
|
||||
self._parent_device.turn_off(outlet=self.outletnumber)
|
||||
self._outlet.off()
|
||||
|
||||
def update(self):
|
||||
"""Trigger update for all switches on the parent device."""
|
||||
self._parent_device.update()
|
||||
self._is_on = (
|
||||
self._parent_device.statuslocal[self.outletnumber - 1][2] == 'ON'
|
||||
)
|
||||
self._outletname = '{}_{}'.format(
|
||||
self.controllername,
|
||||
self._parent_device.statuslocal[self.outletnumber - 1][1]
|
||||
)
|
||||
|
||||
outlet_status = self._parent_device.get_outlet_status(
|
||||
self._outlet_number)
|
||||
|
||||
self._name = outlet_status[1]
|
||||
self._state = outlet_status[2] == 'ON'
|
||||
|
||||
|
||||
class DINRelayDevice(object):
|
||||
"""Device representation for per device throttling."""
|
||||
|
||||
def __init__(self, device):
|
||||
def __init__(self, power_switch):
|
||||
"""Initialize the DINRelay device."""
|
||||
self._device = device
|
||||
self.statuslocal = None
|
||||
self._power_switch = power_switch
|
||||
self._statuslist = None
|
||||
|
||||
def turn_on(self, **kwargs):
|
||||
"""Instruct the relay to turn on."""
|
||||
self._device.on(**kwargs)
|
||||
|
||||
def turn_off(self, **kwargs):
|
||||
"""Instruct the relay to turn off."""
|
||||
self._device.off(**kwargs)
|
||||
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.statuslocal = self._device.statuslist()
|
||||
self._statuslist = self._power_switch.statuslist()
|
||||
@@ -14,7 +14,7 @@ from homeassistant.const import (
|
||||
import homeassistant.helpers.config_validation as cv
|
||||
from homeassistant.const import TEMP_CELSIUS, STATE_UNKNOWN
|
||||
|
||||
REQUIREMENTS = ['pyW215==0.5.1']
|
||||
REQUIREMENTS = ['pyW215==0.6.0']
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
@@ -23,9 +23,9 @@ DEFAULT_PASSWORD = ''
|
||||
DEFAULT_USERNAME = 'admin'
|
||||
CONF_USE_LEGACY_PROTOCOL = 'use_legacy_protocol'
|
||||
|
||||
ATTR_CURRENT_CONSUMPTION = 'Current Consumption'
|
||||
ATTR_TOTAL_CONSUMPTION = 'Total Consumption'
|
||||
ATTR_TEMPERATURE = 'Temperature'
|
||||
ATTR_CURRENT_CONSUMPTION = 'power_consumption'
|
||||
ATTR_TOTAL_CONSUMPTION = 'total_consumption'
|
||||
ATTR_TEMPERATURE = 'temperature'
|
||||
|
||||
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
|
||||
vol.Required(CONF_HOST): cv.string,
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
"""Support for powering relays in a DoorBird video doorbell."""
|
||||
import datetime
|
||||
import logging
|
||||
import voluptuous as vol
|
||||
|
||||
from homeassistant.components.doorbird import DOMAIN as DOORBIRD_DOMAIN
|
||||
from homeassistant.components.switch import SwitchDevice, PLATFORM_SCHEMA
|
||||
from homeassistant.const import CONF_SWITCHES
|
||||
import homeassistant.helpers.config_validation as cv
|
||||
|
||||
DEPENDENCIES = ['doorbird']
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
SWITCHES = {
|
||||
"open_door": {
|
||||
"name": "Open Door",
|
||||
"icon": {
|
||||
True: "lock-open",
|
||||
False: "lock"
|
||||
},
|
||||
"time": datetime.timedelta(seconds=3)
|
||||
},
|
||||
"light_on": {
|
||||
"name": "Light On",
|
||||
"icon": {
|
||||
True: "lightbulb-on",
|
||||
False: "lightbulb"
|
||||
},
|
||||
"time": datetime.timedelta(minutes=5)
|
||||
}
|
||||
}
|
||||
|
||||
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
|
||||
vol.Required(CONF_SWITCHES, default=[]):
|
||||
vol.All(cv.ensure_list([vol.In(SWITCHES)]))
|
||||
})
|
||||
|
||||
|
||||
def setup_platform(hass, config, add_devices, discovery_info=None):
|
||||
"""Set up the DoorBird switch platform."""
|
||||
device = hass.data.get(DOORBIRD_DOMAIN)
|
||||
|
||||
switches = []
|
||||
for switch in SWITCHES:
|
||||
_LOGGER.debug("Adding DoorBird switch %s", SWITCHES[switch]["name"])
|
||||
switches.append(DoorBirdSwitch(device, switch))
|
||||
|
||||
add_devices(switches)
|
||||
_LOGGER.info("Added DoorBird switches")
|
||||
|
||||
|
||||
class DoorBirdSwitch(SwitchDevice):
|
||||
"""A relay in a DoorBird device."""
|
||||
|
||||
def __init__(self, device, switch):
|
||||
"""Initialize a relay in a DoorBird device."""
|
||||
self._device = device
|
||||
self._switch = switch
|
||||
self._state = False
|
||||
self._assume_off = datetime.datetime.min
|
||||
|
||||
@property
|
||||
def name(self):
|
||||
"""Get the name of the switch."""
|
||||
return SWITCHES[self._switch]["name"]
|
||||
|
||||
@property
|
||||
def icon(self):
|
||||
"""Get an icon to display."""
|
||||
return "mdi:{}".format(SWITCHES[self._switch]["icon"][self._state])
|
||||
|
||||
@property
|
||||
def is_on(self):
|
||||
"""Get the assumed state of the relay."""
|
||||
return self._state
|
||||
|
||||
def turn_on(self, **kwargs):
|
||||
"""Power the relay."""
|
||||
if self._switch == "open_door":
|
||||
self._state = self._device.open_door()
|
||||
elif self._switch == "light_on":
|
||||
self._state = self._device.turn_light_on()
|
||||
|
||||
now = datetime.datetime.now()
|
||||
self._assume_off = now + SWITCHES[self._switch]["time"]
|
||||
|
||||
def turn_off(self, **kwargs):
|
||||
"""The relays are time-based."""
|
||||
raise NotImplementedError("DoorBird relays cannot be manually turned "
|
||||
"off.")
|
||||
|
||||
def update(self):
|
||||
"""Wait for the correct amount of assumed time to pass."""
|
||||
if self._state and self._assume_off <= datetime.datetime.now():
|
||||
self._state = False
|
||||
self._assume_off = datetime.datetime.min
|
||||
@@ -6,8 +6,9 @@ The idea was taken from https://github.com/KpaBap/hue-flux/
|
||||
For more details about this component, please refer to the documentation at
|
||||
https://home-assistant.io/components/switch.flux/
|
||||
"""
|
||||
from datetime import time
|
||||
import datetime
|
||||
import logging
|
||||
|
||||
import voluptuous as vol
|
||||
|
||||
from homeassistant.components.light import is_on, turn_on
|
||||
@@ -46,7 +47,7 @@ PLATFORM_SCHEMA = vol.Schema({
|
||||
vol.Required(CONF_LIGHTS): cv.entity_ids,
|
||||
vol.Optional(CONF_NAME, default="Flux"): cv.string,
|
||||
vol.Optional(CONF_START_TIME): cv.time,
|
||||
vol.Optional(CONF_STOP_TIME, default=time(22, 0)): cv.time,
|
||||
vol.Optional(CONF_STOP_TIME, default=datetime.time(22, 0)): cv.time,
|
||||
vol.Optional(CONF_START_CT, default=4000):
|
||||
vol.All(vol.Coerce(int), vol.Range(min=1000, max=40000)),
|
||||
vol.Optional(CONF_SUNSET_CT, default=3000):
|
||||
@@ -171,12 +172,22 @@ class FluxSwitch(SwitchDevice):
|
||||
"""Update all the lights using flux."""
|
||||
if now is None:
|
||||
now = dt_now()
|
||||
|
||||
sunset = get_astral_event_date(self.hass, 'sunset', now.date())
|
||||
start_time = self.find_start_time(now)
|
||||
stop_time = now.replace(
|
||||
hour=self._stop_time.hour, minute=self._stop_time.minute,
|
||||
second=0)
|
||||
|
||||
if stop_time <= start_time:
|
||||
# stop_time does not happen in the same day as start_time
|
||||
if start_time < now:
|
||||
# stop time is tomorrow
|
||||
stop_time += datetime.timedelta(days=1)
|
||||
elif now < start_time:
|
||||
# stop_time was yesterday since the new start_time is not reached
|
||||
stop_time -= datetime.timedelta(days=1)
|
||||
|
||||
if start_time < now < sunset:
|
||||
# Daytime
|
||||
time_state = 'day'
|
||||
@@ -192,15 +203,24 @@ class FluxSwitch(SwitchDevice):
|
||||
else:
|
||||
# Nightime
|
||||
time_state = 'night'
|
||||
if now < stop_time and now > start_time:
|
||||
now_time = now
|
||||
|
||||
if now < stop_time:
|
||||
if stop_time < start_time and stop_time.day == sunset.day:
|
||||
# we need to use yesterday's sunset time
|
||||
sunset_time = sunset - datetime.timedelta(days=1)
|
||||
else:
|
||||
sunset_time = sunset
|
||||
|
||||
# pylint: disable=no-member
|
||||
night_length = int(stop_time.timestamp() -
|
||||
sunset_time.timestamp())
|
||||
seconds_from_sunset = int(now.timestamp() -
|
||||
sunset_time.timestamp())
|
||||
percentage_complete = seconds_from_sunset / night_length
|
||||
else:
|
||||
now_time = stop_time
|
||||
percentage_complete = 1
|
||||
|
||||
temp_range = abs(self._sunset_colortemp - self._stop_colortemp)
|
||||
night_length = int(stop_time.timestamp() - sunset.timestamp())
|
||||
seconds_from_sunset = int(now_time.timestamp() -
|
||||
sunset.timestamp())
|
||||
percentage_complete = seconds_from_sunset / night_length
|
||||
temp_offset = temp_range * percentage_complete
|
||||
if self._sunset_colortemp > self._stop_colortemp:
|
||||
temp = self._sunset_colortemp - temp_offset
|
||||
|
||||
@@ -21,8 +21,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
|
||||
|
||||
devices = []
|
||||
for conf in discovery_info[ATTR_DISCOVER_DEVICES]:
|
||||
new_device = HMSwitch(hass, conf)
|
||||
new_device.link_homematic()
|
||||
new_device = HMSwitch(conf)
|
||||
devices.append(new_device)
|
||||
|
||||
add_devices(devices)
|
||||
|
||||
@@ -130,7 +130,7 @@ class InsteonLocalSwitchDevice(SwitchDevice):
|
||||
|
||||
@property
|
||||
def name(self):
|
||||
"""Return the the name of the node."""
|
||||
"""Return the name of the node."""
|
||||
return self.node.deviceName
|
||||
|
||||
@property
|
||||
|
||||
@@ -55,12 +55,12 @@ class InsteonPLMSwitchDevice(SwitchDevice):
|
||||
|
||||
@property
|
||||
def address(self):
|
||||
"""Return the the address of the node."""
|
||||
"""Return the address of the node."""
|
||||
return self._address
|
||||
|
||||
@property
|
||||
def name(self):
|
||||
"""Return the the name of the node."""
|
||||
"""Return the name of the node."""
|
||||
return self._name
|
||||
|
||||
@property
|
||||
|
||||
@@ -1,14 +1,16 @@
|
||||
"""
|
||||
Support KNX switching actuators.
|
||||
Support for KNX/IP switches.
|
||||
|
||||
For more details about this platform, please refer to the documentation at
|
||||
https://home-assistant.io/components/switch.knx/
|
||||
"""
|
||||
import asyncio
|
||||
import voluptuous as vol
|
||||
|
||||
from homeassistant.components.knx import (KNXConfig, KNXGroupAddress)
|
||||
from homeassistant.components.switch import (SwitchDevice, PLATFORM_SCHEMA)
|
||||
from homeassistant.components.knx import DATA_KNX, ATTR_DISCOVER_DEVICES
|
||||
from homeassistant.components.switch import PLATFORM_SCHEMA, SwitchDevice
|
||||
from homeassistant.const import CONF_NAME
|
||||
from homeassistant.core import callback
|
||||
import homeassistant.helpers.config_validation as cv
|
||||
|
||||
CONF_ADDRESS = 'address'
|
||||
@@ -24,30 +26,85 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
|
||||
})
|
||||
|
||||
|
||||
def setup_platform(hass, config, add_devices, discovery_info=None):
|
||||
"""Set up the KNX switch platform."""
|
||||
add_devices([KNXSwitch(hass, KNXConfig(config))])
|
||||
@asyncio.coroutine
|
||||
def async_setup_platform(hass, config, async_add_devices,
|
||||
discovery_info=None):
|
||||
"""Set up switch(es) for KNX platform."""
|
||||
if DATA_KNX not in hass.data \
|
||||
or not hass.data[DATA_KNX].initialized:
|
||||
return False
|
||||
|
||||
if discovery_info is not None:
|
||||
async_add_devices_discovery(hass, discovery_info, async_add_devices)
|
||||
else:
|
||||
async_add_devices_config(hass, config, async_add_devices)
|
||||
|
||||
return True
|
||||
|
||||
|
||||
class KNXSwitch(KNXGroupAddress, SwitchDevice):
|
||||
"""Representation of a KNX switch device."""
|
||||
@callback
|
||||
def async_add_devices_discovery(hass, discovery_info, async_add_devices):
|
||||
"""Set up switches for KNX platform configured via xknx.yaml."""
|
||||
entities = []
|
||||
for device_name in discovery_info[ATTR_DISCOVER_DEVICES]:
|
||||
device = hass.data[DATA_KNX].xknx.devices[device_name]
|
||||
entities.append(KNXSwitch(hass, device))
|
||||
async_add_devices(entities)
|
||||
|
||||
def turn_on(self, **kwargs):
|
||||
"""Turn the switch on.
|
||||
|
||||
This sends a value 0 to the group address of the device
|
||||
"""
|
||||
self.group_write(1)
|
||||
self._state = [1]
|
||||
if not self.should_poll:
|
||||
self.schedule_update_ha_state()
|
||||
@callback
|
||||
def async_add_devices_config(hass, config, async_add_devices):
|
||||
"""Set up switch for KNX platform configured within plattform."""
|
||||
import xknx
|
||||
switch = xknx.devices.Switch(
|
||||
hass.data[DATA_KNX].xknx,
|
||||
name=config.get(CONF_NAME),
|
||||
group_address=config.get(CONF_ADDRESS),
|
||||
group_address_state=config.get(CONF_STATE_ADDRESS))
|
||||
hass.data[DATA_KNX].xknx.devices.add(switch)
|
||||
async_add_devices([KNXSwitch(hass, switch)])
|
||||
|
||||
def turn_off(self, **kwargs):
|
||||
"""Turn the switch off.
|
||||
|
||||
This sends a value 1 to the group address of the device
|
||||
"""
|
||||
self.group_write(0)
|
||||
self._state = [0]
|
||||
if not self.should_poll:
|
||||
self.schedule_update_ha_state()
|
||||
class KNXSwitch(SwitchDevice):
|
||||
"""Representation of a KNX switch."""
|
||||
|
||||
def __init__(self, hass, device):
|
||||
"""Initialization of KNXSwitch."""
|
||||
self.device = device
|
||||
self.hass = hass
|
||||
self.async_register_callbacks()
|
||||
|
||||
@callback
|
||||
def async_register_callbacks(self):
|
||||
"""Register callbacks to update hass after device was changed."""
|
||||
@asyncio.coroutine
|
||||
def after_update_callback(device):
|
||||
"""Callback after device was updated."""
|
||||
# pylint: disable=unused-argument
|
||||
yield from self.async_update_ha_state()
|
||||
self.device.register_device_updated_cb(after_update_callback)
|
||||
|
||||
@property
|
||||
def name(self):
|
||||
"""Return the name of the KNX device."""
|
||||
return self.device.name
|
||||
|
||||
@property
|
||||
def should_poll(self):
|
||||
"""No polling needed within KNX."""
|
||||
return False
|
||||
|
||||
@property
|
||||
def is_on(self):
|
||||
"""Return true if device is on."""
|
||||
return self.device.state
|
||||
|
||||
@asyncio.coroutine
|
||||
def async_turn_on(self, **kwargs):
|
||||
"""Turn the device on."""
|
||||
yield from self.device.set_on()
|
||||
|
||||
@asyncio.coroutine
|
||||
def async_turn_off(self, **kwargs):
|
||||
"""Turn the device off."""
|
||||
yield from self.device.set_off()
|
||||
@@ -8,7 +8,7 @@ import logging
|
||||
|
||||
from homeassistant.components.lutron_caseta import (
|
||||
LUTRON_CASETA_SMARTBRIDGE, LutronCasetaDevice)
|
||||
from homeassistant.components.switch import SwitchDevice
|
||||
from homeassistant.components.switch import SwitchDevice, DOMAIN
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
@@ -20,7 +20,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
|
||||
"""Set up Lutron switch."""
|
||||
devs = []
|
||||
bridge = hass.data[LUTRON_CASETA_SMARTBRIDGE]
|
||||
switch_devices = bridge.get_devices_by_type("WallSwitch")
|
||||
switch_devices = bridge.get_devices_by_domain(DOMAIN)
|
||||
|
||||
for switch_device in switch_devices:
|
||||
dev = LutronCasetaLight(switch_device, bridge)
|
||||
|
||||
@@ -111,7 +111,7 @@ class MqttSwitch(SwitchDevice):
|
||||
elif payload == self._payload_off:
|
||||
self._state = False
|
||||
|
||||
self.hass.async_add_job(self.async_update_ha_state())
|
||||
self.async_schedule_update_ha_state()
|
||||
|
||||
@callback
|
||||
def availability_message_received(topic, payload, qos):
|
||||
@@ -121,7 +121,7 @@ class MqttSwitch(SwitchDevice):
|
||||
elif payload == self._payload_not_available:
|
||||
self._available = False
|
||||
|
||||
self.hass.async_add_job(self.async_update_ha_state())
|
||||
self.async_schedule_update_ha_state()
|
||||
|
||||
if self._state_topic is None:
|
||||
# Force into optimistic mode.
|
||||
@@ -173,7 +173,7 @@ class MqttSwitch(SwitchDevice):
|
||||
if self._optimistic:
|
||||
# Optimistically assume that switch has changed state.
|
||||
self._state = True
|
||||
self.hass.async_add_job(self.async_update_ha_state())
|
||||
self.async_schedule_update_ha_state()
|
||||
|
||||
@asyncio.coroutine
|
||||
def async_turn_off(self, **kwargs):
|
||||
@@ -187,4 +187,4 @@ class MqttSwitch(SwitchDevice):
|
||||
if self._optimistic:
|
||||
# Optimistically assume that switch has changed state.
|
||||
self._state = False
|
||||
self.hass.async_add_job(self.async_update_ha_state())
|
||||
self.async_schedule_update_ha_state()
|
||||
@@ -4,7 +4,6 @@ Support for MySensors switches.
|
||||
For more details about this platform, please refer to the documentation at
|
||||
https://home-assistant.io/components/switch.mysensors/
|
||||
"""
|
||||
import logging
|
||||
import os
|
||||
|
||||
import voluptuous as vol
|
||||
@@ -15,9 +14,6 @@ from homeassistant.components.switch import DOMAIN, SwitchDevice
|
||||
from homeassistant.config import load_yaml_config_file
|
||||
from homeassistant.const import ATTR_ENTITY_ID, STATE_OFF, STATE_ON
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
DEPENDENCIES = []
|
||||
|
||||
ATTR_IR_CODE = 'V_IR_SEND'
|
||||
SERVICE_SEND_IR_CODE = 'mysensors_send_ir_code'
|
||||
|
||||
@@ -29,82 +25,37 @@ SEND_IR_CODE_SERVICE_SCHEMA = vol.Schema({
|
||||
|
||||
def setup_platform(hass, config, add_devices, discovery_info=None):
|
||||
"""Set up the mysensors platform for switches."""
|
||||
# Only act if loaded via mysensors by discovery event.
|
||||
# Otherwise gateway is not setup.
|
||||
if discovery_info is None:
|
||||
return
|
||||
|
||||
gateways = hass.data.get(mysensors.MYSENSORS_GATEWAYS)
|
||||
if not gateways:
|
||||
return
|
||||
|
||||
platform_devices = []
|
||||
|
||||
for gateway in gateways:
|
||||
# Define the S_TYPES and V_TYPES that the platform should handle as
|
||||
# states. Map them in a dict of lists.
|
||||
pres = gateway.const.Presentation
|
||||
set_req = gateway.const.SetReq
|
||||
map_sv_types = {
|
||||
pres.S_DOOR: [set_req.V_ARMED],
|
||||
pres.S_MOTION: [set_req.V_ARMED],
|
||||
pres.S_SMOKE: [set_req.V_ARMED],
|
||||
pres.S_LIGHT: [set_req.V_LIGHT],
|
||||
pres.S_LOCK: [set_req.V_LOCK_STATUS],
|
||||
pres.S_IR: [set_req.V_IR_SEND],
|
||||
}
|
||||
device_class_map = {
|
||||
pres.S_DOOR: MySensorsSwitch,
|
||||
pres.S_MOTION: MySensorsSwitch,
|
||||
pres.S_SMOKE: MySensorsSwitch,
|
||||
pres.S_LIGHT: MySensorsSwitch,
|
||||
pres.S_LOCK: MySensorsSwitch,
|
||||
pres.S_IR: MySensorsIRSwitch,
|
||||
}
|
||||
if float(gateway.protocol_version) >= 1.5:
|
||||
map_sv_types.update({
|
||||
pres.S_BINARY: [set_req.V_STATUS, set_req.V_LIGHT],
|
||||
pres.S_SPRINKLER: [set_req.V_STATUS],
|
||||
pres.S_WATER_LEAK: [set_req.V_ARMED],
|
||||
pres.S_SOUND: [set_req.V_ARMED],
|
||||
pres.S_VIBRATION: [set_req.V_ARMED],
|
||||
pres.S_MOISTURE: [set_req.V_ARMED],
|
||||
})
|
||||
map_sv_types[pres.S_LIGHT].append(set_req.V_STATUS)
|
||||
device_class_map.update({
|
||||
pres.S_BINARY: MySensorsSwitch,
|
||||
pres.S_SPRINKLER: MySensorsSwitch,
|
||||
pres.S_WATER_LEAK: MySensorsSwitch,
|
||||
pres.S_SOUND: MySensorsSwitch,
|
||||
pres.S_VIBRATION: MySensorsSwitch,
|
||||
pres.S_MOISTURE: MySensorsSwitch,
|
||||
})
|
||||
if float(gateway.protocol_version) >= 2.0:
|
||||
map_sv_types.update({
|
||||
pres.S_WATER_QUALITY: [set_req.V_STATUS],
|
||||
})
|
||||
device_class_map.update({
|
||||
pres.S_WATER_QUALITY: MySensorsSwitch,
|
||||
})
|
||||
|
||||
devices = {}
|
||||
gateway.platform_callbacks.append(mysensors.pf_callback_factory(
|
||||
map_sv_types, devices, device_class_map, add_devices))
|
||||
platform_devices.append(devices)
|
||||
device_class_map = {
|
||||
'S_DOOR': MySensorsSwitch,
|
||||
'S_MOTION': MySensorsSwitch,
|
||||
'S_SMOKE': MySensorsSwitch,
|
||||
'S_LIGHT': MySensorsSwitch,
|
||||
'S_LOCK': MySensorsSwitch,
|
||||
'S_IR': MySensorsIRSwitch,
|
||||
'S_BINARY': MySensorsSwitch,
|
||||
'S_SPRINKLER': MySensorsSwitch,
|
||||
'S_WATER_LEAK': MySensorsSwitch,
|
||||
'S_SOUND': MySensorsSwitch,
|
||||
'S_VIBRATION': MySensorsSwitch,
|
||||
'S_MOISTURE': MySensorsSwitch,
|
||||
'S_WATER_QUALITY': MySensorsSwitch,
|
||||
}
|
||||
mysensors.setup_mysensors_platform(
|
||||
hass, DOMAIN, discovery_info, device_class_map,
|
||||
add_devices=add_devices)
|
||||
|
||||
def send_ir_code_service(service):
|
||||
"""Set IR code as device state attribute."""
|
||||
entity_ids = service.data.get(ATTR_ENTITY_ID)
|
||||
ir_code = service.data.get(ATTR_IR_CODE)
|
||||
devices = mysensors.get_mysensors_devices(hass, DOMAIN)
|
||||
|
||||
if entity_ids:
|
||||
_devices = [device for gw_devs in platform_devices
|
||||
for device in gw_devs.values()
|
||||
_devices = [device for device in devices.values()
|
||||
if isinstance(device, MySensorsIRSwitch) and
|
||||
device.entity_id in entity_ids]
|
||||
else:
|
||||
_devices = [device for gw_devs in platform_devices
|
||||
for device in gw_devs.values()
|
||||
_devices = [device for device in devices.values()
|
||||
if isinstance(device, MySensorsIRSwitch)]
|
||||
|
||||
kwargs = {ATTR_IR_CODE: ir_code}
|
||||
@@ -120,7 +71,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
|
||||
schema=SEND_IR_CODE_SERVICE_SCHEMA)
|
||||
|
||||
|
||||
class MySensorsSwitch(mysensors.MySensorsDeviceEntity, SwitchDevice):
|
||||
class MySensorsSwitch(mysensors.MySensorsEntity, SwitchDevice):
|
||||
"""Representation of the value of a MySensors Switch child node."""
|
||||
|
||||
@property
|
||||
@@ -131,9 +82,7 @@ class MySensorsSwitch(mysensors.MySensorsDeviceEntity, SwitchDevice):
|
||||
@property
|
||||
def is_on(self):
|
||||
"""Return True if switch is on."""
|
||||
if self.value_type in self._values:
|
||||
return self._values[self.value_type] == STATE_ON
|
||||
return False
|
||||
return self._values.get(self.value_type) == STATE_ON
|
||||
|
||||
def turn_on(self, **kwargs):
|
||||
"""Turn the switch on."""
|
||||
@@ -159,24 +108,18 @@ class MySensorsIRSwitch(MySensorsSwitch):
|
||||
|
||||
def __init__(self, *args):
|
||||
"""Set up instance attributes."""
|
||||
MySensorsSwitch.__init__(self, *args)
|
||||
super().__init__(*args)
|
||||
self._ir_code = None
|
||||
|
||||
@property
|
||||
def is_on(self):
|
||||
"""Return True if switch is on."""
|
||||
set_req = self.gateway.const.SetReq
|
||||
if set_req.V_LIGHT in self._values:
|
||||
return self._values[set_req.V_LIGHT] == STATE_ON
|
||||
return False
|
||||
return self._values.get(set_req.V_LIGHT) == STATE_ON
|
||||
|
||||
def turn_on(self, **kwargs):
|
||||
"""Turn the IR switch on."""
|
||||
set_req = self.gateway.const.SetReq
|
||||
if set_req.V_LIGHT not in self._values:
|
||||
_LOGGER.error('missing value_type: %s at node: %s, child: %s',
|
||||
set_req.V_LIGHT.name, self.node_id, self.child_id)
|
||||
return
|
||||
if ATTR_IR_CODE in kwargs:
|
||||
self._ir_code = kwargs[ATTR_IR_CODE]
|
||||
self.gateway.set_child_value(
|
||||
@@ -194,10 +137,6 @@ class MySensorsIRSwitch(MySensorsSwitch):
|
||||
def turn_off(self, **kwargs):
|
||||
"""Turn the IR switch off."""
|
||||
set_req = self.gateway.const.SetReq
|
||||
if set_req.V_LIGHT not in self._values:
|
||||
_LOGGER.error('missing value_type: %s at node: %s, child: %s',
|
||||
set_req.V_LIGHT.name, self.node_id, self.child_id)
|
||||
return
|
||||
self.gateway.set_child_value(
|
||||
self.node_id, self.child_id, set_req.V_LIGHT, 0)
|
||||
if self.gateway.optimistic:
|
||||
@@ -207,6 +146,5 @@ class MySensorsIRSwitch(MySensorsSwitch):
|
||||
|
||||
def update(self):
|
||||
"""Update the controller with the latest value from a sensor."""
|
||||
MySensorsSwitch.update(self)
|
||||
if self.value_type in self._values:
|
||||
self._ir_code = self._values[self.value_type]
|
||||
super().update()
|
||||
self._ir_code = self._values.get(self.value_type)
|
||||
@@ -13,7 +13,8 @@ import voluptuous as vol
|
||||
|
||||
from homeassistant.components.switch import (SwitchDevice, PLATFORM_SCHEMA)
|
||||
from homeassistant.const import (
|
||||
CONF_NAME, CONF_RESOURCE, CONF_TIMEOUT, CONF_METHOD)
|
||||
CONF_NAME, CONF_RESOURCE, CONF_TIMEOUT, CONF_METHOD, CONF_USERNAME,
|
||||
CONF_PASSWORD)
|
||||
from homeassistant.helpers.aiohttp_client import async_get_clientsession
|
||||
import homeassistant.helpers.config_validation as cv
|
||||
from homeassistant.helpers.template import Template
|
||||
@@ -41,6 +42,8 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
|
||||
vol.All(vol.Lower, vol.In(SUPPORT_REST_METHODS)),
|
||||
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
|
||||
vol.Optional(CONF_TIMEOUT, default=DEFAULT_TIMEOUT): cv.positive_int,
|
||||
vol.Inclusive(CONF_USERNAME, 'authentication'): cv.string,
|
||||
vol.Inclusive(CONF_PASSWORD, 'authentication'): cv.string,
|
||||
})
|
||||
|
||||
|
||||
@@ -53,8 +56,13 @@ def async_setup_platform(hass, config, async_add_devices, discovery_info=None):
|
||||
is_on_template = config.get(CONF_IS_ON_TEMPLATE)
|
||||
method = config.get(CONF_METHOD)
|
||||
name = config.get(CONF_NAME)
|
||||
username = config.get(CONF_USERNAME)
|
||||
password = config.get(CONF_PASSWORD)
|
||||
resource = config.get(CONF_RESOURCE)
|
||||
websession = async_get_clientsession(hass)
|
||||
|
||||
auth = None
|
||||
if username:
|
||||
auth = aiohttp.BasicAuth(username, password=password)
|
||||
|
||||
if is_on_template is not None:
|
||||
is_on_template.hass = hass
|
||||
@@ -65,37 +73,32 @@ def async_setup_platform(hass, config, async_add_devices, discovery_info=None):
|
||||
timeout = config.get(CONF_TIMEOUT)
|
||||
|
||||
try:
|
||||
with async_timeout.timeout(timeout, loop=hass.loop):
|
||||
req = yield from websession.get(resource)
|
||||
switch = RestSwitch(name, resource, method, auth, body_on, body_off,
|
||||
is_on_template, timeout)
|
||||
|
||||
req = yield from switch.get_device_state(hass)
|
||||
if req.status >= 400:
|
||||
_LOGGER.error("Got non-ok response from resource: %s", req.status)
|
||||
return False
|
||||
|
||||
else:
|
||||
async_add_devices([switch])
|
||||
except (TypeError, ValueError):
|
||||
_LOGGER.error("Missing resource or schema in configuration. "
|
||||
"Add http:// or https:// to your URL")
|
||||
return False
|
||||
except (asyncio.TimeoutError, aiohttp.ClientError):
|
||||
_LOGGER.error("No route to resource/endpoint: %s", resource)
|
||||
return False
|
||||
|
||||
async_add_devices(
|
||||
[RestSwitch(hass, name, resource, method, body_on, body_off,
|
||||
is_on_template, timeout)])
|
||||
|
||||
|
||||
class RestSwitch(SwitchDevice):
|
||||
"""Representation of a switch that can be toggled using REST."""
|
||||
|
||||
def __init__(self, hass, name, resource, method, body_on, body_off,
|
||||
def __init__(self, name, resource, method, auth, body_on, body_off,
|
||||
is_on_template, timeout):
|
||||
"""Initialize the REST switch."""
|
||||
self._state = None
|
||||
self.hass = hass
|
||||
self._name = name
|
||||
self._resource = resource
|
||||
self._method = method
|
||||
self._auth = auth
|
||||
self._body_on = body_on
|
||||
self._body_off = body_off
|
||||
self._is_on_template = is_on_template
|
||||
@@ -115,54 +118,61 @@ class RestSwitch(SwitchDevice):
|
||||
def async_turn_on(self, **kwargs):
|
||||
"""Turn the device on."""
|
||||
body_on_t = self._body_on.async_render()
|
||||
websession = async_get_clientsession(self.hass)
|
||||
|
||||
try:
|
||||
with async_timeout.timeout(self._timeout, loop=self.hass.loop):
|
||||
request = yield from getattr(websession, self._method)(
|
||||
self._resource, data=bytes(body_on_t, 'utf-8'))
|
||||
req = yield from self.set_device_state(body_on_t)
|
||||
|
||||
if req.status == 200:
|
||||
self._state = True
|
||||
else:
|
||||
_LOGGER.error(
|
||||
"Can't turn on %s. Is resource/endpoint offline?",
|
||||
self._resource)
|
||||
except (asyncio.TimeoutError, aiohttp.ClientError):
|
||||
_LOGGER.error("Error while turn on %s", self._resource)
|
||||
return
|
||||
|
||||
if request.status == 200:
|
||||
self._state = True
|
||||
else:
|
||||
_LOGGER.error("Can't turn on %s. Is resource/endpoint offline?",
|
||||
self._resource)
|
||||
|
||||
@asyncio.coroutine
|
||||
def async_turn_off(self, **kwargs):
|
||||
"""Turn the device off."""
|
||||
body_off_t = self._body_off.async_render()
|
||||
websession = async_get_clientsession(self.hass)
|
||||
|
||||
try:
|
||||
with async_timeout.timeout(self._timeout, loop=self.hass.loop):
|
||||
request = yield from getattr(websession, self._method)(
|
||||
self._resource, data=bytes(body_off_t, 'utf-8'))
|
||||
req = yield from self.set_device_state(body_off_t)
|
||||
if req.status == 200:
|
||||
self._state = False
|
||||
else:
|
||||
_LOGGER.error(
|
||||
"Can't turn off %s. Is resource/endpoint offline?",
|
||||
self._resource)
|
||||
except (asyncio.TimeoutError, aiohttp.ClientError):
|
||||
_LOGGER.error("Error while turn off %s", self._resource)
|
||||
return
|
||||
|
||||
if request.status == 200:
|
||||
self._state = False
|
||||
else:
|
||||
_LOGGER.error("Can't turn off %s. Is resource/endpoint offline?",
|
||||
self._resource)
|
||||
@asyncio.coroutine
|
||||
def set_device_state(self, body):
|
||||
"""Send a state update to the device."""
|
||||
websession = async_get_clientsession(self.hass)
|
||||
|
||||
with async_timeout.timeout(self._timeout, loop=self.hass.loop):
|
||||
req = yield from getattr(websession, self._method)(
|
||||
self._resource, auth=self._auth, data=bytes(body, 'utf-8'))
|
||||
return req
|
||||
|
||||
@asyncio.coroutine
|
||||
def async_update(self):
|
||||
"""Get the latest data from REST API and update the state."""
|
||||
websession = async_get_clientsession(self.hass)
|
||||
|
||||
"""Get the current state, catching errors."""
|
||||
try:
|
||||
with async_timeout.timeout(self._timeout, loop=self.hass.loop):
|
||||
request = yield from websession.get(self._resource)
|
||||
text = yield from request.text()
|
||||
yield from self.get_device_state(self.hass)
|
||||
except (asyncio.TimeoutError, aiohttp.ClientError):
|
||||
_LOGGER.exception("Error while fetch data.")
|
||||
return
|
||||
|
||||
@asyncio.coroutine
|
||||
def get_device_state(self, hass):
|
||||
"""Get the latest data from REST API and update the state."""
|
||||
websession = async_get_clientsession(hass)
|
||||
|
||||
with async_timeout.timeout(self._timeout, loop=hass.loop):
|
||||
req = yield from websession.get(self._resource, auth=self._auth)
|
||||
text = yield from req.text()
|
||||
|
||||
if self._is_on_template is not None:
|
||||
text = self._is_on_template.async_render_with_possible_json_value(
|
||||
@@ -181,3 +191,5 @@ class RestSwitch(SwitchDevice):
|
||||
self._state = False
|
||||
else:
|
||||
self._state = None
|
||||
|
||||
return req
|
||||
@@ -35,7 +35,7 @@ PLATFORM_SCHEMA = vol.Schema({
|
||||
vol.All(cv.ensure_list, [cv.string]),
|
||||
vol.Optional(CONF_NOGROUP_ALIASES, default=[]):
|
||||
vol.All(cv.ensure_list, [cv.string]),
|
||||
vol.Optional(CONF_FIRE_EVENT, default=False): cv.boolean,
|
||||
vol.Optional(CONF_FIRE_EVENT): cv.boolean,
|
||||
vol.Optional(CONF_SIGNAL_REPETITIONS): vol.Coerce(int),
|
||||
vol.Optional(CONF_GROUP, default=True): cv.boolean,
|
||||
# deprecated config options
|
||||
|
||||
@@ -21,7 +21,7 @@ def setup_platform(hass, config, add_devices_callback, discovery_info=None):
|
||||
import RFXtrx as rfxtrxmod
|
||||
|
||||
# Add switch from config file
|
||||
switches = rfxtrx.get_devices_from_config(config, RfxtrxSwitch, hass)
|
||||
switches = rfxtrx.get_devices_from_config(config, RfxtrxSwitch)
|
||||
add_devices_callback(switches)
|
||||
|
||||
def switch_update(event):
|
||||
@@ -31,7 +31,7 @@ def setup_platform(hass, config, add_devices_callback, discovery_info=None):
|
||||
event.device.known_to_be_rollershutter:
|
||||
return
|
||||
|
||||
new_device = rfxtrx.get_new_device(event, config, RfxtrxSwitch, hass)
|
||||
new_device = rfxtrx.get_new_device(event, config, RfxtrxSwitch)
|
||||
if new_device:
|
||||
add_devices_callback([new_device])
|
||||
|
||||
|
||||
@@ -29,7 +29,7 @@ mysensors_send_ir_code:
|
||||
|
||||
fields:
|
||||
entity_id:
|
||||
description: Name(s) of entites that should have the IR code set and be turned on. Platform dependent.
|
||||
description: Name(s) of entities that should have the IR code set and be turned on. Platform dependent.
|
||||
example: 'switch.living_room_1_1'
|
||||
|
||||
V_IR_SEND:
|
||||
|
||||
@@ -39,7 +39,7 @@ class TellstickSwitch(TellstickDevice, ToggleEntity):
|
||||
return None
|
||||
|
||||
def _parse_tellcore_data(self, tellcore_data):
|
||||
"""Turn the value recieved from tellcore into something useful."""
|
||||
"""Turn the value received from tellcore into something useful."""
|
||||
return None
|
||||
|
||||
def _update_model(self, new_state, data):
|
||||
|
||||
@@ -0,0 +1,144 @@
|
||||
"""
|
||||
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/
|
||||
"""
|
||||
import logging
|
||||
import telnetlib
|
||||
from datetime import timedelta
|
||||
|
||||
import voluptuous as vol
|
||||
|
||||
from homeassistant.components.switch import (SwitchDevice, PLATFORM_SCHEMA,
|
||||
ENTITY_ID_FORMAT)
|
||||
from homeassistant.const import (
|
||||
CONF_RESOURCE, CONF_NAME, CONF_SWITCHES, CONF_VALUE_TEMPLATE,
|
||||
CONF_COMMAND_OFF, CONF_COMMAND_ON, CONF_COMMAND_STATE, CONF_PORT)
|
||||
import homeassistant.helpers.config_validation as cv
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
DEFAULT_PORT = 23
|
||||
|
||||
SWITCH_SCHEMA = vol.Schema({
|
||||
vol.Required(CONF_COMMAND_ON): cv.string,
|
||||
vol.Required(CONF_COMMAND_OFF): cv.string,
|
||||
vol.Optional(CONF_COMMAND_STATE): cv.string,
|
||||
vol.Optional(CONF_NAME): cv.string,
|
||||
vol.Optional(CONF_PORT, default=DEFAULT_PORT): cv.port,
|
||||
vol.Required(CONF_RESOURCE): cv.string,
|
||||
vol.Required(CONF_VALUE_TEMPLATE): cv.template,
|
||||
})
|
||||
|
||||
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
|
||||
vol.Required(CONF_SWITCHES): vol.Schema({cv.slug: SWITCH_SCHEMA}),
|
||||
})
|
||||
|
||||
SCAN_INTERVAL = timedelta(seconds=10)
|
||||
|
||||
|
||||
# pylint: disable=unused-argument
|
||||
def setup_platform(hass, config, add_devices, 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 False
|
||||
|
||||
add_devices(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):
|
||||
"""Default ist 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
|
||||
@@ -103,7 +103,7 @@ class SwitchTemplate(SwitchDevice):
|
||||
@callback
|
||||
def template_switch_state_listener(entity, old_state, new_state):
|
||||
"""Handle target device state changes."""
|
||||
self.hass.async_add_job(self.async_update_ha_state(True))
|
||||
self.async_schedule_update_ha_state(True)
|
||||
|
||||
@callback
|
||||
def template_switch_startup(event):
|
||||
@@ -111,7 +111,7 @@ class SwitchTemplate(SwitchDevice):
|
||||
async_track_state_change(
|
||||
self.hass, self._entities, template_switch_state_listener)
|
||||
|
||||
self.hass.async_add_job(self.async_update_ha_state(True))
|
||||
self.async_schedule_update_ha_state(True)
|
||||
|
||||
self.hass.bus.async_listen_once(
|
||||
EVENT_HOMEASSISTANT_START, template_switch_startup)
|
||||
|
||||
+3
-2
@@ -1,8 +1,9 @@
|
||||
"""Support for Xiaomi binary sensors."""
|
||||
"""Support for Xiaomi aqara binary sensors."""
|
||||
import logging
|
||||
|
||||
from homeassistant.components.switch import SwitchDevice
|
||||
from homeassistant.components.xiaomi import (PY_XIAOMI_GATEWAY, XiaomiDevice)
|
||||
from homeassistant.components.xiaomi_aqara import (PY_XIAOMI_GATEWAY,
|
||||
XiaomiDevice)
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
Reference in new issue
Block a user