core/homeassistant/components/switch/rpi_gpio.py

87 lines
2.4 KiB
Python
Raw Normal View History

2015-08-02 16:05:28 +00:00
"""
2016-01-15 12:35:06 +00:00
Allows to configure a switch using RPi GPIO.
2015-10-21 21:05:54 +00:00
For more details about this platform, please refer to the documentation at
2015-11-09 12:12:18 +00:00
https://home-assistant.io/components/switch.rpi_gpio/
2015-08-02 16:05:28 +00:00
"""
import logging
2016-02-19 05:27:50 +00:00
import voluptuous as vol
from homeassistant.components.switch import PLATFORM_SCHEMA
import homeassistant.components.rpi_gpio as rpi_gpio
2016-02-19 05:27:50 +00:00
from homeassistant.const import DEVICE_DEFAULT_NAME
2015-08-02 16:05:28 +00:00
from homeassistant.helpers.entity import ToggleEntity
import homeassistant.helpers.config_validation as cv
2015-08-02 16:05:28 +00:00
_LOGGER = logging.getLogger(__name__)
DEPENDENCIES = ['rpi_gpio']
CONF_PULL_MODE = 'pull_mode'
CONF_PORTS = 'ports'
CONF_INVERT_LOGIC = 'invert_logic'
DEFAULT_INVERT_LOGIC = False
_SWITCHES_SCHEMA = vol.Schema({
cv.positive_int: cv.string,
})
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Required(CONF_PORTS): _SWITCHES_SCHEMA,
vol.Optional(CONF_INVERT_LOGIC, default=DEFAULT_INVERT_LOGIC): cv.boolean,
})
2015-08-02 16:05:28 +00:00
# pylint: disable=unused-argument
def setup_platform(hass, config, add_devices, discovery_info=None):
2016-03-08 12:35:39 +00:00
"""Setup the Raspberry PI GPIO devices."""
invert_logic = config.get(CONF_INVERT_LOGIC)
switches = []
ports = config.get(CONF_PORTS)
for port, name in ports.items():
switches.append(RPiGPIOSwitch(name, port, invert_logic))
2015-08-02 16:05:28 +00:00
add_devices(switches)
class RPiGPIOSwitch(ToggleEntity):
2016-03-08 12:35:39 +00:00
"""Representation of a Raspberry Pi GPIO."""
def __init__(self, name, port, invert_logic):
2016-03-08 12:35:39 +00:00
"""Initialize the pin."""
2015-08-02 16:05:28 +00:00
self._name = name or DEVICE_DEFAULT_NAME
self._port = port
self._invert_logic = invert_logic
self._state = False
rpi_gpio.setup_output(self._port)
rpi_gpio.write_output(self._port, 1 if self._invert_logic else 0)
2015-08-02 16:05:28 +00:00
@property
def name(self):
2016-03-08 12:35:39 +00:00
"""Return the name of the switch."""
2015-08-02 16:05:28 +00:00
return self._name
@property
def should_poll(self):
2016-03-08 12:35:39 +00:00
"""No polling needed."""
2015-08-02 16:05:28 +00:00
return False
@property
def is_on(self):
2016-03-08 12:35:39 +00:00
"""Return true if device is on."""
2015-08-02 16:05:28 +00:00
return self._state
def turn_on(self):
2016-03-08 12:35:39 +00:00
"""Turn the device on."""
rpi_gpio.write_output(self._port, 0 if self._invert_logic else 1)
self._state = True
2015-08-02 16:05:28 +00:00
self.update_ha_state()
def turn_off(self):
2016-03-08 12:35:39 +00:00
"""Turn the device off."""
rpi_gpio.write_output(self._port, 1 if self._invert_logic else 0)
self._state = False
2015-08-02 16:05:28 +00:00
self.update_ha_state()