Blame view

src/core/pyros_django/obsconfig/configpyros.py 29.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
6686d675   Alexis Koralewski   new version of ob...
4
5
from pykwalify.errors import PyKwalifyException,SchemaError

a2f47fb6   Alexis Koralewski   updating display ...
6
class ConfigPyros:
6686d675   Alexis Koralewski   new version of ob...
7
    # (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 
ee2a5e47   Alexis Koralewski   New version of ob...
8
    # read_files is an history of which config files has been read, where the key is the source file which is linked to a list of files associated to this key
a2f47fb6   Alexis Koralewski   updating display ...
9
    devices_links = {}
ee2a5e47   Alexis Koralewski   New version of ob...
10
11
    current_file = None
    COMPONENT_PATH = "../../../../config/components/"
72519c93   Alexis Koralewski   Updating observat...
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
    GENERIC_DEVICES_PATH = "../../../../config/devices/"
    pickle_file = "obsconfig.p"
    obs_config = None
    devices = None
    computers = None
    agents = None 
    def verify_if_pickle_needs_to_be_updated(self,observatory_config_file)->bool:
        """[summary]

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

        Returns:
            bool: [description]
        """
        if os.path.isfile(self.pickle_file) == False:
            return True
        else:
            pickle_file_mtime = os.path.getmtime(self.pickle_file)
            obs_config_mtime = os.path.getmtime(observatory_config_file)
            if obs_config_mtime > pickle_file_mtime:
                return True
            
            obs_config = self.read_and_check_config_file(observatory_config_file)
            if obs_config is None:
                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

    def load(self,observatory_config_file):
        does_pickle_needs_to_be_updated = self.verify_if_pickle_needs_to_be_updated(observatory_config_file)
        if os.path.isfile(self.pickle_file) and does_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.pickle_file, os.R_OK):
                        pickle_dict = pickle.load(open(self.pickle_file,"rb"))
                        can_pickle_file_be_read = True
                    else:
                        time.sleep(0.5)
            except IOError:
                print("Error when reading the pickle file")
                
            self.obs_config = pickle_dict["obs_config"]
            self.computers = pickle_dict["computers"]
            self.devices = pickle_dict["devices"]
            self.devices_links = pickle_dict["devices_links"]
        else:
            print("Pickle file needs to be created or updated")
            pickle_dict = {}
            
            self.obs_config = self.read_and_check_config_file(observatory_config_file) 
            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
            print("Writing pickle file")
            pickle.dump(pickle_dict,open(self.pickle_file,"wb"))
6686d675   Alexis Koralewski   new version of ob...
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98

    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...
99
100
101
102
103
104
105
106
            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)
        
6686d675   Alexis Koralewski   new version of ob...
107
108
109
110
111
112
113
            c = pykwalify.core.Core(source_file=yaml_file, schema_files=[schema_file])
            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)
            return None
72519c93   Alexis Koralewski   Updating observat...
114
115
        except IOError:
            print("Error when reading the observatory config file")
6686d675   Alexis Koralewski   new version of ob...
116
117
118
119
120
121
122
123
124
125
126

    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...
127
        self.current_file = yaml_file
6686d675   Alexis Koralewski   new version of ob...
128
        try:
72519c93   Alexis Koralewski   Updating observat...
129
130
131
132
133
134
135
136
            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...
137
            with open(yaml_file, 'r') as stream:
72519c93   Alexis Koralewski   Updating observat...
138
                print(f"Reading {yaml_file}")
6686d675   Alexis Koralewski   new version of ob...
139
140
                config_file = yaml.safe_load(stream)

72519c93   Alexis Koralewski   Updating observat...
141
142
143
144
145
146
147
            self.SCHEMA_PATH = os.path.join(os.path.abspath(os.path.dirname(yaml_file)),"../../../config/schemas/")
            self.CONFIG_PATH = os.path.dirname(yaml_file)+"/"
            self.COMPONENT_PATH = os.path.join(os.path.abspath(os.path.dirname(yaml_file)),"../../../config/components/")
            self.GENERIC_DEVICES_PATH = os.path.join(os.path.abspath(os.path.dirname(yaml_file)),"../../../config/devices/")
            result = self.check_and_return_config(yaml_file,self.SCHEMA_PATH+config_file["schema"])
            if result is None:
                print("Error when reading and validating config file, please check the errors right above")
