Blame view

src/core/pyros_django/obsconfig/configpyros.py 49.2 KB
dd54dc29   Alexis Koralewski   Updating schemas,...
1
#!/usr/bin/env python3
6686d675   Alexis Koralewski   new version of ob...
2
import pykwalify.core
72519c93   Alexis Koralewski   Updating observat...
3
import yaml,sys,logging,os, pickle, time
a9789880   Alexis Koralewski   Add new way to st...
4
from datetime import datetime
6686d675   Alexis Koralewski   new version of ob...
5
from pykwalify.errors import PyKwalifyException,SchemaError
a9789880   Alexis Koralewski   Add new way to st...
6
from pathlib import Path
a2f47fb6   Alexis Koralewski   updating display ...
7
class ConfigPyros:
6686d675   Alexis Koralewski   new version of ob...
8
    # (AKo) : Config file path is checked on the settings file, if the file isn't valid (i.e not found) the error will be launched by the settings file when starting the application 
a2f47fb6   Alexis Koralewski   updating display ...
9
    devices_links = {}
ee2a5e47   Alexis Koralewski   New version of ob...
10
    current_file = None
f110f276   Alexis Koralewski   adding new functi...
11
12
    #COMPONENT_PATH = os.path.join(os.environ["DJANGO_PATH"],"../../../config/components/")
    #GENERIC_DEVICES_PATH = os.path.join(os.environ["DJANGO_PATH"],"../../../config/devices/")
72519c93   Alexis Koralewski   Updating observat...
13
14
15
16
17
    pickle_file = "obsconfig.p"
    obs_config = None
    devices = None
    computers = None
    agents = None 
2f12f96d   Alexis Koralewski   add Yaml editor f...
18
    obs_config_file_content = None
f110f276   Alexis Koralewski   adding new functi...
19
    #obs_config_path = os.environ.get("PATH_TO_OBSCONF_FOLDER",os.path.join(os.environ["DJANGO_PATH"],"../../../privatedev/config/default/"))
2f12f96d   Alexis Koralewski   add Yaml editor f...
20
    errors = None
72519c93   Alexis Koralewski   Updating observat...
21
    def verify_if_pickle_needs_to_be_updated(self,observatory_config_file)->bool:
f110f276   Alexis Koralewski   adding new functi...
22
        """
72519c93   Alexis Koralewski   Updating observat...
23
24
25
26
27
28
29

        Args:
            observatory_config_file ([type]): [description]

        Returns:
            bool: [description]
        """
f110f276   Alexis Koralewski   adding new functi...
30
31
32
        self.CONFIG_PATH = os.path.dirname(observatory_config_file)+"/"
        self.obs_config_path = self.CONFIG_PATH
        #self.CONFIG_PATH = self.obs_config_path
be09bdbc   Alexis Koralewski   Check if observat...
33
        if os.path.isfile(self.CONFIG_PATH+self.pickle_file) == False:
72519c93   Alexis Koralewski   Updating observat...
34
35
            return True
        else:
be09bdbc   Alexis Koralewski   Check if observat...
36
            pickle_file_mtime = os.path.getmtime(self.CONFIG_PATH+self.pickle_file)
72519c93   Alexis Koralewski   Updating observat...
37
            obs_config_mtime = os.path.getmtime(observatory_config_file)
72519c93   Alexis Koralewski   Updating observat...
38
39
            
            obs_config = self.read_and_check_config_file(observatory_config_file)
a9789880   Alexis Koralewski   Add new way to st...
40
41
            if obs_config_mtime > pickle_file_mtime:
                # create obs file (yaml) from pickle["obsconfig"] with date of pickle within history folder-> nom ficher + année + mois + jour + datetime (avec secondes) -> YYYY/MM/DD H:m:s
2f12f96d   Alexis Koralewski   add Yaml editor f...
42
                pickle_datetime = datetime.utcfromtimestamp(pickle_file_mtime).strftime("%Y%m%d_%H%M%S")
a9789880   Alexis Koralewski   Add new way to st...
43
44
45
                # Create history folder if doesn't exist
                Path(self.obs_config_path+"/history/").mkdir(parents=True, exist_ok=True)
                file_name = f"{self.obs_config_path}/history/observatory_{pickle_datetime}.yml"
b755ff73   Alexis Koralewski   adding variables ...
46
47
                config_file = open(observatory_config_file,"r")

a9789880   Alexis Koralewski   Add new way to st...
48
                with open(file_name, 'w') as f:
b755ff73   Alexis Koralewski   adding variables ...
49
                    f.write(config_file.read())
a9789880   Alexis Koralewski   Add new way to st...
50
                return True
be09bdbc   Alexis Koralewski   Check if observat...
51
            if obs_config == None:
72519c93   Alexis Koralewski   Updating observat...
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
                print(f"Error when trying to read config file (path of config file : {observatory_config_file}")
                return -1
            self.obs_config = obs_config
            # check last date of modification for devices files
            for device in self.obs_config["OBSERVATORY"]["DEVICES"]:
                device_file = self.CONFIG_PATH+device["DEVICE"]["file"]
                device_file_mtime = os.path.getmtime(device_file)
                if device_file_mtime > pickle_file_mtime:
                    return True
                
            for computer in self.obs_config["OBSERVATORY"]["COMPUTERS"]:
                computer_file = self.CONFIG_PATH+computer["COMPUTER"]["file"]
                computer_file_mtime = os.path.getmtime(computer_file)
                if computer_file_mtime > pickle_file_mtime:
                    return True
        return False

3d4ab326   Alexis Koralewski   adding new attrib...
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
    def load(self, observatory_config_file):
        pickle_needs_to_be_updated = self.verify_if_pickle_needs_to_be_updated(observatory_config_file)
        if pickle_needs_to_be_updated == False and self.obs_config != None:
            return None
        else:
            if os.path.isfile(self.CONFIG_PATH+self.pickle_file) and pickle_needs_to_be_updated == False:
                print("Reading pickle file")
                try:
                    can_pickle_file_be_read = False
                    while can_pickle_file_be_read != True:
                        if os.access(self.CONFIG_PATH+self.pickle_file, os.R_OK):
                            pickle_dict = pickle.load(open(self.CONFIG_PATH+self.pickle_file,"rb"))
                            can_pickle_file_be_read = True
                        else:
                            time.sleep(0.5)
                except IOError:
                    print("Error when reading the pickle file")
                try:
                    self.obs_config = pickle_dict["obs_config"]
                    self.computers = pickle_dict["computers"]
                    self.devices = pickle_dict["devices"]
                    self.devices_links = pickle_dict["devices_links"]
                    self.obs_config_file_content = pickle_dict["obs_config_file_content"]
                    self.raw_config =  pickle_dict["raw_config"] 
                except:
                    # we rewrite the pickle file, the content will be the same otherwise we would be in the else case
                    print("Rewritting the pickle file (an error occured while reading it, the content will be the same as it was")
                    pickle_dict = {}
                    
                    self.obs_config = self.read_and_check_config_file(observatory_config_file) 
                    obs_file = open(observatory_config_file,"r")
                    pickle_dict["raw_config"] = obs_file.read()
                    obs_file.close()
                    self.raw_config =  pickle_dict["raw_config"] 
                    pickle_dict["obs_config"] = self.obs_config
                    pickle_dict["devices"] = self.get_devices()
                    pickle_dict["computers"] = self.get_computers()
                    pickle_dict["devices_links"] = self.devices_links
                    pickle_dict["obs_config_file_content"] = self.read_and_check_config_file(observatory_config_file) 
                    print("Writing pickle file")
                    pickle.dump(pickle_dict,open(self.CONFIG_PATH+self.pickle_file,"wb"))    
            else:
                print("Pickle file needs to be created or updated")
