Added PIN mappings to gpio plugin, support for read/write by PIN name and read_all method

This commit is contained in:
Fabio Manganiello 2018-08-22 19:09:17 +02:00
parent a6339de159
commit 133dd4570e

View file

@ -16,16 +16,44 @@ class GpioPlugin(Plugin):
* **RPi.GPIO** (`pip install RPi.GPIO`) * **RPi.GPIO** (`pip install RPi.GPIO`)
""" """
def __init__(self, *args, **kwargs): def __init__(self, pins=None, *args, **kwargs):
"""
:param pins: Configuration for the GPIO PINs as an pin_number -> name map.
:type pins: dict
Example::
{
14: "LED_1",
15: "LED_2",
16: "MOTOR",
17: "SENSOR"
}
"""
super().__init__(*args, **kwargs) super().__init__(*args, **kwargs)
self.pins_by_number = pins if pins else {}
self.pins_by_name = { name:number
for (number, name) in self.pins_by_number.items() }
def _get_pin_number(self, pin):
try:
pin = int(str(pin))
except ValueError:
pin = self.pins_by_name.get(pin)
if not pin:
raise RuntimeError('Unknown PIN name: "{}"'.format(pin))
return pin
@action @action
def write(self, pin, val): def write(self, pin, val):
""" """
Write a byte value to a pin. Write a byte value to a pin.
:param pin: PIN number :param pin: PIN number or configured name
:type pin: int :type pin: int or str
:param val: Value to write :param val: Value to write
:type val: int :type val: int
@ -43,6 +71,7 @@ class GpioPlugin(Plugin):
import RPi.GPIO as gpio import RPi.GPIO as gpio
pin = self._get_pin_number(pin)
gpio.setmode(gpio.BCM) gpio.setmode(gpio.BCM)
gpio.setup(pin, gpio.OUT) gpio.setup(pin, gpio.OUT)
gpio.output(pin, val) gpio.output(pin, val)
@ -58,9 +87,8 @@ class GpioPlugin(Plugin):
""" """
Reads a value from a PIN. Reads a value from a PIN.
:param pin: PIN number :param pin: PIN number or configured name.
:type pin: int :type pin: int or str
:returns: dict :returns: dict
Response:: Response::
@ -74,6 +102,7 @@ class GpioPlugin(Plugin):
import RPi.GPIO as gpio import RPi.GPIO as gpio
pin = self._get_pin_number(pin)
gpio.setmode(gpio.BCM) gpio.setmode(gpio.BCM)
gpio.setup(pin, gpio.IN) gpio.setup(pin, gpio.IN)
val = gpio.input(pin) val = gpio.input(pin)
@ -84,6 +113,32 @@ class GpioPlugin(Plugin):
'method': 'read', 'method': 'read',
} }
@action
def read_all(self):
"""
Reads the values from all the configured PINs and returns them as a list. It will raise a RuntimeError if no PIN mappings were configured.
:returns: list
"""
import RPi.GPIO as gpio
if not self.pins_by_number:
raise RuntimeError("No PIN mappings were provided/configured")
values = []
for (pin, name) in self.pins_by_number.keys():
gpio.setmode(gpio.BCM)
gpio.setup(pin, gpio.IN)
val = gpio.input(pin)
values.append({
'pin': pin,
'name': name,
'val': val,
})
return values
# vim:sw=4:ts=4:et: # vim:sw=4:ts=4:et: