瀏覽代碼

add include statement

nico 8 年之前
父節點
當前提交
041910559c

+ 9 - 156
brain.yml

@@ -1,164 +1,17 @@
 ---
-  - name: "Send push message"
-    neurons:
-      - push_message:
-           message: "Message to send"
-           api_key: "my_token_key"
-           channel_name: "my_chanel_name"
-    signals:
-      - order: "push message"
-
-  - name: "get the weather"
-    neurons:
-      - openweathermap:
-          api_key: "fdfba4097c318aed7836b2a85a6a05ef"
-          lang: "fr"
-          temp_unit: "celsius"
-          location : "grenoble"
-          country: "FR"
-          say_template:
-          - "Aujourd'hui a {{ location }} le temps est {{ weather_today }} avec une température de {{ temp_today_temp }} degrés et demain le temps sera {{ weather_tomorrow }} avec une température de {{ temp_tomorrow_temp }} degrés"
-    signals:
-      - order: "quel temps fait-il "
-
   - name: "say hello"
     neurons:
       - say:
           message:
             - "Bonjour monsieur"
     signals:
-      - order: "dis bonjour"
-
-  - name: "Meaning of life"
-    neurons:
-      - say:
-          message:
-            - "42"
-          tts: "voxygen"
-    signals:
-      - order: "sens de la vie"
-
-  - name: "Run a simple script"
-    neurons:
-      - script:
-          path: "/home/nico/test.sh"
-      - say:
-          message: "Script lancé, monsieur"
-    signals:
-      - order: "lance le script"
-
-  - name: "Say local date"
-    neurons:
-      - systemdate:
-          tts: "voxygen"
-          say_template:
-            - "il est {{ hours }} heure et {{ minutes }} minute"
-    signals:
-      - order: "quelle heure est-il"
-
-  - name: "Say local date from template"
-    neurons:
-      - systemdate:
-          file_template: en_systemdate_template_example.j2
-    signals:
-      - order: "test heure"
-
-  - name: "Close rolling shutter"
-    neurons:
-      - command: "curl http://192.168.0.22:5000/fermeture -d \"password=monpass\" -X POST"
-      - say:
-          message: "Fermeture en cours, monsieur"
-    signals:
-      - order: "ferme les volets"
-
-  - name: "Open rolling shutter"
-    neurons:
-      - command: "curl http://192.168.0.22:5000/ouverture -d \"password=monpass\" -X POST"
-      - say:
-          message: "Ouverture en cours, monsieur"
-    signals:
-      - order: "ouvre les volets"
-
-  - name: "Start steam"
-    neurons:
-      - command: "curl -i --user admin:secret -H \"Content-Type: application/json\" -X POST -d '{\"app_name\":\"kodi\",\"state\":\"stop\"}' http://192.168.0.17:8000/app"
-      - command: "curl -i --user admin:secret -H \"Content-Type: application/json\" -X POST -d '{\"app_name\":\"steam\",\"state\":\"start\"}' http://192.168.0.17:8000/app"
-      - say:
-          message: "Lancement en cours, monsieur"
-    signals:
-      - order: "lance Steam"
-
-  - name: "Start Kodi"
-    neurons:
-      - command: "curl -i --user admin:secret -H \"Content-Type: application/json\" -X POST -d '{\"app_name\":\"steam\",\"state\":\"stop\"}' http://192.168.0.17:8000/app"
-      - command: "curl -i --user admin:secret -H \"Content-Type: application/json\" -X POST -d '{\"app_name\":\"kodi\",\"state\":\"start\"}' http://192.168.0.17:8000/app"
-      - say:
-          message: "Lancement en cours, monsieur"
-    signals:
-      - order: "lance Cody"
-
-  - name: "Start music"
-    neurons:
-      - command: "curl -i --user admin:secret -H \"Content-Type: application/json\" -X POST -d '{\"app_name\":\"music\",\"state\":\"start\"}' http://192.168.0.17:8000/app"
-      - say:
-          message: "Musique lance, monsieur"
-    signals:
-      - order: "mais nous de la musique"
-      - order: "musique rock"
-
-  - name: "Stop music"
-    neurons:
-      - command: "curl -i --user admin:secret -H \"Content-Type: application/json\" -X POST -d '{\"app_name\":\"music\",\"state\":\"stop\"}' http://192.168.0.17:8000/app"
-      - say:
-          message: "musique stoppé, monsieur"
-    signals:
-      - order: "arrête la musique"
-      - order: "stop la musique"
-      - order: "éteins la musique"
+      - order: "bonjour"
 