b755ff73   Alexis Koralewski   adding variables ...
112
                pickle_dict = {}
72519c93   Alexis Koralewski   Updating observat...
113
                
b755ff73   Alexis Koralewski   adding variables ...
114
                self.obs_config = self.read_and_check_config_file(observatory_config_file) 
b755ff73   Alexis Koralewski   adding variables ...
115
116
117
118
119
120
                pickle_dict["obs_config"] = self.obs_config
                pickle_dict["devices"] = self.get_devices()
                pickle_dict["computers"] = self.get_computers()
                pickle_dict["devices_links"] = self.devices_links
                pickle_dict["obs_config_file_content"] = self.read_and_check_config_file(observatory_config_file) 
                print("Writing pickle file")
3d4ab326   Alexis Koralewski   adding new attrib...
121
                pickle.dump(pickle_dict,open(self.CONFIG_PATH+self.pickle_file,"wb"))
6686d675   Alexis Koralewski   new version of ob...
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136

    def check_and_return_config(self,yaml_file:str,schema_file:str)->dict:
        """
        Check if yaml_file is valid for the schema_file and return an dictionary of the config file

        Args:
            yaml_file (str): Path to the config_file to be validated
            schema_file (str): Path to the schema file 

        Returns:
            dict: dictionary of the config file (with values)
        """
        # disable pykwalify error to clean the output
        logging.disable(logging.ERROR)
        try:
72519c93   Alexis Koralewski   Updating observat...
137
138
139
140
141
142
143
144
            can_yaml_file_be_read = False
            while can_yaml_file_be_read != True:
                if os.access(yaml_file, os.R_OK):
                    can_yaml_file_be_read = True
                else:
                    print(f"{yaml_file} can't be accessed, waiting for availability")
                    time.sleep(0.5)
        
2f12f96d   Alexis Koralewski   add Yaml editor f...
145
            c = pykwalify.core.Core(source_file=yaml_file, schema_files=[self.SCHEMA_PATH+schema_file])
6686d675   Alexis Koralewski   new version of ob...
146
147
148
149
150
            return c.validate(raise_exception=True)
        except SchemaError:
            for error in c.errors:
                print("Error :",str(error).split(". Path")[0])
                print("Path to error :",error.path)
2f12f96d   Alexis Koralewski   add Yaml editor f...
151
                self.errors = c.errors
6686d675   Alexis Koralewski   new version of ob...
152
            return None
72519c93   Alexis Koralewski   Updating observat...
153
154
        except IOError:
            print("Error when reading the observatory config file")
6686d675   Alexis Koralewski   new version of ob...
155

2f12f96d   Alexis Koralewski   add Yaml editor f...
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
    @staticmethod
    def check_config(yaml_file:str,schema_file:str)->any:
        """
        Check if yaml_file is valid for the schema_file and return a boolean or list of errors according the schema

        Args:
            yaml_file (str): Path to the config_file to be validated
            schema_file (str): Path to the schema file 

        Returns:
            any: boolean (True) if the configuration is valid according the schema or a list of error otherwise
        """
        # disable pykwalify error to clean the output
        logging.disable(logging.ERROR)
        try:
            can_yaml_file_be_read = False
            while can_yaml_file_be_read != True:
                if os.access(yaml_file, os.R_OK):
                    can_yaml_file_be_read = True
                else:
                    print(f"{yaml_file} can't be accessed, waiting for availability")
                    time.sleep(0.5)
        
            c = pykwalify.core.Core(source_file=yaml_file, schema_files=[schema_file])
            c.validate(raise_exception=True)
            return True
        except SchemaError:
            for error in c.errors:
                print("Error :",str(error).split(". Path")[0])
                print("Path to error :",error.path)
                
            return c.errors
        except IOError:
            print("Error when reading the observatory config file")
            
6686d675   Alexis Koralewski   new version of ob...
191
192
193
194
195
196
197
198
199
200
    def read_and_check_config_file(self,yaml_file:str)->dict:
        """
        Read the schema key of the config file to retrieve schema name and proceed to the checking of that config file
        Call check_and_return_config function and print its return.

        Args:
            yaml_file (str): path to the config file
        Returns:
            dict: Dictionary of the config file (with values)
        """
ee2a5e47   Alexis Koralewski   New version of ob...
201
        self.current_file = yaml_file
6686d675   Alexis Koralewski   new version of ob...
202
        try:
72519c93   Alexis Koralewski   Updating observat...
203
204
205
206
207
208
209
210
            can_config_file_be_read = False
            while can_config_file_be_read != True:
                
                if os.access(yaml_file, os.R_OK):
                    can_config_file_be_read = True
                else:
                    print(f"{yaml_file} can't be accessed, waiting for availability")
                    time.sleep(0.5)
6686d675   Alexis Koralewski   new version of ob...
211
            with open(yaml_file, 'r') as stream:
72519c93   Alexis Koralewski   Updating observat...
212
                print(f"Reading {yaml_file}")
6686d675   Alexis Koralewski   new version of ob...
213
214
                config_file = yaml.safe_load(stream)

f110f276   Alexis Koralewski   adding new functi...
215
216
            self.DJANGO_PATH = os.environ.get("DJANGO_PATH",os.path.abspath(os.path.dirname(yaml_file)))
            self.SCHEMA_PATH = os.path.join(self.DJANGO_PATH,"../../../config/schemas/")
2f12f96d   Alexis Koralewski   add Yaml editor f...
217
            self.CONFIG_PATH = self.obs_config_path
f110f276   Alexis Koralewski   adding new functi...
218
219
            self.COMPONENT_PATH = os.path.join(self.DJANGO_PATH,"../../../config/components/")
            self.GENERIC_DEVICES_PATH = os.path.join(self.DJANGO_PATH,"../../../config/devices/")
2f12f96d   Alexis Koralewski   add Yaml editor f...
220
            result = self.check_and_return_config(yaml_file,config_file["schema"])
be09bdbc   Alexis Koralewski   Check if observat...
221
            if result == None:
72519c93   Alexis Koralewski   Updating observat...
222
                print("Error when reading and validating config file, please check the errors right above")
be09bdbc   Alexis Koralewski   Check if observat...
223
                exit(1)
72519c93   Alexis Koralewski   Updating observat...
224
            return result
ee2a5e47   Alexis Koralewski   New version of ob...
225
226
227
228
229
230
231

        except yaml.YAMLError as exc:
            print(exc)
        except Exception as e:
            print(e)
            return None
    
72519c93   Alexis Koralewski   Updating observat...
232
    def read_generic_component_and_return_attributes(self,component_name:str)->dict:
ee2a5e47   Alexis Koralewski   New version of ob...
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
        file_path = self.COMPONENT_PATH + component_name + ".yml"
        try:
            with open(file_path, 'r') as stream:
                config_file = yaml.safe_load(stream)  
                
                attributes = {}
                for attribute in config_file:
                
                    attribute = attribute["attribute"]
                    attributes[attribute.pop("key")] = attribute
                return attributes
        except yaml.YAMLError as exc:
            print(exc)
        except Exception as e:
            print(e)
            return None
    
    def read_capability_of_device(self,capability:dict)->dict:
        """
b4d06c1f   Alexis Koralewski   Improving device ...
252
        Read capability of device and inherit attributes from generic component then overwrite attributes defined in device config
ee2a5e47   Alexis Koralewski   New version of ob...
253
254

        Args:
b4d06c1f   Alexis Koralewski   Improving device ...
255
            capability (dict): dictionary containing a capabilitiy (keys : component and attributes)
ee2a5e47   Alexis Koralewski   New version of ob...
256
257

        Returns:
b4d06c1f   Alexis Koralewski   Improving device ...
258
            dict: dictionary of capability inherited by generic component and overwritten his attributes by current attributes of capability
ee2a5e47   Alexis Koralewski   New version of ob...
259
260
        """
        
