Merge remote-tracking branch 'balloob/dev' into feature/enhance_wemo

This commit is contained in:
pavoni committed 2015-08-30 22:47:49 +01:00
commit bfbaaa8e9f
167 files changed
+6705 -2728

No files matched your search

+2 -5
View File
@@ -11,7 +11,7 @@ from homeassistant.helpers.entity import ToggleEntity
from homeassistant.const import (
STATE_ON, SERVICE_TURN_ON, SERVICE_TURN_OFF, ATTR_ENTITY_ID)
from homeassistant.components import group, discovery, wink, isy994
from homeassistant.components import group, discovery, wink, isy994, verisure
DOMAIN = 'switch'
DEPENDENCIES = []
@@ -34,6 +34,7 @@ DISCOVERY_PLATFORMS = {
discovery.SERVICE_WEMO: 'wemo',
wink.DISCOVER_SWITCHES: 'wink',
isy994.DISCOVER_SWITCHES: 'isy994',
verisure.DISCOVER_SWITCHES: 'verisure'
}
PROP_TO_ATTR = {
@@ -49,21 +50,18 @@ _LOGGER = logging.getLogger(__name__)
def is_on(hass, entity_id=None):
""" Returns if the switch is on based on the statemachine. """
entity_id = entity_id or ENTITY_ID_ALL_SWITCHES
return hass.states.is_state(entity_id, STATE_ON)
def turn_on(hass, entity_id=None):
""" Turns all or specified switch on. """
data = {ATTR_ENTITY_ID: entity_id} if entity_id else None
hass.services.call(DOMAIN, SERVICE_TURN_ON, data)
def turn_off(hass, entity_id=None):
""" Turns all or specified switch off. """
data = {ATTR_ENTITY_ID: entity_id} if entity_id else None
hass.services.call(DOMAIN, SERVICE_TURN_OFF, data)
@@ -88,7 +86,6 @@ def setup(hass, config):
switch.update_ha_state(True)
hass.services.register(DOMAIN, SERVICE_TURN_OFF, handle_switch_service)
hass.services.register(DOMAIN, SERVICE_TURN_ON, handle_switch_service)
return True
+117
View File
@@ -0,0 +1,117 @@
"""
homeassistant.components.switch.edimax
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Support for Edimax switches.
Configuration:
To use the Edimax switch you will need to add something like the following to
your config/configuration.yaml.
switch:
platform: edimax
host: 192.168.1.32
username: YOUR_USERNAME
password: YOUR_PASSWORD
name: Edimax Smart Plug
Variables:
host
*Required
This is the IP address of your Edimax switch. Example: 192.168.1.32
username
*Required
Your username to access your Edimax switch.
password
*Required
Your password.
name
*Optional
The name to use when displaying this switch instance.
"""
import logging
from homeassistant.helpers import validate_config
from homeassistant.components.switch import SwitchDevice, DOMAIN
from homeassistant.const import CONF_HOST, CONF_USERNAME, CONF_PASSWORD,\
CONF_NAME
# constants
DEFAULT_USERNAME = 'admin'
DEFAULT_PASSWORD = '1234'
DEVICE_DEFAULT_NAME = 'Edimax Smart Plug'
REQUIREMENTS = ['https://github.com/rkabadi/pyedimax/archive/' +
'365301ce3ff26129a7910c501ead09ea625f3700.zip']
# setup logger
_LOGGER = logging.getLogger(__name__)
# pylint: disable=unused-argument
def setup_platform(hass, config, add_devices_callback, discovery_info=None):
""" Find and return Edimax Smart Plugs. """
try:
# pylint: disable=no-name-in-module, import-error
from pyedimax.smartplug import SmartPlug
except ImportError:
_LOGGER.error('Failed to import pyedimax')
return False
# pylint: disable=global-statement
# check for required values in configuration file
if not validate_config({DOMAIN: config},
{DOMAIN: [CONF_HOST]},
_LOGGER):
return False
host = config.get(CONF_HOST)
auth = (config.get(CONF_USERNAME, DEFAULT_USERNAME),
config.get(CONF_PASSWORD, DEFAULT_PASSWORD))
name = config.get(CONF_NAME, DEVICE_DEFAULT_NAME)
add_devices_callback([SmartPlugSwitch(SmartPlug(host, auth), name)])
class SmartPlugSwitch(SwitchDevice):
""" Represents an Edimax Smart Plug switch. """
def __init__(self, smartplug, name):
self.smartplug = smartplug
self._name = name
@property
def name(self):
""" Returns the name of the Smart Plug, if any. """
return self._name
@property
def current_power_mwh(self):
""" Current power usage in mwh. """
try:
return float(self.smartplug.now_power) / 1000000.0
except ValueError:
return None
@property
def today_power_mw(self):
""" Today total power usage in mw. """
try:
return float(self.smartplug.now_energy_day) / 1000.0
except ValueError:
return None
@property
def is_on(self):
""" True if switch is on. """
return self.smartplug.state == 'ON'
def turn_on(self, **kwargs):
""" Turns the switch on. """
self.smartplug.state = 'ON'
def turn_off(self):
""" Turns the switch off. """
self.smartplug.state = 'OFF'
@@ -1,24 +1,21 @@
"""
homeassistant.components.switch.hikvision
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Support turning on/off motion detection on Hikvision cameras.
Note: Currently works using default https port only.
CGI API Guide:
http://bit.ly/1RuyUuF
CGI API Guide: http://bit.ly/1RuyUuF
Configuration:
To use the Hikvision motion detection
switch you will need to add something like the
following to your config/configuration.yaml
To use the Hikvision motion detection switch you will need to add something
like the following to your config/configuration.yaml
switch:
platform: hikvisioncam
name: Hikvision Cam 1 Motion Detection
host: 192.168.1.26
host: 192.168.1.32
username: YOUR_USERNAME
password: YOUR_PASSWORD
@@ -30,16 +27,15 @@ This is the IP address of your Hikvision camera. Example: 192.168.1.32
username
*Required
Your Hikvision camera username
Your Hikvision camera username.
password
*Required
Your Hikvision camera username
Your Hikvision camera username.
name
*Optional
The name to use when displaying this switch instance.
"""
from homeassistant.helpers.entity import ToggleEntity
from homeassistant.const import STATE_ON, STATE_OFF
@@ -53,7 +49,7 @@ except ImportError:
hikvision.api = None
_LOGGING = logging.getLogger(__name__)
REQUIREMENTS = ['hikvision>=0.4']
REQUIREMENTS = ['hikvision==0.4']
# pylint: disable=too-many-arguments
# pylint: disable=too-many-instance-attributes
+57 -30
View File
@@ -18,12 +18,16 @@ sensor:
name: My switch
2:
name: My other switch
coils:
0:
name: My coil switch
VARIABLES:
- "slave" = slave number (ignored and can be omitted if not serial Modbus)
- "registers" contains a list of relevant registers to read from
- it must contain a "bits" section, listing relevant bits
- "coils" contains a list of relevant coils to read from/write to
- each named bit will create a switch
"""
@@ -34,6 +38,7 @@ import homeassistant.components.modbus as modbus
from homeassistant.helpers.entity import ToggleEntity
_LOGGER = logging.getLogger(__name__)
DEPENDENCIES = ['modbus']
def setup_platform(hass, config, add_devices, discovery_info=None):
@@ -44,25 +49,36 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
_LOGGER.error("No slave number provided for serial Modbus")
return False
registers = config.get("registers")
for regnum, register in registers.items():
bits = register.get("bits")
for bitnum, bit in bits.items():
if bit.get("name"):
switches.append(ModbusSwitch(bit.get("name"),
slave,
regnum,
bitnum))
if registers:
for regnum, register in registers.items():
bits = register.get("bits")
for bitnum, bit in bits.items():
if bit.get("name"):
switches.append(ModbusSwitch(bit.get("name"),
slave,
regnum,
bitnum))
coils = config.get("coils")
if coils:
for coilnum, coil in coils.items():
switches.append(ModbusSwitch(coil.get("name"),
slave,
coilnum,
0,
coil=True))
add_devices(switches)
class ModbusSwitch(ToggleEntity):
# pylint: disable=too-many-arguments
""" Represents a Modbus switch. """
def __init__(self, name, slave, register, bit):
def __init__(self, name, slave, register, bit, coil=False):
self._name = name
self.slave = int(slave) if slave else 1
self.register = int(register)
self.bit = int(bit)
self._coil = coil
self._is_on = None
self.register_value = None
@@ -92,33 +108,44 @@ class ModbusSwitch(ToggleEntity):
""" Get the name of the switch. """
return self._name
@property
def state_attributes(self):
attr = super().state_attributes
return attr
def turn_on(self, **kwargs):
""" Set switch on. """
if self.register_value is None:
self.update()
val = self.register_value | (0x0001 << self.bit)
modbus.NETWORK.write_register(unit=self.slave,
address=self.register,
value=val)
if self._coil:
modbus.NETWORK.write_coil(self.register, True)
else:
val = self.register_value | (0x0001 << self.bit)
modbus.NETWORK.write_register(unit=self.slave,
address=self.register,
value=val)
def turn_off(self, **kwargs):
""" Set switch off. """
if self.register_value is None:
self.update()
val = self.register_value & ~(0x0001 << self.bit)
modbus.NETWORK.write_register(unit=self.slave,
address=self.register,
value=val)
if self._coil:
modbus.NETWORK.write_coil(self.register, False)
else:
val = self.register_value & ~(0x0001 << self.bit)
modbus.NETWORK.write_register(unit=self.slave,
address=self.register,
value=val)
def update(self):
result = modbus.NETWORK.read_holding_registers(unit=self.slave,
address=self.register,
count=1)
val = 0
for i, res in enumerate(result.registers):
val += res * (2**(i*16))
self.register_value = val
self._is_on = (val & (0x0001 << self.bit) > 0)
""" Update the state of the switch. """
if self._coil:
result = modbus.NETWORK.read_coils(self.register, 1)
self.register_value = result.bits[0]
self._is_on = self.register_value
else:
result = modbus.NETWORK.read_holding_registers(
unit=self.slave, address=self.register,
count=1)
val = 0
for i, res in enumerate(result.registers):
val += res * (2**(i*16))
self.register_value = val
self._is_on = (val & (0x0001 << self.bit) > 0)
+153
View File
@@ -0,0 +1,153 @@
# -*- coding: utf-8 -*-
"""
homeassistant.components.switch.mqtt
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Allows to configure a MQTT switch.
In an ideal scenario, the MQTT device will have a state topic to publish
state changes. If these messages are published with RETAIN flag, the MQTT
switch will receive an instant state update after subscription and will
start with correct state. Otherwise, the initial state of the switch will
be false/off.
When a state topic is not available, the switch will work in optimistic mode.
In this mode, the switch will immediately change state after every command.
Otherwise, the switch will wait for state confirmation from device
(message from state_topic).
Optimistic mode can be forced, even if state topic is available.
Try to enable it, if experiencing incorrect switch operation.
Configuration:
switch:
platform: mqtt
name: "Bedroom Switch"
state_topic: "home/bedroom/switch1"
command_topic: "home/bedroom/switch1/set"
payload_on: "ON"
payload_off: "OFF"
optimistic: false
Variables:
name
*Optional
The name of the switch. Default is 'MQTT Switch'.
state_topic
*Optional
The MQTT topic subscribed to receive state updates.
If not specified, optimistic mode will be forced.
command_topic
*Required
The MQTT topic to publish commands to change the switch state.
payload_on
*Optional
The payload that represents enabled state. Default is "ON".
payload_off
*Optional
The payload that represents disabled state. Default is "OFF".
optimistic
*Optional
Flag that defines if switch works in optimistic mode. Default is false.
"""
import logging
import homeassistant.components.mqtt as mqtt
from homeassistant.components.switch import SwitchDevice
_LOGGER = logging.getLogger(__name__)
DEFAULT_NAME = "MQTT Switch"
DEFAULT_PAYLOAD_ON = "ON"
DEFAULT_PAYLOAD_OFF = "OFF"
DEFAULT_OPTIMISTIC = False
DEPENDENCIES = ['mqtt']
# pylint: disable=unused-argument
def setup_platform(hass, config, add_devices_callback, discovery_info=None):
""" Add MQTT Switch """
if config.get('command_topic') is None:
_LOGGER.error("Missing required variable: command_topic")
return False
add_devices_callback([MqttSwitch(
hass,
config.get('name', DEFAULT_NAME),
config.get('state_topic'),
config.get('command_topic'),
config.get('payload_on', DEFAULT_PAYLOAD_ON),
config.get('payload_off', DEFAULT_PAYLOAD_OFF),
config.get('optimistic', DEFAULT_OPTIMISTIC))])
# pylint: disable=too-many-arguments, too-many-instance-attributes
class MqttSwitch(SwitchDevice):
""" Represents a switch that can be togggled using MQTT """
def __init__(self, hass, name, state_topic, command_topic,
payload_on, payload_off, optimistic):
self._state = False
self._hass = hass
self._name = name
self._state_topic = state_topic
self._command_topic = command_topic
self._payload_on = payload_on
self._payload_off = payload_off
self._optimistic = optimistic
def message_received(topic, payload, qos):
""" A new MQTT message has been received. """
if payload == self._payload_on:
self._state = True
self.update_ha_state()
elif payload == self._payload_off:
self._state = False
self.update_ha_state()
if self._state_topic is None:
# force optimistic mode
self._optimistic = True
else:
# subscribe the state_topic
mqtt.subscribe(hass, self._state_topic, message_received)
@property
def should_poll(self):
""" No polling needed """
return False
@property
def name(self):
""" The name of the switch """
return self._name
@property
def is_on(self):
""" True if device is on. """
return self._state
def turn_on(self, **kwargs):
""" Turn the device on. """
mqtt.publish(self.hass, self._command_topic, self._payload_on)
if self._optimistic:
# optimistically assume that switch has changed state
self._state = True
self.update_ha_state()
def turn_off(self, **kwargs):
""" Turn the device off. """
mqtt.publish(self.hass, self._command_topic, self._payload_off)
if self._optimistic:
# optimistically assume that switch has changed state
self._state = False
self.update_ha_state()
+134
View File
@@ -0,0 +1,134 @@
"""
homeassistant.components.switch.rpi_gpio
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Allows to control the GPIO pins of a Raspberry Pi.
Note: To use RPi GPIO, Home Assistant must be run as root.
Configuration:
switch:
platform: rpi_gpio
invert_logic: false
ports:
11: Fan Office
12: Light Desk
Variables:
invert_logic
*Optional
If true, inverts the output logic to ACTIVE LOW. Default is false (ACTIVE HIGH)
ports
*Required
An array specifying the GPIO ports to use and the name to use in the frontend.
"""
import logging
try:
import RPi.GPIO as GPIO
except ImportError:
GPIO = None
from homeassistant.helpers.entity import ToggleEntity
from homeassistant.const import (DEVICE_DEFAULT_NAME,
EVENT_HOMEASSISTANT_START,
EVENT_HOMEASSISTANT_STOP)
DEFAULT_INVERT_LOGIC = False
REQUIREMENTS = ['RPi.GPIO==0.5.11']
_LOGGER = logging.getLogger(__name__)
# pylint: disable=unused-argument
def setup_platform(hass, config, add_devices, discovery_info=None):
""" Sets up the Raspberry PI GPIO ports. """
if GPIO is None:
_LOGGER.error('RPi.GPIO not available. rpi_gpio ports ignored.')
return
# pylint: disable=no-member
GPIO.setmode(GPIO.BCM)
switches = []
invert_logic = config.get('invert_logic', DEFAULT_INVERT_LOGIC)
ports = config.get('ports')
for port_num, port_name in ports.items():
switches.append(RPiGPIOSwitch(port_name, port_num, invert_logic))
add_devices(switches)
def cleanup_gpio(event):
""" Stuff to do before stop home assistant. """
# pylint: disable=no-member
GPIO.cleanup()
def prepare_gpio(event):
""" Stuff to do when home assistant starts. """
hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, cleanup_gpio)
hass.bus.listen_once(EVENT_HOMEASSISTANT_START, prepare_gpio)
class RPiGPIOSwitch(ToggleEntity):
""" Represents a port that can be toggled using Raspberry Pi GPIO. """
def __init__(self, name, gpio, invert_logic):
self._name = name or DEVICE_DEFAULT_NAME
self._gpio = gpio
self._active_state = not invert_logic
self._state = not self._active_state
# pylint: disable=no-member
GPIO.setup(gpio, GPIO.OUT)
@property
def name(self):
""" The name of the port. """
return self._name
@property
def should_poll(self):
""" No polling needed. """
return False
@property
def is_on(self):
""" True if device is on. """
return self._state
def turn_on(self, **kwargs):
""" Turn the device on. """
if self._switch(self._active_state):
self._state = True
self.update_ha_state()
def turn_off(self, **kwargs):
""" Turn the device off. """
if self._switch(not self._active_state):
self._state = False
self.update_ha_state()
def _switch(self, new_state):
""" Change the output value to Raspberry Pi GPIO port. """
_LOGGER.info('Setting GPIO %s to %s', self._gpio, new_state)
# pylint: disable=bare-except
try:
# pylint: disable=no-member
GPIO.output(self._gpio, 1 if new_state else 0)
except:
_LOGGER.error('GPIO "%s" output failed', self._gpio)
return False
return True
# pylint: disable=no-self-use
@property
def device_state_attributes(self):
""" Returns device specific state attributes. """
return None
@property
def state_attributes(self):
""" Returns optional state attributes. """
data = {}
device_attr = self.device_state_attributes
if device_attr is not None:
data.update(device_attr)
return data
@@ -19,6 +19,8 @@ import tellcore.constants as tellcore_constants
SINGAL_REPETITIONS = 1
REQUIREMENTS = ['tellcore-py==1.0.4']
# pylint: disable=unused-argument
def setup_platform(hass, config, add_devices_callback, discovery_info=None):
@@ -1,8 +1,7 @@
"""
homeassistant.components.switch.transmission
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Enable or disable Transmission BitTorrent client Turtle Mode
Enable or disable Transmission BitTorrent client Turtle Mode.
Configuration:
@@ -29,37 +28,32 @@ The port your Transmission daemon uses, defaults to 9091. Example: 8080
username
*Optional
Your Transmission username, if you use authentication
Your Transmission username, if you use authentication.
password
*Optional
Your Transmission username, if you use authentication
Your Transmission username, if you use authentication.
name
*Optional
The name to use when displaying this Transmission instance.
"""
from homeassistant.const import CONF_HOST, CONF_USERNAME, CONF_PASSWORD
from homeassistant.const import STATE_ON, STATE_OFF
from homeassistant.helpers.entity import ToggleEntity
# pylint: disable=no-name-in-module, import-error
import transmissionrpc
from transmissionrpc.error import TransmissionError
import logging
_LOGGING = logging.getLogger(__name__)
REQUIREMENTS = ['transmissionrpc>=0.11']
REQUIREMENTS = ['transmissionrpc==0.11']
# pylint: disable=unused-argument
def setup_platform(hass, config, add_devices_callback, discovery_info=None):
""" Sets up the sensors. """
""" Sets up the transmission sensor. """
host = config.get(CONF_HOST)
username = config.get(CONF_USERNAME, None)
password = config.get(CONF_PASSWORD, None)
@@ -87,7 +81,6 @@ def setup_platform(hass, config, add_devices_callback, discovery_info=None):
class TransmissionSwitch(ToggleEntity):
""" A Transmission sensor. """
def __init__(self, transmission_client, name):
+10 -14
View File
@@ -1,9 +1,11 @@
"""
homeassistant.components.switch.vera
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Support for Vera switches.
Configuration:
To use the Vera lights you will need to add something like the following to
your config/configuration.yaml
your config/configuration.yaml.
switch:
platform: vera
@@ -15,38 +17,32 @@ switch:
13:
name: Another Switch
VARIABLES:
Variables:
vera_controller_url
*Required
This is the base URL of your vera controller including the port number if not
running on 80
Example: http://192.168.1.21:3480/
running on 80. Example: http://192.168.1.21:3480/
device_data
*Optional
This contains an array additional device info for your Vera devices. It is not
required and if not specified all lights configured in your Vera controller
will be added with default values. You should use the id of your vera device
as the key for the device within device_data
as the key for the device within device_data.
These are the variables for the device_data array:
name
*Optional
This parameter allows you to override the name of your Vera device in the HA
interface, if not specified the value configured for the device in your Vera
will be used
will be used.
exclude
*Optional
This parameter allows you to exclude the specified device from homeassistant,
it should be set to "true" if you want this device excluded
it should be set to "true" if you want this device excluded.
"""
import logging
import time
@@ -82,7 +78,7 @@ def get_devices(hass, config):
devices = vera_controller.get_devices([
'Switch', 'Armable Sensor', 'On/Off Switch'])
except RequestException:
# There was a network related error connecting to the vera controller
# There was a network related error connecting to the vera controller.
_LOGGER.exception("Error communicating with Vera API")
return False
@@ -103,7 +99,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
class VeraSwitch(ToggleEntity):
""" Represents a Vera Switch """
""" Represents a Vera Switch. """
def __init__(self, vera_device, extra_data=None):
self.vera_device = vera_device
@@ -0,0 +1,63 @@
"""
homeassistant.components.switch.verisure
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Support for Verisure Smartplugs
"""
import logging
import homeassistant.components.verisure as verisure
from homeassistant.components.switch import SwitchDevice
_LOGGER = logging.getLogger(__name__)
def setup_platform(hass, config, add_devices, discovery_info=None):
""" Sets up the Arduino platform. """
if not verisure.MY_PAGES:
_LOGGER.error('A connection has not been made to Verisure mypages.')
return False
switches = []
switches.extend([
VerisureSmartplug(value)
for value in verisure.get_smartplug_status().values()
if verisure.SHOW_SMARTPLUGS
])
add_devices(switches)
class VerisureSmartplug(SwitchDevice):
""" Represents a Verisure smartplug. """
def __init__(self, smartplug_status):
self._id = smartplug_status.id
self.status_on = verisure.MY_PAGES.SMARTPLUG_ON
self.status_off = verisure.MY_PAGES.SMARTPLUG_OFF
@property
def name(self):
""" Get the name (location) of the smartplug. """
return verisure.get_smartplug_status()[self._id].location
@property
def is_on(self):
""" Returns True if on """
plug_status = verisure.get_smartplug_status()[self._id].status
return plug_status == self.status_on
def turn_on(self):
""" Set smartplug status on """
verisure.MY_PAGES.set_smartplug_status(
self._id,
self.status_on)
def turn_off(self):
""" Set smartplug status off """
verisure.MY_PAGES.set_smartplug_status(
self._id,
self.status_off)
def update(self):
verisure.update()
+3 -1
View File
@@ -8,6 +8,8 @@ import logging
from homeassistant.components.switch import SwitchDevice
REQUIREMENTS = ['pywemo==0.2']
# pylint: disable=unused-argument
def setup_platform(hass, config, add_devices_callback, discovery_info=None):
@@ -16,7 +18,7 @@ def setup_platform(hass, config, add_devices_callback, discovery_info=None):
import pywemo.discovery as discovery
if discovery_info is not None:
device = discovery.device_from_description(discovery_info)
device = discovery.device_from_description(discovery_info[2])
if device:
add_devices_callback([WemoSwitch(device)])
+3
View File
@@ -9,6 +9,9 @@ import logging
from homeassistant.components.wink import WinkToggleDevice
from homeassistant.const import CONF_ACCESS_TOKEN
REQUIREMENTS = ['https://github.com/balloob/python-wink/archive/' +
'c2b700e8ca866159566ecf5e644d9c297f69f257.zip']
def setup_platform(hass, config, add_devices, discovery_info=None):
""" Sets up the Wink platform. """