From 022a997dc296e7de57878cf01ac737a8410c2ebd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Krist=C3=B3f=20T=C3=B3th?= Date: Tue, 3 Jul 2018 19:06:54 +0200 Subject: [PATCH] Implement monkey patching callbacks in YamlFSM config --- lib/tfw/yaml_fsm.py | 31 +++++++++++++++++++++++++++---- 1 file changed, 27 insertions(+), 4 deletions(-) diff --git a/lib/tfw/yaml_fsm.py b/lib/tfw/yaml_fsm.py index fb54103..bb16b12 100644 --- a/lib/tfw/yaml_fsm.py +++ b/lib/tfw/yaml_fsm.py @@ -1,3 +1,6 @@ +from subprocess import Popen +from functools import partial + import yaml from transitions import State @@ -7,12 +10,32 @@ from tfw import FSMBase class YamlFSM(FSMBase): def __init__(self, config_file): self.config = self.parse_config(config_file) - self.states = [State(**state) for state in self.config['states']] - super(YamlFSM, self).__init__() - for transition in self.config['transitions']: - self.machine.add_transition(**transition) + self.patch_config_callbacks() + self.setup_states() + super(YamlFSM, self).__init__() # FSMBase.__init__() requires states + self.setup_transitions() @staticmethod def parse_config(config_file): with open(config_file, 'r') as ifile: return yaml.load(ifile) + + def setup_states(self): + self.states = [State(**state) for state in self.config['states']] + + def setup_transitions(self): + for transition in self.config['transitions']: + self.machine.add_transition(**transition) + + def patch_config_callbacks(self): + topatch = {'on_enter', 'on_exit', 'prepare', 'before', 'after'} + + for array in {'states', 'transitions'}: + for i, json_obj in enumerate(self.config[array]): + for attribute, value in json_obj.items(): + if attribute in topatch: + self.config[array][i][attribute] = partial(self.run, value) + + @staticmethod + def run(command, event): + Popen(command, shell=True)