72519c93   Alexis Koralewski   Updating observat...
261
        component_attributes = self.read_generic_component_and_return_attributes(capability["component"])
ee2a5e47   Alexis Koralewski   New version of ob...
262
263
        
        attributes = {}
b4d06c1f   Alexis Koralewski   Improving device ...
264
        # get all attributes of device's capability
ee2a5e47   Alexis Koralewski   New version of ob...
265
266
267
268
269
        for attribute in capability["attributes"]:
            attribute = attribute["attribute"]
        
            attributes[attribute.pop("key")] = attribute
        
b4d06c1f   Alexis Koralewski   Improving device ...
270
        # for each attributes of generic component attributes
ee2a5e47   Alexis Koralewski   New version of ob...
271
        for attribute_name in attributes.keys():
72519c93   Alexis Koralewski   Updating observat...
272
            # merge attributes of general component with specified component in device config file
ee2a5e47   Alexis Koralewski   New version of ob...
273
            new_attributes = {**component_attributes[attribute_name],**attributes[attribute_name]}
282540c5   Alexis Koralewski   Config class: imp...
274
275
276
            if "is_enum" in component_attributes[attribute_name].keys():
                # make an intersection of both list of values
                new_attributes["value"] = list(set(attributes[attribute_name]["value"]) & set(component_attributes[attribute_name]["value"]))
3e86f19c   Alexis Koralewski   config class : im...
277
278
279
                if len(new_attributes["value"]) == 0:
                    print(f"Value of lastly read device's attribute '{attribute_name}' isn't one of the values of component configuration for this device (component configuration value(s): {component_attributes[attribute_name]['value']}) (actual value : {attributes[attribute_name]['value']})")
                    exit(1)
ee2a5e47   Alexis Koralewski   New version of ob...
280
281
            component_attributes[attribute_name] = new_attributes
        
b4d06c1f   Alexis Koralewski   Improving device ...
282
        # return inherited and overwritten attributes of capability
ee2a5e47   Alexis Koralewski   New version of ob...
283
284
285
        capability["attributes"] = component_attributes
        return capability

a6617686   Etienne Pallier   new wrapper scrip...
286
    def get_devices_names_and_file(self) -> dict:
a2f47fb6   Alexis Koralewski   updating display ...
287
        """
b4d06c1f   Alexis Koralewski   Improving device ...
288
        Return a dictionary giving the device file name by the device name 
a2f47fb6   Alexis Koralewski   updating display ...
289
        Returns:
b4d06c1f   Alexis Koralewski   Improving device ...
290
            dict: key is device name, value is file name
a2f47fb6   Alexis Koralewski   updating display ...
291
292
        """
        devices_names_and_files = {}
72519c93   Alexis Koralewski   Updating observat...
293
        for device in self.obs_config["OBSERVATORY"]["DEVICES"]:
a2f47fb6   Alexis Koralewski   updating display ...
294
295
296
297
298
            device = device["DEVICE"]
            
            devices_names_and_files[device["name"]] = device["file"]
        return devices_names_and_files

72519c93   Alexis Koralewski   Updating observat...
299
    def read_device_config_file(self,config_file_name:str,is_generic=False)->dict:
ee2a5e47   Alexis Koralewski   New version of ob...
300
        """
b4d06c1f   Alexis Koralewski   Improving device ...
301
302
303
        Read the device config file, inherit generic device config if "generic" key is present in "DEVICE".
        Associate capabilities of attached_devices if this device has attached_devices.
        Inherit capabilities from generic component and overwritte attributes defined in the device config
ee2a5e47   Alexis Koralewski   New version of ob...
304
        Args:
b4d06c1f   Alexis Koralewski   Improving device ...
305
306
            config_file_name (str): file name to be read
            is_generic (bool, optional): tells if we're reading a generic configuration (is_generic =True) or not (is_generic = False). Defaults to False.
ee2a5e47   Alexis Koralewski   New version of ob...
307
308

        Returns:
b4d06c1f   Alexis Koralewski   Improving device ...
309
            dict: formatted device configuration (attributes, capabilities...)
ee2a5e47   Alexis Koralewski   New version of ob...
310
311
        """
        self.current_file = config_file_name
c132ba0f   Alexis Koralewski   Fixing TNC config...
312
313
314
315
316
317
318
319
320
321
        devices_name_and_file = self.get_devices_names_and_file()
        if not is_generic:
            # check if device config file is listed in observatory configuration
            current_device_name = [device for device,file_name in devices_name_and_file.items() if file_name in config_file_name[len(self.CONFIG_PATH):] ]
            if len(current_device_name) <= 0:
                print(f"Current file '{config_file_name[len(self.CONFIG_PATH):]}' isn't listed in observatory configuration")
                print("The devices names and files are: ")
                for device_name,file_name in devices_name_and_file.items():
                    print(f"device name: '{device_name}', device filename: '{file_name}'")
                exit(1)
72519c93   Alexis Koralewski   Updating observat...
322
        print(f"Reading {config_file_name}")
ee2a5e47   Alexis Koralewski   New version of ob...
323
324
325
        try:
            with open(config_file_name, 'r') as stream:
                config_file = yaml.safe_load(stream)
b4d06c1f   Alexis Koralewski   Improving device ...
326
                # if we're reading a generic device configuration, the path to get the schema is different than usual
f110f276   Alexis Koralewski   adding new functi...
327
                self.SCHEMA_PATH =os.path.join(self.DJANGO_PATH,"../../../config/schemas/")
72519c93   Alexis Koralewski   Updating observat...
328
                
b4d06c1f   Alexis Koralewski   Improving device ...
329
                # read and verify that the device configuration match the schema
2f12f96d   Alexis Koralewski   add Yaml editor f...
330
                result = self.check_and_return_config(config_file_name,config_file["schema"])
b4d06c1f   Alexis Koralewski   Improving device ...
331
                # if the configuration didn't match the schema or had an error when reading the file
be09bdbc   Alexis Koralewski   Check if observat...
332
                if result == None:
ee2a5e47   Alexis Koralewski   New version of ob...
333
                    print("Error when reading and validating config file, please check the errors right above")
2f12f96d   Alexis Koralewski   add Yaml editor f...
334
                    exit(1)
ee2a5e47   Alexis Koralewski   New version of ob...
335
                else:
b4d06c1f   Alexis Koralewski   Improving device ...
336
337
                    # the configuration is valid
                    # storing DEVICE key in device (DEVICE can contains : attributes of device, capabilities, attached devices)
ee2a5e47   Alexis Koralewski   New version of ob...
338
                    device = result["DEVICE"]
b4d06c1f   Alexis Koralewski   Improving device ...
339
340
                    generic_device_config = None
                    # if the device is associated to an generic configuration, we'll read that generic configuration to inherit his attributes
72519c93   Alexis Koralewski   Updating observat...
341
                    if "generic" in device:
b4d06c1f   Alexis Koralewski   Improving device ...
342
                        # storing the whole current config
72519c93   Alexis Koralewski   Updating observat...
343
                        current_config = result
b4d06c1f   Alexis Koralewski   Improving device ...
344
345
346
                        # read and get the generic device config
                        generic_device_config = self.read_device_config_file(self.GENERIC_DEVICES_PATH+device["generic"],is_generic=True)
                        # merge whole device config but we need to merge capabilities differently after
72519c93   Alexis Koralewski   Updating observat...
347
                        new_config = {**generic_device_config["DEVICE"],**current_config["DEVICE"]}