-  - name: "Ansible test"
-    neurons:
-      - ansible_tasks: "tasks.yml"
-      - say:
-          message: "Tache terminée"
-    signals:
-      - order: "playbook"
-
-  - name: "Stop kalliope"
-    neurons:
-      - say:
-          message: "Aurevoir"
-      - kill_switch
-    signals:
-      - order: "ferme-toi"
-
-  - name: "check email"
-    neurons:
-      - gmail_checker:
-          username: "me@gmail.com"
-          password: "my_password"
-          file_template: fr_gmail.j2
-    signals:
-      - order: "est-ce que j'ai des emails"
-
-  - name: "run soundcloud"
-    neurons:
-      - soundcloud:
-          username: "me@gmail.com"
-          password: "my_password"
-          args:
-            - artist_name
-            - music_name
-    signals:
-      - order: "I would like to hear the song {{ music_name }}"
-      - order: "I would like to hear {{ artist_name }}"
-
-  - name: "find my phone"
-    neurons:
-      - say:
-          message: "Je fais sonner le téléphone, monsieur"
-      - tasker_autoremote:
-          key: "APA91bqmY"
-          message: "lost"
-    signals:
-      - order: "où est mon téléphone"
+  - !include brains/ansible_playbook.yml
+  - !include brains/gmail_checker.yml
+  - !include brains/kill_switch.yml
+  - !include brains/openweathermap.yml
+  - !include brains/push_message.yml
+  - !include brains/script.yml
+  - !include brains/shell.yml
+  - !include brains/systemdate.yml

+ 9 - 0
brains/ansible_playbook.yml

@@ -0,0 +1,9 @@
+---
+
+  - name: "Ansible test"
+    neurons:
+      - ansible_playbook: "tasks.yml"
+      - say:
+          message: "Tache terminée"
+    signals:
+      - order: "playbook"

+ 10 - 0
brains/gmail_checker.yml

@@ -0,0 +1,10 @@
+---
+
+  - name: "check email"
+    neurons:
+      - gmail_checker:
+          username: "me@gmail.com"
+          password: "my_password"
+          file_template: fr_gmail.j2
+    signals:
+      - order: "est-ce que j'ai des emails"

+ 9 - 0
brains/kill_switch.yml

@@ -0,0 +1,9 @@
+---
+
+  - name: "Stop kalliope"
+    neurons:
+      - say:
+          message: "Aurevoir"
+      - kill_switch
+    signals:
+      - order: "ferme-toi"

+ 13 - 0
brains/openweathermap.yml

@@ -0,0 +1,13 @@
+---
+  - name: "get the weather"
+    neurons:
+      - openweathermap:
+          api_key: "fdfba4097c318aed7836b2a85a6a05ef"
+          lang: "fr"
+          temp_unit: "celsius"
+          location : "grenoble"
+          country: "FR"
+          say_template:
+          - "Aujourd'hui a {{ location }} le temps est {{ weather_today }} avec une température de {{ temp_today_temp }} degrés et demain le temps sera {{ weather_tomorrow }} avec une température de {{ temp_tomorrow_temp }} degrés"
+    signals:
+      - order: "quel temps fait-il "

+ 9 - 0
brains/push_message.yml

@@ -0,0 +1,9 @@
+---
+  - name: "Send push message"
+    neurons:
+      - push_message:
+           message: "Message to send"
+           api_key: "my_token_key"
+           channel_name: "my_chanel_name"
+    signals:
+      - order: "push message"

+ 9 - 0
brains/script.yml

@@ -0,0 +1,9 @@
+---
+  - name: "Run a simple script"
+    neurons:
+      - script:
+          path: "/home/nico/test.sh"
+      - say:
+          message: "Script lancé, monsieur"
+    signals:
+      - order: "lance le script"

+ 63 - 0
brains/shell.yml