ee2a5e47   Alexis Koralewski   New version of ob...
148

72519c93   Alexis Koralewski   Updating observat...
149
            return result
ee2a5e47   Alexis Koralewski   New version of ob...
150
151
152
153
154
155
156

        except yaml.YAMLError as exc:
            print(exc)
        except Exception as e:
            print(e)
            return None
    
72519c93   Alexis Koralewski   Updating observat...
157
    def read_generic_component_and_return_attributes(self,component_name:str)->dict:
ee2a5e47   Alexis Koralewski   New version of ob...
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
        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:
        """
        

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

        Returns:
            dict: [description]
        """
        
72519c93   Alexis Koralewski   Updating observat...
186
        component_attributes = self.read_generic_component_and_return_attributes(capability["component"])
ee2a5e47   Alexis Koralewski   New version of ob...
187
188
189
190
191
192
193
194
195
196
197
198
199
        
        attributes = {}
        for attribute in capability["attributes"]:
            attribute = attribute["attribute"]
        
            attributes[attribute.pop("key")] = attribute
        
        for attribute_name in attributes.keys():
            # merging values from general component to specific values of component in config file
            if "is_Enum" in component_attributes[attribute_name].keys():
                # check if value of this attribute is in Enum of general component attribute definition
                enum_values = component_attributes[attribute_name]["value"]
                if attributes[attribute_name]["value"][0] in enum_values:
72519c93   Alexis Koralewski   Updating observat...
200
                    # merge attributes of general component with specified component in device config file
ee2a5e47   Alexis Koralewski   New version of ob...
201
202
203
204
                    new_attributes = {**component_attributes[attribute_name],**attributes[attribute_name]}
                else:
                    print(f"Error in file {self.current_file} : attribute \"{attribute_name}\" isn't in enum. Accepted values for this attribute : \"{enum_values}\"")
                    exit(1)
72519c93   Alexis Koralewski   Updating observat...
205
            # merge attributes of general component with specified component in device config file
ee2a5e47   Alexis Koralewski   New version of ob...
206
207
208
209
210
211
212
213
            new_attributes = {**component_attributes[attribute_name],**attributes[attribute_name]}
            component_attributes[attribute_name] = new_attributes
        
        capability["attributes"] = component_attributes
        return capability



a2f47fb6   Alexis Koralewski   updating display ...
214
215
216
217
218
219
220
221
    def get_devices_names_and_file(self)->dict:
        """
        

        Returns:
            dict: [description]
        """
        devices_names_and_files = {}
72519c93   Alexis Koralewski   Updating observat...
222
        for device in self.obs_config["OBSERVATORY"]["DEVICES"]:
a2f47fb6   Alexis Koralewski   updating display ...
223
224
225
226
227
            device = device["DEVICE"]
            
            devices_names_and_files[device["name"]] = device["file"]
        return devices_names_and_files

72519c93   Alexis Koralewski   Updating observat...
228
    def read_device_config_file(self,config_file_name:str,is_generic=False)->dict:
ee2a5e47   Alexis Koralewski   New version of ob...
229
230
231
232
233
234
235
236
237
        """

        Args:
            config_file_name (str): [description]

        Returns:
            dict: [description]
        """
        self.current_file = config_file_name
72519c93   Alexis Koralewski   Updating observat...
238
        print(f"Reading {config_file_name}")
ee2a5e47   Alexis Koralewski   New version of ob...
239
240
241
        try:
            with open(config_file_name, 'r') as stream:
                config_file = yaml.safe_load(stream)
72519c93   Alexis Koralewski   Updating observat...
242
243
244
245
246
                if is_generic:
                    self.SCHEMA_PATH = os.path.join(os.path.abspath(os.path.dirname(config_file_name)),"../schemas/")
                else:
                    self.SCHEMA_PATH = os.path.join(os.path.abspath(os.path.dirname(config_file_name)),"../../../config/schemas/")
                
ee2a5e47   Alexis Koralewski   New version of ob...
247
248
249
250
251
252
                result = self.check_and_return_config(config_file_name,self.SCHEMA_PATH+config_file["schema"])
                if result is None:
                    print("Error when reading and validating config file, please check the errors right above")
                else:
                    device = result["DEVICE"]
                    