72519c93   Alexis Koralewski   Updating observat...
348
349
                        result["DEVICE"] = new_config

b4d06c1f   Alexis Koralewski   Improving device ...
350
                    # device has capabilities
ee2a5e47   Alexis Koralewski   New version of ob...
351
352
                    if "CAPABILITIES" in device:
                        capabilities = []
b4d06c1f   Alexis Koralewski   Improving device ...
353
354
355
356
                        # if the device is associated to a generic device we need to associate his capabilities with the generic capabilities and overwrite them
                        if generic_device_config != None:
                            # we're making a copy of generic device config so we can remove items during loop
                            copy_generic_device_config = generic_device_config.copy()
282540c5   Alexis Koralewski   Config class: imp...
357
                            # We have to extend capabilities of generic device configuration
b4d06c1f   Alexis Koralewski   Improving device ...
358
359
360
361
                            for capability in current_config["DEVICE"]["CAPABILITIES"]:
                                is_capability_in_generic_config = False
                                current_config_capability = capability["CAPABILITY"]
                                current_config_component = current_config_capability["component"]
b4d06c1f   Alexis Koralewski   Improving device ...
362
363
364
365
366
367
                                # find if this component was defined in generic_device_config
                                for index,generic_config_capability in enumerate(generic_device_config["DEVICE"]["CAPABILITIES"]):
                                    # if the current capability is the capability of the component we're looking for
                                    if current_config_component == generic_config_capability["component"]:
                                        is_capability_in_generic_config = True
                                        # we're merging their attributes
3e86f19c   Alexis Koralewski   config class : im...
368
                                        new_attributes = generic_config_capability["attributes"].copy()
282540c5   Alexis Koralewski   Config class: imp...
369
370
371
372
373
374
375
376
377
378
379
380
381
                                        attributes = {}
                                        current_config_attributes = current_config_capability["attributes"]                                        
                                        generic_config_attributes = generic_config_capability["attributes"]
                                        for attribute in current_config_attributes:
                                            attribute = attribute["attribute"]
                                            attributes[attribute.pop("key")] = attribute
                                        # for each attributes of device component attributes
                                        for attribute_name in attributes.keys():
                                            # merge attributes of general component with specified component in device config file
                                            new_attributes[attribute_name] = {**generic_config_attributes[attribute_name],**attributes[attribute_name]}
                                            if "is_enum" in generic_config_attributes[attribute_name].keys():
                                                # make an intersection of both list of values
                                                new_attributes[attribute_name]["value"] = list(set(attributes[attribute_name]["value"]) & set(generic_config_attributes[attribute_name]["value"]))
3e86f19c   Alexis Koralewski   config class : im...
382
383
384
                                                if len(new_attributes[attribute_name]["value"]) == 0:
                                                    print(f"Value of device '{config_file_name}' for attribute '{attribute_name}' isn't one of the values of generic configuration for this device (generic value(s): {generic_config_attributes[attribute_name]['value']}) (actual value : {attributes[attribute_name]['value']})")
                                                    exit(1)
b4d06c1f   Alexis Koralewski   Improving device ...
385
386
                                        # removing this capability from generic device configuration
                                        generic_device_config["DEVICE"]["CAPABILITIES"].pop(index)
282540c5   Alexis Koralewski   Config class: imp...
387
                                        capabilities.append({"component": current_config_component,"attributes":new_attributes}) 
b4d06c1f   Alexis Koralewski   Improving device ...
388
389
                                        break
                                if is_capability_in_generic_config == False:
282540c5   Alexis Koralewski   Config class: imp...
390
                                    current_config_capability = self.read_capability_of_device(current_config_capability)
b4d06c1f   Alexis Koralewski   Improving device ...
391
392
393
394
395
396
397
398
399
400
                                    # the component defined in the current_config isn't defined in generic config (should not happen but we'll deal with that case anyway) : we're simply adding this capability
                                    capabilities.append(current_config_capability)
                            # looping through generic device config's capabilities in order to add them to current device configuration
                            for generic_config_capability in generic_device_config["DEVICE"]["CAPABILITIES"]:
                                capabilities.append(generic_config_capability)
                        else:
                            # device not associated to a generic device configuration
                            for capability in device["CAPABILITIES"]:
                                capability = capability["CAPABILITY"]
                                capabilities.append(self.read_capability_of_device(capability))
ee2a5e47   Alexis Koralewski   New version of ob...
401
                        device["CAPABILITIES"] = capabilities
b4d06c1f   Alexis Koralewski   Improving device ...
402
403
                        # associate capabilities to final device configuration (stored in result variable)
                        result["DEVICE"]["CAPABILITIES"] = device["CAPABILITIES"]
ee2a5e47   Alexis Koralewski   New version of ob...
404
                    if "ATTACHED_DEVICES" in device.keys():
b4d06c1f   Alexis Koralewski   Improving device ...
405
                        # device has attached devices, we need to read their configuration in order to get their capabilities and add them to the current device
a2f47fb6   Alexis Koralewski   updating display ...
406
407
                        devices_name_and_file = self.get_devices_names_and_file()
                        active_devices = self.get_active_devices()
ee2a5e47   Alexis Koralewski   New version of ob...
408
                        for attached_device in device["ATTACHED_DEVICES"]:
a2f47fb6   Alexis Koralewski   updating display ...
409
                            is_attached_device_link_to_agent = False
b4d06c1f   Alexis Koralewski   Improving device ...
410
                            # we're looking for if the attached device is associated to an agent (i.e. the device is considered as 'active'). However an attached_device shoudn't be active
a2f47fb6   Alexis Koralewski   updating display ...
411
                            for active_device in active_devices:
a2f47fb6   Alexis Koralewski   updating display ...
412
                                if devices_name_and_file[active_device] == attached_device["file"]:
b4d06c1f   Alexis Koralewski   Improving device ...
413
                                    # the attached device is an active device (so it's linked to an agent)
a2f47fb6   Alexis Koralewski   updating display ...
414
415
                                    is_attached_device_link_to_agent = True
                                    break
a2f47fb6   Alexis Koralewski   updating display ...
416
                            if self.CONFIG_PATH+attached_device["file"] != config_file_name and not is_attached_device_link_to_agent:
b4d06c1f   Alexis Koralewski   Improving device ...
417
                            # if the attached device isn't the device itself and not active
72519c93   Alexis Koralewski   Updating observat...
418
                                
b4d06c1f   Alexis Koralewski   Improving device ...
419
                                # get configuration of attached device
a2f47fb6   Alexis Koralewski   updating display ...
420
                                config_of_attached_device = self.read_device_config_file(self.CONFIG_PATH+attached_device["file"])
a2f47fb6   Alexis Koralewski   updating display ...
421
422
423
                                capabilities_of_attached_device = None
                                if "CAPABILITIES" in config_of_attached_device["DEVICE"].keys():
                                    capabilities_of_attached_device = config_of_attached_device["DEVICE"]["CAPABILITIES"]
be09bdbc   Alexis Koralewski   Check if observat...
424
                                if capabilities_of_attached_device != None:
a2f47fb6   Alexis Koralewski   updating display ...
425
                                    # get name of device corresponding to the config file name
