#!/usr/bin/env python3 # -*- coding: utf-8 -*- """buttond.py: Watch a Rasberry Pi GPIO button. Exec Hog4 comment macros.""" __author__ = "Kevin Matz" __copyright__ = "Copyright 2019, Company 235, LLC" __credits__ = ["Kevin Matz"] __license__ = "MIT" __version__ = "1.0" __maintainer__ = "Kevin Matz" __email__ = "kevin@company235.com" __status__ = "Prototype" import configparser from bacon.script import comment from gpiozero import Button, GPIODeviceError from signal import pause # use mock pins when not working on Pi hardware # from gpiozero.pins.mock import MockFactory # from gpiozero import Device # Device.pin_factory = MockFactory() # callback intermidiary to sanitize user input def _activate(macro): if macro is None: return macro = macro.strip('\"').upper() if macro is "": return # pass macro to baconscript print("doing macro ", macro) comment(macro) # empty button directory _buttons = {} # open config file config = configparser.ConfigParser(allow_no_value=True) config.read('buttons.cfg') # set up each buttons for b in config.get('button', 'names').split(','): try: # move to config section c = config[b] # read from settings pin = c.get('pin', None) closed = c.get('close', None) opened = c.get('open', None) # set up button on pin print('init', b, 'on GPIO', pin) _buttons[b] = Button(pin) # connect button callbacks to anonymous functions print('connecting', b, '"closed" to macro', closed) _buttons[b].when_pressed = lambda macro=closed: _activate(macro) print('connecting', b, '"opened" to macro', opened) _buttons[b].when_released = lambda macro=opened: _activate(macro) except (KeyError, GPIODeviceError) as e: print('Error configuring button', b, e) continue # clear temp variables off the stack try: del pin, closed, opened del c, config except NameError as e: print('failed to release memory', e) # when run directly, sleep until button signal or KeyboardInterrupt if __name__ == '__main__': try: pause() except KeyboardInterrupt: print() else: # indicate prefered method of sleeping when laoded as a module print('call signal.pause() instead of time.sleep()')