core/homeassistant/components/switch/mystrom.py

100 lines
3.1 KiB
Python
Raw Normal View History

2015-11-25 16:21:11 +00:00
"""
homeassistant.components.switch.mystrom
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Support for myStrom switches.
For more details about this component, please refer to the documentation at
https://home-assistant.io/components/switch.mystrom/
"""
import logging
import requests
from homeassistant.components.switch import SwitchDevice
DEFAULT_NAME = 'myStrom Switch'
_LOGGER = logging.getLogger(__name__)
def setup_platform(hass, config, add_devices, discovery_info=None):
""" Find and return myStrom switches. """
host = config.get('host')
2015-11-25 16:21:11 +00:00
if host is None:
_LOGGER.error('Missing required variable: host')
2015-11-25 16:21:11 +00:00
return False
resource = 'http://{}'.format(host)
2015-11-25 16:21:11 +00:00
try:
requests.get(resource, timeout=10)
except requests.exceptions.ConnectionError:
_LOGGER.error("No route to device %s. "
"Please check the IP address in the configuration file",
host)
2015-11-25 16:21:11 +00:00
return False
add_devices([MyStromSwitch(
config.get('name', DEFAULT_NAME),
resource)])
2015-11-25 16:21:11 +00:00
class MyStromSwitch(SwitchDevice):
""" Represents a myStrom switch. """
def __init__(self, name, resource):
2015-11-25 17:07:29 +00:00
self._state = False
2015-11-25 16:21:11 +00:00
self._name = name
self._resource = resource
self.consumption = 0
@property
def name(self):
""" The name of the switch. """
return self._name
@property
def is_on(self):
""" True if switch is on. """
return self._state
@property
def current_power_mwh(self):
""" Current power consumption in mwh. """
return self.consumption
def turn_on(self, **kwargs):
""" Turn the switch on. """
2015-11-25 17:07:29 +00:00
try:
request = requests.get('{}/relay'.format(self._resource),
params={'state': '1'},
timeout=10)
if request.status_code == 200:
self._state = True
except requests.exceptions.ConnectionError:
2015-11-25 16:21:11 +00:00
_LOGGER.error("Can't turn on %s. Is device offline?",
self._resource)
def turn_off(self, **kwargs):
""" Turn the switch off. """
2015-11-25 17:07:29 +00:00
try:
request = requests.get('{}/relay'.format(self._resource),
params={'state': '0'},
timeout=10)
if request.status_code == 200:
self._state = False
except requests.exceptions.ConnectionError:
_LOGGER.error("Can't turn on %s. Is device offline?",
2015-11-25 16:21:11 +00:00
self._resource)
def update(self):
""" Gets the latest data from REST API and updates the state. """
try:
request = requests.get('{}/report'.format(self._resource),
timeout=10)
2015-11-29 21:49:05 +00:00
data = request.json()
self._state = bool(data['relay'])
self.consumption = data['power']
2015-11-25 16:21:11 +00:00
except requests.exceptions.ConnectionError:
_LOGGER.error("No route to device '%s'. Is device offline?",
self._resource)