c132ba0f   Alexis Koralewski   Fixing TNC config...
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
                                    parent_device_name = [device for device,file_name in devices_name_and_file.items() if file_name == config_file_name[len(self.CONFIG_PATH):]]
                                    attached_device_name = [device for device,file_name in devices_name_and_file.items() if file_name == attached_device["file"]]
                                    if len(parent_device_name) > 0 :
                                        parent_device_name = parent_device_name[0]
                                    else:
                                        print(f"Attached device filename '{config_file_name[len(self.CONFIG_PATH):]}' is not listed in observatory devices files names")
                                        print("The devices names and files are: ")
                                        for device_name,file_name in devices_name_and_file.items():
                                            print(f"device name: '{device_name}', device filename: '{file_name}'")
                                        exit(1)
                                    if len(attached_device_name) > 0 :
                                        attached_device_name = attached_device_name[0]
                                    else:
                                        
                                        print(f"Attached device filename '{attached_device['file']}' is not listed in observatory devices files names")
                                        print("The devices names and files are: ")
                                        for device_name,file_name in devices_name_and_file.items():
                                            print(f"device name: '{device_name}', device filename: '{file_name}'")
                                        exit(1)
b4d06c1f   Alexis Koralewski   Improving device ...
445
                                    # associate attached device to his 'parent' device (parent device is the currently read device)
a2f47fb6   Alexis Koralewski   updating display ...
446
447
                                    self.devices_links[attached_device_name] = parent_device_name
                                    for capability in capabilities_of_attached_device:
b4d06c1f   Alexis Koralewski   Improving device ...
448
                                        # add capabilities of attached device to current device
a2f47fb6   Alexis Koralewski   updating display ...
449
                                        result["DEVICE"]["CAPABILITIES"].append(capability)
6686d675   Alexis Koralewski   new version of ob...
450
451
452
                return result
        except yaml.YAMLError as exc:
            print(exc)
dd54dc29   Alexis Koralewski   Updating schemas,...
453
454
        except Exception as e:
            print(e)
c132ba0f   Alexis Koralewski   Fixing TNC config...
455
456
            exit(1)
            #return None
6686d675   Alexis Koralewski   new version of ob...
457

a6617686   Etienne Pallier   new wrapper scrip...
458
    def __init__(self, observatory_config_file:str, unit_name:str="") -> None:
6686d675   Alexis Koralewski   new version of ob...
459
460
461
462
463
464
465
        """
        Initiate class with the config file
        set content attribute to a dictionary containing all values from the config file

        Args:
            config_file_name (str): path to the config file
        """
72519c93   Alexis Koralewski   Updating observat...
466
        self.load(observatory_config_file)
4290c2cf   Alexis Koralewski   adding unit choic...
467
468
469
470
471
        if unit_name == "":
            # By default we will use the first unit
            self.unit_name = self.get_units_name()[0]
        else:
            self.unit_name = unit_name
6686d675   Alexis Koralewski   new version of ob...
472

a6617686   Etienne Pallier   new wrapper scrip...
473
    def get_obs_name(self) -> str:
6686d675   Alexis Koralewski   new version of ob...
474
475
476
477
478
479
        """
        Return name of the observatory

        Returns:
            str: Name of the observatory
        """
72519c93   Alexis Koralewski   Updating observat...
480
        return self.obs_config["OBSERVATORY"]["name"]
6686d675   Alexis Koralewski   new version of ob...
481

a6617686   Etienne Pallier   new wrapper scrip...
482
    def get_channels(self, unit_name: str) -> dict:
4290c2cf   Alexis Koralewski   adding unit choic...
483
        
6686d675   Alexis Koralewski   new version of ob...
484
485
486
        """
        return dictionary of channels

4290c2cf   Alexis Koralewski   adding unit choic...
487
488
        Args:
            unit_name (str): Name of the unit
6686d675   Alexis Koralewski   new version of ob...
489
490
491
        Returns:
            dict: [description]
        """
4290c2cf   Alexis Koralewski   adding unit choic...
492
        unit = self.get_unit_by_name(unit_name)
6686d675   Alexis Koralewski   new version of ob...
493
494
495
496
        channels = {}
        
        for channel_id in range(len(unit["TOPOLOGY"]["CHANNELS"])):
            channel = unit["TOPOLOGY"]["CHANNELS"][channel_id]["CHANNEL"]
ee2a5e47   Alexis Koralewski   New version of ob...
497
            channels[channel["name"]] = channel
6686d675   Alexis Koralewski   new version of ob...
498
499
        return channels
    
a6617686   Etienne Pallier   new wrapper scrip...
500
    def get_computers(self) -> dict:
6686d675   Alexis Koralewski   new version of ob...
501
502
503
504
505
506
        """
        return dictionary of computers

        Returns:
            dict: [description]
        """
72519c93   Alexis Koralewski   Updating observat...
507
508
509
510
511
512
513
514
515
516
        if self.computers != None:
            return self.computers
        else:
            computers = {}
            for computer_id in range(len(self.obs_config["OBSERVATORY"]["COMPUTERS"])):
                computer = self.obs_config["OBSERVATORY"]["COMPUTERS"][computer_id]["COMPUTER"]
                if( "file" in computer.keys() ):
                    computer["computer_config"]= self.read_and_check_config_file(self.CONFIG_PATH+computer["file"])["COMPUTER"]
                computers[computer["name"]] = computer
            return computers
a6617686   Etienne Pallier   new wrapper scrip...
517
518

    def get_devices(self) -> dict:
6686d675   Alexis Koralewski   new version of ob...
519
520
        """
        return dictionary of devices
a6617686   Etienne Pallier   new wrapper scrip...
521

6686d675   Alexis Koralewski   new version of ob...
522
523
524
        Returns:
            dict: [description]
        """
72519c93   Alexis Koralewski   Updating observat...
525
526
527
528
529
530
531
532
533
534
535
        if self.devices != None:
            return self.devices

        else:
            devices = {}
            for device_id in range(len(self.obs_config["OBSERVATORY"]["DEVICES"])):
                device = self.obs_config["OBSERVATORY"]["DEVICES"][device_id]["DEVICE"]
                if( "file" in device.keys() ):
                    device["device_config"] = self.read_device_config_file(self.CONFIG_PATH+device["file"])["DEVICE"]
                devices[device["name"]] = device
            return devices
6686d675   Alexis Koralewski   new version of ob...
536

c132ba0f   Alexis Koralewski   Fixing TNC config...
537
538
539
540
541
542
543
544
545
546
547
    def get_devices_names(self)->list:
        """Return the list of devices names of an observatory

        Returns:
            list: list of names of devices
        """
        devices_names = []
        for device in self.obs_config["OBSERVATORY"]["DEVICES"]:
            devices_names.append(device["DEVICE"]["name"])
        return devices_names

4290c2cf   Alexis Koralewski   adding unit choic...
548
    def get_agents(self,unit_name)->dict:
6686d675   Alexis Koralewski   new version of ob...
549
550
551
        """
        return dictionary of agents 

4290c2cf   Alexis Koralewski   adding unit choic...
552
553
554
        Args:
            unit_name (str): name of the unit

6686d675   Alexis Koralewski   new version of ob...
555
556
557
        Returns:
            dict: dictionary of agents. For each agents tell the name, computer, device, protocole, etc...
        """
4290c2cf   Alexis Koralewski   adding unit choic...
558
        unit = self.get_unit_by_name(unit_name)
72519c93   Alexis Koralewski   Updating observat...
559
560
561
562
563
564
565
566
567
568
569
570
        if self.agents != None:
            return self.agents
        else:
            agents = {}
            
            
            for agent_id in range(len(unit["AGENTS"])):
                # Agents is a list containing dictionary that have only one key
                key = list(unit["AGENTS"][agent_id].keys())[0]
                agent = unit["AGENTS"][agent_id][key]
                agents[agent["name"]] = agent
            return agents
6686d675   Alexis Koralewski   new version of ob...
571

a6617686   Etienne Pallier   new wrapper scrip...
572
    def get_channel_groups(self, unit_name: str) -> dict:
6686d675   Alexis Koralewski   new version of ob...
573
574
575
576
        """
        Return dictionary of channel groups, tell the logic between groups of channels and within a group of channels

        Args:
4290c2cf   Alexis Koralewski   adding unit choic...
577
            unit_name (str): name of the unit
6686d675   Alexis Koralewski   new version of ob...
578
579
580
        Returns:
            dict: dictionary of channel groups (tell the logic and groups of channels)
        """
4290c2cf   Alexis Koralewski   adding unit choic...
581
        unit = self.get_unit_by_name(unit_name)
6686d675   Alexis Koralewski   new version of ob...
582
        info = {}
ee2a5e47   Alexis Koralewski   New version of ob...
583
        info["global_groups_logic"] = unit["TOPOLOGY"]["CHANNEL_GROUPS"]["logic"]
6686d675   Alexis Koralewski   new version of ob...
584
585
586
        info["groups"] = {}
        for group_id in range(len(unit["TOPOLOGY"]["CHANNEL_GROUPS"]["GROUPS"])):
            group = unit["TOPOLOGY"]["CHANNEL_GROUPS"]["GROUPS"][group_id]["GROUP"]
3d4ab326   Alexis Koralewski   adding new attrib...
587
            info["groups"][group["name"]] = group
6686d675   Alexis Koralewski   new version of ob...
588
589
        return info

a6617686   Etienne Pallier   new wrapper scrip...
590
    def get_channel_information(self, unit_name: str, channel_name: str) -> dict:
6686d675   Alexis Koralewski   new version of ob...
591
592
593
594
        """
        Return information of the given channel name of a unit

        Args:
4290c2cf   Alexis Koralewski   adding unit choic...
595
            unit_name (str): Name of the unit 
6686d675   Alexis Koralewski   new version of ob...
596
597
598
599
600
            channel_name (str): name of the channel

        Returns:
            dict: dictionary containing all values that define this channel
        """
4290c2cf   Alexis Koralewski   adding unit choic...
601
        channels = self.get_channels(unit_name)
6686d675   Alexis Koralewski   new version of ob...
602
603
        return channels[channel_name]

a6617686   Etienne Pallier   new wrapper scrip...
604
    def get_topology(self, unit_name:str)->dict:
6686d675   Alexis Koralewski   new version of ob...
605
606
607
608
        """
        Return dictionary of the topology of the observatory

        Args:
4290c2cf   Alexis Koralewski   adding unit choic...
609
            unit_name (str): Name of the unit
6686d675   Alexis Koralewski   new version of ob...
610
611
612
        Returns:
            dict: dictionary representing the topology of an unit (security, mount, channels, channel_groups)
        """
4290c2cf   Alexis Koralewski   adding unit choic...
613
        unit = self.get_unit_by_name(unit_name)
6686d675   Alexis Koralewski   new version of ob...
614
615
616
617
        topology = {}
        for key in unit["TOPOLOGY"].keys():
            branch = unit["TOPOLOGY"][key]
            if key == "CHANNELS":
4290c2cf   Alexis Koralewski   adding unit choic...
618
                topology[key] = self.get_channels(unit_name)
6686d675   Alexis Koralewski   new version of ob...
619
            elif key == "CHANNEL_GROUPS":
4290c2cf   Alexis Koralewski   adding unit choic...
620
                topology[key] = self.get_channel_groups(unit_name)
6686d675   Alexis Koralewski   new version of ob...
621
622
623
624
            else:
                topology[key] = branch
        return topology

a6617686   Etienne Pallier   new wrapper scrip...
625
    def get_active_agents(self, unit_name: str) -> list:
6686d675   Alexis Koralewski   new version of ob...
626
627
628
629
        """
        Return the list of active agents (i.e. agents that have an association with a device)

        Args:
4290c2cf   Alexis Koralewski   adding unit choic...
630
            unit_name (str): Name of the unit
6686d675   Alexis Koralewski   new version of ob...
631
632
633
634

        Returns:
            list: kist of the name of active agents
        """
4290c2cf   Alexis Koralewski   adding unit choic...
635
        return list(self.get_agents(unit_name).keys())
6686d675   Alexis Koralewski   new version of ob...
636
637
638
639
640
641
642
643
644

    def get_units(self)->dict:
        """
        Return all units sort by name defined in the config file

        Returns:
            dict: dictionary giving for a unit_name, his content (name,database,topology,agents,...)
        """
        result = {}
72519c93   Alexis Koralewski   Updating observat...
645
        units = self.obs_config["OBSERVATORY"]["UNITS"]
6686d675   Alexis Koralewski   new version of ob...
646
647
        for unit in units:
            unit = unit["UNIT"]
ee2a5e47   Alexis Koralewski   New version of ob...
648
            result[unit["name"]] = unit
6686d675   Alexis Koralewski   new version of ob...
649
650
        return result

a6617686   Etienne Pallier   new wrapper scrip...
651
    def get_components_agents(self, unit_name: str) -> dict:
6686d675   Alexis Koralewski   new version of ob...
652
653
654
655
        """
        Return dictionary of component_agents of the given unit

        Args:
4290c2cf   Alexis Koralewski   adding unit choic...
656
            unit_name (str): Name of the unit
6686d675   Alexis Koralewski   new version of ob...
657
658
659
660
661

        Returns:
            dict: dictionary sort by component name giving the associated agent (agent name)
        """
        components_agents = {}
4290c2cf   Alexis Koralewski   adding unit choic...
662
        topology = self.get_topology(unit_name)
6686d675   Alexis Koralewski   new version of ob...
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
        for element in topology:
            if element in ("SECURITY","MOUNT","CHANNELS"):
                if(element != "CHANNELS"):
                    for component_agent in topology[element]["COMPONENT_AGENTS"]:
                        component_name = list(component_agent.keys())[0]
                        components_agents[component_name] = component_agent[component_name]
                else:
                    for channel in topology[element]:
                        for component_agent in topology[element][channel]["COMPONENT_AGENTS"]:
                            component_name = list(component_agent.keys())[0]
                            components_agents[component_name] = component_agent[component_name]
        return components_agents

    def get_units_name(self)->list:
        """
        Return list of units names 

        Returns:
            [list]: names of units
        """
        return list(self.get_units().keys())

a6617686   Etienne Pallier   new wrapper scrip...
685
    def get_unit_by_name(self, name: str) -> dict:
6686d675   Alexis Koralewski   new version of ob...
686
        """
a6617686   Etienne Pallier   new wrapper scrip...
687
        Return dictionary containing definition of the unit that matches the given name
6686d675   Alexis Koralewski   new version of ob...
688
689
690
691
692
693
694
695
696

        Args:
            name (str): name of the unit

        Returns:
            dict: dictonary representing the unit
        """
        return self.get_units()[name]
    
a6617686   Etienne Pallier   new wrapper scrip...
697
    def get_agents_per_computer(self, unit_name: str) -> dict:
6686d675   Alexis Koralewski   new version of ob...
698
699
700
701
        """
        Return dictionary that give for each computer, what are the associated agents to it as a list

        Args:
4290c2cf   Alexis Koralewski   adding unit choic...
702
            unit_name (str): Name of the unit
6686d675   Alexis Koralewski   new version of ob...
703
704
705
706
707
708

        Returns:
            dict:  dictionary that give for each computer, what are the associated agents to it as a list

        """
        agents_per_computer = {}
4290c2cf   Alexis Koralewski   adding unit choic...
709
        agents = self.get_agents(unit_name)
6686d675   Alexis Koralewski   new version of ob...
710
        for agent in agents:
ee2a5e47   Alexis Koralewski   New version of ob...
711
712
            computer_name = agents[agent]["computer"]
            if(agents[agent]["computer"] not in agents_per_computer.keys()):