72519c93   Alexis Koralewski   Updating observat...
253
254
255
256
257
258
259
260
                    if "generic" in device:
                        current_config = result
                        generic_device_config = self.read_device_config_file(self.GENERIC_DEVICES_PATH+device["generic"],True)
                        
                        new_config = {**generic_device_config["DEVICE"],**current_config["DEVICE"]}
           
                        result["DEVICE"] = new_config

ee2a5e47   Alexis Koralewski   New version of ob...
261
262
263
264
265
266
267
268
269
270
271
                    if "CAPABILITIES" in device:
                        capabilities = []
                        for capability in device["CAPABILITIES"]:
                            capability = capability["CAPABILITY"]
                            
                            capabilities.append(self.read_capability_of_device(capability))
                            
                            
                            
                        device["CAPABILITIES"] = capabilities
                    if "ATTACHED_DEVICES" in device.keys():
a2f47fb6   Alexis Koralewski   updating display ...
272
273
274
                        
                        devices_name_and_file = self.get_devices_names_and_file()
                        active_devices = self.get_active_devices()
ee2a5e47   Alexis Koralewski   New version of ob...
275
                        for attached_device in device["ATTACHED_DEVICES"]:
a2f47fb6   Alexis Koralewski   updating display ...
276
277
                            is_attached_device_link_to_agent = False
                            for active_device in active_devices:
a2f47fb6   Alexis Koralewski   updating display ...
278
279
280
281
282
                                if devices_name_and_file[active_device] == attached_device["file"]:
                                    is_attached_device_link_to_agent = True
                                    break

                            if self.CONFIG_PATH+attached_device["file"] != config_file_name and not is_attached_device_link_to_agent:
72519c93   Alexis Koralewski   Updating observat...
283
                                
a2f47fb6   Alexis Koralewski   updating display ...
284
285
286
287
288
289
290
291
292
293
                                config_of_attached_device = self.read_device_config_file(self.CONFIG_PATH+attached_device["file"])
                                
                                capabilities_of_attached_device = None
                                if "CAPABILITIES" in config_of_attached_device["DEVICE"].keys():
                                    capabilities_of_attached_device = config_of_attached_device["DEVICE"]["CAPABILITIES"]
                                if capabilities_of_attached_device is not None:
                                    # get name of device corresponding to the config file name
                                    parent_device_name = [device for device,file_name in devices_name_and_file.items() if file_name == config_file_name[len(self.CONFIG_PATH):] ][0]
                                    
                                    attached_device_name = [device for device,file_name in devices_name_and_file.items() if file_name == attached_device["file"]][0]
a2f47fb6   Alexis Koralewski   updating display ...
294
295
296
297
                                    
                                    self.devices_links[attached_device_name] = parent_device_name
                                    for capability in capabilities_of_attached_device:
                                        result["DEVICE"]["CAPABILITIES"].append(capability)
6686d675   Alexis Koralewski   new version of ob...
298
299
300
                return result
        except yaml.YAMLError as exc:
            print(exc)
dd54dc29   Alexis Koralewski   Updating schemas,...
301
302
        except Exception as e:
            print(e)
6686d675   Alexis Koralewski   new version of ob...
303
304
            return None

72519c93   Alexis Koralewski   Updating observat...
305
    def __init__(self,observatory_config_file:str) -> None:
6686d675   Alexis Koralewski   new version of ob...
306
307
308
309
310
311
312
        """
        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...
313
        self.load(observatory_config_file)
6686d675   Alexis Koralewski   new version of ob...
314

6686d675   Alexis Koralewski   new version of ob...
315
316
317
318
319
320
321
322
   
    def get_obs_name(self)->str:
        """
        Return name of the observatory

        Returns:
            str: Name of the observatory
        """
72519c93   Alexis Koralewski   Updating observat...
323
        return self.obs_config["OBSERVATORY"]["name"]
6686d675   Alexis Koralewski   new version of ob...
324
325
326
327
328
329
330
331
332
333
334
335

    def get_channels(self,unit)->dict:
        """
        return dictionary of channels

        Returns:
            dict: [description]
        """
        channels = {}
        
        for channel_id in range(len(unit["TOPOLOGY"]["CHANNELS"])):
            channel = unit["TOPOLOGY"]["CHANNELS"][channel_id]["CHANNEL"]
ee2a5e47   Alexis Koralewski   New version of ob...
336
            channels[channel["name"]] = channel
6686d675   Alexis Koralewski   new version of ob...
337
338
339
340
341
342
343
344
345
        return channels
    
    def get_computers(self)->dict:
        """
        return dictionary of computers

        Returns:
            dict: [description]
        """
72519c93   Alexis Koralewski   Updating observat...
346
347
348
349
350
351
352
353
354
355
        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
6686d675   Alexis Koralewski   new version of ob...
356
357
358
359
360
361
362
363
    
    def get_devices(self)->dict:
        """
        return dictionary of devices
        
        Returns:
            dict: [description]
        """
72519c93   Alexis Koralewski   Updating observat...
364
365
366
367
368
369
370
371
372
373
374
        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...
375
376
377
378
379
380
381
382

    def get_agents(self,unit)->dict:
        """
        return dictionary of agents 

        Returns:
            dict: dictionary of agents. For each agents tell the name, computer, device, protocole, etc...
        """
72519c93   Alexis Koralewski   Updating observat...
383
384
385
386
387
388
389
390
391
392
393
394
        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...
395
396
397
398
399
400
401
402
403
404
405

    def get_channel_groups(self,unit:dict)->dict:
        """
        Return dictionary of channel groups, tell the logic between groups of channels and within a group of channels

        Args:
            unit (dict): dictonary contaning all values of a unit
        Returns:
            dict: dictionary of channel groups (tell the logic and groups of channels)
        """
        info = {}
ee2a5e47   Alexis Koralewski   New version of ob...
406
        info["global_groups_logic"] = unit["TOPOLOGY"]["CHANNEL_GROUPS"]["logic"]
6686d675   Alexis Koralewski   new version of ob...
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
        info["groups"] = {}
        for group_id in range(len(unit["TOPOLOGY"]["CHANNEL_GROUPS"]["GROUPS"])):
            group = unit["TOPOLOGY"]["CHANNEL_GROUPS"]["GROUPS"][group_id]["GROUP"]
            info["groups"][group_id] = group
        return info

    def get_channel_information(self,unit:dict,channel_name:str)->dict:
        """
        Return information of the given channel name of a unit

        Args:
            unit (dict): dictionary representing the unit 
            channel_name (str): name of the channel

        Returns:
            dict: dictionary containing all values that define this channel
        """
        channels = self.get_channels(unit)
        return channels[channel_name]

    def get_topology(self,unit:dict)->dict:
        """
        Return dictionary of the topology of the observatory

        Args:
            unit (dict): dictionary representing the unit
        Returns:
            dict: dictionary representing the topology of an unit (security, mount, channels, channel_groups)
        """
        topology = {}
        for key in unit["TOPOLOGY"].keys():
            branch = unit["TOPOLOGY"][key]
            if key == "CHANNELS":
                topology[key] = self.get_channels(unit)
            elif key == "CHANNEL_GROUPS":
                topology[key] = self.get_channel_groups(unit)
            else:
                topology[key] = branch
        return topology

    def get_active_agents(self,unit:dict)->list:
        """
        Return the list of active agents (i.e. agents that have an association with a device)

        Args:
            unit (dict): dictionary representing the unit

        Returns:
            list: kist of the name of active agents
        """
        return list(self.get_agents(unit).keys())

    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...
467
        units = self.obs_config["OBSERVATORY"]["UNITS"]
6686d675   Alexis Koralewski   new version of ob...
468
469
        for unit in units:
            unit = unit["UNIT"]
ee2a5e47   Alexis Koralewski   New version of ob...
470
            result[unit["name"]] = unit
6686d675   Alexis Koralewski   new version of ob...
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
        return result

    def get_components_agents(self,unit:dict)->dict:
        """
        Return dictionary of component_agents of the given unit

        Args:
            unit (dict): dictionary representing the unit

        Returns:
            dict: dictionary sort by component name giving the associated agent (agent name)
        """
        components_agents = {}
        topology = self.get_topology(unit)
        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())

    def get_unit_by_name(self,name:str)->dict:
        """
        Return dictionary containing definition of the unit that match the given name

        Args:
            name (str): name of the unit

        Returns:
            dict: dictonary representing the unit
        """
        return self.get_units()[name]
    
    def get_agents_per_computer(self,unit:dict)->dict:
        """
        Return dictionary that give for each computer, what are the associated agents to it as a list

        Args:
            unit (dict): dictonary representing the unit

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

        """
        agents_per_computer = {}
        agents = self.get_agents(unit)
        for agent in agents:
ee2a5e47   Alexis Koralewski   New version of ob...
533
534
            computer_name = agents[agent]["computer"]
            if(agents[agent]["computer"] not in agents_per_computer.keys()):
6686d675   Alexis Koralewski   new version of ob...
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
                agents_per_computer[computer_name] = [agent]
            else:
                agents_per_computer[computer_name].append(agent)
        return agents_per_computer


    def get_agents_per_device(self,unit:dict)->dict:
        """
        Return dictionary that give for each device, what are the associated agents to it as a list

        Args:
            unit (dict): dictonary representing the unit

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

        """
        agents_per_device = {}
        agents = self.get_agents(unit)
        for agent in agents:
ee2a5e47   Alexis Koralewski   New version of ob...
555
556
557
            if("device" in agents[agent].keys()):
                device_name = agents[agent]["device"]
                if(agents[agent]["device"] not in agents_per_device.keys()):
6686d675   Alexis Koralewski   new version of ob...
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
                    agents_per_device[device_name] = [agent]
                else:
                    agents_per_device[device_name].append(agent)
        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():
            unit = self.get_unit_by_name(unit_name)
            for device in self.get_agents_per_device(unit):
                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)
            for computer in self.get_agents_per_computer(unit):
                active_computers.append(computer)
        return active_computers

    def get_agent_information(self,unit:dict,agent_name:str)->dict:
        """
        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
        """
        return self.get_agents(unit)[agent_name]

    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]

    def get_database_for_unit(self,unit_name:str)->dict:
        """
        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"]

    def get_device_for_agent(self,unit:dict,agent_name:str)->str:
        """
        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
        """
        agents_per_device = self.get_agents_per_device(unit)
        for device in agents_per_device:
            if agent_name in agents_per_device[device]:
                return self.get_device_information(device)
    def get_unit_of_computer(self,computer_name:str)->str:
        """
        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():
            unit = self.get_unit_by_name(unit_name)
            if(computer_name in self.get_agents_per_computer(unit)):
                return unit_name

    def get_unit_of_device(self,device_name:str)->str:
        """
        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():
            unit = self.get_unit_by_name(unit_name)
            if(device_name in self.get_agents_per_device(unit)):
                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...