@@ -0,0 +1,63 @@
+---
+
+  - name: "Close rolling shutter"
+    neurons:
+      - shell:
+          cmd: "curl http://192.168.0.22:5000/fermeture -d \"password=monpass\" -X POST"
+      - say:
+          message: "Fermeture en cours, monsieur"
+    signals:
+      - order: "ferme les volets"
+
+  - name: "Open rolling shutter"
+    neurons:
+      - shell:
+          cmd: "curl http://192.168.0.22:5000/ouverture -d \"password=monpass\" -X POST"
+      - say:
+          message: "Ouverture en cours, monsieur"
+    signals:
+      - order: "ouvre les volets"
+
+
+  - name: "Start steam"
+    neurons:
+      - shell:
+          cmd: "curl -i --user admin:secret -H \"Content-Type: application/json\" -X POST -d '{\"app_name\":\"kodi\",\"state\":\"stop\"}' http://192.168.0.17:8000/app"
+      - shell:
+          cmd: "curl -i --user admin:secret -H \"Content-Type: application/json\" -X POST -d '{\"app_name\":\"steam\",\"state\":\"start\"}' http://192.168.0.17:8000/app"
+      - say:
+          message: "Lancement en cours, monsieur"
+    signals:
+      - order: "lance Steam"
+
+  - name: "Start Kodi"
+    neurons:
+      - shell:
+          cmd: "curl -i --user admin:secret -H \"Content-Type: application/json\" -X POST -d '{\"app_name\":\"steam\",\"state\":\"stop\"}' http://192.168.0.17:8000/app"
+      - shell:
+          cmd: "curl -i --user admin:secret -H \"Content-Type: application/json\" -X POST -d '{\"app_name\":\"kodi\",\"state\":\"start\"}' http://192.168.0.17:8000/app"
+      - say:
+          message: "Lancement en cours, monsieur"
+    signals:
+      - order: "lance Cody"
+
+  - name: "Start music"
+    neurons:
+      - shell:
+          cmd: "curl -i --user admin:secret -H \"Content-Type: application/json\" -X POST -d '{\"app_name\":\"music\",\"state\":\"start\"}' http://192.168.0.17:8000/app"
+      - say:
+          message: "Musique lance, monsieur"
+    signals:
+      - order: "mais nous de la musique"
+      - order: "musique rock"
+
+  - name: "Stop music"
+    neurons:
+      - shell:
+          cmd: "curl -i --user admin:secret -H \"Content-Type: application/json\" -X POST -d '{\"app_name\":\"music\",\"state\":\"stop\"}' http://192.168.0.17:8000/app"
+      - say:
+          message: "musique stoppé, monsieur"
+    signals:
+      - order: "arrête la musique"
+      - order: "stop la musique"
+      - order: "éteins la musique"

+ 17 - 0
brains/systemdate.yml

@@ -0,0 +1,17 @@
+---
+
+  - name: "Say local date"
+    neurons:
+      - systemdate:
+          tts: "voxygen"
+          say_template:
+            - "il est {{ hours }} heure et {{ minutes }} minute"
+    signals:
+      - order: "quelle heure est-il"
+
+  - name: "Say local date from template"
+    neurons:
+      - systemdate:
+          file_template: en_systemdate_template_example.j2
+    signals:
+      - order: "test heure"

+ 11 - 0
brains/tasker_autoremote.yml

@@ -0,0 +1,11 @@
+---
+
+  - name: "find my phone"
+    neurons:
+      - say:
+          message: "Je fais sonner le téléphone, monsieur"
+      - tasker_autoremote:
+          key: "APA91bqmY"
+          message: "lost"
+    signals:
+      - order: "où est mon téléphone"

+ 4 - 1
core/ConfigurationManager/BrainLoader.py

@@ -41,7 +41,10 @@ class BrainLoader(object):
         # create list of Synapse
         synapses = list()
         for synapses_dict in dict_brain:
-            # print synapses_dict
+            print synapses_dict
+            # if the synapse is a list, it come from an include
+            if isinstance(synapses_dict, list):
+                synapses_dict = synapses_dict[0]
             if ConfigurationChecker().check_synape_dict(synapses_dict):
                 # print "synapses_dict ok"
                 name = synapses_dict["name"]

+ 1 - 1
core/ConfigurationManager/SettingLoader.py

@@ -28,7 +28,7 @@ class SettingLoader(object):
     @classmethod
     def get_yaml_config(cls, file_path=None):
         if file_path is None:
-            file_path = "../../" + FILE_NAME
+            file_path = FILE_NAME
         return YAMLLoader.get_config(file_path)
 
     @classmethod

+ 49 - 8
core/ConfigurationManager/YAMLLoader.py

@@ -1,6 +1,12 @@
+import logging
 import os
 import yaml
 
+from core.Utils import Utils
+
+logging.basicConfig()
+logger = logging.getLogger("kalliope")
+
 
 class YAMLFileNotFound(Exception):
     pass
