浏览代码

add neurone launcher

Nicolas Marcq 8 年之前
父节点
当前提交
80aa8227d0

+ 7 - 5
core/ConfigurationManager/ConfigurationManager.py

@@ -4,8 +4,10 @@ from SettingLoader import SettingLoader
 
 class ConfigurationManager:
 
-    def __init__(self):
-        BRAIN_FILE_NAME = "brain.yml"
-        SETTING_FILE_NAME = "settings.yml"
-        self.brainLoader = BrainLoader(BRAIN_FILE_NAME)
-        self.settingLoader = SettingLoader(SETTING_FILE_NAME)
+    def __init__(self, brain_file_name=None, setting_file_name=None):
+        if brain_file_name is None:
+            brain_file_name = "brain.yml"
+        if setting_file_name is None:
+            setting_file_name = "settings.yml"
+        self.brainLoader = BrainLoader(brain_file_name)
+        self.settingLoader = SettingLoader(setting_file_name)

+ 5 - 0
core/Neurone.py

@@ -12,3 +12,8 @@ class Neurone:
         # the module is imported on fly, depending on the selected tts from settings
         tts_backend = importlib.import_module("tts." + self.tts)
         tts_backend.say(message)
+
+    def debug_kwargs(self, *args, **kwargs):
+        if kwargs is not None:
+            for key, value in kwargs.iteritems():
+                print "%s == %s" % (key, value)

+ 53 - 0
core/NeuroneLauncher.py

@@ -0,0 +1,53 @@
+class NeuroneNotFoundError(Exception):
+    pass
+
+
+def _run_plugin(plugin, parameters=None):
+    """
+    Dynamic loading of a module
+    :param plugin: Module name to load
+    :param parameters: Parameter of the module
+    :return:
+    """
+    print "Run plugin %s with parameter %s" % (plugin, parameters)
+    mod = __import__('neurons', fromlist=[plugin])
+    try:
+        klass = getattr(mod, plugin)
+    except AttributeError:
+        print "Error: No module named %s " % plugin
+        raise NeuroneNotFoundError
+
+    if klass is not None:
+        # run the plugin
+        if not parameters:
+            klass()
+        elif isinstance(parameters, dict):
+            klass(**parameters)
+        else:
+            klass(parameters)
+
+
+class NeuroneLauncher:
+
+    def __init__(self):
+        pass
+
+    @staticmethod
+    def start_neurone(neuron):
+        """
+        Neuron dict to start. {'neurone_name': {'args1': 'value1',  'args2': 'value2'}}
+        :param neuron: Dict with neuron declaration
+        :type neuron: Dict
+        :return:
+        """
+        if isinstance(neuron, dict):
+            for plugin, parameters in neuron.items():
+                # capitalizes the first letter (because classes have first letter upper case)
+                plugin = plugin.capitalize()
+                _run_plugin(plugin, parameters)
+        else:
+            plugin = neuron
+            # capitalizes the first letter (because classes have first letter upper case)
+            plugin = plugin.capitalize()
+            _run_plugin(plugin)
+

+ 4 - 26
core/OrderAnalyser.py

@@ -1,5 +1,7 @@
 import re
 
+from core.NeuroneLauncher import NeuroneLauncher
+
 
 class OrderAnalyser:
     def __init__(self, order, main_controller=None):
@@ -27,16 +29,7 @@ class OrderAnalyser:
                     print "Order found! Run neurons: %s" % el["neurons"]
                     neurons = el["neurons"]
                     for neuron in neurons:
-                        if isinstance(neuron, dict):
-                            for plugin, parameter in neuron.items():
-                                # capitalizes the first letter (because classes have first letter upper case)
-                                plugin = plugin.capitalize()
-                                self._run_plugin(plugin, parameter)
-                        else:
-                            plugin = neuron
-                            # capitalizes the first letter (because classes have first letter upper case)
-                            plugin = plugin.capitalize()
-                            self._run_plugin(plugin)
+                        NeuroneLauncher().start_neurone(neuron)
 
         # once we ran all plugin, we can start back jarvis trigger
         if self.main_controller is not None:
@@ -52,21 +45,6 @@ class OrderAnalyser:
 
         if re.search(my_regex, self.order, re.IGNORECASE):
             return True
