Fix RPi_GPIO switch and add extra parameters

This commit is contained in:
sfam 2015-08-25 23:23:51 +01:00
parent d0c674b756
commit 0a9d82fe6f

View File

@ -2,21 +2,28 @@
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
active_state: "HIGH"
ports:
11: Fan Office
12: Light Desk
Variables:
active_state
*Optional
Defines which GPIO state corresponds to a ACTIVE switch. Default is 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
@ -27,6 +34,8 @@ from homeassistant.const import (DEVICE_DEFAULT_NAME,
EVENT_HOMEASSISTANT_START,
EVENT_HOMEASSISTANT_STOP)
DEFAULT_ACTIVE_STATE = "HIGH"
REQUIREMENTS = ['RPi.GPIO>=0.5.11']
_LOGGER = logging.getLogger(__name__)
@ -38,10 +47,13 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
_LOGGER.error('RPi.GPIO not available. rpi_gpio ports ignored.')
return
GPIO.setmode(GPIO.BCM)
switches = []
active_state = config.get('active_state', DEFAULT_ACTIVE_STATE)
ports = config.get('ports')
for port_num, port_name in ports.items():
switches.append(RPiGPIOSwitch(port_name, port_num))
switches.append(RPiGPIOSwitch(port_name, port_num, active_state))
add_devices(switches)
def cleanup_gpio(event):
@ -59,10 +71,11 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
class RPiGPIOSwitch(ToggleEntity):
""" Represents a port that can be toggled using Raspberry Pi GPIO. """
def __init__(self, name, gpio):
def __init__(self, name, gpio, active_state):
self._name = name or DEVICE_DEFAULT_NAME
self._state = False
self._state = False if self._active_state == "HIGH" else True
self._gpio = gpio
self._active_state = active_state
# pylint: disable=no-member
GPIO.setup(gpio, GPIO.OUT)
@ -83,13 +96,13 @@ class RPiGPIOSwitch(ToggleEntity):
def turn_on(self, **kwargs):
""" Turn the device on. """
if self._switch(True):
if self._switch(True if self._active_state == "HIGH" else False):
self._state = True
self.update_ha_state()
def turn_off(self, **kwargs):
""" Turn the device off. """
if self._switch(False):
if self._switch(False if self._active_state == "HIGH" else True):
self._state = False
self.update_ha_state()