684
        return self.get_devices()[device_name]["device_config"].get("power")
6686d675   Alexis Koralewski   new version of ob...
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699


    def get_device_capabilities(self,device_name:str)->list:
        """
        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...
700
        return capabilities
6686d675   Alexis Koralewski   new version of ob...
701
702
703
704
705
706
707
708
709
710
711
712

    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...
713
        return self.get_devices()[device_name]["device_config"].get("connector")
6686d675   Alexis Koralewski   new version of ob...
714
715
716
717
718
719
720
721
722
723
724
725

    def get_computer_power(self,computer_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 connector of device
        """
ee2a5e47   Alexis Koralewski   New version of ob...
726
        return self.get_computers()[computer_name]["computer_config"].get("power")
dd54dc29   Alexis Koralewski   Updating schemas,...
727
728
729


def main():
a2f47fb6   Alexis Koralewski   updating display ...
730
    config = ConfigPyros("../../../../privatedev/config/guitalens/observatory_guitalens.yml")
72519c93   Alexis Koralewski   Updating observat...
731
    print(config.get_devices()["FLI-Kepler4040"]["device_config"])
ee2a5e47   Alexis Koralewski   New version of ob...
732
733
    print(config.get_devices()["FLI-Kepler4040"]["device_config"]["CAPABILITIES"][1]["attributes"]["manufacturer"])
    print(config.get_devices()["FLI-Kepler4040"]["device_config"]["CAPABILITIES"])
dd54dc29   Alexis Koralewski   Updating schemas,...
734
735
736
if __name__ == "__main__": 

    main()