6686d675   Alexis Koralewski   new version of ob...
713
714
715
716
717
718
                agents_per_computer[computer_name] = [agent]
            else:
                agents_per_computer[computer_name].append(agent)
        return agents_per_computer


4290c2cf   Alexis Koralewski   adding unit choic...
719
    def get_agents_per_device(self,unit_name:str)->dict:
6686d675   Alexis Koralewski   new version of ob...
720
721
722
723
        """
        Return dictionary that give for each device, what are the associated agents to it as a list

        Args:
4290c2cf   Alexis Koralewski   adding unit choic...
724
            unit_name (str): Name of the unit
6686d675   Alexis Koralewski   new version of ob...
725
726
727
728
729
730

        Returns:
            dict:  dictionary that give for each device, what are the associated agents to it as a list

        """
        agents_per_device = {}
4290c2cf   Alexis Koralewski   adding unit choic...
731
        agents = self.get_agents(unit_name)
6686d675   Alexis Koralewski   new version of ob...
732
        for agent in agents:
ee2a5e47   Alexis Koralewski   New version of ob...
733
734
            if("device" in agents[agent].keys()):
                device_name = agents[agent]["device"]
c132ba0f   Alexis Koralewski   Fixing TNC config...
735
736
737
738
739
                if device_name in self.get_devices_names():
                    if(agents[agent]["device"] not in agents_per_device.keys()):
                        agents_per_device[device_name] = [agent]
                    else:
                        agents_per_device[device_name].append(agent)
6686d675   Alexis Koralewski   new version of ob...
740
                else:
c132ba0f   Alexis Koralewski   Fixing TNC config...
741
742
                    print(f"Error: device name '{device_name}' for agent '{agent}' is not known in the configuration file. The device name must match one of the names defined in the DEVICES section")
                    exit(1)
6686d675   Alexis Koralewski   new version of ob...
743
744
745
746
747
748
749
750
751
752
753
        return agents_per_device

    def get_active_devices(self)->list:
        """
        Return a list of active device names

        Returns:
            list: list of active device names
        """
        active_devices = []
        for unit_name in self.get_units():
4290c2cf   Alexis Koralewski   adding unit choic...
754
            for device in self.get_agents_per_device(unit_name):
6686d675   Alexis Koralewski   new version of ob...
755
756
757
758
759
760
761
762
763
764
765
766
767
                active_devices.append(device)
        return active_devices

    def get_active_computers(self)->list:
        """
        Return a list of active computer names

        Returns:
            list: list of active computer names
        """
        active_computers = []
        for unit_name in self.get_units():
            unit = self.get_unit_by_name(unit_name)
4290c2cf   Alexis Koralewski   adding unit choic...
768
            for computer in self.get_agents_per_computer(unit_name):
6686d675   Alexis Koralewski   new version of ob...
769
770
771
                active_computers.append(computer)
        return active_computers

4290c2cf   Alexis Koralewski   adding unit choic...
772
    def get_agent_information(self,unit_name:str,agent_name:str)->dict:
6686d675   Alexis Koralewski   new version of ob...
773
774
775
776
777
778
779
780
781
782
        """
        Give the dictionary of attributes of the agent for an unit.

        Args:
            unit (dict): dictonary representing the unit
            agent_name (str): agent name

        Returns:
            dict: dictionary containing attributes of the agent
        """
4290c2cf   Alexis Koralewski   adding unit choic...
783
        return self.get_agents(unit_name)[agent_name]
6686d675   Alexis Koralewski   new version of ob...
784
785
786
787
788
789
790
791
792
793
794
795
796

    def get_device_information(self,device_name:str)->dict:
        """
        Give the dictionary of the attributes of the device 

        Args:
            device_name (str): device name

        Returns:
            dict: dictionary containing attributes of the device
        """
        return self.get_devices()[device_name]

a6617686   Etienne Pallier   new wrapper scrip...
797
    def get_database_for_unit(self, unit_name: str) -> dict:
6686d675   Alexis Koralewski   new version of ob...
798
799
800
801
802
803
804
805
806
807
808
        """
        Return dictionary of attributes of the database for an unit

        Args:
            unit_name (str): unit name

        Returns:
            dict: dictionary of attributes of the database for an unit
        """
        return self.get_unit_by_name(unit_name)["DATABASE"]

a6617686   Etienne Pallier   new wrapper scrip...
809
    def get_device_for_agent(self, unit_name: str, agent_name: str) -> str:
6686d675   Alexis Koralewski   new version of ob...
810
811
812
813
814
815
816
817
818
819
        """
        Return device name associated to the agent

        Args:
            unit (dict): dictonary representing the unit
            agent_name (str): agent name

        Returns:
            str: device name associated to this agent
        """
4290c2cf   Alexis Koralewski   adding unit choic...
820
        agents_per_device = self.get_agents_per_device(unit_name)
6686d675   Alexis Koralewski   new version of ob...
821
822
823
        for device in agents_per_device:
            if agent_name in agents_per_device[device]:
                return self.get_device_information(device)
a6617686   Etienne Pallier   new wrapper scrip...
824
825

    def get_unit_of_computer(self, computer_name: str) -> str:
6686d675   Alexis Koralewski   new version of ob...
826
827
828
829
830
831
832
833
834
835
        """
        Return the name of the unit where the computer is used

        Args:
            computer_name (str): computer name

        Returns:
            str: unit name
        """
        for unit_name in self.get_units():
4290c2cf   Alexis Koralewski   adding unit choic...
836
            if(computer_name in self.get_agents_per_computer(unit_name)):
6686d675   Alexis Koralewski   new version of ob...
837
838
                return unit_name

a6617686   Etienne Pallier   new wrapper scrip...
839
    def get_unit_of_device(self, device_name:str)->str:
6686d675   Alexis Koralewski   new version of ob...
840
841
842
843
844
845
846
847
848
849
        """
        Return the name of the unit where the device is used

        Args:
            device_name (str): device name

        Returns:
            str: unit name
        """
        for unit_name in self.get_units():
4290c2cf   Alexis Koralewski   adding unit choic...
850
            if(device_name in self.get_agents_per_device(unit_name)):
6686d675   Alexis Koralewski   new version of ob...
851
852
853
854
855
856
857
858
859
860
861
862
863
                return unit_name

    def get_device_power(self,device_name:str)->dict:
        """
        Return dictionary that contains informations about power if this information is present in the device config file

        Return None if this information isn't stored in device's config file
        Args:
            device_name (str): name of the device

        Returns:
            dict: informations about power of device
        """
ee2a5e47   Alexis Koralewski   New version of ob...
864
        return self.get_devices()[device_name]["device_config"].get("power")
6686d675   Alexis Koralewski   new version of ob...
865
866


a6617686   Etienne Pallier   new wrapper scrip...
867
    def get_device_capabilities(self, device_name:str)->list:
6686d675   Alexis Koralewski   new version of ob...
868
869
870
871
872
873
874
875
876
877
878
879
        """
        Return dictionary that contains informations about capabilities if this information is present in the device config file

        Return empty list if this information isn't stored in device's config file
        Args:
            device_name (str): name of the device

        Returns:
            list: list of capabilities of device
        """
        list_of_capabilities = []
        capabilities = self.get_devices()[device_name]["device_config"].get("CAPABILITIES")
ee2a5e47   Alexis Koralewski   New version of ob...
880
        return capabilities
6686d675   Alexis Koralewski   new version of ob...
881
882
883
884
885
886
887
888
889
890
891
892

    def get_device_connector(self,device_name:str)->dict:
        """
        Return dictionary that contains informations about connector if this information is present in the device config file

        Return None if this information isn't stored in device's config file
        Args:
            device_name (str): name of the device

        Returns:
            dict: informations about connector of device
        """