@@ -17,11 +23,46 @@ class YAMLLoader:
         Load settings file
         :return: cfg : the configuration file
         """
-        # Load settings.
-        __location__ = os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(__file__)))
-        try:
-            with open(os.path.join(__location__, yaml_file)) as ymlfile:
-                cfg = yaml.load(ymlfile)
-            return cfg
-        except IOError:
-            raise YAMLFileNotFound("The file path %s does not exist" % yaml_file)
+        # # Load settings.
+        # __location__ = os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(__file__)))
+        # try:
+        #     with open(os.path.join(__location__, yaml_file)) as ymlfile:
+        #         cfg = yaml.load(ymlfile)
+        #     return cfg
+        # except IOError:
+        #     raise YAMLFileNotFound("The file path %s does not exist" % yaml_file)
+        current_dir = os.path.dirname(os.path.abspath(__file__))
+        logger.debug("Current dir: %s " % current_dir)
+        root_dir = os.path.join(current_dir, "../../")
+        root_dir = os.path.normpath(root_dir)
+        logger.debug("Root dir: %s " % root_dir)
+        file_path_to_load = os.path.join(root_dir, yaml_file)
+        logger.debug("File path to load: %s " % file_path_to_load)
+        if os.path.isfile(yaml_file):
+            data = IncludeLoader(open(file_path_to_load, 'r')).get_data()
+            print Utils.print_yaml_nicely(data)
+            return data
+        else:
+            raise YAMLFileNotFound("File %s not found" % file_path_to_load)
+
+
+class IncludeLoader(yaml.Loader):
+
+    def __init__(self, *args, **kwargs):
+        super(IncludeLoader, self).__init__(*args, **kwargs)
+        self.add_constructor('!include', self._include)
+        if 'root' in kwargs:
+            self.root = kwargs['root']
+        elif isinstance(self.stream, file):
+            self.root = os.path.dirname(self.stream.name)
+        else:
+            self.root = os.path.curdir
+
+    def _include(self, loader, node):
+        oldRoot = self.root
+        filename = os.path.join(self.root, loader.construct_scalar(node))
+        self.root = os.path.dirname(filename)
+        print self.root
+        data = yaml.load(open(filename, 'r'))
+        self.root = oldRoot
+        return data

+ 10 - 0
core/Utils.py

@@ -73,3 +73,13 @@ class Utils(object):
             else:
                 return klass(parameters)
         return None
+
+    @classmethod
+    def print_yaml_nicely(cls, to_print):
+        """
+        Used for debug
+        :param to_print: Dict to print nicely
+        :return:
+        """
+        import json
+        print json.dumps(to_print, indent=2)

+ 1 - 1
neurons/__init__.py

@@ -1,4 +1,4 @@
-from ansible_tasks import Ansible_tasks
+from ansible_playbook import Ansible_playbook
 from command import Command
 from kill_switch import Kill_switch
 from say import Say

+ 1 - 0
neurons/ansible_playbook/__init__.py

@@ -0,0 +1 @@
+from ansible_playbook import Ansible_playbook

+ 2 - 2
neurons/ansible_tasks/ansible_tasks.py → neurons/ansible_playbook/ansible_playbook.py

@@ -7,9 +7,9 @@ from ansible.executor.playbook_executor import PlaybookExecutor
 from core.NeuronModule import NeuronModule
 
 
-class Ansible_tasks(NeuronModule):
+class Ansible_playbook(NeuronModule):
     def __init__(self, task_file, **kwargs):
-        super(Ansible_tasks, self).__init__(**kwargs)
+        super(Ansible_playbook, self).__init__(**kwargs)
         Options = namedtuple('Options',
                              ['connection', 'forks', 'become', 'become_method', 'become_user', 'check', 'listhosts',
                               'listtasks', 'listtags', 'syntax', 'module_path'])

+ 0 - 1
neurons/ansible_tasks/__init__.py

@@ -1 +0,0 @@
-from ansible_tasks import Ansible_tasks

+ 4 - 4
test.py

@@ -4,6 +4,7 @@ import re
 from collections import Counter
 
 from core import OrderAnalyser
+from core.ConfigurationManager import YAMLLoader
 from neurons import Systemdate
 from neurons.tasker_autoremote.tasker_autoremote import Tasker_autoremote
 
@@ -11,10 +12,8 @@ logging.basicConfig()
 logger = logging.getLogger("kalliope")
 logger.setLevel(logging.DEBUG)
 
-
-
-order = "test heure"
-oa = OrderAnalyser(order)
+order = "playbook"
+oa = OrderAnalyser(order=order)
 oa.start()
 
 
@@ -23,3 +22,4 @@ oa.start()
 
 
 
+

+ 0 - 12
test.yml

@@ -1,12 +0,0 @@
----
-  - name: "wake up"
-    neurons:
-      - say:
-          message:
-            - "Bonjour monsieur"
-      - systemdate:
-          say_template:
-            - "Il est {{ hours }} heures et {{ minutes }} minutes"
-      - command: "mplayer http://192.99.17.12:6410/"
-    signals:
-      - event: "20 12 * * *"