Skip to content

Instantly share code, notes, and snippets.

@bennuttall
Last active August 21, 2017 11:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bennuttall/d34bcf7d01a186a7833d3f6e8a315c3d to your computer and use it in GitHub Desktop.
Save bennuttall/d34bcf7d01a186a7833d3f6e8a315c3d to your computer and use it in GitHub Desktop.
GPIO Zero YAML/JSON config parser
import gpiozero
from signal import pause
import json
try:
import yaml
except ImportError:
yaml = None
classes = {
name: cls
for name, cls in gpiozero.__dict__.items()
if isinstance(cls, type) and issubclass(cls, gpiozero.Device)
}
class GPIOZeroConfigParser:
def __init__(self, config_file):
ext = config_file.split('.')[-1]
_format = {
'json': json,
'yml': yaml
}[ext]
with open(config_file, 'r') as f:
self.config = _format.load(f)
self.devices = {}
self.device_data = {}
self.classes = set()
for device in self.config['devices']:
for obj_name, data in device.items():
class_name, *args = data.split(', ')
ClassName = classes[class_name]
self.classes.add(ClassName)
self.devices[obj_name] = ClassName(*[int(arg) for arg in args])
self.device_data[obj_name] = {
'class_name': class_name,
'args': [int(arg) for arg in args]
}
for connection in self.config['connections']:
for source_device_ref, value_device_ref in connection.items():
source_device = self.devices[source_device_ref]
value_device = self.devices[value_device_ref]
source_device.source = value_device.values
def to_python(self):
classes = ', '.join(obj.__name__ for obj in self.classes)
devices = '\n'.join(
'{} = {}({})'.format(obj_name, data['class_name'], *data['args'])
for obj_name, data in self.device_data.items()
)
connections = '\n'.join(
'{}.source = {}.values'.format(source_device, value_device)
for connection in self.config['connections']
for source_device, value_device in connection.items()
)
return """from gpiozero import {}
from signal import pause
{}
{}
pause()""".format(classes, devices, connections)
{
"devices": [
{"led": "LED, 17"},
{"btn": "Button, 18"}
],
"connections": [
{"led": "btn"}
]
}
devices:
- led: LED, 17
- btn: Button, 18
connections:
- led: btn
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment