Blame view

src/core/pyros_django/common/models.py 105 KB
5ce2836f   Alexis Koralewski   update models (ad...
1
2
##from __future__ import unicode_literals

7735aaa7   Etienne Pallier   updated Agent spe...
3
4
5
# (EP 21/9/22) To allow autoreferencing (ex: AgentCmd.create() returns a AgentCmd)
from __future__ import annotations

5ce2836f   Alexis Koralewski   update models (ad...
6
# Stdlib imports
7138789e   Etienne Pallier   new Agent with 3 ...
7
from numpy import False_
1ba49504   Alexis Koralewski   fixing CSS and JS...
8
from src.device_controller.abstract_component.device_controller import DeviceCmd
5ce2836f   Alexis Koralewski   update models (ad...
9
10
11
12
13
from enum import Enum
from datetime import datetime, timedelta, date
from dateutil.relativedelta import relativedelta
import os
import sys
bc750a56   Etienne Pallier   Allow commands to...
14
from typing import Any, List, Tuple, Optional
d02249e6   Etienne Pallier   Added CMD_EXEC_ER...
15
16
17
import re

# Django imports
5ce2836f   Alexis Koralewski   update models (ad...
18
19
20
from django.core.validators import MaxValueValidator, MinValueValidator

# DJANGO imports
a6e63604   Alexis Koralewski   adding agentSP an...
21
from django.contrib.auth.models import AbstractUser, UserManager
5ce2836f   Alexis Koralewski   update models (ad...
22
23
24
25
26
from django.db import models
from django.db.models import Q, Max
from django.core.validators import MaxValueValidator, MinValueValidator
from django.db.models.deletion import DO_NOTHING
from django.db.models.expressions import F
5a434264   Alexis Koralewski   New version of Sc...
27
from django.db.models.query import QuerySet
5ce2836f   Alexis Koralewski   update models (ad...
28
29
30
31
32
from model_utils import Choices
from django.utils import timezone
# Project imports
# DeviceCommand is used by class Command
sys.path.append("../../..")
5ce2836f   Alexis Koralewski   update models (ad...
33
34
35
36
37
38
39
40
41
42
43
44
45
46

''' 
NOT USED - to be removed
class PyrosState(Enum):
    START = 'Starting'
    PA = 'Passive'
    INI = "INIT"
    STAND = "Standby"
    SCHED_START = 'Scheduler startup'
    SCHED = 'Scheduler'
    SCHED_CLOSE = 'Scheduler closing'
'''


5ce2836f   Alexis Koralewski   update models (ad...
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
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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
"""
STYLE RULES
===========
https://simpleisbetterthancomplex.com/tips/2018/02/10/django-tip-22-designing-better-models.html
https://steelkiwi.com/blog/best-practices-working-django-models-python/

- Model name => singular
    Call it Company instead of Companies. 
    A model definition is the representation of a single object (the object in this example is a company), 
    and not a collection of companies
    The model definition is a class, so always use CapWords convention (no underscores)
    E.g. User, Permission, ContentType, etc.

- For the model’s attributes use snake_case.
    E.g. first_name, last_name, etc

- Blank and Null Fields (https://simpleisbetterthancomplex.com/tips/2016/07/25/django-tip-8-blank-or-null.html)
    - Null: It is database-related. Defines if a given database column will accept null values or not.
    - Blank: It is validation-related. It will be used during forms validation, when calling form.is_valid().
    Do not use null=True for text-based fields that are optional.
    Otherwise, you will end up having two possible values for “no data”, that is: None and an empty string.
    Having two possible values for “no data” is redundant.
    The Django convention is to use the empty string, not NULL.
    Example:
        # The default values of `null` and `blank` are `False`.
        class Person(models.Model):
            name = models.CharField(max_length=255)  # Mandatory
            bio = models.TextField(max_length=500, blank=True)  # Optional (don't put null=True)
            birth_date = models.DateField(null=True, blank=True) # Optional (here you may add null=True)
    The default values of null and blank are False.
    Special case, when you need to accept NULL values for a BooleanField, use NullBooleanField instead.

- Choices : you can use Choices from the model_utils library. Take model Article, for instance:
    from model_utils import Choices
    class Article(models.Model):
        STATUSES = Choices(
            (0, 'draft', _('draft')),
            (1, 'published', _('published'))   )
        status = models.IntegerField(choices=STATUSES, default=STATUSES.draft)

- Reverse Relationships

    - related_name :
    Rule of thumb: if you are not sure what would be the related_name, 
    use the plural of the model holding the ForeignKey.
    ex:
        class Company:
            name = models.CharField(max_length=30)
        class Employee:
            first_name = models.CharField(max_length=30)
            last_name = models.CharField(max_length=30)
            company = models.ForeignKey(Company, on_delete=models.CASCADE, related_name='employees')
    usage:
        google = Company.objects.get(name='Google')
        google.employees.all()
        You can also use the reverse relationship to modify the company field on the Employee instances:
        vitor = Employee.objects.get(first_name='Vitor')
        google = Company.objects.get(name='Google')
        google.employees.add(vitor)

    - related_query_name :
        This kind of relationship also applies to query filters. 
        For example, if I wanted to list all companies that employs people named ‘Vitor’, I could do the following:
        companies = Company.objects.filter(employee__first_name='Vitor')
        If you want to customize the name of this relationship, here is how we do it:
            class Employee:
                first_name = models.CharField(max_length=30)
                last_name = models.CharField(max_length=30)
                company = models.ForeignKey(
                    Company,
                    on_delete=models.CASCADE,
                    related_name='employees',
                    related_query_name='person'
                )
        Then the usage would be:
        companies = Company.objects.filter(person__first_name='Vitor')

    To use it consistently, related_name goes as plural and related_query_name goes as singular.


GENERAL EXAMPLE
=======

from django.db import models
from django.urls import reverse

class Company(models.Model):
    # CHOICES
    PUBLIC_LIMITED_COMPANY = 'PLC'
    PRIVATE_COMPANY_LIMITED = 'LTD'
    LIMITED_LIABILITY_PARTNERSHIP = 'LLP'
    COMPANY_TYPE_CHOICES = (
        (PUBLIC_LIMITED_COMPANY, 'Public limited company'),
        (PRIVATE_COMPANY_LIMITED, 'Private company limited by shares'),
        (LIMITED_LIABILITY_PARTNERSHIP, 'Limited liability partnership'),
    )

    # DATABASE FIELDS
    name = models.CharField('name', max_length=30)
    vat_identification_number = models.CharField('VAT', max_length=20)
    company_type = models.CharField('type', max_length=3, choices=COMPANY_TYPE_CHOICES)

    # MANAGERS
    objects = models.Manager()
    limited_companies = LimitedCompanyManager()

    # META CLASS
    class Meta:
        verbose_name = 'company'
        verbose_name_plural = 'companies'

    # TO STRING METHOD
    def __str__(self):
        return self.name

    # SAVE METHOD
    def save(self, *args, **kwargs):
        do_something()
        super().save(*args, **kwargs)  # Call the "real" save() method.
        do_something_else()

    # ABSOLUTE URL METHOD
    def get_absolute_url(self):
        return reverse('company_details', kwargs={'pk': self.id})

    # OTHER METHODS
    def process_invoices(self):
        do_something()

"""


def printd(*args, **kwargs):
1ba49504   Alexis Koralewski   fixing CSS and JS...
180
181
    if os.environ.get('PYROS_DEBUG', '0') == '1':
        print('(MODEL)', *args, **kwargs)
5ce2836f   Alexis Koralewski   update models (ad...
182
183
184
185

# ---
# --- Utility functions
# ---
1ba49504   Alexis Koralewski   fixing CSS and JS...
186
187
188
189


def get_or_create_unique_row_from_model(model: models.Model):
    # return model.objects.get(id=1) if model.objects.exists() else model.objects.create(id=1)
5ce2836f   Alexis Koralewski   update models (ad...
190
191
192
193
194
195
196
197
198
    return model.objects.first() if model.objects.exists() else model.objects.create(id=1)


"""
------------------------
   BASE MODEL CLASSES
------------------------
"""

1ba49504   Alexis Koralewski   fixing CSS and JS...
199

5ce2836f   Alexis Koralewski   update models (ad...
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
class Device(models.Model):
    name = models.CharField(max_length=45, blank=True, null=True)
    desc = models.TextField(blank=True, null=True)
    created = models.DateTimeField(blank=True, null=True, auto_now_add=True)
    updated = models.DateTimeField(blank=True, null=True, auto_now=True)
    is_online = models.BooleanField(default=False)
    status = models.CharField(max_length=11, blank=True, null=True)
    maintenance_date = models.DateTimeField(blank=True, null=True)

    class Meta:
        abstract = True

    def __str__(self):
        return (str(self.name))

1ba49504   Alexis Koralewski   fixing CSS and JS...
215

5ce2836f   Alexis Koralewski   update models (ad...
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
class Request(models.Model):
    pyros_user = models.ForeignKey(
        'PyrosUser', on_delete=models.DO_NOTHING, related_name="requests")
    scientific_program = models.ForeignKey(
        'ScientificProgram', on_delete=models.DO_NOTHING, related_name="requests", blank=True, null=True)
    name = models.CharField(max_length=45, blank=True, null=True)
    desc = models.TextField(blank=True, null=True)
    created = models.DateTimeField(blank=True, null=True, auto_now_add=True)
    updated = models.DateTimeField(blank=True, null=True, auto_now=True)
    is_alert = models.BooleanField(default=False)
    target_type = models.CharField(max_length=8, blank=True, null=True)
    status = models.CharField(max_length=10, blank=True, null=True)
    autodeposit = models.BooleanField(default=False)
    checkpoint = models.CharField(max_length=45, blank=True, null=True)
    flag = models.CharField(max_length=45, blank=True, null=True)
    complete = models.BooleanField(default=False)
    submitted = models.BooleanField(default=False)

    class Meta:
        managed = True
        db_table = 'request'

    def __str__(self):
        return (str(self.name))


5ce2836f   Alexis Koralewski   update models (ad...
242
243
244
245
246
247
"""
------------------------
   OTHER MODEL CLASSES
------------------------
"""

1ba49504   Alexis Koralewski   fixing CSS and JS...
248
249
250
# TODO: A VIRER car remplacé par AgentDeviceStatus


5ce2836f   Alexis Koralewski   update models (ad...
251
252
class AgentDeviceTelescopeStatus(models.Model):
    #created = models.DateTimeField('status date', blank=True, null=True, auto_now_add=True)
1ba49504   Alexis Koralewski   fixing CSS and JS...
253
254
    updated = models.DateTimeField(
        'status date', blank=True, null=True, auto_now=True)
5ce2836f   Alexis Koralewski   update models (ad...
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
    radec = models.CharField('agent mode', max_length=30, blank=True)

    class Meta:
        managed = True
        db_table = 'agent_device_telescope_status'
        #verbose_name = "agent survey"
        #verbose_name_plural = "agents survey"

    """
    def __str__(self):
        return (f"Agent {self.name} at {self.updated} in mode {self.mode} and status {self.status}")
    """


class AgentDeviceStatus(models.Model):
    """Table storing various status parameters for EACH Device.

    Attributes:
        attr1 (str): Description of `attr1`.
        attr2 (:obj:`int`, optional): Description of `attr2`.

    """
    #created = models.DateTimeField('status date', blank=True, null=True, auto_now_add=True)
1ba49504   Alexis Koralewski   fixing CSS and JS...
278
279
    agent = models.CharField(
        'Name of the agent that saved this parameter', max_length=45, blank=True, null=True)
5ce2836f   Alexis Koralewski   update models (ad...
280
    #radec = models.CharField('agent mode', max_length=30, blank=True)
1ba49504   Alexis Koralewski   fixing CSS and JS...
281
282
283
284
    status = models.CharField(
        'status parameters json dictionnary (ex: {radec:..., speed:...})', max_length=300, blank=True, null=True)
    date_updated = models.DateTimeField(
        'status parameter date', blank=True, null=True, auto_now=True)
5ce2836f   Alexis Koralewski   update models (ad...
285
286
287
288
289
290
291
292
293
294
295

    class Meta:
        managed = True
        db_table = 'agent_device_status'
        verbose_name = "agent device status"
        verbose_name_plural = "agent devices status"

    def __str__(self):
        return (f"Agent {self.agent} last status is ({self.status}) (saved at {self.date_updated})")

    @classmethod
1ba49504   Alexis Koralewski   fixing CSS and JS...
296
    def getStatusForAgent(cls, agent: str) -> str:
5ce2836f   Alexis Koralewski   update models (ad...
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
        return cls.objects.filter(agent=agent)[0] if cls.objects.filter(agent=agent).exists() else cls.objects.create(agent=agent)
        '''
        return cls.objects.filter(agent=agent)[0].status if cls.objects.filter(agent=agent).exists() else cls.objects.create(agent=agent).status
        agent_status = cls.objects.filter(agent=agent)
        if agent_status.exists(): 
            return agent_status[0].status
        else:
            return cls.objects.create(agent=agent)
        '''


class AgentLogs(models.Model):
    created = models.DateTimeField(blank=True, null=True, auto_now_add=True)
    name = models.CharField(max_length=50)
    message = models.TextField(blank=True, null=True)

    class Meta:
        managed = True
        db_table = 'agent_logs'

    def __str__(self):
        return (f"{self.created} {self.name} {self.message}")


class AgentSurvey(models.Model):
    """
    | id | name | created | updated | validity_duration (default=1mn) | mode (active/idle) | status (launch/init/loop/exit/...) |
    """

6fbe2e20   Etienne Pallier   last minute.com m...
326
327
328
329
330
331
332
333
    # --- MODES ---
    '''
    In all modes, the Agent listens to commands sent to him and executes Agent level GENERAL ones.
    - MODE_IDLE : "idle" mode, does nothing, only executes Agent level GENERAL commands (DO_RESTART, DO_EXIT, DO_ABORT, DO_FLUSH, SET_ACTIVE, ...)
    - MODE_ROUTINE : idem IDLE + executes routine process (before & after)
    - MODE_ATTENTIVE : idem ROUTINE + executes Agent level SPECIFIC commands (commands specific to this agent, that only this agent understands and can execute)
    Default mode is MODE_ATTENTIVE (most active mode)
    '''
97331a11   Etienne Pallier   Simplification de...
334
335
336
337
    MODE_CHOICES = Choices(
        "IDLE",  
        "ROUTINE",  
        "ATTENTIVE",
6fbe2e20   Etienne Pallier   last minute.com m...
338
339
    )

6fbe2e20   Etienne Pallier   last minute.com m...
340
    # --- STATUSES ---
97331a11   Etienne Pallier   Simplification de...
341
342
343
344
    ''' Agent steps '''
    STATUS_CHOICES = Choices(
        'LAUNCHED',
        'INITIALIZING',
02c12676   Etienne Pallier   Renamed Agent Sta...
345
        'IN_MAIN_LOOP_START',
547df0ef   Etienne Pallier   routine_process_b...
346
        'IN_MAIN_LOOP_ROUTINE_ITER_START',
02c12676   Etienne Pallier   Renamed Agent Sta...
347
        'IN_MAIN_LOOP_GET_NEXT_CMD',
547df0ef   Etienne Pallier   routine_process_b...
348
        'IN_MAIN_LOOP_ROUTINE_ITER_END',
02c12676   Etienne Pallier   Renamed Agent Sta...
349
350
        'EXITING',      # STOP or HARD restart
        'RESTARTING',   # SOFT restart
6fbe2e20   Etienne Pallier   last minute.com m...
351
    )
5ce2836f   Alexis Koralewski   update models (ad...
352
353
354
355
356
357
358
359

    name = models.CharField(max_length=50, unique=True)
    #name = models.CharField(max_length=50, blank=True, null=True, unique=True)
    #created = models.DateTimeField(blank=True, null=True, auto_now_add=True)
    created = models.DateTimeField(blank=True, null=True, auto_now_add=True)
    updated = models.DateTimeField(blank=True, null=True, auto_now=True)
    validity_duration = models.PositiveIntegerField(default=90)
    #validity_duration = models.DurationField(default=90)
1ba49504   Alexis Koralewski   fixing CSS and JS...
360
    mode = models.CharField('agent mode', max_length=15,
97331a11   Etienne Pallier   Simplification de...
361
362
363
                            blank=True, choices=MODE_CHOICES,
                            #default = MODE_CHOICES.ATTENTIVE
    )
1ba49504   Alexis Koralewski   fixing CSS and JS...
364
    status = models.CharField(
22a6b074   Etienne Pallier   bugfix - routine_...
365
        max_length=40, blank=True, choices=STATUS_CHOICES)
5ce2836f   Alexis Koralewski   update models (ad...
366
    iteration = models.IntegerField(blank=True, null=True)
9bd7ac9e   Alexis Koralewski   Adding timeout co...
367
    nb_restart_max = models.IntegerField(blank=True,null=True,default=3)
6a41fe96   Alexis Koralewski   Add current_nb_re...
368
    current_nb_restart = models.IntegerField(blank=True,null=True,default=0)
5ce2836f   Alexis Koralewski   update models (ad...
369
370
371
372
373
374
375
376
    class Meta:
        managed = True
        db_table = 'agent_survey'
        #verbose_name = "agent survey"
        #verbose_name_plural = "agents survey"

    def __str__(self):
        return (f"Agent {self.name} at {self.updated} in mode {self.mode} and status {self.status}")
8b41b6cc   Etienne Pallier   ajout methodes is...
377

411b2df6   Etienne Pallier   ajout methode is_...
378
379
    # Testing agent status
    
8b41b6cc   Etienne Pallier   ajout methodes is...
380
381
    def is_launched(self): return self.status == self.STATUS_CHOICES.LAUNCHED
    def is_initializing(self): return self.status == self.STATUS_CHOICES.INITIALIZING
411b2df6   Etienne Pallier   ajout methode is_...
382
383
    
    def is_in_main_loop_start(self): return self.status == self.STATUS_CHOICES.IN_MAIN_LOOP
8b41b6cc   Etienne Pallier   ajout methodes is...
384
385
386
    def is_in_routine_bef(self): return self.status == self.STATUS_CHOICES.IN_ROUTINE_BEF
    def is_in_get_next_cmd(self): return self.status == self.STATUS_CHOICES.IN_GET_NEXT_CMD
    def is_in_routine_aft(self): return self.status == self.STATUS_CHOICES.IN_ROUTINE_AFT
411b2df6   Etienne Pallier   ajout methode is_...
387
388
389
    def is_in_main_loop(self): 
        return self.is_in_main_loop_start() or self.is_in_routine_bef() or self.is_in_get_next_cmd() or self.is_in_routine_aft()
    
8b41b6cc   Etienne Pallier   ajout methodes is...
390
391
    def is_stopping(self): return self.status == self.STATUS_CHOICES.EXITING
    def is_restarting(self): return self.status == self.STATUS_CHOICES.RESTARTING
d4cf685d   Etienne Pallier   ajout methode is_...
392
    def is_stopping_or_restarting(self): return self.is_stopping() or self.is_restarting()
5ce2836f   Alexis Koralewski   update models (ad...
393
394
395
396
397


class Album(models.Model):
    sequence = models.ForeignKey(
        'Sequence', on_delete=models.CASCADE, related_name="albums")
3b81a22b   Alexis Koralewski   Rework on Request...
398
399
    # detector = models.ForeignKey(
    #     'Detector', models.DO_NOTHING, related_name="albums", blank=True, null=True)
0318e3c9   Alexis Koralewski   Add tests for F05...
400
    #name_of_channel = models.CharField(blank=True,null=True,max_length=150)
5ce2836f   Alexis Koralewski   update models (ad...
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
    name = models.CharField(max_length=45, blank=True, null=True)
    desc = models.TextField(blank=True, null=True)
    created = models.DateTimeField(blank=True, null=True, auto_now_add=True)
    updated = models.DateTimeField(blank=True, null=True, auto_now=True)
    complete = models.BooleanField(default=False)

    class Meta:
        managed = True
        db_table = 'album'
        #verbose_name_plural = "Albums"

    def __str__(self):
        return (str(self.name))


class Alert(Request):
1ba49504   Alexis Koralewski   fixing CSS and JS...
417
418
    request = models.OneToOneField(
        'Request', on_delete=models.CASCADE, default='', parent_link=True)
5ce2836f   Alexis Koralewski   update models (ad...
419
420
421
422
    strategyobs = models.ForeignKey(
        'StrategyObs', models.DO_NOTHING, related_name="alerts", blank=True, null=True)
    voevent_file = models.CharField(max_length=45, blank=True, null=True)
    author = models.CharField(max_length=45, blank=True, null=True)
1ba49504   Alexis Koralewski   fixing CSS and JS...
423
424
    burst_jd = models.DecimalField(
        max_digits=15, decimal_places=8, blank=True, null=True)
5ce2836f   Alexis Koralewski   update models (ad...
425
426
427
    burst_ra = models.FloatField(max_length=45, blank=True, null=True)
    burst_dec = models.FloatField(max_length=45, blank=True, null=True)
    astro_coord_system = models.CharField(max_length=45, blank=True, null=True)
1ba49504   Alexis Koralewski   fixing CSS and JS...
428
429
430
431
    jd_send = models.DecimalField(
        max_digits=15, decimal_places=8, blank=True, null=True)
    jd_received = models.DecimalField(
        max_digits=15, decimal_places=8, blank=True, null=True)
5ce2836f   Alexis Koralewski   update models (ad...
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
    trig_id = models.IntegerField(blank=True, null=True)
    error_radius = models.FloatField(max_length=45, blank=True, null=True)
    defly_not_grb = models.BooleanField(default=False)
    editor = models.CharField(max_length=45, blank=True, null=True)
    soln_status = models.CharField(max_length=45, blank=True, null=True)
    pkt_ser_num = models.IntegerField(blank=True, null=True)

    class Meta:
        managed = True
        db_table = 'alert'

    def __str__(self):
        return str(self.trig_id)

    def request_name(self):
        return self.__str__()

    request_name.short_description = "Name"


5ce2836f   Alexis Koralewski   update models (ad...
452
class AgentCmd(models.Model):
5ce2836f   Alexis Koralewski   update models (ad...
453
    """
573eeae6   Etienne Pallier   Agent ne depend p...
454
455
456
457
458
459
460
    Command sent to an Agent

    Can be either :
    - an "agent level" (general or specific) command
    OR
    - a "device level" command

5ce2836f   Alexis Koralewski   update models (ad...
461
462
    | id | sender | recipient | name | validity_duration (default=60) | s_deposit_time | r_read_time

6875e6b1   Etienne Pallier   Ajout Sequence st...
463
    See doc/models_Command_state_diag.pu for PlantUML state diagram
5ce2836f   Alexis Koralewski   update models (ad...
464
465
    """

dbc484ed   Etienne Pallier   CmdException* mov...
466
467
468
469
470
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
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551

    ###
    # =================================================================
    #    EXCEPTIONS classes
    # =================================================================
    ###

    class CmdException(Exception):
        ''' Base class for all Agent command exceptions '''
        # pass
        def __init__( self, cmd:Union[AgentCmd,str], msg:str=None):
            self.cmd = cmd
            self._msg = msg
            self.cmd_name = cmd if isinstance(cmd,str) else cmd.name
        @property
        def msg(self):
            msg = "EXCEPTION on command "+self.cmd_name
            return msg if not self._msg else msg+': '+self._msg
        # Default message if print exception
        def __str__(self):
            return self.msg
            '''
            msg = "EXCEPTION on command "+self.cmd_name
            return msg if not self.msg else msg+': '+self.msg
            '''
        '''
        def __str__(self):
            return f"The Agent command '{self.cmd.name}' is unknown to the agent"
            #return f"({type(self).__name__}): Device Generic command has no implementation in the controller"
        '''

    # --- CMD PENDING (non running) EXCEPTIONS ---

    # @Override
    class CmdExceptionUnknown(CmdException):
        ''' Raised when a PENDING (non running) Agent (specific) cmd is NOT known by the agent '''
        # @Override
        def __init__( self, cmd, msg:str=None):
            super().__init__(cmd, msg if msg else "Unknown command")
        #def __str__(self): return self.msg if self.msg else f"The Agent command '{self.cmd_name}' is unknown to the agent"

    # @Override
    class CmdExceptionUnimplemented(CmdException):
        ''' Raised when a PENDING (non running) Agent Specific cmd is known by the agent but not implemented '''
        # @Override
        def __init__( self, cmd, msg:str=None):
            super().__init__(cmd, msg if msg else "Command is known by the agent but not implemented")
        #def __str__(self): return f"The Agent command '{self.cmd_name}' is known by the agent but not implemented"

    # @Override
    class CmdExceptionBadArgs(CmdException):
        ''' Raised when a PENDING (non running) Agent cmd has bad, missing, or too many argument(s) '''
        # @Override
        def __init__( self, cmd, msg:str=None):
            super().__init__(cmd, msg if msg else "Command has bad, missing, or too many argument(s)")
        #def __str__(self): return f"The Agent command '{self.cmd_name}' has bad, missing, or too many argument(s)"


    # --- CMD RUNNING EXCEPTIONS ---

    # @Override
    class CmdExceptionExecError(CmdException):
        ''' Raised when a RUNNING Agent cmd has had a running error  '''
        # @Override
        def __init__( self, cmd, msg:str=None):
            super().__init__(cmd, msg if msg else "Error during Execution")
        #def __str__(self): return f"The running Agent command '{self.cmd_name}' has had an error (during execution)"

    # @Override
    class CmdExceptionExecTimeout(CmdException):
        ''' Raised when a RUNNING Agent cmd is timeout  '''
        # @Override
        def __init__( self, cmd, msg:str=None):
            super().__init__(cmd, msg if msg else "Execution is TIMEOUT")
        #def __str__(self): return f"The running Agent command '{self.cmd_name}' is timeout"

    # @Override
    class CmdExceptionExecKilled(CmdException):
        ''' Raised when a RUNNING Agent cmd has been aborted (by another agent)  '''
        # @Override
        def __init__( self, cmd, msg:str=None):
            super().__init__(cmd, msg if msg else "Command was KILLED during Execution (by another agent")
        #def __str__(self): return f"The running Agent command '{self.cmd_name}' has been killed (by another agent)"



5ce2836f   Alexis Koralewski   update models (ad...
552
553
    # -------------- Command CONSTANTS --------------

1a6fd283   Etienne Pallier   ajout gestion val...
554
    # Command status codes
5ce2836f   Alexis Koralewski   update models (ad...
555
    CMD_STATUS_CODES = Choices(
cbbd0c65   Etienne Pallier   Updated models.Ag...
556
        
1a6fd283   Etienne Pallier   ajout gestion val...
557
558
559
        # Cmd is pending, waiting for execution
        "CMD_PENDING",  

cbbd0c65   Etienne Pallier   Updated models.Ag...
560
561
562
563
564
565
566
567
568
569

        ### 1 - ERRORS BEFORE EVEN BEING RUN ###

        # Cmd is invalid (unknown or bad args)
        "CMD_INVALID",

        # Cmd is not yet implemented (by recipient agent)
        "CMD_UNIMPLEMENTED",

        # Cmd was skipped (not run, because the agent is IDLE (or in a mode which does not allow execution of this command)
1ba49504   Alexis Koralewski   fixing CSS and JS...
570
        "CMD_SKIPPED",
1a6fd283   Etienne Pallier   ajout gestion val...
571
572
573

        # Cmd is out of date (expired)
        # because it has been pending for too long
cbbd0c65   Etienne Pallier   Updated models.Ag...
574
575
576
        #"CMD_OUTOFDATE",
        "CMD_EXPIRED",

1a6fd283   Etienne Pallier   ajout gestion val...
577

cbbd0c65   Etienne Pallier   Updated models.Ag...
578
579
580
581
582
583
584
585
        ### 2 - RUNNING ###
        # Cmd is running (after having been "read")
        "CMD_RUNNING",  


        ### 3 - ERRORS WHILE RUNNING ###

        # - Cmd was run and finished ok 
1a6fd283   Etienne Pallier   ajout gestion val...
586
587
        # ( simulé par un sleep(3) dans AgentX.core_process() )
        "CMD_EXECUTED",
cbbd0c65   Etienne Pallier   Updated models.Ag...
588
589
590
591
592
593
594
595
596
597
598

        # - Cmd was running, but then an error occured
        "CMD_EXEC_ERROR",  

        # - Cmd was running, but took too much time and timeout was reached
        "CMD_EXEC_TIMEOUT",  

        # - Cmd was aborted, killed by another agent
        #"CMD_KILLED",
        "CMD_EXEC_KILLED",

5ce2836f   Alexis Koralewski   update models (ad...
599
    )
f3a4f48f   Etienne Pallier   Agent : nombreux ...
600

0685952d   Etienne Pallier   Implementation pr...
601
602
603
    # Command default validity duration (from sending time) BEFORE execution, before being perempted (in sec)
    # => Each command validity can be set by SENDER when sending command, it will then be managed by RECIPIENT
    # => From the time a command was sent (cmd.s_deposit_time), it is still valid during DEFAULT_VALIDITY_DURATION sec.
1a6fd283   Etienne Pallier   ajout gestion val...
604
605
606
607
608
609
    # => After that, it is considered as "expired" (obsolete) and must be marked as "CMD_OUTOFDATE" and not be executed anymore (and can be purged)
    # => Thus, a command is expired FROM time = s_deposit_time + VALIDITY_DURATION
    # (except if it is RUNNING, i.e. in state CMD_RUNNING)
    DEFAULT_VALIDITY_DURATION = 1 * 3600 # s

    # Command default execution timeout (in sec)
0685952d   Etienne Pallier   Implementation pr...
610
    # => Each command timeout is set by RECIPIENT (in AGENT_SPECIFIC_COMMANDS), and it will be managed by RECIPIENT
1a6fd283   Etienne Pallier   ajout gestion val...
611
612
613
614
615
616
617
618
619
620
621
622
623
    # => Execution of a command MUST NOT last more than EXEC_TIMEOUT seconds (from execution start time cmd.r_start_time)
    # => Otherwise the (recipient) agent executing the command is responsible to abort it and mark it as "CMD_KILLED"
    DEFAULT_EXEC_TIMEOUT = 60 # s

    # -------------- Command FIELDS --------------

    #sender = models.CharField(max_length=50, blank=True, null=True, unique=True)
    # Sender and Recipient agents
    sender = models.CharField(max_length=50, help_text='sender agent name', null=False)
    recipient = models.CharField(max_length=50, help_text='recipient agent name', null=False)
    ##name = models.CharField(max_length=400, help_text='command name', null=False)
    full_name = models.CharField(max_length=400, help_text='command full name (with type and args)', null=False)
    
eb6649f7   Etienne Pallier   bugfix DEFAULT_VA...
624
    validity_duration = models.PositiveIntegerField('(in sec)', default=DEFAULT_VALIDITY_DURATION)
1a6fd283   Etienne Pallier   ajout gestion val...
625
626
627
628
629
    exec_timeout = models.PositiveIntegerField('(in sec)', default=DEFAULT_EXEC_TIMEOUT)
    
    #state = models.CharField(choices = CMD_STATUS_CODES, default=CMD_STATUS_CODES.CMD_PENDING, max_length=20)
    state = models.CharField(choices=CMD_STATUS_CODES, default=CMD_STATUS_CODES.CMD_PENDING, max_length=20)
    #state = models.IntegerField(choices=CMD_STATUS_CODES, default=RSCODE_PENDING)
cbbd0c65   Etienne Pallier   Updated models.Ag...
630
    
1a6fd283   Etienne Pallier   ajout gestion val...
631
    # TODO: maybe à mettre au format json (key:value)
088d73f1   Etienne Pallier   remove deprecated...
632
633
    ##result = models.CharField(max_length=1000, blank=True)
    result = models.TextField(blank=True, null=False)
1a6fd283   Etienne Pallier   ajout gestion val...
634
635
636
637
638
639
640

    # - on creation: (AUTO) Automatically set at table line creation (line created by the sender)
    s_deposit_time = models.DateTimeField(blank=True, null=True, auto_now_add=True)
    # - on reading:
    r_read_time = models.DateTimeField(null=True)
    # - on launching:
    r_start_time = models.DateTimeField(null=True)
cbbd0c65   Etienne Pallier   Updated models.Ag...
641
642
643
    # - on end (after execution started or not)
    #end_time = models.DateTimeField(null=True)
    r_end_time = models.DateTimeField(null=True)
1a6fd283   Etienne Pallier   ajout gestion val...
644
645
646
647
648
649
650
651
652
653
654
655
656
657

    # Other agent (than sender or recipient) that set this command to KILLED or EXPIRED
    killer_agent_name = models.CharField(max_length=50, help_text='sender agent name', null=True)

    # Intern field, not saved in DB
    _device_command = None

    class Meta:
        managed = True
        db_table = 'command'
        #verbose_name = "agent survey"
        #verbose_name_plural = "agents survey"

    _AGENT_GENERAL_COMMANDS = [
7b4ee4fe   Etienne Pallier   cleanup, mark som...
658
        
573eeae6   Etienne Pallier   Agent ne depend p...
659
        # DO commands
f3a4f48f   Etienne Pallier   Agent : nombreux ...
660
661
        # -----------
        
573eeae6   Etienne Pallier   Agent ne depend p...
662
        # - Evaluate the expression given (ex: do_eval 4+3)
1ba49504   Alexis Koralewski   fixing CSS and JS...
663
        "do_eval",
0685952d   Etienne Pallier   Implementation pr...
664
                
573eeae6   Etienne Pallier   Agent ne depend p...
665
        # GET commands
f3a4f48f   Etienne Pallier   Agent : nombreux ...
666
        # ------------
7b4ee4fe   Etienne Pallier   cleanup, mark som...
667

d02249e6   Etienne Pallier   Added CMD_EXEC_ER...
668
669
        # - Get agent current STATUS or STEP (IN_MAIN_LOOP, ...)
        "get_status",
088d73f1   Etienne Pallier   remove deprecated...
670
671
        
        # - Get mode + status + iteration num
573eeae6   Etienne Pallier   Agent ne depend p...
672
        "get_state",
f3a4f48f   Etienne Pallier   Agent : nombreux ...
673
674
        
        # - Get agent current MODE (idle, routine, attentive)
f3a4f48f   Etienne Pallier   Agent : nombreux ...
675
676
        "get_mode",
        
573eeae6   Etienne Pallier   Agent ne depend p...
677
        # SET commands
f3a4f48f   Etienne Pallier   Agent : nombreux ...
678
        # -----------
4d01f948   Etienne Pallier   Agent test bugfix...
679
680
681

        # - Set agent current STATE (IN_MAIN_LOOP, ...) => forbidden
        #"set_state",
f3a4f48f   Etienne Pallier   Agent : nombreux ...
682
683
        
        # - Set agent current MODE (idle, routine, attentive)
340ca843   Etienne Pallier   fixed get_specifi...
684
        ##"set_current_mode", # + value to set
f3a4f48f   Etienne Pallier   Agent : nombreux ...
685
686
        "set_mode", # + value to set

1efe537f   Etienne Pallier   ajout des command...
687
688
        
        # -----------
f3a4f48f   Etienne Pallier   Agent : nombreux ...
689
690
691
        # ### (PRIORITY) DO Commands => executed in priority (even if other pending commands exist) ###
        # -----------
        
0685952d   Etienne Pallier   Implementation pr...
692
693
694
695
696
697
698
        # - Finish your current command and then make a normal clean stop
        # ARGS (optional) :
        #   - "asap" (default) (wait for agent to finish its current processing, then exit)
        #   - "now" (abort agent current processing + exit)
        #   - "noprio" (not priority) (priority by default)
        "do_stop",
        # TODO: a virer => do_stop asap
7b4ee4fe   Etienne Pallier   cleanup, mark som...
699
        # @deprecated
088d73f1   Etienne Pallier   remove deprecated...
700
        ##"do_exit",
0685952d   Etienne Pallier   Implementation pr...
701
        # TODO: a virer => do_stop now
7b4ee4fe   Etienne Pallier   cleanup, mark som...
702
        # @deprecated
088d73f1   Etienne Pallier   remove deprecated...
703
        ##"do_abort",
0685952d   Etienne Pallier   Implementation pr...
704

46dd2085   Etienne Pallier   agent cleanup
705
        #FIXME: à implémenter
0685952d   Etienne Pallier   Implementation pr...
706
707
708
709
710
711
712
713
        # - 
        # ARGS :
        #   - "stop" : Temporaly stop execution of new commands (let them accumulate)
        #   - "resume" : Resume execution of commands (accumulated since "do_exec_commands stop")
        #   - "noprio" : not priority (by default => priority)        
        "do_exec_commands",

        # - Stop currently running command or/and routine
1efe537f   Etienne Pallier   ajout des command...
714
715
716
        # ARGS :
        #   - "cmd" : stop currently running specific command
        #   - "routine" : stop currently running routine process
39fd2bca   Etienne Pallier   Agent v2 en cours...
717
        #   - "both" (default) : stop currently running current cmd and routine process
1efe537f   Etienne Pallier   ajout des command...
718
        "do_stop_current", # + arg "cmd" or "routine"
0685952d   Etienne Pallier   Implementation pr...
719
        # TODO: a virer => do_stop_current now
340ca843   Etienne Pallier   fixed get_specifi...
720
        # @deprecated
088d73f1   Etienne Pallier   remove deprecated...
721
        ##"do_abort_current_command",
1efe537f   Etienne Pallier   ajout des command...
722
        
da405f5b   Etienne Pallier   get_all_cmds remp...
723
724
        # - Delete all your pending commands
        "do_flush_pending_commands", 
088d73f1   Etienne Pallier   remove deprecated...
725
726
        # @deprecated
        ##"do_flush_commands", 
1efe537f   Etienne Pallier   ajout des command...
727
        
1efe537f   Etienne Pallier   ajout des command...
728
729
730
731
        # - Restart your global loop (starting with init())
        # ARGS (optional) :
        #   - "asap" (default) (wait for agent to finish its current processing, then restart loop)
        #   - "now" (abort agent current processing + restart loop)
0685952d   Etienne Pallier   Implementation pr...
732
        #   - "noprio" (not priority, priority by default)
340ca843   Etienne Pallier   fixed get_specifi...
733
        "do_restart", # + arg "asap" (default) or "now"
f3a4f48f   Etienne Pallier   Agent : nombreux ...
734

da405f5b   Etienne Pallier   get_all_cmds remp...
735
        "get_all_cmds",
088d73f1   Etienne Pallier   remove deprecated...
736
        # @deprecated
3ec16e74   Alexis Koralewski   Add flexible form...
737
        "get_specific_cmds",
c655f27d   Alexis Koralewski   fixing agent_deta...
738

5ce2836f   Alexis Koralewski   update models (ad...
739
    ]
f3a4f48f   Etienne Pallier   Agent : nombreux ...
740
741
742
743

    # Priority commands, executed as soon as in the received commands list (BEFORE any other pending command)
    # NB : must be a subset of _AGENT_GENERAL_COMMANDS
    _AGENT_GENERAL_PRIORITY_COMMANDS = [
39fd2bca   Etienne Pallier   Agent v2 en cours...
744
        
46dd2085   Etienne Pallier   agent cleanup
745
        # 1 - NO STOP commands => will not stop the Agent or any running cmd
088d73f1   Etienne Pallier   remove deprecated...
746
747
        "get_all_cmds",
        # @deprecated
d02249e6   Etienne Pallier   Added CMD_EXEC_ER...
748
        "get_specific_cmds",
da405f5b   Etienne Pallier   get_all_cmds remp...
749
        "do_flush_pending_commands", 
0685952d   Etienne Pallier   Implementation pr...
750
        "do_exec_commands"
340ca843   Etienne Pallier   fixed get_specifi...
751
        
46dd2085   Etienne Pallier   agent cleanup
752
        # 2 - PARTIAL STOP command => will just stop current running cmd (and routine)
0685952d   Etienne Pallier   Implementation pr...
753
        "do_stop_current",
39fd2bca   Etienne Pallier   Agent v2 en cours...
754
        
46dd2085   Etienne Pallier   agent cleanup
755
756
        # 3 - (TOTAL) STOP commands => will stop the Agent (waiting or not for it to finish what it is doing)
        #"do_exit",
0685952d   Etienne Pallier   Implementation pr...
757
        "do_stop",
39fd2bca   Etienne Pallier   Agent v2 en cours...
758
759
760
        "do_restart",
        # @deprecated
        ###"do_restart_loop",
f3a4f48f   Etienne Pallier   Agent : nombreux ...
761
762
    ]

5ce2836f   Alexis Koralewski   update models (ad...
763
764
    # -------------- Command CLASS (static) METHODS --------------

795c826a   Etienne Pallier   Ajout de la gesti...
765
766
767
768
769
770
771
    @classmethod
    def is_generic(self, cmd_name:str) ->bool :
        '''
        Generic if starts with get_, set_, or do_
        '''
        return cmd_name.startswith( ('get_', 'set_', 'do_') )

5ce2836f   Alexis Koralewski   update models (ad...
772
    # Avoid to override the Model __init__ method
7735aaa7   Etienne Pallier   updated Agent spe...
773
    # See https://docs.djangoproject.com/en/stable/ref/models/instances/#creating-objects
5ce2836f   Alexis Koralewski   update models (ad...
774
    @classmethod
7735aaa7   Etienne Pallier   updated Agent spe...
775
    def create(cls, agent_from:str, agent_to:str, cmd_name:str, cmd_args:str=None, cmd_validity:int=None) -> AgentCmd :
1a6fd283   Etienne Pallier   ajout gestion val...
776
777
778
        #print(agent_to)
        if '.' in agent_to:
            agent_to, component_name = agent_to.split('.')
5ce2836f   Alexis Koralewski   update models (ad...
779
            cmd_name = component_name+'.'+cmd_name
d02249e6   Etienne Pallier   Added CMD_EXEC_ER...
780
781
        # remove all excessive spaces
        print(cmd_args)
1ba49504   Alexis Koralewski   fixing CSS and JS...
782
        if cmd_args:
d02249e6   Etienne Pallier   Added CMD_EXEC_ER...
783
            cmd_args = re.sub(r"\s+", " ", cmd_args).strip()
1a6fd283   Etienne Pallier   ajout gestion val...
784
            cmd_name += ' ' + cmd_args
1ba49504   Alexis Koralewski   fixing CSS and JS...
785
        # cls._device_command=DeviceCommand(cmd_name)
1a6fd283   Etienne Pallier   ajout gestion val...
786
        if cmd_validity is None: cmd_validity = cls.DEFAULT_VALIDITY_DURATION
0685952d   Etienne Pallier   Implementation pr...
787
        #if cmd_timeout is None: cmd_timeout = cls.DEFAULT_EXEC_TIMEOUT
5ce2836f   Alexis Koralewski   update models (ad...
788
        return cls(
1a6fd283   Etienne Pallier   ajout gestion val...
789
790
            sender=agent_from,
            recipient=agent_to,
5ce2836f   Alexis Koralewski   update models (ad...
791
            full_name=cmd_name,
1a6fd283   Etienne Pallier   ajout gestion val...
792
            validity_duration=cmd_validity,
0685952d   Etienne Pallier   Implementation pr...
793
            #exec_timeout=cmd_timeout,
5ce2836f   Alexis Koralewski   update models (ad...
794
795
796
797
798
799
800
801
802
        )

    """
    @classmethod
    def send(cls, cmd:Command):
        cls.objects.create(sender=cmd.name, recipient=cmd.recipient, name=cmd.name)
    """

    @classmethod
7735aaa7   Etienne Pallier   updated Agent spe...
803
804
    def send_cmd_from_to(cls, agent_from, agent_to, cmd_name, cmd_args=None, cmd_validity:int=None)->AgentCmd:
        """ Create and send a command, then return it """
1ba49504   Alexis Koralewski   fixing CSS and JS...
805
        # def send(cls, from_agent, to_agent, cmd_name, cmd_args=None):
5ce2836f   Alexis Koralewski   update models (ad...
806
807
808
809
810
811
812
813
        """
        ex: send("AgentA",“AgentB”,"EVAL”,“3+4”)
        """
        '''
        if cmd_args: cmd_name += ' '+cmd_args
        #Command.objects.create(sender=self.name, recipient=r_agent, name=cmd_name)
        cmd = cls(sender=from_agent, recipient=to_agent, name=cmd_name)
        '''
0685952d   Etienne Pallier   Implementation pr...
814
        cmd = cls.create(agent_from, agent_to, cmd_name, cmd_args, cmd_validity)
5ce2836f   Alexis Koralewski   update models (ad...
815
        cmd.send()
1ba49504   Alexis Koralewski   fixing CSS and JS...
816
817
        # cmd.set_as_pending()
        # cmd.save()
5ce2836f   Alexis Koralewski   update models (ad...
818
819
        return cmd

5ce2836f   Alexis Koralewski   update models (ad...
820
    @classmethod
1a6fd283   Etienne Pallier   ajout gestion val...
821
    def max_deposit_date_for_peremption(cls):
998f175c   Alexis Koralewski   fix datetime.utcnow
822
        return datetime.now(tz=timezone.utc) - timedelta(seconds=cls.DEFAULT_VALIDITY_DURATION)
8decb416   Etienne Pallier   UTC par defaut da...
823
        #return datetime.utcnow().astimezone() - timedelta(seconds=cls.DEFAULT_VALIDITY_DURATION)
eb6649f7   Etienne Pallier   bugfix DEFAULT_VA...
824
        #return datetime.utcnow().astimezone() - timedelta(hours=cls.DEFAULT_VALIDITY_DURATION)
5ce2836f   Alexis Koralewski   update models (ad...
825
826

    @classmethod
30eeadc1   Etienne Pallier   cleanup
827
828
829
830
    #def delete_commands_with_running_status_for_agent(cls, agent_name):
    def kill_false_running_cmd_if_exists_for_agent(cls, agent_name):
        #FIXME: check that this command is not REALLY running (ex: cmd sent to device), and if so, kill it (or let it finish ?)
        printd("Kill (false) 'running' command if exists:")
5ce2836f   Alexis Koralewski   update models (ad...
831
832
        running_commands = cls.objects.filter(
            # only commands for agent agent_name
1ba49504   Alexis Koralewski   fixing CSS and JS...
833
            recipient=agent_name,
5ce2836f   Alexis Koralewski   update models (ad...
834
            # only running commands
1ba49504   Alexis Koralewski   fixing CSS and JS...
835
            state=cls.CMD_STATUS_CODES.CMD_RUNNING,
5ce2836f   Alexis Koralewski   update models (ad...
836
            # only not expired commands
1a6fd283   Etienne Pallier   ajout gestion val...
837
            #s_deposit_time__gte = cls.max_deposit_date_for_peremption(),
5ce2836f   Alexis Koralewski   update models (ad...
838
839
        )
        if running_commands:
30eeadc1   Etienne Pallier   cleanup
840
841
842
843
            #AgentCmd.show_commands(running_commands)
            cls.show_commands(running_commands)
            #running_commands.delete()
            for cmd in running_commands:
a7b5f02c   Etienne Pallier   simplified agent ...
844
                cmd.set_as_pending()
30eeadc1   Etienne Pallier   cleanup
845
                cmd.set_as_skipped("Skip this cmd because false running cmd (at agent start)")
1ba49504   Alexis Koralewski   fixing CSS and JS...
846
847
        else:
            printd("<None>")
5ce2836f   Alexis Koralewski   update models (ad...
848
849
850
851
852
853
854
855
856
857
858

    @classmethod
    def delete_pending_commands_for_agent(cls, agent_name):
        """
        Delete all pending commands sent to agent_name,
        except very recent commands.
        This (exception) is to avoid a "data race" where for example agentB is executing a "flush" command 
        while agentA is sending command to agentB... :
        - agentB will then delete the command just sent by agentA
        - agentA will check regularly the status of its sent command, and this will crash as this command exists no more !!
        """
30eeadc1   Etienne Pallier   cleanup
859
        printd("Delete all pending command(s) if exists (except very recent ones, less than 2 sec ago):")
8decb416   Etienne Pallier   UTC par defaut da...
860
        #now_minus_2sec = datetime.utcnow().astimezone() - timedelta(seconds=2)
998f175c   Alexis Koralewski   fix datetime.utcnow
861
        now_minus_2sec = datetime.now(tz=timezone.utc) - timedelta(seconds=2)
5ce2836f   Alexis Koralewski   update models (ad...
862
863
864
        #print("now_minus_2sec", now_minus_2sec)
        pending_commands = cls.objects.filter(
            # only commands for agent agent_name
1ba49504   Alexis Koralewski   fixing CSS and JS...
865
            recipient=agent_name,
5ce2836f   Alexis Koralewski   update models (ad...
866
            # only running commands
1ba49504   Alexis Koralewski   fixing CSS and JS...
867
            state=cls.CMD_STATUS_CODES.CMD_PENDING,
5ce2836f   Alexis Koralewski   update models (ad...
868
            # except very recent commands : take only commands that are more than 2 sec old
1ba49504   Alexis Koralewski   fixing CSS and JS...
869
            s_deposit_time__lt=now_minus_2sec
5ce2836f   Alexis Koralewski   update models (ad...
870
871
872
873
        )
        if pending_commands:
            AgentCmd.show_commands(pending_commands)
            pending_commands.delete()
1ba49504   Alexis Koralewski   fixing CSS and JS...
874
875
        else:
            printd("<None>")
5ce2836f   Alexis Koralewski   update models (ad...
876
877

    @classmethod
486d24e2   Etienne Pallier   Bugfix list of re...
878
879
880
881
882
883
884
885
886
887
888
889
890
891
    def get_pending_commands_for_agent(cls, agent_name)->QuerySet:
        #print("peremption date", COMMAND_PEREMPTION_DATE_FROM_NOW)
        return cls.objects.filter(
            # only pending commands
            state=cls.CMD_STATUS_CODES.CMD_PENDING,
            # only commands for agent agent_name
            recipient=agent_name,
            # recipient__startswith=agent_name,
            # Q(recipient.split('.')[0] = agent_name),
            # only not expired commands
            #s_deposit_time__gte = cls.max_deposit_date_for_peremption(),
        ).order_by("s_deposit_time")

    @classmethod
bc750a56   Etienne Pallier   Allow commands to...
892
    def get_pending_and_running_commands_for_agent(cls, agent_name)->QuerySet:
5ce2836f   Alexis Koralewski   update models (ad...
893
894
        #print("peremption date", COMMAND_PEREMPTION_DATE_FROM_NOW)
        return cls.objects.filter(
1a6fd283   Etienne Pallier   ajout gestion val...
895
896
            # only pending or running commands
            Q(state=cls.CMD_STATUS_CODES.CMD_PENDING) | Q(state=cls.CMD_STATUS_CODES.CMD_RUNNING),
5ce2836f   Alexis Koralewski   update models (ad...
897
            # only commands for agent agent_name
1ba49504   Alexis Koralewski   fixing CSS and JS...
898
899
900
            recipient=agent_name,
            # recipient__startswith=agent_name,
            # Q(recipient.split('.')[0] = agent_name),
5ce2836f   Alexis Koralewski   update models (ad...
901
            # only not expired commands
1a6fd283   Etienne Pallier   ajout gestion val...
902
            #s_deposit_time__gte = cls.max_deposit_date_for_peremption(),
5ce2836f   Alexis Koralewski   update models (ad...
903
904
905
906
907
908
909
910
911
912
913
914
        ).order_by("s_deposit_time")

    @classmethod
    def get_commands_sent_to_agent(cls, agent_name):
        return cls.objects.filter(recipient=agent_name)

    @classmethod
    def get_commands_sent_by_agent(cls, agent_name):
        return cls.objects.filter(sender=agent_name)

    @classmethod
    def get_last_N_commands_sent_to_agent(cls, agent_name, N):
1ba49504   Alexis Koralewski   fixing CSS and JS...
915
916
        # filter(since=since)
        # return cls.objects.all()[:nb_cmds]
5ce2836f   Alexis Koralewski   update models (ad...
917
        #commands = cls.objects.filter(recipient = agent_name).order_by('-id')[:N]
1ba49504   Alexis Koralewski   fixing CSS and JS...
918
919
        commands = cls.get_commands_sent_to_agent(
            agent_name).order_by('-id')[:N]
5ce2836f   Alexis Koralewski   update models (ad...
920
921
922
923
        return list(reversed(commands))

    @classmethod
    def get_last_N_commands_sent_by_agent(cls, agent_name, N):
1ba49504   Alexis Koralewski   fixing CSS and JS...
924
925
        # filter(since=since)
        # return cls.objects.all()[:nb_cmds]
5ce2836f   Alexis Koralewski   update models (ad...
926
        #commands = cls.objects.filter(recipient = agent_name).order_by('-id')[:N]
1ba49504   Alexis Koralewski   fixing CSS and JS...
927
928
        commands = cls.get_commands_sent_by_agent(
            agent_name).order_by('-id')[:N]
5ce2836f   Alexis Koralewski   update models (ad...
929
930
931
932
933
        return list(reversed(commands))

    @classmethod
    def purge_old_commands_sent_to_agent(cls, agent_name):
        """
1a6fd283   Etienne Pallier   ajout gestion val...
934
        Delete commands (which agent_name is recipient of) older than VALIDITY_DURATION (like 1h)
5ce2836f   Alexis Koralewski   update models (ad...
935
936
937
        ATTENTION !!! EXCEPT the RUNNING command !!!
        NB: datetime.utcnow() is equivalent to datetime.now(timezone.utc)
        """
1ba49504   Alexis Koralewski   fixing CSS and JS...
938
        printd(
eb6649f7   Etienne Pallier   bugfix DEFAULT_VA...
939
            f"(Looking for commands sent to me that are not executing and perempted - i.e. older than {cls.DEFAULT_VALIDITY_DURATION/60} minute(s))")
5ce2836f   Alexis Koralewski   update models (ad...
940
941
942
943
        #COMMAND_PEREMPTION_DATE_FROM_NOW = datetime.utcnow() - timedelta(hours = cls.COMMANDS_PEREMPTION_HOURS)
        #print("peremption date", COMMAND_PEREMPTION_DATE_FROM_NOW)
        old_commands = cls.objects.filter(
            # only commands for agent agent_name
1ba49504   Alexis Koralewski   fixing CSS and JS...
944
            recipient=agent_name,
5ce2836f   Alexis Koralewski   update models (ad...
945
            # only expired commands
1a6fd283   Etienne Pallier   ajout gestion val...
946
            s_deposit_time__lt=cls.max_deposit_date_for_peremption(),
5ce2836f   Alexis Koralewski   update models (ad...
947
        ).exclude(
1ba49504   Alexis Koralewski   fixing CSS and JS...
948
            state=cls.CMD_STATUS_CODES.CMD_RUNNING
5ce2836f   Alexis Koralewski   update models (ad...
949
950
951
952
953
954
955
956
957
958
        )
        if old_commands.exists():
            printd("Found old commands to delete:")
            #for cmd in old_commands: print(cmd)
            cls.show_commands(old_commands)
            old_commands.delete()
        else:
            printd("<None>")

    @classmethod
1ba49504   Alexis Koralewski   fixing CSS and JS...
959
960
961
    # def show_commands(cls, commands:models.query):
    def show_commands(cls, commands: list, do_it: bool = False):
        # def show_commands(cls, commands:List[Commmand]):
5ce2836f   Alexis Koralewski   update models (ad...
962
963
        #if not commands.exists(): print("<No command>")
        commands = list(commands)
1ba49504   Alexis Koralewski   fixing CSS and JS...
964
        if len(commands) == 0:
f3a4f48f   Etienne Pallier   Agent : nombreux ...
965
966
967
            print("<None>")
            #if do_it: print("<None>")
            #else: printd("<None>")
1ba49504   Alexis Koralewski   fixing CSS and JS...
968
        for cmd in commands:
f3a4f48f   Etienne Pallier   Agent : nombreux ...
969
970
971
            print("-", cmd.name, cmd)
            #if do_it: print("-", cmd.name, cmd)
            #else: printd("-", cmd.name, cmd)
5ce2836f   Alexis Koralewski   update models (ad...
972
973
974
975

    # -------------- AgentCmd INSTANCE METHODS --------------

    def __str__(self):
1ba49504   Alexis Koralewski   fixing CSS and JS...
976
        # return (f"Commmand '{self.name}' ({self.state}) sent by agent {self.sender} to agent {self.recipient} at {self.s_deposit_time}")
5ce2836f   Alexis Koralewski   update models (ad...
977
        cmd_sent_time = f" at {self.s_deposit_time}" if self.s_deposit_time else ''
607a7131   Etienne Pallier   validity and time...
978
        return (f"Commmand '{self.full_name}' ({self.state}) sent to agent {self.recipient}{cmd_sent_time} (validity={self.validity_duration}s,timeout={self.exec_timeout}s) [by agent {self.sender}]")
5ce2836f   Alexis Koralewski   update models (ad...
979
980

    @property
573eeae6   Etienne Pallier   Agent ne depend p...
981
    def device_command(self) -> DeviceCmd :
5ce2836f   Alexis Koralewski   update models (ad...
982
983
984
985
986
987
988
        if not self._device_command:
            self._device_command = DeviceCmd(self.full_name)
            #dc = self._device_command
            #print("...DEVICE CMD:", dc.full_name, dc.name, dc.devtype, dc.args)
        return self._device_command

    @property
1f638223   Etienne Pallier   Ameliorations Age...
989
990
991
    #def name_and_args(self) -> Tuple[str, str] :
    def name_and_args(self) -> Tuple[str, List] :
        ###return self.device_command.name_and_args
5ce2836f   Alexis Koralewski   update models (ad...
992
993
994
995
996
997
        '''
        cmd_name_and_args = self.full_name
        if '.' in cmd_name_and_args:
            cmd_name_and_args = cmd_name_and_args.split('.')[1]
        return cmd_name_and_args
        '''
573eeae6   Etienne Pallier   Agent ne depend p...
998
999
        ''' Return command name and args if exist '''
        # By default, no args
2912abf2   Etienne Pallier   Agent specific co...
1000
1001
        #cmd_args = None
        cmd_args = []
573eeae6   Etienne Pallier   Agent ne depend p...
1002
        cmd_name = self.full_name
5ce2836f   Alexis Koralewski   update models (ad...
1003
1004
        if ' ' in cmd_name:
            cmd_name, *cmd_args = cmd_name.split(' ')
573eeae6   Etienne Pallier   Agent ne depend p...
1005
1006
1007
        return cmd_name, cmd_args


ba30549a   Etienne Pallier   updated methods r...
1008
1009
    #def get_full_name_parts(self) -> list :
    def get_full_name_parts(self) -> Tuple[str, str, str] :
573eeae6   Etienne Pallier   Agent ne depend p...
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
        ''' Return command device type, name, and args from any command type (agent or device level) '''

        # No device type by default for an Agent command
        # cmd_type ?
        dev_type = None
        
        # By default, no args
        cmd_args = None

        cmd_name = self.full_name
        
        # Device command with device component type (dev_type)
        if '.' in cmd_name: 
            return self.device_command.get_full_name_parts()

        # Simple command with args (no dev_type)
        if ' ' in cmd_name:
1f638223   Etienne Pallier   Ameliorations Age...
1027
            cmd_name, *cmd_args = self.name_and_args
573eeae6   Etienne Pallier   Agent ne depend p...
1028
1029
1030

        return dev_type, cmd_name, cmd_args

5ce2836f   Alexis Koralewski   update models (ad...
1031
1032
1033

    @property
    def name(self):
1f638223   Etienne Pallier   Ameliorations Age...
1034
1035
1036
        ###return self.device_command.name
        #_,cmd_name,_ = self.get_full_name_parts()
        cmd_name,_ = self.name_and_args
5ce2836f   Alexis Koralewski   update models (ad...
1037
        return cmd_name
5ce2836f   Alexis Koralewski   update models (ad...
1038
1039
1040

    @property
    def args(self):
1f638223   Etienne Pallier   Ameliorations Age...
1041
1042
1043
        ###return self.device_command.args
        #_,_,cmd_args = self.get_full_name_parts()
        _,cmd_args = self.name_and_args
5ce2836f   Alexis Koralewski   update models (ad...
1044
        return cmd_args
5ce2836f   Alexis Koralewski   update models (ad...
1045
1046
1047
1048
1049

    @property
    def device_type(self): return self.device_command.devtype

    def send(self):
1ba49504   Alexis Koralewski   fixing CSS and JS...
1050
        # self.save()
5ce2836f   Alexis Koralewski   update models (ad...
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
        self.set_as_pending()

    '''
    def tokenize(self):
        cmd_name, *cmd_args = self.full_name.split(' ')
        return cmd_name, cmd_args
    '''

    # --- BOOLEAN (test) functions ---

    def is_agent_general_cmd(self):
        """
        Is this a general command ?
        It is the case if command is of style "do_set:state:idle" or "do_restart" or "do_flush"...
        """
        ##name = self.name
        ##if " " in name: name,args = name.split()
        ##name = self.name.split(' ')[0]
        ##cmd_name, _ = self.tokenize()
1ba49504   Alexis Koralewski   fixing CSS and JS...
1070
        # return cmd_name in self.GENERIC_COMMANDS
5ce2836f   Alexis Koralewski   update models (ad...
1071
1072
        #print("**********************CMD NAME is", self.name, "in ???", self._AGENT_GENERAL_COMMANDS)
        return self.name in self._AGENT_GENERAL_COMMANDS
1ba49504   Alexis Koralewski   fixing CSS and JS...
1073
        # "CMD_OUTOFDATE" # cde périmée
5ce2836f   Alexis Koralewski   update models (ad...
1074

f3a4f48f   Etienne Pallier   Agent : nombreux ...
1075
1076
1077
    def is_agent_general_priority_cmd(self):
        return self.name in self._AGENT_GENERAL_PRIORITY_COMMANDS

5ce2836f   Alexis Koralewski   update models (ad...
1078
1079
1080
    def is_read(self):
        return self.r_read_time is not None

ef335590   Etienne Pallier   Agent v2 asynchro...
1081
1082
1083
1084
1085
1086
    #
    # CMD status management
    #

    def get_status(self):
        return self.state
d6441fe9   Etienne Pallier   new methods is_xx...
1087
1088

    # 1 - pending
5ce2836f   Alexis Koralewski   update models (ad...
1089
1090
1091
    def is_pending(self):
        return self.state == self.CMD_STATUS_CODES.CMD_PENDING

d6441fe9   Etienne Pallier   new methods is_xx...
1092
1093
1094
1095
    # 2 - ERROR cases (from PENDING)
    def is_invalid(self): return self.state == self.CMD_STATUS_CODES.CMD_INVALID
    def is_unimplemented(self): return self.state == self.CMD_STATUS_CODES.CMD_UNIMPLEMENTED
    def is_skipped(self): return self.state == self.CMD_STATUS_CODES.CMD_SKIPPED
5ce2836f   Alexis Koralewski   update models (ad...
1096
    def is_expired(self):
cbbd0c65   Etienne Pallier   Updated models.Ag...
1097
1098
1099
        if self.state == self.CMD_STATUS_CODES.CMD_EXPIRED: return True
        # Must NOT be running
        if self.is_running(): return False
1ba49504   Alexis Koralewski   fixing CSS and JS...
1100
        # return (datetime.utcnow() - self.s_deposit_time) > timedelta(seconds = self.validity_duration)
8decb416   Etienne Pallier   UTC par defaut da...
1101
        #elapsed_time = (datetime.utcnow().astimezone() - self.s_deposit_time)
998f175c   Alexis Koralewski   fix datetime.utcnow
1102
        elapsed_time = ( datetime.now(tz=timezone.utc) - self.s_deposit_time )
5ce2836f   Alexis Koralewski   update models (ad...
1103
        printd("elapsed_time", elapsed_time)
1ba49504   Alexis Koralewski   fixing CSS and JS...
1104
        return elapsed_time > timedelta(seconds=self.validity_duration)
5ce2836f   Alexis Koralewski   update models (ad...
1105
1106
1107
1108
1109
1110
        """
        elapsed_time = cmd.r_read_time - cmd.s_deposit_time
        max_time = timedelta(seconds = cmd.validity_duration)
        print(f"Elapsed time is {elapsed_time}, (max is {max_time})")
        if elapsed_time > max_time:
        """
d6441fe9   Etienne Pallier   new methods is_xx...
1111
1112
1113
1114
1115
1116
    # finished with issue (from pending)
    def is_pending_issue(self): return self.is_invalid() or self.is_unimplemented() or self.is_skipped() or self.is_expired()

    # 3 - running
    def is_running(self):
        return self.state == self.CMD_STATUS_CODES.CMD_RUNNING
5ce2836f   Alexis Koralewski   update models (ad...
1117

d6441fe9   Etienne Pallier   new methods is_xx...
1118
1119
1120
1121
1122
1123
1124
1125
    # 4 - ERROR cases (from RUNNING)
    def is_exec_error(self): return self.state == self.CMD_STATUS_CODES.CMD_EXEC_ERROR
    def is_exec_killed(self): return self.state == self.CMD_STATUS_CODES.CMD_EXEC_KILLED
    # alias
    def is_killed(self): return self.is_exec_killed()
    # alias
    def is_timeout(self): return self.is_exec_timeout()
    def is_exec_timeout(self):
cbbd0c65   Etienne Pallier   Updated models.Ag...
1126
        if self.state == self.CMD_STATUS_CODES.CMD_EXEC_TIMEOUT: return True
1a6fd283   Etienne Pallier   ajout gestion val...
1127
1128
1129
        # Must be running
        if not self.is_running(): return False
        # return (datetime.utcnow() - self.s_deposit_time) > timedelta(seconds = self.validity_duration)
8decb416   Etienne Pallier   UTC par defaut da...
1130
        #elapsed_time = (datetime.utcnow().astimezone() - self.r_start_time)
998f175c   Alexis Koralewski   fix datetime.utcnow
1131
        elapsed_time = (datetime.now(tz=timezone.utc) - self.r_start_time)
1a6fd283   Etienne Pallier   ajout gestion val...
1132
1133
        printd("elapsed_time since exec", elapsed_time)
        return elapsed_time > timedelta(seconds=self.exec_timeout)
d6441fe9   Etienne Pallier   new methods is_xx...
1134
1135
1136
1137
1138
1139
1140
    # finished with any execution issue
    def is_exec_issue(self): return self.state.startswith("CMD_EXEC_")

    # 5 - Execution finished
    # Cmd is finished if not pending or running
    def is_finished(self):
        return not (self.is_pending() or self.is_running())
9d235d12   Etienne Pallier   simplify get_spec...
1141
    # Cmd is finished with error : finished but NOT executed (= ALL except : CMD_PENDING, CMD_RUNNING, or CMD_EXECUTED)
d6441fe9   Etienne Pallier   new methods is_xx...
1142
1143
1144
1145
1146
1147
    def is_finished_with_error(self):
        return self.is_finished() and not self.is_executed()
    # Cmd is finished without error (normal case)
    def is_executed(self):
        return self.state == self.CMD_STATUS_CODES.CMD_EXECUTED

1a6fd283   Etienne Pallier   ajout gestion val...
1148

9d235d12   Etienne Pallier   simplify get_spec...
1149

5ce2836f   Alexis Koralewski   update models (ad...
1150
1151
1152
1153
1154
1155
1156
1157
1158
    # --- GETTERS/SETTERS functions ---

    def get_result(self):
        return self.result

    def get_updated_result(self):
        self.refresh_from_db()
        return self.result

7138789e   Etienne Pallier   new Agent with 3 ...
1159
    def set_result(self, result: str, do_save:bool=True):
5ce2836f   Alexis Koralewski   update models (ad...
1160
        self.result = result
7138789e   Etienne Pallier   new Agent with 3 ...
1161
        if do_save: self.save()
5ce2836f   Alexis Koralewski   update models (ad...
1162

7138789e   Etienne Pallier   new Agent with 3 ...
1163
    def set_read_time(self, do_save:bool=True):
8decb416   Etienne Pallier   UTC par defaut da...
1164
        #self.r_read_time = datetime.utcnow().astimezone()
998f175c   Alexis Koralewski   fix datetime.utcnow
1165
        self.r_read_time = datetime.now(tz=timezone.utc)
5ce2836f   Alexis Koralewski   update models (ad...
1166
        # Optimization: update only 1 field
7138789e   Etienne Pallier   new Agent with 3 ...
1167
        if do_save: self.save(update_fields=["r_read_time"])
5ce2836f   Alexis Koralewski   update models (ad...
1168

7735aaa7   Etienne Pallier   updated Agent spe...
1169
1170
1171
1172
    #
    # Set cmd status
    #

927b033b   Etienne Pallier   update AgentBasic...
1173
    # - From None
7735aaa7   Etienne Pallier   updated Agent spe...
1174
1175
1176
    def set_as_pending(self):
        self.set_state_to(self.CMD_STATUS_CODES.CMD_PENDING)

927b033b   Etienne Pallier   update AgentBasic...
1177
    # - from PENDING
7735aaa7   Etienne Pallier   updated Agent spe...
1178
    def set_as_unimplemented(self, result:str=None):
927b033b   Etienne Pallier   update AgentBasic...
1179
1180
        #assert self.is_pending(), "An Unimplemented Command must have been PENDING"
        self.set_state_to(self.CMD_STATUS_CODES.CMD_UNIMPLEMENTED, result=result)
7735aaa7   Etienne Pallier   updated Agent spe...
1181
    def set_as_invalid(self, result:str=None):
927b033b   Etienne Pallier   update AgentBasic...
1182
1183
        #assert self.is_pending()
        self.set_state_to(self.CMD_STATUS_CODES.CMD_INVALID, result=result)
7735aaa7   Etienne Pallier   updated Agent spe...
1184
    def set_as_skipped(self, result:str=None):
927b033b   Etienne Pallier   update AgentBasic...
1185
        #assert self.is_pending()
7735aaa7   Etienne Pallier   updated Agent spe...
1186
        self.set_state_to(self.CMD_STATUS_CODES.CMD_SKIPPED, result=result)
7735aaa7   Etienne Pallier   updated Agent spe...
1187
    def set_as_expired(self):
927b033b   Etienne Pallier   update AgentBasic...
1188
        #assert self.is_pending()
9d235d12   Etienne Pallier   simplify get_spec...
1189
        #print(f"- Set this command as expired (older than its validity duration of {self.validity_duration}s): {self}")
7735aaa7   Etienne Pallier   updated Agent spe...
1190
        self.set_state_to(self.CMD_STATUS_CODES.CMD_EXPIRED)
7735aaa7   Etienne Pallier   updated Agent spe...
1191
    def set_as_running(self):
ef335590   Etienne Pallier   Agent v2 asynchro...
1192
1193
        #FIXMD: log.info() au lieu de print()
        print('-'*6 + " STARTING COMMAND EXEC")
927b033b   Etienne Pallier   update AgentBasic...
1194
        #assert self.is_pending()
7735aaa7   Etienne Pallier   updated Agent spe...
1195
1196
1197
1198
1199
1200
1201
        printd(f"- Set command {self.name} as running")
        self.set_state_to(self.CMD_STATUS_CODES.CMD_RUNNING)

    '''
    def set_as_executed(self):
        self.set_state_to(self.CMD_STATUS_CODES.CMD_EXECUTED)
    '''
927b033b   Etienne Pallier   update AgentBasic...
1202
    # - from RUNNING
7138789e   Etienne Pallier   new Agent with 3 ...
1203
    def set_as_processed(self, result:str=None):
927b033b   Etienne Pallier   update AgentBasic...
1204
       # assert self.is_running(), "a PROCESSED command must have been RUNNING"
5ce2836f   Alexis Koralewski   update models (ad...
1205
        printd(f"- Set command {self.name} as processed")
7138789e   Etienne Pallier   new Agent with 3 ...
1206
        self.set_state_to(self.CMD_STATUS_CODES.CMD_EXECUTED, result=result)
1ba49504   Alexis Koralewski   fixing CSS and JS...
1207
        # print(self)
5ce2836f   Alexis Koralewski   update models (ad...
1208
1209
1210
1211
1212
1213
1214
        """
        self.state = self.CMD_STATUS_CODES.CMD_EXECUTED
        self.r_processed_time = datetime.utcnow().astimezone()
        self.save()
        """
        # Optimization: update the related fields, but does not work, why ?
        ##self.save(update_fields=["state", "r_processed_time"])
cbbd0c65   Etienne Pallier   Updated models.Ag...
1215
    #def set_as_outofdate(self):
7735aaa7   Etienne Pallier   updated Agent spe...
1216
1217
1218
    def set_as_exec_error(self, result:str=None):
        assert self.is_running()
        self.set_state_to(self.CMD_STATUS_CODES.CMD_EXEC_ERROR, result=result)
7735aaa7   Etienne Pallier   updated Agent spe...
1219
1220
1221
    def set_as_exec_timeout(self, result:str=None):
        assert self.is_running()
        self.set_state_to(self.CMD_STATUS_CODES.CMD_EXEC_TIMEOUT, result=result)
7735aaa7   Etienne Pallier   updated Agent spe...
1222
1223
1224
    def set_as_exec_timeout(self, result:str=None):
        assert self.is_running()
        self.set_state_to(self.CMD_STATUS_CODES.CMD_EXEC_TIMEOUT, result=result)
927b033b   Etienne Pallier   update AgentBasic...
1225
1226
    def set_as_killed_by(self, author_agent_name:str, result:str=None):
        #assert self.is_running()
5ce2836f   Alexis Koralewski   update models (ad...
1227
1228
        printd(f"- Set command {self.name} as killed")
        #print(f"- Set this command as killed: {self}")
927b033b   Etienne Pallier   update AgentBasic...
1229
        self.set_state_to(self.CMD_STATUS_CODES.CMD_EXEC_KILLED, author_agent_name=author_agent_name, result=result)
5ce2836f   Alexis Koralewski   update models (ad...
1230

927b033b   Etienne Pallier   update AgentBasic...
1231
1232
    # General method to change state
    def set_state_to(self, status_new: str, author_agent_name: str = None, result:str=None):
7138789e   Etienne Pallier   new Agent with 3 ...
1233
        '''
927b033b   Etienne Pallier   update AgentBasic...
1234
        If result is present it will be set in the "result" field
7138789e   Etienne Pallier   new Agent with 3 ...
1235
        '''
8decb416   Etienne Pallier   UTC par defaut da...
1236
        #now_time = datetime.utcnow().astimezone()
998f175c   Alexis Koralewski   fix datetime.utcnow
1237
        now_time = datetime.now(tz=timezone.utc)
927b033b   Etienne Pallier   update AgentBasic...
1238
        
bc750a56   Etienne Pallier   Allow commands to...
1239
1240
        # result can be "0" which is false...
        if result is not None: 
7138789e   Etienne Pallier   new Agent with 3 ...
1241
            self.set_result(result, False)
927b033b   Etienne Pallier   update AgentBasic...
1242
        
d02249e6   Etienne Pallier   Added CMD_EXEC_ER...
1243
        '''
927b033b   Etienne Pallier   update AgentBasic...
1244
1245
1246
        # - Changing state to PENDING (from None)
        if status_new == self.CMD_STATUS_CODES.CMD_PENDING:
            self.s_deposit_time = now_time
d02249e6   Etienne Pallier   Added CMD_EXEC_ER...
1247
        '''
927b033b   Etienne Pallier   update AgentBasic...
1248
1249
1250

        # - Changing state from PENDING
        #if status_new in (self.CMD_STATUS_CODES.CMD_RUNNING, self.CMD_STATUS_CODES.CMD_SKIPPED, self.CMD_STATUS_CODES.CMD_EXPIRED):
d02249e6   Etienne Pallier   Added CMD_EXEC_ER...
1251
        if status_new in (
927b033b   Etienne Pallier   update AgentBasic...
1252
1253
1254
1255
1256
1257
1258
1259
            # Errors cases
            self.CMD_STATUS_CODES.CMD_INVALID,
            self.CMD_STATUS_CODES.CMD_UNIMPLEMENTED,
            self.CMD_STATUS_CODES.CMD_SKIPPED, 
            self.CMD_STATUS_CODES.CMD_EXPIRED,
            # Normal case
            self.CMD_STATUS_CODES.CMD_RUNNING
        ):
5ce2836f   Alexis Koralewski   update models (ad...
1260
            assert self.is_pending()
927b033b   Etienne Pallier   update AgentBasic...
1261
1262
            # - go RUNNING => set start time
            if status_new == self.CMD_STATUS_CODES.CMD_RUNNING:
5ce2836f   Alexis Koralewski   update models (ad...
1263
                self.r_start_time = now_time
927b033b   Etienne Pallier   update AgentBasic...
1264
1265
            # - go in error => set end time
            else:
cbbd0c65   Etienne Pallier   Updated models.Ag...
1266
                self.r_end_time = now_time
927b033b   Etienne Pallier   update AgentBasic...
1267
1268
1269
1270
1271
1272
                # EXPIRED
                if status_new == self.CMD_STATUS_CODES.CMD_EXPIRED:
                    self.killer_agent_name = author_agent_name
        
        # - Changing state from RUNNING (CMD_EXECUTED, CMD_EXEC_...)
        #elif status_new in (self.CMD_STATUS_CODES.CMD_EXECUTED, self.CMD_STATUS_CODES.CMD_EXEC_KILLED):
d02249e6   Etienne Pallier   Added CMD_EXEC_ER...
1273
        elif status_new != self.CMD_STATUS_CODES.CMD_PENDING:
5ce2836f   Alexis Koralewski   update models (ad...
1274
            assert self.is_running()
cbbd0c65   Etienne Pallier   Updated models.Ag...
1275
            self.r_end_time = now_time
927b033b   Etienne Pallier   update AgentBasic...
1276
            if status_new == self.CMD_STATUS_CODES.CMD_EXEC_KILLED:
5ce2836f   Alexis Koralewski   update models (ad...
1277
1278
                self.killer_agent_name = author_agent_name
        # Update command status
927b033b   Etienne Pallier   update AgentBasic...
1279
        self.state = status_new
5ce2836f   Alexis Koralewski   update models (ad...
1280
1281
        self.save()
        # Optimization, but does not work, why ?...
1ba49504   Alexis Koralewski   fixing CSS and JS...
1282
        # self.save(update_fields=["state"])
5ce2836f   Alexis Koralewski   update models (ad...
1283
1284
1285


class Config(models.Model):
1ba49504   Alexis Koralewski   fixing CSS and JS...
1286
1287
    PYROS_STATE = ["Starting", "Passive", "Standby",
                   "Remote", "Startup", "Scheduler", "Closing"]
5ce2836f   Alexis Koralewski   update models (ad...
1288
1289
1290
1291

    id = models.IntegerField(default='1', primary_key=True)
    #latitude = models.FloatField(default=1)
    latitude = models.DecimalField(
1ba49504   Alexis Koralewski   fixing CSS and JS...
1292
        max_digits=4, decimal_places=2,
5ce2836f   Alexis Koralewski   update models (ad...
1293
1294
1295
1296
1297
1298
1299
1300
1301
        default=1,
        validators=[
            MaxValueValidator(90),
            MinValueValidator(-90)
        ]
    )
    local_time_zone = models.FloatField(default=1)
    #longitude = models.FloatField(default=1)
    longitude = models.DecimalField(
1ba49504   Alexis Koralewski   fixing CSS and JS...
1302
        max_digits=5, decimal_places=2,
5ce2836f   Alexis Koralewski   update models (ad...
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
        default=1,
        validators=[
            MaxValueValidator(360),
            MinValueValidator(-360)
        ]
    )
    altitude = models.FloatField(default=1)
    horizon_line = models.FloatField(default=1)
    row_data_save_frequency = models.IntegerField(default='300')
    request_frequency = models.IntegerField(default='300')
    analysed_data_save = models.IntegerField(default='300')
    telescope_ip_address = models.CharField(max_length=45, default="127.0.0.1")
    camera_ip_address = models.CharField(max_length=45, default="127.0.0.1")
    plc_ip_address = models.CharField(max_length=45, default="127.0.0.1")

    # TODO: changer ça, c'est pas clair du tout...
    # True = mode Scheduler-standby, False = mode Remote !!!!
    global_mode = models.BooleanField(default='True')

    ack = models.BooleanField(default='False')
    bypass = models.BooleanField(default='True')
    lock = models.BooleanField(default='False')
    pyros_state = models.CharField(max_length=25, default=PYROS_STATE[0])
    force_passive_mode = models.BooleanField(default='False')
    plc_timeout_seconds = models.PositiveIntegerField(default=60)
    majordome_state = models.CharField(max_length=25, default="")
    ntc = models.BooleanField(default='False')
    majordome_restarted = models.BooleanField(default='False')

    class Meta:
        managed = True
        db_table = 'config'
        verbose_name_plural = "Config"

    def __str__(self):
        return (str(self.__dict__))


5ce2836f   Alexis Koralewski   update models (ad...
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
class Country(models.Model):
    name = models.CharField(max_length=45, blank=True, null=True)
    desc = models.TextField(blank=True, null=True)
    quota = models.FloatField(blank=True, null=True)

    class Meta:
        managed = True
        db_table = 'country'
        verbose_name_plural = "Countries"

    def __str__(self):
        return (str(self.name))


class Detector(Device):
    VIS = "Visible camera"
    NIR = "Cagire"

    telescope = models.ForeignKey(
        'Telescope', models.DO_NOTHING, related_name="detectors")
    nb_photo_x = models.IntegerField(blank=True, null=True)
    nb_photo_y = models.IntegerField(blank=True, null=True)
    photo_size_x = models.IntegerField(blank=True, null=True)
    photo_size_y = models.IntegerField(blank=True, null=True)
    has_shutter = models.BooleanField(default=False)
    equivalent_foc_len = models.CharField(max_length=45, blank=True, null=True)
    acq_start = models.DateTimeField(blank=True, null=True)
    acq_stop = models.DateTimeField(blank=True, null=True)
    check_temp = models.FloatField(blank=True, null=True)
    gain = models.FloatField(blank=True, null=True)
    readout_noise = models.FloatField(blank=True, null=True)
    readout_time = models.FloatField(blank=True, null=True)
    idcam_readout_mode = models.IntegerField(blank=True, null=True)

    class Meta:
        managed = True
        db_table = 'detector'

    def __str__(self):
        return str(self.name)

    def device_name(self):
        return self.__str__()
    device_name.short_description = "Name"


class Dome(Device):
    DOME = "Dome"

    open = models.BooleanField(default=False, blank=True)

    class Meta:
        managed = True
        db_table = 'dome'

    def __str__(self):
        return str(self.name)

    def device_name(self):
        return self.__str__()
    device_name.short_description = "Name"


5ce2836f   Alexis Koralewski   update models (ad...
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
class Filter(Device):
    VIS_FILTER_1 = "First visible filter"
    VIS_FILTER_2 = "Second visible filter"
    NIR_FILTER_1 = "First infrared filter"
    NIR_FILTER_2 = "Second infrared filter"

    filter_wheel = models.ForeignKey(
        "FilterWheel", models.DO_NOTHING, related_name="filters", blank=True, null=True)
    category = models.CharField(max_length=1, blank=True, null=True)
    transmission_curve_doc = models.CharField(
        max_length=45, blank=True, null=True)

    class Meta:
        managed = True
        db_table = 'filter'

    def __str__(self):
        return (str(self.name))

    def device_name(self):
        return self.__str__()
    device_name.short_description = "Name"


class FilterWheel(Device):
    detector = models.OneToOneField(Detector, on_delete=models.CASCADE,
                                    related_name="filter_wheel", blank=True, null=True)

    class Meta:
        managed = True
        db_table = 'filter_wheel'

    def __str__(self):
        return (str(self.name))

    def device_name(self):
        return self.__str__()
    device_name.short_description = "Name"


class Image(models.Model):
1ba49504   Alexis Koralewski   fixing CSS and JS...
1445
1446
    plan = models.ForeignKey(
        'Plan', on_delete=models.CASCADE, related_name="images")
5ce2836f   Alexis Koralewski   update models (ad...
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
    nrtanalysis = models.ForeignKey(
        'NrtAnalysis', models.DO_NOTHING, blank=True, null=True, related_name="images")
    name = models.CharField(max_length=45, blank=True, null=True)
    desc = models.TextField(blank=True, null=True)
    created = models.DateTimeField(blank=True, null=True, auto_now_add=True)
    updated = models.DateTimeField(blank=True, null=True, auto_now=True)
    date_from_gps = models.CharField(max_length=45, blank=True, null=True)
    level = models.IntegerField(blank=True, null=True)
    type = models.CharField(max_length=5, blank=True, null=True)
    quality = models.CharField(max_length=45, blank=True, null=True)
    flaggps = models.CharField(max_length=45, blank=True, null=True)
    exposure = models.CharField(max_length=45, blank=True, null=True)
    tempext = models.CharField(max_length=45, blank=True, null=True)
    pressure = models.CharField(max_length=45, blank=True, null=True)
    humidext = models.CharField(max_length=45, blank=True, null=True)
    wind = models.CharField(max_length=45, blank=True, null=True)
    wind_dir = models.CharField(max_length=45, blank=True, null=True)
    dwnimg = models.CharField(max_length=45, blank=True, null=True)
    dwncata = models.CharField(max_length=45, blank=True, null=True)
    dwn = models.CharField(max_length=45, blank=True, null=True)
    level0_fits_name = models.CharField(max_length=45, blank=True, null=True)
    level1a_fits_name = models.CharField(max_length=45, blank=True, null=True)
    level1b_fits_name = models.CharField(max_length=45, blank=True, null=True)

    class Meta:
        managed = True
        db_table = 'image'

    def __str__(self):
        return (str(self.name))


class Log(models.Model):
    agent = models.CharField(max_length=45, blank=True, null=True)
    created = models.DateTimeField(blank=True, null=True, auto_now_add=True)
    message = models.TextField(blank=True, null=True)

    class Meta:
        managed = True
        db_table = 'log'

    def __str__(self):
        return (str(self.agent))


class NrtAnalysis(models.Model):
    name = models.CharField(max_length=45, blank=True, null=True)
    desc = models.TextField(blank=True, null=True)
    created = models.DateTimeField(blank=True, null=True, auto_now_add=True)
    updated = models.DateTimeField(blank=True, null=True, auto_now=True)
    analysis = models.TextField(blank=True, null=True)

    class Meta:
        managed = True
        db_table = 'nrtanalysis'
        verbose_name_plural = "Nrt analyzes"

    def __str__(self):
        return (str(self.name))


3b81a22b   Alexis Koralewski   Rework on Request...
1508
"""
5ce2836f   Alexis Koralewski   update models (ad...
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
class Plan(models.Model):
    album = models.ForeignKey(Album, on_delete=models.CASCADE, related_name="plans")
    filter = models.ForeignKey(Filter, models.DO_NOTHING, related_name="plans", blank=True, null=True)
    name = models.CharField(max_length=45, blank=True, null=True)
    desc = models.CharField(max_length=45, blank=True, null=True)
    created = models.DateTimeField(blank=True, null=True, auto_now_add=True)
    updated = models.DateTimeField(blank=True, null=True, auto_now=True)
    duration = models.FloatField(default=0, blank=True, null=True)
    position = models.CharField(max_length=45, blank=True, null=True)
    exposure_time = models.FloatField(blank=True, null=True)
    nb_images = models.IntegerField(blank=True, null=True)
    dithering = models.BooleanField(default=False)
    complete = models.BooleanField(default=False)

    class Meta:
        managed = True
        db_table = 'plan'

    def __str__(self):
        return (str(self.name))
3b81a22b   Alexis Koralewski   Rework on Request...
1529
"""
5ce2836f   Alexis Koralewski   update models (ad...
1530

1ba49504   Alexis Koralewski   fixing CSS and JS...
1531

3b81a22b   Alexis Koralewski   Rework on Request...
1532
class Plan(models.Model):
1ba49504   Alexis Koralewski   fixing CSS and JS...
1533
1534
    album = models.ForeignKey(
        Album, on_delete=models.CASCADE, related_name="plans")
3b81a22b   Alexis Koralewski   Rework on Request...
1535
1536
1537
    created = models.DateTimeField(blank=True, null=True, auto_now_add=True)
    updated = models.DateTimeField(blank=True, null=True, auto_now=True)
    duration = models.FloatField(default=0, blank=True, null=True)
1ba49504   Alexis Koralewski   fixing CSS and JS...
1538
1539
1540
    nb_images = models.PositiveIntegerField(
        blank=True, null=True, validators=[MinValueValidator(1)])
    config_attributes = models.JSONField(blank=True, null=True)
4a596eec   Alexis Koralewski   Updating SP, Sequ...
1541
    complete = models.BooleanField(default=False)
1ba49504   Alexis Koralewski   fixing CSS and JS...
1542

864ec466   Alexis Koralewski   Renaming common t...
1543
1544
    class Meta:
        db_table = "plan"
5ce2836f   Alexis Koralewski   update models (ad...
1545

bbf0ac6e   Alexis Koralewski   Adding unique con...
1546
1547
1548
    def __str__(self) -> str:
        return f"Plan of Album {self.album.name} has {self.nb_images} image(s)"

5ce2836f   Alexis Koralewski   update models (ad...
1549
class PlcDeviceStatus(models.Model):
1ba49504   Alexis Koralewski   fixing CSS and JS...
1550
1551
1552
1553
1554
1555
    device = models.ForeignKey(
        'PlcDevice', on_delete=models.CASCADE, related_name='current_status')
    created = models.DateTimeField(
        auto_now_add=True, editable=False, blank=True)
    outside_temp = models.DecimalField(
        max_digits=15, decimal_places=8, blank=True, null=True)
5ce2836f   Alexis Koralewski   update models (ad...
1556
    outside_temp_unit = models.CharField(max_length=45, blank=True, null=True)
1ba49504   Alexis Koralewski   fixing CSS and JS...
1557
1558
1559
1560
1561
1562
    outside_humidity = models.DecimalField(
        max_digits=15, decimal_places=8, blank=True, null=True)
    outside_humidity_unit = models.CharField(
        max_length=45, blank=True, null=True)
    pressure = models.DecimalField(
        max_digits=15, decimal_places=8, blank=True, null=True)
5ce2836f   Alexis Koralewski   update models (ad...
1563
    pressure_unit = models.CharField(max_length=45, blank=True, null=True)
1ba49504   Alexis Koralewski   fixing CSS and JS...
1564
1565
    rain_rate = models.DecimalField(
        max_digits=15, decimal_places=8, blank=True, null=True)
5ce2836f   Alexis Koralewski   update models (ad...
1566
    rain_rate_unit = models.CharField(max_length=45, blank=True, null=True)
1ba49504   Alexis Koralewski   fixing CSS and JS...
1567
1568
    wind_speed = models.DecimalField(
        max_digits=15, decimal_places=8, blank=True, null=True)
5ce2836f   Alexis Koralewski   update models (ad...
1569
    wind_speed_unit = models.CharField(max_length=45, blank=True, null=True)
1ba49504   Alexis Koralewski   fixing CSS and JS...
1570
1571
    wind_dir = models.DecimalField(
        max_digits=15, decimal_places=8, blank=True, null=True)
5ce2836f   Alexis Koralewski   update models (ad...
1572
    wind_dir_unit = models.CharField(max_length=45, blank=True, null=True)
1ba49504   Alexis Koralewski   fixing CSS and JS...
1573
1574
    dew_point = models.DecimalField(
        max_digits=15, decimal_places=8, blank=True, null=True)
5ce2836f   Alexis Koralewski   update models (ad...
1575
    dew_point_unit = models.CharField(max_length=45, blank=True, null=True)
1ba49504   Alexis Koralewski   fixing CSS and JS...
1576
1577
    analog = models.DecimalField(
        max_digits=15, decimal_places=8, blank=True, null=True)
5ce2836f   Alexis Koralewski   update models (ad...
1578
    analog_unit = models.CharField(max_length=45, blank=True, null=True)
1ba49504   Alexis Koralewski   fixing CSS and JS...
1579
1580
    digital = models.DecimalField(
        max_digits=15, decimal_places=8, blank=True, null=True)
5ce2836f   Alexis Koralewski   update models (ad...
1581
    digital_unit = models.CharField(max_length=45, blank=True, null=True)
1ba49504   Alexis Koralewski   fixing CSS and JS...
1582
1583
    inside_temp = models.DecimalField(
        max_digits=15, decimal_places=8, blank=True, null=True)
5ce2836f   Alexis Koralewski   update models (ad...
1584
    inside_temp_unit = models.CharField(max_length=45, blank=True, null=True)
1ba49504   Alexis Koralewski   fixing CSS and JS...
1585
1586
1587
1588
    inside_humidity = models.DecimalField(
        max_digits=15, decimal_places=8, blank=True, null=True)
    inside_humidity_unit = models.CharField(
        max_length=45, blank=True, null=True)
5ce2836f   Alexis Koralewski   update models (ad...
1589
    wind_dir_cardinal = models.CharField(max_length=45, blank=True, null=True)
1ba49504   Alexis Koralewski   fixing CSS and JS...
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
    wind_dir_cardinal_unit = models.CharField(
        max_length=45, blank=True, null=True)
    sensor_temperature = models.DecimalField(
        max_digits=15, decimal_places=8, blank=True, null=True)
    sensor_temperature_unit = models.CharField(
        max_length=45, blank=True, null=True)
    sky_temperature = models.DecimalField(
        max_digits=15, decimal_places=8, blank=True, null=True)
    sky_temperature_unit = models.CharField(
        max_length=45,  blank=True, null=True)
5ce2836f   Alexis Koralewski   update models (ad...
1600
    status = models.CharField(max_length=45, blank=True, null=True)
1ba49504   Alexis Koralewski   fixing CSS and JS...
1601
1602
    current = models.DecimalField(
        max_digits=15, decimal_places=8, blank=True, null=True)
5ce2836f   Alexis Koralewski   update models (ad...
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
    current_unit = models.CharField(max_length=45, blank=True, null=True)
    is_safe = models.BooleanField(default=True)
    plc_mode = models.CharField(max_length=4, null=True)
    lights = models.CharField(max_length=3, null=True)
    shutters = models.CharField(max_length=5, null=True)

    class Meta:
        managed = True
        db_table = 'plc_devices_status'

    def __str__(self):
        return (str(self.__dict__))

    '''
        TODO : This function is Ugly,
        we should change this with a function pointer array
        and setters getters for each attribute
    '''
1ba49504   Alexis Koralewski   fixing CSS and JS...
1621

5ce2836f   Alexis Koralewski   update models (ad...
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
    def setValue(self, key, value, unit=""):
        if key == "Temperature_outside":
            self.outside_temp = value
            self.outside_temp_unit = unit
        elif key == "Humidity_outside":
            self.outside_humidity = value
            self.outside_humidity_unit = unit
        elif key == "_Pressure":
            self.pressure = value
            self.pressure_unit = unit
1ba49504   Alexis Koralewski   fixing CSS and JS...
1632
        elif key == "Rain_boolean":  # RainRate
5ce2836f   Alexis Koralewski   update models (ad...
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
            self.rain_rate = value
            self.rain_rate_unit = 'boulean'
        elif key == "Wind_speed":
            self.wind_speed = value
            self.wind_speed_unit = unit
        elif key == "Wind_dir":
            self.wind_dir = value
            self.wind_dir_unit = unit
        elif key == "_DewPoint":
            self.dew_point = value
            self.dew_point_unit = unit
        elif key == "_analog":
            self.analog = value
            self.analog_unit = unit
        elif key == "_digital":
            self.digital = value
            self.digital_unit = unit
        elif key == "_InsideTemp":
            self.inside_temp = value
            self.inside_temp_unit = unit
        elif key == "_InsideHumidity":
            self.inside_humidity = value
            self.inside_humidity_unit = unit
        elif key == "_WindDirCardinal":
            self.wind_dir_cardinal = value
            self.wind_dir_cardinal_unit = unit
        elif key == "_SensorTemperature":
            self.sensor_temperature = value
            self.sensor_temperature_unit = unit
        elif key == "_SkyTemperature":
            self.sky_temperature = value
            self.sky_temperature_unit = unit
        # PM 20190222 try patch
        elif key == "Error_code":
            self.status = value
        elif key == "current":
            self.current = value
            self.current_unit = unit
        elif key == "mode":
            self.plc_mode = value
        elif key == "is_safe":
            self.is_safe = value
        elif key == "LIGHTS":
            self.lights = value
        elif key == "SHUTTERS":
            self.shutters = value
        else:
            # PM 20190222 ignore unrecognized
            #raise KeyError("Key " + str(key) + " unrecognized")
            pass

1ba49504   Alexis Koralewski   fixing CSS and JS...
1684

5ce2836f   Alexis Koralewski   update models (ad...
1685
1686
1687
1688
1689
1690
1691
class PlcDevice(Device):
    #device = models.ForeignKey('Plc', on_delete=models.CASCADE, related_name='plc_devices')
    name = models.CharField(max_length=45, blank=True, null=True)
    desc = models.TextField(blank=True, null=True)
    created = models.DateTimeField(blank=True, null=True, auto_now_add=True)
    updated = models.DateTimeField(blank=True, null=True, auto_now=True)

5ce2836f   Alexis Koralewski   update models (ad...
1692
1693
1694
1695
1696
1697
1698
1699
    class Meta:
        managed = True
        db_table = 'plc_devices'

    def __str__(self):
        return str(self.name)


1ba49504   Alexis Koralewski   fixing CSS and JS...
1700
# class Plc(Device):
5ce2836f   Alexis Koralewski   update models (ad...
1701
1702
1703
1704
1705
1706
 #   last_update_status = models.DateTimeField(blank=True, null=True)
#    i
 #   class Meta:
  #      managed = True
   #     db_table = 'plc'

5a434264   Alexis Koralewski   New version of Sc...
1707
class ScienceTheme(models.Model):
1ba49504   Alexis Koralewski   fixing CSS and JS...
1708
1709
    name = models.CharField(max_length=120, blank=False,
                            null=False, default="", unique=True)
5a434264   Alexis Koralewski   New version of Sc...
1710
1711
1712

    def __str__(self) -> str:
        return str(self.name)
1ba49504   Alexis Koralewski   fixing CSS and JS...
1713

864ec466   Alexis Koralewski   Renaming common t...
1714
1715
    class Meta:
        db_table = "science_theme"
1ba49504   Alexis Koralewski   fixing CSS and JS...
1716

5ce2836f   Alexis Koralewski   update models (ad...
1717
class Institute(models.Model):
1ba49504   Alexis Koralewski   fixing CSS and JS...
1718
1719
1720
1721
    name = models.CharField(max_length=100, blank=False,
                            null=False, unique=True)
    quota = models.IntegerField(
        validators=[MinValueValidator(0), MaxValueValidator(100)])
5ce2836f   Alexis Koralewski   update models (ad...
1722
1723
1724
1725
1726
    #representative_user = models.ForeignKey("PyrosUser", on_delete=models.DO_NOTHING,related_name="institutes",default=1)

    def __str__(self) -> str:
        return str(self.name)

864ec466   Alexis Koralewski   Renaming common t...
1727
1728
    class Meta:
        db_table = "institute"
1ba49504   Alexis Koralewski   fixing CSS and JS...
1729

a6e63604   Alexis Koralewski   adding agentSP an...
1730
1731
1732
class PyrosUserManager(UserManager):
    def tac_users(self):
        return PyrosUser.objects.filter(user_level__name="TAC")
1ba49504   Alexis Koralewski   fixing CSS and JS...
1733

a6e63604   Alexis Koralewski   adding agentSP an...
1734
    def unit_users(self):
1ba49504   Alexis Koralewski   fixing CSS and JS...
1735
1736
        return PyrosUser.objects.filter(Q(user_level__name="Unit-PI") | Q(user_level__name="Unit-board"))

a6e63604   Alexis Koralewski   adding agentSP an...
1737

5ce2836f   Alexis Koralewski   update models (ad...
1738
class PyrosUser(AbstractUser):
1ba49504   Alexis Koralewski   fixing CSS and JS...
1739
1740
    username = models.CharField(
        max_length=255, blank=False, null=False, unique=True)
5ce2836f   Alexis Koralewski   update models (ad...
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
    is_active = models.BooleanField(default='False')
    first_time = models.BooleanField(default='False')
    country = models.ForeignKey(
        Country, on_delete=models.DO_NOTHING, related_name="pyros_users")
    user_level = models.ManyToManyField(
        'UserLevel', related_name="pyros_users")
    desc = models.TextField(blank=True, null=True)
    created = models.DateTimeField(blank=True, null=True, auto_now_add=True)
    updated = models.DateTimeField(blank=True, null=True, auto_now=True)
    tel = models.CharField(max_length=45, blank=True, null=True)
    address = models.TextField(max_length=100, blank=True, null=True)
    laboratory = models.CharField(max_length=45, blank=True, null=True)
1ba49504   Alexis Koralewski   fixing CSS and JS...
1753
1754
    institute = models.ForeignKey(
        Institute, on_delete=DO_NOTHING, related_name="pyros_users")
5ce2836f   Alexis Koralewski   update models (ad...
1755
    is_institute_representative = models.BooleanField(default=False)
1ba49504   Alexis Koralewski   fixing CSS and JS...
1756
1757
    motive_of_registration = models.TextField(
        max_length=300, blank=False, default="")
5ce2836f   Alexis Koralewski   update models (ad...
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
    # last_connect = models.DateTimeField(blank=True, null=True)
    # cur_connect = models.DateTimeField(blank=True, null=True)
    # putvalid_beg = models.DateTimeField(blank=True, null=True)
    # putvalid_end = models.DateTimeField(blank=True, null=True)
    # acqvalid_beg = models.CharField(max_length=45, blank=True, null=True)
    # acqvalid_end = models.CharField(max_length=45, blank=True, null=True)
    # quota = models.FloatField(blank=True, null=True)
    # quota_rea = models.FloatField(blank=True, null=True)
    # u_priority = models.IntegerField(blank=True, null=True)
    # p_priority = models.IntegerField(blank=True, null=True)
    # dir_level = models.IntegerField(blank=True, null=True)
    # can_del_void_req = models.BooleanField(default=False)
1ba49504   Alexis Koralewski   fixing CSS and JS...
1770
1771
1772
1773
    validator = models.ForeignKey(
        "PyrosUser", on_delete=models.DO_NOTHING, null=True, related_name="pyros_users")
    referee_themes = models.ManyToManyField(
        "ScienceTheme", related_name="referee_themes", blank=True)
a6e63604   Alexis Koralewski   adding agentSP an...
1774
1775

    objects = PyrosUserManager()
1ba49504   Alexis Koralewski   fixing CSS and JS...
1776

5ce2836f   Alexis Koralewski   update models (ad...
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
    class Meta:
        managed = True
        db_table = 'pyros_user'

    def __str__(self):
        return (str(self.get_username()))

    def user_username(self):
        return self.__str__()
    user_username.short_description = "Username"

1ba49504   Alexis Koralewski   fixing CSS and JS...
1788
    def get_priority(self) -> int:
5ce2836f   Alexis Koralewski   update models (ad...
1789
1790
1791
1792
1793
1794
        """
        return maximum priority of all roles of the user

        Returns:
            int: maximum priority
        """
1ba49504   Alexis Koralewski   fixing CSS and JS...
1795
        return PyrosUser.objects.get(id=self.id).user_level.all().aggregate(Max("priority"))["priority__max"]
5ce2836f   Alexis Koralewski   update models (ad...
1796

1ba49504   Alexis Koralewski   fixing CSS and JS...
1797
    def get_roles_str(self) -> str:
5ce2836f   Alexis Koralewski   update models (ad...
1798
1799
1800
1801
1802
1803
1804
1805
        """
        return string that represent all roles assigned to the user

        Returns:
            str: string of all roles assigned to user
        """
        roles_str = ""
        # loop on all roles assigned to user
1ba49504   Alexis Koralewski   fixing CSS and JS...
1806
1807
        for role in PyrosUser.objects.get(id=self.id).user_level.all():
            roles_str += role.name + ", "
5ce2836f   Alexis Koralewski   update models (ad...
1808
1809
        return roles_str[:-2]

1ba49504   Alexis Koralewski   fixing CSS and JS...
1810
    def get_list_of_roles(self) -> list:
5ce2836f   Alexis Koralewski   update models (ad...
1811
1812
1813
1814
1815
1816
        """
        return list of all roles assigned to the user

        Returns:
            list: list of all roles assigned to user
        """
1ba49504   Alexis Koralewski   fixing CSS and JS...
1817
        return PyrosUser.objects.get(id=self.id).user_level.all().values_list("name", flat=True)
5ce2836f   Alexis Koralewski   update models (ad...
1818
1819

    # Note for the next functions : We take the first result of the query because it should be only one result with the filter applied since each UserLevel has a unique priority.
1ba49504   Alexis Koralewski   fixing CSS and JS...
1820
    def get_max_priority_desc(self) -> str:
5ce2836f   Alexis Koralewski   update models (ad...
1821
1822
1823
1824
1825
1826
        """
        return the desc of the maximum priority of all roles assigned to user

        Returns:
            str:  desc of the maximum priority of all roles assigned to user
        """
1ba49504   Alexis Koralewski   fixing CSS and JS...
1827
        return PyrosUser.objects.get(id=self.id).user_level.filter(priority=self.get_priority())[0].desc
5ce2836f   Alexis Koralewski   update models (ad...
1828

1ba49504   Alexis Koralewski   fixing CSS and JS...
1829
    def get_max_priority_quota(self) -> int:
5ce2836f   Alexis Koralewski   update models (ad...
1830
1831
1832
1833
1834
1835
        """
        return the quota of the maximum priority of all roles assigned to user

        Returns:
            int:  quota of the maximum priority of all roles assigned to user
        """
1ba49504   Alexis Koralewski   fixing CSS and JS...
1836
        return PyrosUser.objects.get(id=self.id).user_level.filter(priority=self.get_priority())[0].quota
5ce2836f   Alexis Koralewski   update models (ad...
1837

1ba49504   Alexis Koralewski   fixing CSS and JS...
1838
    def get_referee_themes_as_str(self) -> str:
077d5a23   Alexis Koralewski   adding science th...
1839
1840
1841
        """
        Return the list of science themes associated to that user if user is a TAC.
        Return empty string otherwise
5ce2836f   Alexis Koralewski   update models (ad...
1842

077d5a23   Alexis Koralewski   adding science th...
1843
1844
1845
1846
1847
        Returns:
            str: list of science themes associated to that user
        """
        str = ""
        if self.referee_themes != None:
1ba49504   Alexis Koralewski   fixing CSS and JS...
1848
1849
            for science_theme in PyrosUser.objects.get(id=self.id).referee_themes.all():
                str += science_theme.name + ", "
077d5a23   Alexis Koralewski   adding science th...
1850
1851
1852
            return str[:-2]
        else:
            return str
4a596eec   Alexis Koralewski   Updating SP, Sequ...
1853

4a596eec   Alexis Koralewski   Updating SP, Sequ...
1854
    def get_scientific_program(self) -> QuerySet:
1ba49504   Alexis Koralewski   fixing CSS and JS...
1855
1856
1857
1858
        sp_where_user_is_sp_pi = ScientificProgram.objects.filter(
            sp_pi=self.id)
        other_sp_of_user = ScientificProgram.objects.filter(id__in=SP_Period.objects.filter(id__in=SP_Period_User.objects.filter(
            user=PyrosUser.objects.get(username=self.username)).values("SP_Period")).values_list("scientific_program", flat=True))
4a596eec   Alexis Koralewski   Updating SP, Sequ...
1859
1860
        sp_of_user = sp_where_user_is_sp_pi | other_sp_of_user
        return sp_of_user
1ba49504   Alexis Koralewski   fixing CSS and JS...
1861

ad3b297c   Alexis Koralewski   add pagination to...
1862
    def get_scientific_program_where_user_is_sp_pi(self) -> QuerySet:
1ba49504   Alexis Koralewski   fixing CSS and JS...
1863
1864
        sp_where_user_is_sp_pi = ScientificProgram.objects.filter(
            sp_pi=self.id)
ad3b297c   Alexis Koralewski   add pagination to...
1865
        return sp_where_user_is_sp_pi
4a596eec   Alexis Koralewski   Updating SP, Sequ...
1866

5ce2836f   Alexis Koralewski   update models (ad...
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
# class Schedule(models.Model):
#     created = models.DateTimeField(blank=True, null=True, auto_now_add=True)
#     plan_start = models.DecimalField(
#         default=0.0, max_digits=15, decimal_places=8)
#     plan_end = models.DecimalField(
#         default=0.0, max_digits=15, decimal_places=8)
#     flag = models.CharField(max_length=45, blank=True, null=True)
#
#     class Meta:
#         managed = True
#         db_table = 'schedule'
#
#     def __str__(self):
#         return (str(self.created))


class Schedule(models.Model):
    sequences = models.ManyToManyField(
        'Sequence', through='ScheduleHasSequences', related_name='schedules')
    created = models.DateTimeField(blank=True, null=True, auto_now_add=True)
    plan_night_start = models.DecimalField(
        default=0.0, max_digits=15, decimal_places=8)
    plan_end = models.DecimalField(
        default=0.0, max_digits=15, decimal_places=8)
    plan_start = models.DecimalField(
        default=0.0, max_digits=15, decimal_places=8)
    flag = models.CharField(max_length=45, blank=True, null=True)

    class Meta:
        managed = True
        db_table = 'schedule'
        verbose_name_plural = "Schedules"

    def __str__(self):
        return (str(self.created))

1ba49504   Alexis Koralewski   fixing CSS and JS...
1903

5a434264   Alexis Koralewski   New version of Sc...
1904
class PeriodManager(models.Manager):
077d5a23   Alexis Koralewski   adding science th...
1905
    # to get the currently active period, use exploitation_period()
1ba49504   Alexis Koralewski   fixing CSS and JS...
1906
    def currently_active_period(self) -> QuerySet:
5a434264   Alexis Koralewski   New version of Sc...
1907
        today = timezone.now().date()
1ba49504   Alexis Koralewski   fixing CSS and JS...
1908
        return Period.objects.get(start_date__lte=today, end_date__gt=today)
5ce2836f   Alexis Koralewski   update models (ad...
1909

1ba49504   Alexis Koralewski   fixing CSS and JS...
1910
    def submission_periods(self) -> QuerySet:
077d5a23   Alexis Koralewski   adding science th...
1911
1912
1913
1914
        today = timezone.now().date()
        submission_periods_id = []
        periods = Period.objects.filter(start_date__gte=today)
        for period in periods:
077d5a23   Alexis Koralewski   adding science th...
1915
1916
1917
1918
1919
            if period.submission_start_date <= today and period.submission_end_date > today:
                submission_periods_id.append(period.id)
        periods = periods.filter(id__in=submission_periods_id)
        return periods

1ba49504   Alexis Koralewski   fixing CSS and JS...
1920
    def evaluation_periods(self) -> QuerySet:
077d5a23   Alexis Koralewski   adding science th...
1921
1922
1923
1924
1925
1926
1927
1928
1929
        today = timezone.now().date()
        evaluation_periods_id = []
        periods = Period.objects.filter(start_date__gte=today)
        for period in periods:
            if period.submission_end_date <= today and period.unit_pi_validation_start_date > today:
                evaluation_periods_id.append(period.id)
        periods = periods.filter(id__in=evaluation_periods_id)
        return periods

1ba49504   Alexis Koralewski   fixing CSS and JS...
1930
    def validation_periods(self) -> QuerySet:
077d5a23   Alexis Koralewski   adding science th...
1931
1932
1933
1934
        today = timezone.now().date()
        validation_periods_id = []
        periods = Period.objects.filter(start_date__gte=today)
        for period in periods:
a6e63604   Alexis Koralewski   adding agentSP an...
1935
            if period.unit_pi_validation_start_date <= today and period.notification_start_date > today:
077d5a23   Alexis Koralewski   adding science th...
1936
1937
1938
1939
                validation_periods_id.append(period.id)
        periods = periods.filter(id__in=validation_periods_id)
        return periods

1ba49504   Alexis Koralewski   fixing CSS and JS...
1940
    def notification_periods(self) -> QuerySet:
077d5a23   Alexis Koralewski   adding science th...
1941
1942
1943
1944
        today = timezone.now().date()
        notification_periods_id = []
        periods = Period.objects.filter(start_date__gte=today)
        for period in periods:
a6e63604   Alexis Koralewski   adding agentSP an...
1945
            if period.notification_start_date <= today and period.start_date > today:
077d5a23   Alexis Koralewski   adding science th...
1946
1947
1948
1949
                notification_periods_id.append(period.id)
        periods = periods.filter(id__in=notification_periods_id)
        return periods

1ba49504   Alexis Koralewski   fixing CSS and JS...
1950
    def exploitation_period(self) -> any:
077d5a23   Alexis Koralewski   adding science th...
1951
1952
1953
1954
1955
1956
1957
        today = timezone.now().date()
        periods = Period.objects.filter(start_date__lte=today)
        for period in periods:
            if period.start_date <= today and period.end_date > today:
                return period
        return None

1ba49504   Alexis Koralewski   fixing CSS and JS...
1958
    def latest_period(self) -> any:
077d5a23   Alexis Koralewski   adding science th...
1959
        today = timezone.now().date()
1ba49504   Alexis Koralewski   fixing CSS and JS...
1960
1961
        future_period = Period.objects.filter(
            start_date__gt=today).order_by("-start_date").first()
077d5a23   Alexis Koralewski   adding science th...
1962
1963
1964
1965
        if future_period is None:
            # no future period defined so we return the current period
            return self.exploitation_period()
        return future_period
1ba49504   Alexis Koralewski   fixing CSS and JS...
1966
1967

    def previous_periods(self) -> any:
077d5a23   Alexis Koralewski   adding science th...
1968
        today = timezone.now().date()
1ba49504   Alexis Koralewski   fixing CSS and JS...
1969
1970
        previous_periods = Period.objects.filter(start_date__lt=today).order_by(
            "-start_date").exclude(id=self.exploitation_period().id)
077d5a23   Alexis Koralewski   adding science th...
1971
        return previous_periods
1ba49504   Alexis Koralewski   fixing CSS and JS...
1972
1973

    def next_period(self) -> any:
a6e63604   Alexis Koralewski   adding agentSP an...
1974
        current_period = self.exploitation_period()
1ba49504   Alexis Koralewski   fixing CSS and JS...
1975
1976
        next_period = Period.objects.filter(
            start_date__gt=current_period.start_date).order_by("start_date").first()
a6e63604   Alexis Koralewski   adding agentSP an...
1977
1978
        return next_period

077d5a23   Alexis Koralewski   adding science th...
1979

5ce2836f   Alexis Koralewski   update models (ad...
1980
class Period(models.Model):
5a434264   Alexis Koralewski   New version of Sc...
1981
1982
    # if change of default value, those values need to be changed also in create_period and edit_period.html (Javascript )
    today = timezone.now().date()
5ce2836f   Alexis Koralewski   update models (ad...
1983
    today_plus_six_months = today + relativedelta(months=+6)
5a434264   Alexis Koralewski   New version of Sc...
1984
    today_minus_six_months = today + relativedelta(months=-6)
1ba49504   Alexis Koralewski   fixing CSS and JS...
1985
1986
    today_minus_one_month_and_half = today + \
        relativedelta(months=-1) + relativedelta(days=-15)
5a434264   Alexis Koralewski   New version of Sc...
1987
1988
    today_minus_fifteen_days = today + relativedelta(days=-15)
    end_date_plus_one_year = today_plus_six_months + relativedelta(years=+1)
1ba49504   Alexis Koralewski   fixing CSS and JS...
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
    end_date_plus_eleven_year = today_plus_six_months + \
        relativedelta(years=+11)

    start_date = models.DateField(
        blank=True, null=True, default=timezone.now, editable=True)

    exploitation_duration = models.PositiveIntegerField(
        blank=True, null=True, default=182, editable=True)
    submission_duration = models.PositiveIntegerField(
        blank=True, null=True, default=136, editable=True)
    evaluation_duration = models.PositiveIntegerField(
        blank=True, null=True, default=31, editable=True)
    validation_duration = models.PositiveIntegerField(
        blank=True, null=True, default=5, editable=True)
    notification_duration = models.PositiveIntegerField(
        blank=True, null=True, default=10, editable=True)
    property_of_data_duration = models.PositiveIntegerField(
        blank=True, null=True, default=365, editable=True)
    data_accessibility_duration = models.PositiveIntegerField(
        blank=True, null=True, default=365*10, editable=True)
077d5a23   Alexis Koralewski   adding science th...
2009
2010
2011
2012
2013
2014
2015

    @property
    def end_date(self):
        return self.start_date + relativedelta(days=self.exploitation_duration)

    @property
    def submission_start_date(self):
a6e63604   Alexis Koralewski   adding agentSP an...
2016
        return self.start_date + relativedelta(days=-(self.submission_duration+self.evaluation_duration+self.validation_duration+self.notification_duration))
1ba49504   Alexis Koralewski   fixing CSS and JS...
2017

077d5a23   Alexis Koralewski   adding science th...
2018
2019
    @property
    def submission_end_date(self):
a6e63604   Alexis Koralewski   adding agentSP an...
2020
        return self.submission_start_date + relativedelta(days=self.submission_duration)
077d5a23   Alexis Koralewski   adding science th...
2021
2022
2023

    @property
    def unit_pi_validation_start_date(self):
a6e63604   Alexis Koralewski   adding agentSP an...
2024
        return self.submission_end_date + relativedelta(days=self.evaluation_duration)
077d5a23   Alexis Koralewski   adding science th...
2025
2026
2027

    @property
    def notification_start_date(self):
a6e63604   Alexis Koralewski   adding agentSP an...
2028
        return self.unit_pi_validation_start_date + relativedelta(days=self.validation_duration)
077d5a23   Alexis Koralewski   adding science th...
2029
2030
2031
2032
2033
2034
2035
2036
2037

    @property
    def property_of_data_end_date(self):
        return self.end_date + relativedelta(days=self.property_of_data_duration)

    @property
    def data_accessibility_end_date(self):
        return self.end_date + relativedelta(days=self.data_accessibility_duration)

077d5a23   Alexis Koralewski   adding science th...
2038
2039
    """
    end_date =  models.DateField(blank=True, null=True, default=start_date_plus_six_months,editable=True)    
5a434264   Alexis Koralewski   New version of Sc...
2040
2041
2042
2043
2044
    submission_start_date = models.DateField(blank=True, null=True, default=today_minus_six_months,editable=True)    
    submission_end_date = models.DateField(blank=True, null=True, default=today_minus_one_month_and_half,editable=True)    
    unit_pi_validation_start_date = models.DateField(blank=True, null=True, default=today_minus_fifteen_days,editable=True)    
    property_of_data_end_date = models.DateField(blank=True, null=True, default=end_date_plus_one_year,editable=True)     
    data_accessibility_end_date = models.DateField(blank=True, null=True, default=end_date_plus_eleven_year,editable=True)    
077d5a23   Alexis Koralewski   adding science th...
2045
2046
    
    #class Meta:
5ce2836f   Alexis Koralewski   update models (ad...
2047
        # constrains start_date and duration to be unique (We don't want to have multiple records in db that represent the same period)
077d5a23   Alexis Koralewski   adding science th...
2048
2049
2050
    #    constraints = [
    #        models.UniqueConstraint(fields=["start_date","duration"], name="unique_period")   
    #    ]
5ce2836f   Alexis Koralewski   update models (ad...
2051
    """
5a434264   Alexis Koralewski   New version of Sc...
2052
2053

    objects = PeriodManager()
4a596eec   Alexis Koralewski   Updating SP, Sequ...
2054

5ce2836f   Alexis Koralewski   update models (ad...
2055
    def __str__(self) -> str:
1ba49504   Alexis Koralewski   fixing CSS and JS...
2056
        return "P"+str(self.id)+" ("+self.start_date.strftime("%d/%m/%Y") + " to " + self.end_date.strftime("%d/%m/%Y")+")"
4a596eec   Alexis Koralewski   Updating SP, Sequ...
2057

1ba49504   Alexis Koralewski   fixing CSS and JS...
2058
    def is_currently_active(self) -> bool:
5a434264   Alexis Koralewski   New version of Sc...
2059
        today = timezone.now().date()
fce7ff0f   Alexis Koralewski   Change of compari...
2060
        return self.start_date <= today < self.end_date
4a596eec   Alexis Koralewski   Updating SP, Sequ...
2061
2062
2063
2064

    def can_submit_sequence(self) -> bool:
        today = timezone.now().date()
        return today >= self.notification_start_date
1ba49504   Alexis Koralewski   fixing CSS and JS...
2065

864ec466   Alexis Koralewski   Renaming common t...
2066
2067
2068
    class Meta:
        db_table = "period"

5a434264   Alexis Koralewski   New version of Sc...
2069

4a596eec   Alexis Koralewski   Updating SP, Sequ...
2070
2071
2072
class ScientificProgramManager(models.Manager):
    def observable_programs(self):
        exploitable_sp = []
1ba49504   Alexis Koralewski   fixing CSS and JS...
2073

4a596eec   Alexis Koralewski   Updating SP, Sequ...
2074
2075
        for sp_period in SP_Period.objects.all():
            if sp_period.can_submit_sequence():
1ba49504   Alexis Koralewski   fixing CSS and JS...
2076
                exploitable_sp.append(sp_period.scientific_program.id)
4a596eec   Alexis Koralewski   Updating SP, Sequ...
2077
2078
        return ScientificProgram.objects.filter(id__in=exploitable_sp)

5a434264   Alexis Koralewski   New version of Sc...
2079

5ce2836f   Alexis Koralewski   update models (ad...
2080
class ScientificProgram(models.Model):
5ce2836f   Alexis Koralewski   update models (ad...
2081

1ba49504   Alexis Koralewski   fixing CSS and JS...
2082
2083
2084
2085
2086
    created = models.DateTimeField(blank=True, null=True, auto_now_add=True)
    updated = models.DateTimeField(blank=True, null=True, auto_now=True)
    name = models.CharField(max_length=30, blank=False,
                            null=False, default="", unique=True)
    description_short = models.TextField(default="", max_length=320)
5a434264   Alexis Koralewski   New version of Sc...
2087
    description_long = models.TextField(default="")
1ba49504   Alexis Koralewski   fixing CSS and JS...
2088
2089
2090
2091
2092
2093
    institute = models.ForeignKey(
        Institute, on_delete=models.DO_NOTHING, related_name="scientific_programs")
    sp_pi = models.ForeignKey(
        "PyrosUser", on_delete=models.DO_NOTHING, related_name="Scientific_Program_Users")
    science_theme = models.ForeignKey(
        "ScienceTheme", on_delete=models.DO_NOTHING, related_name="scientific_program_theme", default=1)
5a434264   Alexis Koralewski   New version of Sc...
2094
    is_auto_validated = models.BooleanField(default=False)
4a596eec   Alexis Koralewski   Updating SP, Sequ...
2095
2096
    objects = ScientificProgramManager()

5ce2836f   Alexis Koralewski   update models (ad...
2097
2098
2099
2100
    class Meta:
        managed = True
        db_table = 'scientific_program'

5ce2836f   Alexis Koralewski   update models (ad...
2101
2102
2103
    def __str__(self):
        return (str(self.name))

4a596eec   Alexis Koralewski   Updating SP, Sequ...
2104

5ce2836f   Alexis Koralewski   update models (ad...
2105
class SP_Period(models.Model):
5a434264   Alexis Koralewski   New version of Sc...
2106
2107
2108
2109
2110
2111
    STATUSES_DRAFT = "Draft"
    STATUSES_SUBMITTED = "Submitted"
    STATUSES_EVALUATED = "Evaluated"
    STATUSES_ACCEPTED = "Accepted"
    STATUSES_REJECTED = "Rejected"
    STATUSES = [
1ba49504   Alexis Koralewski   fixing CSS and JS...
2112
2113
2114
2115
2116
        (STATUSES_DRAFT, "Draft"),
        (STATUSES_SUBMITTED, "Submitted"),
        (STATUSES_EVALUATED, "Evaluated"),
        (STATUSES_ACCEPTED, "Accepted"),
        (STATUSES_REJECTED, "Rejected")
5a434264   Alexis Koralewski   New version of Sc...
2117
2118
2119
2120
2121
    ]
    VOTES_YES = "A: Accepted"
    VOTES_NO = "C: Refused"
    VOTES_TO_DISCUSS = "B: To be discussed"
    VOTES = [
1ba49504   Alexis Koralewski   fixing CSS and JS...
2122
2123
2124
        (VOTES_YES, "A: Accepted"),
        (VOTES_TO_DISCUSS, "B: To be discussed"),
        (VOTES_NO, "C: Refused")
5a434264   Alexis Koralewski   New version of Sc...
2125
2126
2127
2128
    ]
    IS_VALID_ACCEPTED = "Accepted"
    IS_VALID_REJECTED = "Rejected"
    IS_VALID = [
1ba49504   Alexis Koralewski   fixing CSS and JS...
2129
2130
        (IS_VALID_ACCEPTED, "Accepted"),
        (IS_VALID_REJECTED, "Rejected")
5a434264   Alexis Koralewski   New version of Sc...
2131
2132
2133
2134
2135
    ]

    VISIBILITY_YES = "Yes"
    VISIBILITY_NO = "No"
    VISIBILITY_CHOICES = [
1ba49504   Alexis Koralewski   fixing CSS and JS...
2136
2137
        (VISIBILITY_YES, "Yes"),
        (VISIBILITY_NO, "No"),
5a434264   Alexis Koralewski   New version of Sc...
2138
    ]
1ba49504   Alexis Koralewski   fixing CSS and JS...
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
    period = models.ForeignKey(
        Period, on_delete=models.DO_NOTHING, related_name="SP_Periods")
    scientific_program = models.ForeignKey(
        ScientificProgram, on_delete=models.DO_NOTHING, related_name="SP_Periods")
    public_visibility = models.TextField(
        choices=VISIBILITY_CHOICES, default=VISIBILITY_YES)
    referee1 = models.ForeignKey(
        PyrosUser, on_delete=models.DO_NOTHING, related_name="TAC1_judgement", null=True)
    vote_referee1 = models.TextField(
        choices=VOTES, default=VOTES_YES, blank=True)
5a434264   Alexis Koralewski   New version of Sc...
2149
    reason_referee1 = models.TextField(blank=True)
1ba49504   Alexis Koralewski   fixing CSS and JS...
2150
2151
2152
2153
    referee2 = models.ForeignKey(
        PyrosUser, on_delete=models.DO_NOTHING, related_name="TAC2_judgement", null=True)
    vote_referee2 = models.TextField(
        choices=VOTES, default=VOTES_YES, blank=True)
5a434264   Alexis Koralewski   New version of Sc...
2154
    reason_referee2 = models.TextField(blank=True)
1ba49504   Alexis Koralewski   fixing CSS and JS...
2155
2156
2157
    is_valid = models.TextField(
        choices=IS_VALID, default=IS_VALID_REJECTED, blank=True)
    status = models.TextField(choices=STATUSES, default=STATUSES_DRAFT)
5a434264   Alexis Koralewski   New version of Sc...
2158
2159
    quota_minimal = models.PositiveIntegerField(default=0)
    quota_nominal = models.PositiveIntegerField(default=0)
1ba49504   Alexis Koralewski   fixing CSS and JS...
2160
2161
    quota_allocated = models.PositiveIntegerField(default=0, blank=True)
    quota_remaining = models.PositiveIntegerField(default=0, blank=True)
5a434264   Alexis Koralewski   New version of Sc...
2162
    over_quota_duration = models.PositiveIntegerField(default=0)
1ba49504   Alexis Koralewski   fixing CSS and JS...
2163
2164
2165
    over_quota_duration_allocated = models.PositiveIntegerField(
        default=0, blank=True)
    over_quota_duration_remaining = models.PositiveIntegerField(default=0)
5a434264   Alexis Koralewski   New version of Sc...
2166
    token = models.PositiveIntegerField(default=0)
1ba49504   Alexis Koralewski   fixing CSS and JS...
2167
2168
2169
    token_allocated = models.PositiveIntegerField(default=0, blank=True)
    token_remaining = models.PositiveIntegerField(default=0, blank=True)
    priority = models.PositiveIntegerField(default=0, blank=True)
5a434264   Alexis Koralewski   New version of Sc...
2170

5ce2836f   Alexis Koralewski   update models (ad...
2171
2172
    def is_currently_active(self):
        return self.period.is_currently_active()
5a434264   Alexis Koralewski   New version of Sc...
2173

4a596eec   Alexis Koralewski   Updating SP, Sequ...
2174
2175
2176
    def can_submit_sequence(self) -> bool:
        return self.is_currently_active() or self.period.can_submit_sequence() and self.status == self.STATUSES_ACCEPTED

864ec466   Alexis Koralewski   Renaming common t...
2177
2178
    class Meta:
        db_table = "sp_period"
1ba49504   Alexis Koralewski   fixing CSS and JS...
2179

5ce2836f   Alexis Koralewski   update models (ad...
2180
class SP_Period_User(models.Model):
1ba49504   Alexis Koralewski   fixing CSS and JS...
2181
2182
2183
2184
    SP_Period = models.ForeignKey(
        SP_Period, on_delete=models.DO_NOTHING, related_name="SP_Period_Users")
    user = models.ForeignKey(
        "PyrosUser", on_delete=models.CASCADE, related_name="SP_Period_Users")
5a434264   Alexis Koralewski   New version of Sc...
2185
    #is_SP_PI = models.BooleanField(default=False)
5ce2836f   Alexis Koralewski   update models (ad...
2186

5a434264   Alexis Koralewski   New version of Sc...
2187
2188
    class Meta:
        unique_together = ('SP_Period', 'user')
864ec466   Alexis Koralewski   Renaming common t...
2189
        db_table = "sp_period_user"
1ba49504   Alexis Koralewski   fixing CSS and JS...
2190
2191


5a434264   Alexis Koralewski   New version of Sc...
2192
class SP_Period_Guest(models.Model):
1ba49504   Alexis Koralewski   fixing CSS and JS...
2193
2194
    SP_Period = models.ForeignKey(
        SP_Period, on_delete=models.DO_NOTHING, related_name="SP_Period_Guests")
5a434264   Alexis Koralewski   New version of Sc...
2195
    email = models.EmailField(max_length=254)
a6e63604   Alexis Koralewski   adding agentSP an...
2196

864ec466   Alexis Koralewski   Renaming common t...
2197
2198
    class Meta:
        db_table = "sp_period_guest"
1ba49504   Alexis Koralewski   fixing CSS and JS...
2199

a6e63604   Alexis Koralewski   adding agentSP an...
2200
2201
2202
2203
2204
2205
class SP_PeriodWorkflow(models.Model):
    SUBMISSION = "SUB"
    EVALUATION = "EVAL"
    VALIDATION = "VALI"
    NOTIFICATION = "NOTI"
    ACTIONS_CHOICES = (
1ba49504   Alexis Koralewski   fixing CSS and JS...
2206
2207
2208
2209
        (SUBMISSION, "Submission"),
        (EVALUATION, "Evaluation"),
        (VALIDATION, "Validation"),
        (NOTIFICATION, "Notification")
a6e63604   Alexis Koralewski   adding agentSP an...
2210
    )
1ba49504   Alexis Koralewski   fixing CSS and JS...
2211
2212
2213
    action = models.CharField(max_length=120, choices=ACTIONS_CHOICES)
    period = models.ForeignKey(
        "Period", on_delete=models.DO_NOTHING, related_name="SP_Period_Workflows")
a6e63604   Alexis Koralewski   adding agentSP an...
2214
2215
    created = models.DateTimeField(blank=True, null=True, auto_now_add=True)

864ec466   Alexis Koralewski   Renaming common t...
2216
2217
    class Meta:
        db_table = "sp_period_workflow"
1ba49504   Alexis Koralewski   fixing CSS and JS...
2218

5ce2836f   Alexis Koralewski   update models (ad...
2219
class Sequence(models.Model):
5ce2836f   Alexis Koralewski   update models (ad...
2220
2221

    """ Definition of Status enum values """
ad3b297c   Alexis Koralewski   add pagination to...
2222
2223
    INVALID = "INVL"
    DRAFT = "DRAFT"
5ce2836f   Alexis Koralewski   update models (ad...
2224

ad3b297c   Alexis Koralewski   add pagination to...
2225
2226
    # INCOMPLETE = "INCPL"
    # COMPLETE = "CPL"
5ce2836f   Alexis Koralewski   update models (ad...
2227
2228
    TOBEPLANNED = "TBP"
    PLANNED = "PLND"
ad3b297c   Alexis Koralewski   add pagination to...
2229
    UNPLANNABLE = "UNPLN"
5ce2836f   Alexis Koralewski   update models (ad...
2230
    REJECTED = "RJTD"
ad3b297c   Alexis Koralewski   add pagination to...
2231
2232
2233
2234
2235
2236
2237
2238
2239
    REC_RUNNING = "RUN"
    REC_FINISHED = "EXD"
    REC_CANCELED = "CNCLD"
    PROC_RUNNING = "PROC_RUN"
    PROC_CANCELED = "PROC_CNCLD"
    PROC_FINISHED = "PROC_EXD"
    # PENDING = "PNDG"
    # EXECUTING = "EXING"
    # EXECUTED = "EXD"
5ce2836f   Alexis Koralewski   update models (ad...
2240
    CANCELLED = "CNCLD"
5ce2836f   Alexis Koralewski   update models (ad...
2241
    STATUS_CHOICES = (
ad3b297c   Alexis Koralewski   add pagination to...
2242
2243
        (INVALID, "Invalid"),
        (DRAFT, "DRAFT"),
5ce2836f   Alexis Koralewski   update models (ad...
2244
2245
2246
        (TOBEPLANNED, "To be planned"),
        (PLANNED, "Planned"),
        (UNPLANNABLE, "Unplannable"),
5ce2836f   Alexis Koralewski   update models (ad...
2247
        (REJECTED, "Rejected"),
ad3b297c   Alexis Koralewski   add pagination to...
2248
        (REC_RUNNING, "Recording running"),
1ba49504   Alexis Koralewski   fixing CSS and JS...
2249
        (REC_FINISHED, "Recording finished"),
ad3b297c   Alexis Koralewski   add pagination to...
2250
2251
2252
2253
        (REC_CANCELED, "Recording canceled"),
        (PROC_RUNNING, "Processing running"),
        (PROC_FINISHED, "Processing finished"),
        (PROC_CANCELED, "Processing canceled"),
5ce2836f   Alexis Koralewski   update models (ad...
2254
        (CANCELLED, "Cancelled"),
ad3b297c   Alexis Koralewski   add pagination to...
2255
2256
2257
2258
2259
    )
    START_EXPO_PREF_CHOICES = (
        ('IMMEDIATE', 'IMMEDIATE'),
        ('BEST_ELEVATION', 'BEST_ELEVATION'),
        ('NO_CONSTRAINT', 'NO_CONSTRAINT'),
5ce2836f   Alexis Koralewski   update models (ad...
2260
2261
    )

1ba49504   Alexis Koralewski   fixing CSS and JS...
2262
2263
2264
    start_expo_pref = models.CharField(max_length=50, blank=False, null=True,
                                       choices=START_EXPO_PREF_CHOICES, default=START_EXPO_PREF_CHOICES[0])
    # request = models.ForeignKey(
3b81a22b   Alexis Koralewski   Rework on Request...
2265
2266
    #    Request, on_delete=models.CASCADE, related_name="sequences")
    pyros_user = models.ForeignKey(
1ba49504   Alexis Koralewski   fixing CSS and JS...
2267
        'PyrosUser', on_delete=models.DO_NOTHING, related_name="sequences", blank=True, null=True)
3b81a22b   Alexis Koralewski   Rework on Request...
2268
2269
    scientific_program = models.ForeignKey(
        'ScientificProgram', on_delete=models.DO_NOTHING, related_name="sequences", blank=True, null=True)
bbf0ac6e   Alexis Koralewski   Adding unique con...
2270
    name = models.CharField(max_length=45, blank=True, null=True, unique=True)
5ce2836f   Alexis Koralewski   update models (ad...
2271
2272
2273
    desc = models.TextField(blank=True, null=True)
    created = models.DateTimeField(blank=True, null=True, auto_now_add=True)
    updated = models.DateTimeField(blank=True, null=True, auto_now=True)
bce55cd9   Alexis Koralewski   Reworking Sequenc...
2274
2275
    last_modified_by =  models.ForeignKey(
        'PyrosUser', on_delete=models.DO_NOTHING, related_name="+", blank=True, null=True)
5ce2836f   Alexis Koralewski   update models (ad...
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
    is_alert = models.BooleanField(default=False)
    status = models.CharField(
        max_length=11, blank=True, null=True, choices=STATUS_CHOICES)
    target_coords = models.CharField(max_length=100, blank=True, null=True)
    with_drift = models.BooleanField(default=False)
    priority = models.IntegerField(blank=True, null=True)
    analysis_method = models.CharField(max_length=45, blank=True, null=True)
    moon_min = models.IntegerField(blank=True, null=True)
    alt_min = models.IntegerField(blank=True, null=True)
    type = models.CharField(max_length=6, blank=True, null=True)
    img_current = models.CharField(max_length=45, blank=True, null=True)
    img_total = models.CharField(max_length=45, blank=True, null=True)
    not_obs = models.BooleanField(default=False)
    obsolete = models.BooleanField(default=False)
    processing = models.BooleanField(default=False)
    flag = models.CharField(max_length=45, blank=True, null=True)
1ba49504   Alexis Koralewski   fixing CSS and JS...
2292
2293
2294
2295
2296
2297
2298
2299
    period = models.ForeignKey(
        "Period", on_delete=models.DO_NOTHING, related_name="sequences", blank=True, null=True)

    start_date = models.DateTimeField(
        blank=True, null=True, default=timezone.now, editable=True)
    end_date = models.DateTimeField(
        blank=True, null=True, default=timezone.now, editable=True)
    # jd1 et jd2 = julian day start / end
5ce2836f   Alexis Koralewski   update models (ad...
2300
2301
    jd1 = models.DecimalField(default=0.0, max_digits=15, decimal_places=8)
    jd2 = models.DecimalField(default=0.0, max_digits=15, decimal_places=8)
1ba49504   Alexis Koralewski   fixing CSS and JS...
2302
2303
2304
2305
2306
    tolerance_before = models.CharField(
        max_length=50, default="1s", blank=True, null=True)
    tolerance_after = models.CharField(
        max_length=50, default="1min", blank=True, null=True)

ad3b297c   Alexis Koralewski   add pagination to...
2307
    #t_prefered = models.DecimalField(default=-1.0, max_digits=15, decimal_places=8)
5ce2836f   Alexis Koralewski   update models (ad...
2308
2309
    duration = models.DecimalField(
        default=-1.0, max_digits=15, decimal_places=8)
077d5a23   Alexis Koralewski   adding science th...
2310
    # décomposer duration en duration pointing + duration album
5ce2836f   Alexis Koralewski   update models (ad...
2311
    overhead = models.DecimalField(default=0, max_digits=15, decimal_places=8)
3b81a22b   Alexis Koralewski   Rework on Request...
2312
    submitted = models.BooleanField(default=False)
1ba49504   Alexis Koralewski   fixing CSS and JS...
2313
    config_attributes = models.JSONField(blank=True, null=True)
5ce2836f   Alexis Koralewski   update models (ad...
2314
2315
2316

    ra = models.FloatField(blank=True, null=True)
    dec = models.FloatField(blank=True, null=True)
1ba49504   Alexis Koralewski   fixing CSS and JS...
2317
    complete = models.BooleanField(default=False, null=True, blank=True)
5ce2836f   Alexis Koralewski   update models (ad...
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363

    class Meta:
        managed = True
        db_table = 'sequence'

    def __str__(self):
        return (str(self.name))


class ScheduleHasSequences(models.Model):
    # (EP) TODO: C'est pas un pb d'utiliser 2 fois le meme nom "shs" pour 2 choses differentes ???!!!
    schedule = models.ForeignKey(
        'Schedule', on_delete=models.CASCADE, related_name="shs")
    sequence = models.ForeignKey(
        'Sequence', on_delete=models.CASCADE, related_name="shs")

    status = models.CharField(
        max_length=11, blank=True, null=True, choices=Sequence.STATUS_CHOICES)
    desc = models.CharField(max_length=45, blank=True, null=True)
    tsp = models.DecimalField(default=-1.0, max_digits=15, decimal_places=8)
    tep = models.DecimalField(default=-1.0, max_digits=15, decimal_places=8)
    deltaTL = models.DecimalField(
        default=-1.0, max_digits=15, decimal_places=8)
    deltaTR = models.DecimalField(
        default=-1.0, max_digits=15, decimal_places=8)

    class Meta:
        managed = True
        db_table = 'schedule_has_sequences'


class SiteWatch(models.Model):
    OPEN = "OPEN"
    CLOSE = "CLOSE"
    ON = "ON"
    OFF = "OFF"

    global_status = models.CharField(max_length=255, blank=True, null=True)
    updated = models.DateTimeField(blank=True, null=True, auto_now=True)
    lights = models.CharField(max_length=45, blank=True, null=True)
    dome = models.CharField(max_length=45, blank=True, null=True)
    doors = models.CharField(max_length=45, blank=True, null=True)
    temperature = models.FloatField(blank=True, null=True)
    shutter = models.FloatField(blank=True, null=True)
    pressure = models.FloatField(blank=True, null=True)
    humidity = models.FloatField(blank=True, null=True)
9ee7867b   Alexis Koralewski   Fixing issue with...
2364
    power_input = models.IntegerField(blank=True, null=True)
b9068dc6   Alexis Koralewski   Adding WeatherWat...
2365
    
5ce2836f   Alexis Koralewski   update models (ad...
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
    class Meta:
        managed = True
        db_table = 'sitewatch'
        verbose_name_plural = "Site watches"

    def __str__(self):
        return (str(self.__dict__))

    # TODO
    def setGlobalStatus(self):
        self.global_status = ""
        if self.doors and self.doors.find("open") != -1:
            self.global_status += "DOOR_OPEN "
        if self.lights and self.lights == "on":
            self.global_status += "LIGHTS_ON "
        if self.temperature and float(self.temperature) > 40:
            self.global_status += "TOO_HOT "
        if self.humidity and float(self.humidity) > 80:
            self.global_status += "HUMIDITY_TOO_HIGH "
        if self.global_status == "":
            self.global_status = "OK"
        return 0

    # TODO HANDLE FLAT LAMPS ...
    def setAttribute(self, key, value):
        self.doors = ""
        if key == "InsideHumidity":
            self.humidity = value
        elif key == "Pressure":
            self.pressure = value
        elif key == "InsideTemp":
            self.temperature = value
b9068dc6   Alexis Koralewski   Adding WeatherWat...
2398
2399
2400
        elif key == "Roof_state":
            self.dome = value
        elif key == "Power_input":
9ee7867b   Alexis Koralewski   Fixing issue with...
2401
            self.power_input = value
5ce2836f   Alexis Koralewski   update models (ad...
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
        else:
            return 1
        return 0


class SiteWatchHistory(models.Model):
    id = models.IntegerField(primary_key=True)

    class Meta:
        managed = True
        db_table = 'sitewatchhistory'
        verbose_name_plural = "Site watch histories"


class StrategyObs(models.Model):
    name = models.CharField(max_length=45, blank=True, null=True)
    desc = models.TextField(blank=True, null=True)
    xml_file = models.CharField(max_length=45, blank=True, null=True)
    is_default = models.BooleanField(default=False)

    class Meta:
        managed = True
        db_table = 'strategyobs'
        verbose_name_plural = "Strategy obs"

    def __str__(self):
        return (str(self.name))


1ba49504   Alexis Koralewski   fixing CSS and JS...
2431
# TODO: à virer car utilisé pour Celery (ou bien à utiliser pour les agents)
5ce2836f   Alexis Koralewski   update models (ad...
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
class TaskId(models.Model):
    task = models.CharField(max_length=45, blank=True, null=True)
    created = models.DateTimeField(blank=True, null=True, auto_now_add=True)
    task_id = models.CharField(max_length=45, blank=True, null=True)

    class Meta:
        managed = True
        db_table = 'task_id'

    def __str__(self):
        return (str(self.task) + " - " + str(self.task_id))


5ce2836f   Alexis Koralewski   update models (ad...
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
class Telescope(Device):
    TELESCOPE = "Telescope"

    mount_type = models.CharField(max_length=9, blank=True, null=True)
    diameter = models.FloatField(blank=True, null=True)
    latitude = models.FloatField(blank=True, null=True)
    longitude = models.FloatField(blank=True, null=True)
    sens = models.CharField(max_length=1, blank=True, null=True)
    altitude = models.FloatField(blank=True, null=True)
    readout_time = models.IntegerField(blank=True, null=True)
    slew_time = models.IntegerField(blank=True, null=True)
    slew_dead = models.IntegerField(blank=True, null=True)
    slew_rate_max = models.FloatField(blank=True, null=True)
    horizon_type = models.CharField(max_length=45, blank=True, null=True)
    horizon_def = models.FloatField(blank=True, null=True)
    lim_dec_max = models.FloatField(blank=True, null=True)
    lim_dec_min = models.FloatField(blank=True, null=True)
    lim_ha_rise = models.FloatField(blank=True, null=True)
    lim_ha_set = models.FloatField(blank=True, null=True)
    address = models.CharField(max_length=45, blank=True, null=True)
    night_elev_sun = models.FloatField(blank=True, null=True)
    mpc_code = models.CharField(max_length=45, blank=True, null=True)
1ba49504   Alexis Koralewski   fixing CSS and JS...
2467

5ce2836f   Alexis Koralewski   update models (ad...
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
    class Meta:
        managed = True
        db_table = 'telescope'

    def __str__(self):
        return (self.name)


class TelescopeCommand(models.Model):
    created = models.DateTimeField(blank=True, null=True, auto_now_add=True)
    answered = models.DateTimeField(blank=True, null=True)
    request = models.CharField(blank=False, null=False, max_length=255)
    answer = models.TextField(null=True, blank=True)
1ba49504   Alexis Koralewski   fixing CSS and JS...
2481

5ce2836f   Alexis Koralewski   update models (ad...
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
    class Meta:
        managed = True
        db_table = "telescopecommand"

    def __str__(self):
        return str(self.request) + str(self.created)


class UserLevel(models.Model):
    name = models.CharField(max_length=45, blank=True, null=True)
    desc = models.TextField(blank=True, null=True)
    priority = models.IntegerField(blank=True, null=True)
    quota = models.FloatField(blank=True, null=True)

    class Meta:
        managed = True
        db_table = 'user_level'

    def __str__(self):
        return (str(self.name))


class Version(models.Model):
    module_name = models.CharField(max_length=45, blank=True, null=True)
    version = models.CharField(max_length=15, blank=True, null=True)
    created = models.DateTimeField(blank=True, null=True, auto_now_add=True)
    updated = models.DateTimeField(blank=True, null=True, auto_now=True)

    class Meta:
        managed = True
        db_table = 'version'

    def __str__(self):
        return (str(self.module_name) + " - " + str(self.version))


class WeatherWatch(models.Model):
    WIND_LIMIT = 100
    RAIN_LIMIT = 5

    global_status = models.CharField(max_length=255, blank=True, null=True)
    updated = models.DateTimeField(blank=True, null=True, auto_now=True)
    humidity = models.FloatField(blank=True, null=True)
    wind = models.FloatField(blank=True, null=True)
    wind_dir = models.CharField(max_length=45, blank=True, null=True)
    temperature = models.FloatField(blank=True, null=True)
    pressure = models.FloatField(blank=True, null=True)
    rain = models.FloatField(blank=True, null=True)
    cloud = models.FloatField(blank=True, null=True)

    class Meta:
        managed = True
        db_table = 'weatherwatch'
        verbose_name_plural = "Weather watches"

    def __str__(self):
        return (str(self.__dict__))

    # TODO
    def setGlobalStatus(self):
1ba49504   Alexis Koralewski   fixing CSS and JS...
2542
        # print(self.rain)
5ce2836f   Alexis Koralewski   update models (ad...
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
        self.global_status = ""
        if self.rain and float(self.rain) > 0:
            self.global_status += "RAINING "
        if self.wind and float(self.wind) > 80:
            self.global_status += "WIND_TOO_STRONG "
        if self.humidity and float(self.humidity) > 80:
            self.global_status += "HUMIDITY_TOO_HIGH "
        if self.cloud and float(self.cloud) > 10:
            self.global_status += "TOO_MUCH_CLOUDY "
        if self.global_status == "":
            self.global_status = "OK"
        return 0

    def setAttribute(self, key, value):
        if key == "Rain_boolean":
            self.rain = value
        elif key == "_CloudRate":
            self.cloud = value
        elif key == "Wind_speed":
            self.wind = value
        elif key == "Wind_direction":
            self.wind_dir = value
        elif key == "Temperature_outside":
            self.temperature = value
        elif key == "Humidity_outside":
            self.humidity = value
        elif key == "_Pressure":
            self.pressure = value
        else:
            return 1
        return 0


class WeatherWatchHistory(models.Model):
b9068dc6   Alexis Koralewski   Adding WeatherWat...
2577
    weather = models.ForeignKey('WeatherWatch', on_delete=models.DO_NOTHING, related_name="weatherhistory", null=True, blank=True)
5ce2836f   Alexis Koralewski   update models (ad...
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
    datetime = models.DateTimeField(blank=True, null=True, auto_now_add=True)
    humid_int = models.FloatField(blank=True, null=True)
    humid_ext = models.CharField(max_length=45, blank=True, null=True)
    wind = models.CharField(max_length=45, blank=True, null=True)
    wind_dir = models.CharField(max_length=45, blank=True, null=True)
    temp_int = models.CharField(max_length=45, blank=True, null=True)
    temp_ext = models.CharField(max_length=45, blank=True, null=True)
    pressure = models.CharField(max_length=45, blank=True, null=True)
    rain = models.CharField(max_length=45, blank=True, null=True)
    dwn = models.CharField(max_length=45, blank=True, null=True)

800f4279   Alexis Koralewski   Updating WeatherW...
2589
2590
2591
2592
2593
2594
    humidity = models.FloatField(blank=True, null=True)
    wind = models.FloatField(blank=True, null=True)
    wind_dir = models.CharField(max_length=45, blank=True, null=True)
    temperature = models.FloatField(blank=True, null=True)
    cloud = models.FloatField(blank=True, null=True)

5ce2836f   Alexis Koralewski   update models (ad...
2595
2596
2597
2598
2599
2600
2601
    class Meta:
        managed = True
        db_table = 'weatherwatchhistory'
        verbose_name_plural = "Weather watch histories"

    def __str__(self):
        return (str(self.datetime))
b9068dc6   Alexis Koralewski   Adding WeatherWat...
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619

    def setAttribute(self, key, value):
        if key == "Rain_boolean":
            self.rain = value
        elif key == "_CloudRate":
            self.cloud = value
        elif key == "Wind_speed":
            self.wind = value
        elif key == "Wind_direction":
            self.wind_dir = value
        elif key == "Temperature_outside":
            self.temperature = value
        elif key == "Humidity_outside":
            self.humidity = value
        elif key == "_Pressure":
            self.pressure = value
        else:
            return 1
e186733f   Alexis Koralewski   Adding Majordome ...
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
        return 0

class Majordome(models.Model):
    created = models.DateTimeField(blank=True, null=True, auto_now_add=True)
    updated = models.DateTimeField(blank=True, null=True, auto_now=True)
    # Software Modes
    AUTO_MODE = "AUTO"
    MANUAL_MODE = "MANUAL"
    SOFT_MODE_CHOICES = (
        (AUTO_MODE, 'Auto mode'),
        (MANUAL_MODE, 'Manual mode'),
    )
    DAY_MODE = "DAY"
    NIGHT_MODE = "NIGHT"
    OBS_MODE_CHOICES = (
        (DAY_MODE, "Day mode"),
        (NIGHT_MODE, "Night mode")
    )
    soft_mode = models.CharField(
        choices=SOFT_MODE_CHOICES,
        default=AUTO_MODE,
        max_length=15
    )
    
    obs_mode = models.CharField(
        choices = OBS_MODE_CHOICES,
        default = DAY_MODE,
        max_length=15
    )

    @classmethod
    def object(cls):
        return cls._default_manager.first() 

    def save(self, *args, **kwargs):
        self.pk = self.id = 1
        return super().save(*args, **kwargs)