-
-    def _run_plugin(self, plugin, parameter=None):
-        """
-        Dynamic loading of a module
-        :param plugin: Module name to load
-        :param parameter: Parameter of the module
-        :return:
-        """
-        print "Run plugin %s with parameter %s" % (plugin, parameter)
-        mod = __import__('neurons', fromlist=[plugin])
-        klass = getattr(mod, plugin)
-        # run the plugin
-        if not parameter:
-            klass()
-        else:
-            klass(parameter)
+        return False
 
 

+ 4 - 1
neurons/say/say.py

@@ -2,6 +2,9 @@ from core import Neurone
 
 
 class Say(Neurone):
-    def __init__(self, message):
+    def __init__(self, *args , **kwargs):
         Neurone.__init__(self)
+
+        # get message to spell out loud
+        message = kwargs.get('message', "")
         self.say(message)

+ 28 - 3
neurons/script/script.py

@@ -1,9 +1,34 @@
 from core import Neurone
 import subprocess
+import os
+
+
+class ScriptNotFound(Exception):
+    pass
+
+
+class ScriptNotExecutable(Exception):
+    pass
 
 
 class Script(Neurone):
-    def __init__(self, script_path):
+    def __init__(self, *args , **kwargs):
         Neurone.__init__(self)
-        p = subprocess.Popen(script_path, stdout=subprocess.PIPE, shell=True)
-        (output, err) = p.communicate()
+
+        # get message to spell out loud
+        script_path = kwargs.get('path', "")
+
+        # test that the file exist and is executable
+        if self.is_exe(script_path):
+            p = subprocess.Popen(script_path, stdout=subprocess.PIPE, shell=True)
+            (output, err) = p.communicate()
+
+
+    def is_exe(self, fpath):
+        returned_value = True
+        if not os.path.isfile(fpath):
+            raise ScriptNotFound()
+        if not os.access(fpath, os.X_OK):
+            raise ScriptNotExecutable()
+
+        return returned_value

+ 0 - 1
neurons/systemdate/systemdate.py

@@ -6,7 +6,6 @@ from core import Neurone
 class Systemdate(Neurone):
     def __init__(self):
         Neurone.__init__(self)
-        date_now = time.strftime("%H:%M")
         hour = time.strftime("%H")
         minute = time.strftime("%M")
         message = "Il est %s heure %s" % (hour, minute)

+ 33 - 15
test.py

@@ -1,26 +1,44 @@
+from core import ConfigurationManager
+from core.NeuroneLauncher import NeuroneLauncher
 from core.OrderAnalyser import OrderAnalyser
 from core.OrderListener import OrderListener
+from neurons.ansible_tasks.ansible_tasks import Ansible_tasks
 
-#
-# oder = OrderListener()
-#
-# oder.start()
-
-# test give hour
-# order = "quelle heure est il?"
-
-# test run script
-# order = "lance script jarvis"
 
 # run command
-order = "playbook"
-order_analyser = OrderAnalyser(order)
+# order = "playbook"
+# order_analyser = OrderAnalyser(order)
+# order_analyser.start()
 
-order_analyser.start()
-# from neurons.ansible_tasks.ansible_tasks import Ansible_tasks
-#
+# test ansible
 # tasks_file = "tasks.yml"
 # ansible_tasks = Ansible_tasks(tasks_file)
 
 
+def test_multi_args(*args , **kwargs):
+    if kwargs is not None:
+        for key, value in kwargs.iteritems():
+            print "%s == %s" % (key, value)
+
+
+conf = ConfigurationManager(brain_file_name="test.yml")
+
+brain = conf.brainLoader.get_config()
+print brain
+
+
+for el in brain:
+    print el["neurons"]
+
+    neurons = el["neurons"]
+    for neuron in neurons:
+        NeuroneLauncher().start_neurone(neuron)
+
+
+    # test_multi_args(**el["neurons"][0]["say"])
+
+
+
+
+
 

+ 8 - 0
test.yml

@@ -0,0 +1,8 @@
+---
+  - name: "Say hello"
+    neurons:
+      - systemdate
+
+    when:
+      - order: "dis bonjour"
+