ee2a5e47   Alexis Koralewski   New version of ob...
893
        return self.get_devices()[device_name]["device_config"].get("connector")
6686d675   Alexis Koralewski   new version of ob...
894

a6617686   Etienne Pallier   new wrapper scrip...
895
    def get_computer_power(self, computer_name: str) -> dict:
6686d675   Alexis Koralewski   new version of ob...
896
897
898
899
900
901
902
903
904
905
        """
        Return dictionary that contains informations about power if this information is present in the device config file

        Return None if this information isn't stored in device's config file
        Args:
            device_name (str): name of the device

        Returns:
            dict: informations about connector of device
        """
ee2a5e47   Alexis Koralewski   New version of ob...
906
        return self.get_computers()[computer_name]["computer_config"].get("power")
dd54dc29   Alexis Koralewski   Updating schemas,...
907

f110f276   Alexis Koralewski   adding new functi...
908
    def getDeviceControllerNameForAgent(self,unit_name:str,agent_name:str)->tuple:
4290c2cf   Alexis Koralewski   adding unit choic...
909
        agent = self.get_agent_information(unit_name,agent_name)
f110f276   Alexis Koralewski   adding new functi...
910
911
912
913
        return (agent["device"],"DeviceController"+agent["device"])

    def getDeviceConfigForDeviceController(self,device_name:str)->dict:
        return self.get_devices()[device_name]["device_config"]
dd54dc29   Alexis Koralewski   Updating schemas,...
914

4290c2cf   Alexis Koralewski   adding unit choic...
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
    def getCommParamsForAgentDevice(self,unit_name:str,agent_name:str)->tuple:
        agent = self.get_agent_information(unit_name,agent_name)
        device_config = self.getDeviceConfigForDeviceController(agent["device"])
        comm_access = agent.get("comm_access",None)
        comm = device_config["comm"]
        return (comm_access,comm)

    def getChannelCapabilities(self,unit_name:str,channel_name:str)->list:
        channel = self.get_channel_information(unit_name,channel_name)
        result = []
        for component_agent in channel["COMPONENT_AGENTS"]:
            component = list(component_agent.keys())[0]
            agent = component_agent[component]
            device = self.getDeviceControllerNameForAgent(unit_name,agent)[0]
            device_capabilities = self.get_device_capabilities(device)
            for capability in device_capabilities:
                if capability["component"] == component:
                    result.append(capability)
        return result

    def getEditableAttributesOfCapability(self,capability:dict)->dict:
        editable_fields = {}
        attributes = capability.get("attributes")
        for attribute in attributes:
c9a2c2f9   Alexis Koralewski   add methods to ge...
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
            if attributes[attribute]["is_editable"]:
                editable_fields[attribute] = attributes[attribute]
        return editable_fields

    def getUneditableAttributesOfCapability(self,capability:dict)->dict:
        uneditable_fields = {}
        attributes = capability.get("attributes")
        for attribute in attributes:
            if attributes[attribute]["is_editable"] == False:
                uneditable_fields[attribute] = attributes[attribute]
        return uneditable_fields

    def getEditableAttributesOfChannel(self,unit_name:str,channel_name:str)->list:
        capabilities = self.getChannelCapabilities(unit_name,channel_name)
        # merged_result = {}
        # for capability in capabilities:
        #     merged_result[capability["component"]] = self.getEditableAttributesOfCapability(capability)
        # return merged_result
        merged_result = []
        for capability in capabilities:
            attributes = self.getEditableAttributesOfCapability(capability)
            if len(attributes.keys()) > 0:
                merged_result.append(attributes)
        return merged_result

    def getUneditableAttributesOfChannel(self,unit_name:str,channel_name:str)->list:
        capabilities = self.getChannelCapabilities(unit_name,channel_name)
        # merged_result = {}
        # for capability in capabilities:
        #     merged_result[capability["component"]] = self.getEditableAttributesOfCapability(capability)
        # return merged_result
        merged_result = []
        for capability in capabilities:
            attributes = self.getUneditableAttributesOfCapability(capability)
            if len(attributes.keys()) > 0:
                merged_result.append(attributes)
        return merged_result
3d4ab326   Alexis Koralewski   adding new attrib...
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992

    def getLogicOfChannelGroups(self,unit_name):
        return self.get_channel_groups(unit_name)["global_group_logic"]

    
    def getGroupOfChannelByName(self, unit_name:str, name_of_channel_group):
        return self.get_channel_groups(unit_name)["groups"][name_of_channel_group]


    def getEditableAttributesOfMount(self,unit_name):
        capabilities = self.get_device_capabilities(self.get_device_for_agent(unit_name,"mount")["name"])
        merged_result = []
        for capability in capabilities:
            attributes = self.getEditableAttributesOfCapability(capability)
            if len(attributes.keys()) > 0:
                merged_result.append(attributes)
        return merged_result
c9a2c2f9   Alexis Koralewski   add methods to ge...
993
        
dd54dc29   Alexis Koralewski   Updating schemas,...
994
def main():
3d4ab326   Alexis Koralewski   adding new attrib...
995
996
997
    # config = ConfigPyros("../../../../privatedev/config/guitalens/observatory_guitalens.yml")
    # unit_name = config.get_units_name()[0]
    # dc = config.getDeviceControllerNameForAgent(unit_name,"mount")[0]
4290c2cf   Alexis Koralewski   adding unit choic...
998
999
    #print(config.getDeviceConfigForDeviceController(dc))
    #print(config.getCommParamsForAgentDevice(unit_name,"mount"))
c9a2c2f9   Alexis Koralewski   add methods to ge...
1000
1001
1002
1003
1004
1005
    # print(config.getChannelCapabilities(unit_name,"OpticalChannel_up"))
    # print(config.get_channel_groups(unit_name))
    # print(config.getEditableAttributesOfCapability(config.getChannelCapabilities(unit_name,"OpticalChannel_up")[0]))
    # print(config.getEditableAttributesOfChannel(unit_name,"OpticalChannel_up"))
    config = ConfigPyros("../../../../privatedev/config/tnc/observatory_tnc.yml")
    unit_name = config.get_units_name()[0]
3d4ab326   Alexis Koralewski   adding new attrib...
1006
    #dc = config.getDeviceControllerNameForAgent(unit_name,"mount")[0]
c9a2c2f9   Alexis Koralewski   add methods to ge...
1007
1008
    #print(config.getDeviceConfigForDeviceController(dc))
    #print(config.getCommParamsForAgentDevice(unit_name,"mount"))
3d4ab326   Alexis Koralewski   adding new attrib...
1009
1010
1011
1012
1013
    # print(config.getChannelCapabilities(unit_name,"OpticalChannel_down2"))
    # print(config.get_channel_groups(unit_name))
    # print(config.getEditableAttributesOfCapability(config.getChannelCapabilities(unit_name,"OpticalChannel_down2")[0]))
    # print(config.getEditableAttributesOfChannel(unit_name,"OpticalChannel_down2"))
    print(config.getEditableAttributesOfMount(unit_name))
18ec3272   Alexis Koralewski   adding path to dj...
1014
1015
1016
1017
    #print(config.get_devices()["FLI-Kepler4040"]["device_config"])
    #print(config.get_devices()["FLI-Kepler4040"]["device_config"]["CAPABILITIES"][1]["attributes"]["manufacturer"])
    #print(config.get_devices()["FLI-Kepler4040"]["device_config"]["CAPABILITIES"])
    #print(config.get_devices()["AstroMecCA-TM350"]["device_config"]["CAPABILITIES"])
dd54dc29   Alexis Koralewski   Updating schemas,...
1018
1019
1020
if __name__ == "__main__": 

    main()