Blame view

src/common/models.py 46.6 KB
fcfc6200   Etienne Pallier   ajout nouvelle co...
1
2
3
##from __future__ import unicode_literals

from enum import Enum
a64ce70a   Etienne Pallier   AgentX specific_p...
4
from datetime import datetime, timedelta
ddf59dd4   haribo   Remaniement :
5

53787d30   Jeremy   Alert now inherit...
6
from django.contrib.auth.models import AbstractUser
3df2d31a   haribo   #3430 : dates are...
7
from django.db import models
fcfc6200   Etienne Pallier   ajout nouvelle co...
8
from django.core.validators import MaxValueValidator, MinValueValidator
082ccda3   Etienne Pallier   pyros.py : enrich...
9
from model_utils import Choices
fcfc6200   Etienne Pallier   ajout nouvelle co...
10

3df2d31a   haribo   #3430 : dates are...
11

a5f1e984   Etienne Pallier   cleanup common/mo...
12
13
14
15
16
17
18
19
20
21
22
23
24
25

''' 
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'
'''


01348735   Etienne Pallier   Bugfix pyros.py s...
26
27
28
29

"""
STYLE RULES
===========
fcfc6200   Etienne Pallier   ajout nouvelle co...
30
31
https://simpleisbetterthancomplex.com/tips/2018/02/10/django-tip-22-designing-better-models.html
https://steelkiwi.com/blog/best-practices-working-django-models-python/
01348735   Etienne Pallier   Bugfix pyros.py s...
32

fcfc6200   Etienne Pallier   ajout nouvelle co...
33
34
35
36
37
- 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)
01348735   Etienne Pallier   Bugfix pyros.py s...
38
39
40
41
42
    E.g. User, Permission, ContentType, etc.

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

fcfc6200   Etienne Pallier   ajout nouvelle co...
43
- Blank and Null Fields (https://simpleisbetterthancomplex.com/tips/2016/07/25/django-tip-8-blank-or-null.html)
01348735   Etienne Pallier   Bugfix pyros.py s...
44
45
46
    - 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.
fcfc6200   Etienne Pallier   ajout nouvelle co...
47
    Otherwise, you will end up having two possible values for “no data”, that is: None and an empty string.
01348735   Etienne Pallier   Bugfix pyros.py s...
48
49
50
51
52
53
54
55
    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)
fcfc6200   Etienne Pallier   ajout nouvelle co...
56
57
58
59
60
61
62
63
64
65
    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)
01348735   Etienne Pallier   Bugfix pyros.py s...
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

- 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()

"""



a5f1e984   Etienne Pallier   cleanup common/mo...
160
161
162
163
164
165
166
"""
------------------------
   BASE MODEL CLASSES
------------------------
"""

class Device(models.Model):
ddf59dd4   haribo   Remaniement :
167
168
169
170
    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)
a5f1e984   Etienne Pallier   cleanup common/mo...
171
172
173
174
175
176
177
178
179
180
    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))

a5f1e984   Etienne Pallier   cleanup common/mo...
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
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)
ddf59dd4   haribo   Remaniement :
196
    complete = models.BooleanField(default=False)
a5f1e984   Etienne Pallier   cleanup common/mo...
197
    submitted = models.BooleanField(default=False)
ddf59dd4   haribo   Remaniement :
198
199
200

    class Meta:
        managed = True
a5f1e984   Etienne Pallier   cleanup common/mo...
201
        db_table = 'request'
ddf59dd4   haribo   Remaniement :
202
203
204
205
206

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


a5f1e984   Etienne Pallier   cleanup common/mo...
207
208
209
210
211
212
213

"""
------------------------
   OTHER MODEL CLASSES
------------------------
"""

30b22ee6   Etienne Pallier   Agent : agentX wo...
214
class Command(models.Model):
a3015e31   Etienne Pallier   table des commandes
215
216
217
218
    """
    | id | sender | receiver | command | validity_duration_sec (default=60) | sender_deposit_time | receiver_read_time
    (l'agent destinataire en profite pour supprimer les commandes périmées qui le concernent)
    """
082ccda3   Etienne Pallier   pyros.py : enrich...
219
220
221
222
223
224
225
226

    # Receiver status codes
    """
    RSCODE_RUNNING = -1 # en cours d’exécution => une fois la cde lue
    RSCODE_EXECUTED = 0 # cde exécutée => simulé par un sleep(3) dans AgentX.core_process())
    RSCODE_PENDING = 1 # cde en attente d'exécution
    RSCODE_SKIPPED = 2 # cde ignorée (je suis idle… et j’ai ignoré cette commande, et je passe à la cde suivante) 
    RSCODE_OUTOFDATE = 3 # cde périmée 
30b22ee6   Etienne Pallier   Agent : agentX wo...
227
    CMD_STATUS_CODES = (
082ccda3   Etienne Pallier   pyros.py : enrich...
228
229
230
231
232
233
234
        RSCODE_RUNNING, # en cours d’exécution => une fois la cde lue
        RSCODE_EXECUTED, # cde exécutée => simulé par un sleep(3) dans AgentX.core_process())
        RSCODE_PENDING, # cde en attente d'exécution
        RSCODE_SKIPPED, # cde ignorée (je suis idle… et j’ai ignoré cette commande, et je passe à la cde suivante) 
        RSCODE_OUTOFDATE, # cde périmée 
    )
    """
30b22ee6   Etienne Pallier   Agent : agentX wo...
235
236
237
238
239
240
    CMD_STATUS_CODES = Choices(
        "CMD_RUNNING", # en cours d’exécution => une fois la cde lue
        "CMD_EXECUTED", # cde exécutée => simulé par un sleep(3) dans AgentX.core_process())
        "CMD_PENDING", # cde en attente d'exécution
        "CMD_SKIPPED", # cde ignorée (je suis idle… et j’ai ignoré cette commande, et je passe à la cde suivante) 
        "CMD_OUTOFDATE" # cde périmée 
082ccda3   Etienne Pallier   pyros.py : enrich...
241
242
    )

30b22ee6   Etienne Pallier   Agent : agentX wo...
243
244
    GENERIC_COMMANDS = ["go_idle", "go_active", "stop"]

a64ce70a   Etienne Pallier   AgentX specific_p...
245
246
247
248
    #COMMANDS_PEREMPTION_HOURS = 48
    COMMANDS_PEREMPTION_HOURS = 60/60


a3015e31   Etienne Pallier   table des commandes
249
    #sender = models.CharField(max_length=50, blank=True, null=True, unique=True)
082ccda3   Etienne Pallier   pyros.py : enrich...
250
251
    sender = models.CharField(max_length=50, help_text='sender agent name')
    receiver = models.CharField(max_length=50)
968d1a72   Alain Klotz   Modfis database s...
252
    command = models.CharField(max_length=400)
082ccda3   Etienne Pallier   pyros.py : enrich...
253
    validity_duration_sec = models.PositiveIntegerField(default=60)
8791e3ec   Etienne Pallier   Agent.py improvem...
254
255

    # Automatically set at table line creation (line created by the sender)
a3015e31   Etienne Pallier   table des commandes
256
    sender_deposit_time = models.DateTimeField(blank=True, null=True, auto_now_add=True)
8791e3ec   Etienne Pallier   Agent.py improvem...
257

082ccda3   Etienne Pallier   pyros.py : enrich...
258
259
260
261
262
    # Set by the receiver :
    # - at reading time
    receiver_read_time = models.DateTimeField(null=True)
    # - after execution
    receiver_processed_time = models.DateTimeField(null=True)
30b22ee6   Etienne Pallier   Agent : agentX wo...
263
264
    receiver_status_code = models.CharField(choices = CMD_STATUS_CODES, default=CMD_STATUS_CODES.CMD_PENDING, max_length=20)
    #receiver_status_code = models.IntegerField(choices=CMD_STATUS_CODES, default=RSCODE_PENDING)
082ccda3   Etienne Pallier   pyros.py : enrich...
265
266
    # TODO: maybe à mettre au format json (key:value)
    result = models.CharField(max_length=400, blank=True)
a3015e31   Etienne Pallier   table des commandes
267
268
269

    class Meta:
        managed = True
30b22ee6   Etienne Pallier   Agent : agentX wo...
270
        db_table = 'command'
a3015e31   Etienne Pallier   table des commandes
271
272
273
274
        #verbose_name = "agent survey"
        #verbose_name_plural = "agents survey"

    def __str__(self):
a64ce70a   Etienne Pallier   AgentX specific_p...
275
276
277
278
279
280
281
282
283
284
285
286
287
288
        return (f"Commmand '{self.command}' sent by agent {self.sender} to agent {self.receiver} at {self.sender_deposit_time}")


    @classmethod
    def get_old_commands_for_agent(cls, receiver_name):
        COMMAND_PEREMPTION_DATE_FROM_NOW = datetime.utcnow() - timedelta(hours = cls.COMMANDS_PEREMPTION_HOURS)
        #print("peremption date", COMMAND_PEREMPTION_DATE_FROM_NOW)
        return cls.objects.filter(
            # only commands for me
            receiver = receiver_name,
            # only pending commands
            sender_deposit_time__lt = COMMAND_PEREMPTION_DATE_FROM_NOW,
        )

30b22ee6   Etienne Pallier   Agent : agentX wo...
289
290
291
292
293
294
295

    def is_generic(self):
        """
        Is this a generic command ?
        It is the case if command is of style "go_idle" or "go_active" or "stop"...
        """
        return self.command in self.GENERIC_COMMANDS
a3015e31   Etienne Pallier   table des commandes
296

a64ce70a   Etienne Pallier   AgentX specific_p...
297
    def is_expired(self):
aa9683a7   Etienne Pallier   bugfix timezone
298
299
        #return (datetime.utcnow() - self.sender_deposit_time) > timedelta(seconds = self.validity_duration_sec)
        return (datetime.utcnow().astimezone() - self.sender_deposit_time) > timedelta(seconds = self.validity_duration_sec)
a64ce70a   Etienne Pallier   AgentX specific_p...
300
301
302
303
304
305
306
        """
        elapsed_time = cmd.receiver_read_time - cmd.sender_deposit_time
        max_time = timedelta(seconds = cmd.validity_duration_sec)
        print(f"Elapsed time is {elapsed_time}, (max is {max_time})")
        if elapsed_time > max_time:
        """

a64ce70a   Etienne Pallier   AgentX specific_p...
307
    def set_read_time(self):
3381a718   Etienne Pallier   Agent : command p...
308
309
        self.receiver_read_time = datetime.utcnow()
        self.save()
a64ce70a   Etienne Pallier   AgentX specific_p...
310
311
312
313
    def set_as_processed(self):
        self.receiver_status_code = self.CMD_STATUS_CODES.CMD_EXECUTED
        self.receiver_processed_time = datetime.utcnow()
        self.save()
3381a718   Etienne Pallier   Agent : command p...
314
315
316
317
318
319
320

    def set_as_outofdate(self):
        self.set_status_to(self.CMD_STATUS_CODES.CMD_OUTOFDATE)
    def set_as_skipped(self):
        self.set_status_to(self.CMD_STATUS_CODES.CMD_SKIPPED)
    def set_as_running(self):
        self.set_status_to(self.CMD_STATUS_CODES.CMD_RUNNING)
a64ce70a   Etienne Pallier   AgentX specific_p...
321
    '''
3381a718   Etienne Pallier   Agent : command p...
322
323
    def set_as_executed(self):
        self.set_status_to(self.CMD_STATUS_CODES.CMD_EXECUTED)
a64ce70a   Etienne Pallier   AgentX specific_p...
324
    '''
3381a718   Etienne Pallier   Agent : command p...
325
326
327
328
329

    def set_status_to(self, status:str):
        self.receiver_status_code = status
        self.save()

a3015e31   Etienne Pallier   table des commandes
330

082ccda3   Etienne Pallier   pyros.py : enrich...
331
class AgentSurvey(models.Model):
0d065f79   Etienne Pallier   new migration fil...
332
    """
a3015e31   Etienne Pallier   table des commandes
333
    | id | name | created | updated | validity_duration_sec (default=1mn) | mode (active/idle) | status (launch/init/loop/exit/...) |
0d065f79   Etienne Pallier   new migration fil...
334
    """
fcfc6200   Etienne Pallier   ajout nouvelle co...
335
336
337
    
    #STATUSES = Choices('new', 'verified', 'published')

01348735   Etienne Pallier   Bugfix pyros.py s...
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
    # Statuses
    STATUS_LAUNCH = "LAUNCHED"
    STATUS_INIT = "INITIALIZING"
    STATUS_MAIN_LOOP = "IN_MAIN_LOOP"
    STATUS_PROCESS_LOOP = "IN_PROCESS_LOOP"
    STATUS_EXIT = "EXITING"

    # Modes
    MODE_ACTIVE = "ACTIVE"
    MODE_IDLE = "IDLE"

    MODE_CHOICES = (
        (MODE_ACTIVE, 'Active mode'),
        (MODE_IDLE, 'Idle mode'),
    )

    STATUS_CHOICES = (
        (STATUS_LAUNCH, "LAUNCHED"),
        (STATUS_INIT, "INITIALIZING"),
        (STATUS_MAIN_LOOP, "IN_MAIN_LOOP"),
        (STATUS_PROCESS_LOOP, "IN_PROCESS_LOOP"),
        (STATUS_EXIT, "EXITING"),
    )

fcfc6200   Etienne Pallier   ajout nouvelle co...
362
363
    name = models.CharField(max_length=50, unique=True)
    #name = models.CharField(max_length=50, blank=True, null=True, unique=True)
a3015e31   Etienne Pallier   table des commandes
364
365
    #created = models.DateTimeField(blank=True, null=True, auto_now_add=True)
    created = models.DateTimeField(blank=True, null=True, auto_now_add=True)
a5f1e984   Etienne Pallier   cleanup common/mo...
366
    updated = models.DateTimeField(blank=True, null=True, auto_now=True)
082ccda3   Etienne Pallier   pyros.py : enrich...
367
368
    validity_duration_sec = models.PositiveIntegerField(default=90)
    #validity_duration_sec = models.DurationField(default=90)
fcfc6200   Etienne Pallier   ajout nouvelle co...
369
370
    mode = models.CharField('agent mode', max_length=15, blank=True, choices=MODE_CHOICES)
    status = models.CharField(max_length=15, blank=True, choices=STATUS_CHOICES)
ddf59dd4   haribo   Remaniement :
371
372
373

    class Meta:
        managed = True
082ccda3   Etienne Pallier   pyros.py : enrich...
374
        db_table = 'agent_survey'
01348735   Etienne Pallier   Bugfix pyros.py s...
375
376
        #verbose_name = "agent survey"
        #verbose_name_plural = "agents survey"
ddf59dd4   haribo   Remaniement :
377
378

    def __str__(self):
24d6b29e   Etienne Pallier   Agent with db_sur...
379
        return (f"Agent {self.name} at {self.updated} in mode {self.mode} and status {self.status}")
ddf59dd4   haribo   Remaniement :
380

ce470283   Jeremy   Plc simulator fin...
381

a5f1e984   Etienne Pallier   cleanup common/mo...
382
383
384
385
386
class Album(models.Model):
    sequence = models.ForeignKey(
        'Sequence', on_delete=models.CASCADE, related_name="albums")
    detector = models.ForeignKey(
        'Detector', models.DO_NOTHING, related_name="albums", blank=True, null=True)
abfb02e2   Jeremy   Device Model is n...
387
388
389
390
    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)
a5f1e984   Etienne Pallier   cleanup common/mo...
391
    complete = models.BooleanField(default=False)
abfb02e2   Jeremy   Device Model is n...
392
393

    class Meta:
a5f1e984   Etienne Pallier   cleanup common/mo...
394
395
        managed = True
        db_table = 'album'
01348735   Etienne Pallier   Bugfix pyros.py s...
396
        #verbose_name_plural = "Albums"
abfb02e2   Jeremy   Device Model is n...
397
398
399
400

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

a5f1e984   Etienne Pallier   cleanup common/mo...
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419

class Alert(Request):
    request = models.OneToOneField('Request', on_delete=models.CASCADE, default='', parent_link=True)
    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)
    burst_jd = models.DecimalField(max_digits=15, decimal_places=8, blank=True, null=True)
    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)
    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)
    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)
6c2793c2   jeremy   Update
420
421
422

    class Meta:
        managed = True
a5f1e984   Etienne Pallier   cleanup common/mo...
423
        db_table = 'alert'
6c2793c2   jeremy   Update
424
425

    def __str__(self):
a5f1e984   Etienne Pallier   cleanup common/mo...
426
        return str(self.trig_id)
6c2793c2   jeremy   Update
427

a5f1e984   Etienne Pallier   cleanup common/mo...
428
429
    def request_name(self):
        return self.__str__()
fe5613f5   jeremy   Update plc protocol
430

a5f1e984   Etienne Pallier   cleanup common/mo...
431
432
433
434
435
436
437
438
    request_name.short_description = "Name"



class Config(models.Model):
    PYROS_STATE = ["Starting", "Passive", "Standby", "Remote", "Startup", "Scheduler", "Closing" ]

    id = models.IntegerField(default='1', primary_key=True)
fcfc6200   Etienne Pallier   ajout nouvelle co...
439
440
441
442
443
444
445
446
447
    #latitude = models.FloatField(default=1)
    latitude = models.DecimalField(
        max_digits=4, decimal_places=2, 
        default=1,
        validators=[
            MaxValueValidator(90),
            MinValueValidator(-90)
        ]
    )
a5f1e984   Etienne Pallier   cleanup common/mo...
448
    local_time_zone = models.FloatField(default=1)
fcfc6200   Etienne Pallier   ajout nouvelle co...
449
450
451
452
453
454
455
456
457
    #longitude = models.FloatField(default=1)
    longitude = models.DecimalField(
        max_digits=5, decimal_places=2, 
        default=1,
        validators=[
            MaxValueValidator(360),
            MinValueValidator(-360)
        ]
    )
a5f1e984   Etienne Pallier   cleanup common/mo...
458
459
460
461
462
463
464
465
    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")
6973f7df   Quentin Durand   PLC STATE + MODE
466

a5f1e984   Etienne Pallier   cleanup common/mo...
467
468
469
470
471
472
473
474
475
476
477
478
479
    # 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')
6c2793c2   jeremy   Update
480
481
482

    class Meta:
        managed = True
a5f1e984   Etienne Pallier   cleanup common/mo...
483
484
        db_table = 'config'
        verbose_name_plural = "Config"
6c2793c2   jeremy   Update
485
486

    def __str__(self):
a5f1e984   Etienne Pallier   cleanup common/mo...
487
        return (str(self.__dict__))
6c2793c2   jeremy   Update
488
489


a5f1e984   Etienne Pallier   cleanup common/mo...
490
491
492
493
494
495
496
497
498
499
500
501
502

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))
6c2793c2   jeremy   Update
503

abfb02e2   Jeremy   Device Model is n...
504
505
506
507

class Detector(Device):
    VIS = "Visible camera"
    NIR = "Cagire"
ddf59dd4   haribo   Remaniement :
508

ddf59dd4   haribo   Remaniement :
509
510
    telescope = models.ForeignKey(
        'Telescope', models.DO_NOTHING, related_name="detectors")
ddf59dd4   haribo   Remaniement :
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
    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):
f7dd3df1   Jeremy   Update simulators...
530
        return str(self.name)
ddf59dd4   haribo   Remaniement :
531
532
533
534
535
536

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


a5f1e984   Etienne Pallier   cleanup common/mo...
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
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"



abfb02e2   Jeremy   Device Model is n...
555
class Filter(Device):
ddf59dd4   haribo   Remaniement :
556
557
558
559
560
    VIS_FILTER_1 = "First visible filter"
    VIS_FILTER_2 = "Second visible filter"
    NIR_FILTER_1 = "First infrared filter"
    NIR_FILTER_2 = "Second infrared filter"

ddf59dd4   haribo   Remaniement :
561
562
563
564
565
566
567
568
569
570
571
    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):
f7dd3df1   Jeremy   Update simulators...
572
        return (str(self.name))
ddf59dd4   haribo   Remaniement :
573
574
575
576
577
578

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


abfb02e2   Jeremy   Device Model is n...
579
class FilterWheel(Device):
ce470283   Jeremy   Plc simulator fin...
580
581
    detector = models.OneToOneField(Detector, on_delete=models.CASCADE,
                                    related_name="filter_wheel", blank=True, null=True)
ddf59dd4   haribo   Remaniement :
582
583
584
585
586
587

    class Meta:
        managed = True
        db_table = 'filter_wheel'

    def __str__(self):
f7dd3df1   Jeremy   Update simulators...
588
        return (str(self.name))
ddf59dd4   haribo   Remaniement :
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635

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


class Image(models.Model):
    plan = models.ForeignKey('Plan', on_delete=models.CASCADE, related_name="images")
    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
a5f1e984   Etienne Pallier   cleanup common/mo...
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
        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))


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))




class PlcDeviceStatus(models.Model):
    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)
    outside_temp_unit = models.CharField(max_length=45, blank=True, null=True)
    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)
    pressure_unit = models.CharField(max_length=45, blank=True, null=True)
    rain_rate = models.DecimalField(max_digits=15, decimal_places=8, blank=True, null=True)
    rain_rate_unit = models.CharField(max_length=45, blank=True, null=True)
    wind_speed = models.DecimalField(max_digits=15, decimal_places=8, blank=True, null=True)
    wind_speed_unit = models.CharField(max_length=45, blank=True, null=True)
    wind_dir = models.DecimalField(max_digits=15, decimal_places=8, blank=True, null=True)
    wind_dir_unit = models.CharField(max_length=45, blank=True, null=True)
    dew_point = models.DecimalField(max_digits=15, decimal_places=8, blank=True, null=True)
    dew_point_unit = models.CharField(max_length=45, blank=True, null=True)
    analog = models.DecimalField(max_digits=15, decimal_places=8, blank=True, null=True)
    analog_unit = models.CharField(max_length=45, blank=True, null=True)
    digital = models.DecimalField(max_digits=15, decimal_places=8, blank=True, null=True)
    digital_unit = models.CharField(max_length=45, blank=True, null=True)
    inside_temp = models.DecimalField(max_digits=15, decimal_places=8, blank=True, null=True)
    inside_temp_unit = models.CharField(max_length=45, blank=True, null=True)
    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)
    wind_dir_cardinal = models.CharField(max_length=45, blank=True, null=True)
    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)
    status = models.CharField(max_length=45, blank=True, null=True)
    current = models.DecimalField(max_digits=15, decimal_places=8, blank=True, null=True)
    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'
ddf59dd4   haribo   Remaniement :
724
725

    def __str__(self):
a5f1e984   Etienne Pallier   cleanup common/mo...
726
        return (str(self.__dict__))
ddf59dd4   haribo   Remaniement :
727

a5f1e984   Etienne Pallier   cleanup common/mo...
728
729
730
731
732
733
    '''
        TODO : This function is Ugly,
        we should change this with a function pointer array
        and setters getters for each attribute
    '''
    def setValue(self, key, value, unit=""):
8c772a38   Patrick Maeght   document it
734
        if key == "Temperature_outside":
a5f1e984   Etienne Pallier   cleanup common/mo...
735
736
            self.outside_temp = value
            self.outside_temp_unit = unit
8c772a38   Patrick Maeght   document it
737
        elif key == "Humidity_outside":
a5f1e984   Etienne Pallier   cleanup common/mo...
738
739
            self.outside_humidity = value
            self.outside_humidity_unit = unit
8c772a38   Patrick Maeght   document it
740
        elif key == "_Pressure":
a5f1e984   Etienne Pallier   cleanup common/mo...
741
742
            self.pressure = value
            self.pressure_unit = unit
8c772a38   Patrick Maeght   document it
743
        elif key == "Rain_boolean": # RainRate
a5f1e984   Etienne Pallier   cleanup common/mo...
744
            self.rain_rate = value
8c772a38   Patrick Maeght   document it
745
746
            self.rain_rate_unit = 'boulean'
        elif key == "Wind_speed":
a5f1e984   Etienne Pallier   cleanup common/mo...
747
748
            self.wind_speed = value
            self.wind_speed_unit = unit
8c772a38   Patrick Maeght   document it
749
        elif key == "Wind_dir":
a5f1e984   Etienne Pallier   cleanup common/mo...
750
751
            self.wind_dir = value
            self.wind_dir_unit = unit
8c772a38   Patrick Maeght   document it
752
        elif key == "_DewPoint":
a5f1e984   Etienne Pallier   cleanup common/mo...
753
754
            self.dew_point = value
            self.dew_point_unit = unit
8c772a38   Patrick Maeght   document it
755
        elif key == "_analog":
a5f1e984   Etienne Pallier   cleanup common/mo...
756
757
            self.analog = value
            self.analog_unit = unit
8c772a38   Patrick Maeght   document it
758
        elif key == "_digital":
a5f1e984   Etienne Pallier   cleanup common/mo...
759
760
            self.digital = value
            self.digital_unit = unit
8c772a38   Patrick Maeght   document it
761
        elif key == "_InsideTemp":
a5f1e984   Etienne Pallier   cleanup common/mo...
762
763
            self.inside_temp = value
            self.inside_temp_unit = unit
8c772a38   Patrick Maeght   document it
764
        elif key == "_InsideHumidity":
a5f1e984   Etienne Pallier   cleanup common/mo...
765
766
            self.inside_humidity = value
            self.inside_humidity_unit = unit
8c772a38   Patrick Maeght   document it
767
        elif key == "_WindDirCardinal":
a5f1e984   Etienne Pallier   cleanup common/mo...
768
769
            self.wind_dir_cardinal = value
            self.wind_dir_cardinal_unit = unit
8c772a38   Patrick Maeght   document it
770
        elif key == "_SensorTemperature":
a5f1e984   Etienne Pallier   cleanup common/mo...
771
772
            self.sensor_temperature = value
            self.sensor_temperature_unit = unit
8c772a38   Patrick Maeght   document it
773
        elif key == "_SkyTemperature":
a5f1e984   Etienne Pallier   cleanup common/mo...
774
775
            self.sky_temperature = value
            self.sky_temperature_unit = unit
8c772a38   Patrick Maeght   document it
776
777
        # PM 20190222 try patch
        elif key == "Error_code":
a5f1e984   Etienne Pallier   cleanup common/mo...
778
779
780
781
782
783
784
785
786
787
788
789
790
            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:
8c772a38   Patrick Maeght   document it
791
792
793
            # PM 20190222 ignore unrecognized
            #raise KeyError("Key " + str(key) + " unrecognized")
            pass
ddf59dd4   haribo   Remaniement :
794

a5f1e984   Etienne Pallier   cleanup common/mo...
795
796
class PlcDevice(Device):
    #device = models.ForeignKey('Plc', on_delete=models.CASCADE, related_name='plc_devices')
ddf59dd4   haribo   Remaniement :
797
798
799
800
    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)
a5f1e984   Etienne Pallier   cleanup common/mo...
801

ddf59dd4   haribo   Remaniement :
802
803
804

    class Meta:
        managed = True
a5f1e984   Etienne Pallier   cleanup common/mo...
805
        db_table = 'plc_devices'
ddf59dd4   haribo   Remaniement :
806
807

    def __str__(self):
a5f1e984   Etienne Pallier   cleanup common/mo...
808
        return str(self.name)
ddf59dd4   haribo   Remaniement :
809

ddf59dd4   haribo   Remaniement :
810

a5f1e984   Etienne Pallier   cleanup common/mo...
811
812
813
814
815
816
#class Plc(Device):
 #   last_update_status = models.DateTimeField(blank=True, null=True)
#    i
 #   class Meta:
  #      managed = True
   #     db_table = 'plc'
ddf59dd4   haribo   Remaniement :
817

ddf59dd4   haribo   Remaniement :
818
819


53787d30   Jeremy   Alert now inherit...
820
class PyrosUser(AbstractUser):
2c61f856   theopuhl   Url change to pat...
821
    username = models.CharField(max_length=255, blank=False, null=False, unique=True)
c5ae1cae   theopuhl   Add send mail + v...
822
823
    is_active = models.BooleanField(default='False')
    first_time = models.BooleanField(default='False')
ddf59dd4   haribo   Remaniement :
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
    country = models.ForeignKey(
        Country, on_delete=models.DO_NOTHING, related_name="pyros_users")
    user_level = models.ForeignKey(
        'UserLevel', on_delete=models.DO_NOTHING, 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)
    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)

    class Meta:
        managed = True
        db_table = 'pyros_user'

    def __str__(self):
53787d30   Jeremy   Alert now inherit...
852
        return (str(self.get_username()))
ddf59dd4   haribo   Remaniement :
853
854
855
856
857
858

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


53787d30   Jeremy   Alert now inherit...
859

53787d30   Jeremy   Alert now inherit...
860

53787d30   Jeremy   Alert now inherit...
861

ddf59dd4   haribo   Remaniement :
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922

# 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))


class ScientificProgram(models.Model):
    pyros_users = models.ManyToManyField(
        'PyrosUser', related_name="scientific_programs")
    name = models.CharField(max_length=45, blank=True, null=True)
    desc = models.TextField(blank=True, null=True)
    quota = models.FloatField(blank=True, null=True)
    priority = models.IntegerField(blank=True, null=True)

    class Meta:
        managed = True
        db_table = 'scientific_program'

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


class Sequence(models.Model):

    """ Definition of Status enum values """

    INCOMPLETE = "INCPL"
    COMPLETE = "CPL"
    TOBEPLANNED = "TBP"
ff448d43   Jeremy   Update
923
    PLANNED = "PLND"
ddf59dd4   haribo   Remaniement :
924
    PENDING = "PNDG"
ddf59dd4   haribo   Remaniement :
925
    EXECUTING = "EXING"
ff448d43   Jeremy   Update
926
    EXECUTED = "EXD"
ddf59dd4   haribo   Remaniement :
927
    REJECTED = "RJTD"
ddf59dd4   haribo   Remaniement :
928
    INVALID = "INVL"
ff448d43   Jeremy   Update
929
930
    CANCELLED = "CNCLD"
    UNPLANNABLE = "UNPLN"
ddf59dd4   haribo   Remaniement :
931
932
933
934
    STATUS_CHOICES = (
        (INCOMPLETE, "Incomplete"),
        (COMPLETE, "Complete"),
        (TOBEPLANNED, "To be planned"),
ff448d43   Jeremy   Update
935
        (PLANNED, "Planned"),
ddf59dd4   haribo   Remaniement :
936
937
938
939
940
941
942
        (UNPLANNABLE, "Unplannable"),
        (PENDING, "Pending"),
        (EXECUTED, "Executed"),
        (EXECUTING, "Executing"),
        (REJECTED, "Rejected"),
        (CANCELLED, "Cancelled"),
        (INVALID, "Invalid"),
ddf59dd4   haribo   Remaniement :
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
    )

    request = models.ForeignKey(
        Request, on_delete=models.CASCADE, related_name="sequences")
    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)
    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)
    jd1 = models.DecimalField(default=0.0, max_digits=15, decimal_places=8)
    jd2 = models.DecimalField(default=0.0, max_digits=15, decimal_places=8)
    t_prefered = models.DecimalField(
        default=-1.0, max_digits=15, decimal_places=8)
    duration = models.DecimalField(
        default=-1.0, max_digits=15, decimal_places=8)
    overhead = models.DecimalField(default=0, max_digits=15, decimal_places=8)

    ra = models.FloatField(blank=True, null=True)
    dec = models.FloatField(blank=True, null=True)

    class Meta:
        managed = True
        db_table = 'sequence'

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


class ScheduleHasSequences(models.Model):
05bdcc44   Etienne Pallier   BIG DEMO tests (s...
987
    # (EP) TODO: C'est pas un pb d'utiliser 2 fois le meme nom "shs" pour 2 choses differentes ???!!!
ddf59dd4   haribo   Remaniement :
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
    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):
c53a13e0   Jeremy   Updating a lot of...
1009
1010
1011
1012
1013
    OPEN = "OPEN"
    CLOSE = "CLOSE"
    ON = "ON"
    OFF = "OFF"

ce470283   Jeremy   Plc simulator fin...
1014
    global_status = models.CharField(max_length=255, blank=True, null=True)
ddf59dd4   haribo   Remaniement :
1015
1016
1017
1018
1019
    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)
ce470283   Jeremy   Plc simulator fin...
1020
1021
    shutter = models.FloatField(blank=True, null=True)
    pressure = models.FloatField(blank=True, null=True)
fe5613f5   jeremy   Update plc protocol
1022
    humidity = models.FloatField(blank=True, null=True)
ddf59dd4   haribo   Remaniement :
1023
1024
1025
1026
1027
1028
1029

    class Meta:
        managed = True
        db_table = 'sitewatch'
        verbose_name_plural = "Site watches"

    def __str__(self):
678838ed   Jeremy   Weather ans insid...
1030
        return (str(self.__dict__))
ddf59dd4   haribo   Remaniement :
1031

ce470283   Jeremy   Plc simulator fin...
1032
1033
1034
    # TODO
    def setGlobalStatus(self):
        self.global_status = ""
678838ed   Jeremy   Weather ans insid...
1035
        if self.doors and self.doors.find("open") != -1:
ce470283   Jeremy   Plc simulator fin...
1036
1037
1038
            self.global_status += "DOOR_OPEN "
        if self.lights and self.lights == "on":
            self.global_status += "LIGHTS_ON "
678838ed   Jeremy   Weather ans insid...
1039
        if self.temperature and float(self.temperature) > 40:
ce470283   Jeremy   Plc simulator fin...
1040
            self.global_status += "TOO_HOT "
678838ed   Jeremy   Weather ans insid...
1041
        if self.humidity and float(self.humidity) > 80:
ce470283   Jeremy   Plc simulator fin...
1042
1043
1044
1045
1046
            self.global_status += "HUMIDITY_TOO_HIGH "
        if self.global_status == "":
            self.global_status = "OK"
        return 0

fe5613f5   jeremy   Update plc protocol
1047
    # TODO HANDLE FLAT LAMPS ...
ce470283   Jeremy   Plc simulator fin...
1048
    def setAttribute(self, key, value):
678838ed   Jeremy   Weather ans insid...
1049
        self.doors = ""
fe5613f5   jeremy   Update plc protocol
1050
        if key == "InsideHumidity":
ce470283   Jeremy   Plc simulator fin...
1051
            self.humidity = value
fe5613f5   jeremy   Update plc protocol
1052
        elif key == "Pressure":
ce470283   Jeremy   Plc simulator fin...
1053
            self.pressure = value
d66e0d93   Quentin Durand   observatory statu...
1054
1055
        elif key == "InsideTemp":
            self.temperature = value
ce470283   Jeremy   Plc simulator fin...
1056
1057
1058
1059
        else:
            return 1
        return 0

ddf59dd4   haribo   Remaniement :
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084

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))


5e45ba9f   Etienne Pallier   Bye Bye Celery (f...
1085
#TODO: à virer car utilisé pour Celery (ou bien à utiliser pour les agents)
ddf59dd4   haribo   Remaniement :
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
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))

cfc9d09c   Jeremy   Added dome simula...
1098

ddf59dd4   haribo   Remaniement :
1099

abfb02e2   Jeremy   Device Model is n...
1100
1101
1102
class Telescope(Device):
    TELESCOPE = "Telescope"

ddf59dd4   haribo   Remaniement :
1103
1104
    mount_type = models.CharField(max_length=9, blank=True, null=True)
    diameter = models.FloatField(blank=True, null=True)
ddf59dd4   haribo   Remaniement :
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
    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)
ddf59dd4   haribo   Remaniement :
1122
1123
1124
1125
1126
    class Meta:
        managed = True
        db_table = 'telescope'

    def __str__(self):
f7dd3df1   Jeremy   Update simulators...
1127
        return (self.name)
ddf59dd4   haribo   Remaniement :
1128
1129


a5f1e984   Etienne Pallier   cleanup common/mo...
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
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)
    class Meta:
        managed = True
        db_table = "telescopecommand"

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


ddf59dd4   haribo   Remaniement :
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
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))

ce470283   Jeremy   Plc simulator fin...
1170

ddf59dd4   haribo   Remaniement :
1171
class WeatherWatch(models.Model):
c53a13e0   Jeremy   Updating a lot of...
1172
1173
1174
    WIND_LIMIT = 100
    RAIN_LIMIT = 5

ce470283   Jeremy   Plc simulator fin...
1175
1176
1177
    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)
ddf59dd4   haribo   Remaniement :
1178
    wind = models.FloatField(blank=True, null=True)
fe5613f5   jeremy   Update plc protocol
1179
    wind_dir = models.CharField(max_length=45, blank=True, null=True)
ce470283   Jeremy   Plc simulator fin...
1180
    temperature = models.FloatField(blank=True, null=True)
ddf59dd4   haribo   Remaniement :
1181
1182
    pressure = models.FloatField(blank=True, null=True)
    rain = models.FloatField(blank=True, null=True)
ce470283   Jeremy   Plc simulator fin...
1183
    cloud = models.FloatField(blank=True, null=True)
ddf59dd4   haribo   Remaniement :
1184
1185
1186
1187
1188
1189
1190

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

    def __str__(self):
678838ed   Jeremy   Weather ans insid...
1191
        return (str(self.__dict__))
ddf59dd4   haribo   Remaniement :
1192

ce470283   Jeremy   Plc simulator fin...
1193
1194
    # TODO
    def setGlobalStatus(self):
fac9194f   Patrick Maeght   get_sensor set d...
1195
        #print(self.rain)
ce470283   Jeremy   Plc simulator fin...
1196
        self.global_status = ""
e15030dc   Patrick Maeght   penelope work part 2
1197
        if self.rain and float(self.rain) > 0:
ce470283   Jeremy   Plc simulator fin...
1198
            self.global_status += "RAINING "
678838ed   Jeremy   Weather ans insid...
1199
        if self.wind and float(self.wind) > 80:
ce470283   Jeremy   Plc simulator fin...
1200
            self.global_status += "WIND_TOO_STRONG "
678838ed   Jeremy   Weather ans insid...
1201
        if self.humidity and float(self.humidity) > 80:
ce470283   Jeremy   Plc simulator fin...
1202
            self.global_status += "HUMIDITY_TOO_HIGH "
678838ed   Jeremy   Weather ans insid...
1203
        if self.cloud and float(self.cloud) > 10:
ce470283   Jeremy   Plc simulator fin...
1204
1205
1206
1207
1208
1209
            self.global_status += "TOO_MUCH_CLOUDY "
        if self.global_status == "":
            self.global_status = "OK"
        return 0

    def setAttribute(self, key, value):
e15030dc   Patrick Maeght   penelope work part 2
1210
        if key == "Rain_boolean":
ce470283   Jeremy   Plc simulator fin...
1211
            self.rain = value
e15030dc   Patrick Maeght   penelope work part 2
1212
        elif key == "_CloudRate":
ce470283   Jeremy   Plc simulator fin...
1213
            self.cloud = value
e15030dc   Patrick Maeght   penelope work part 2
1214
        elif key == "Wind_speed":
ce470283   Jeremy   Plc simulator fin...
1215
            self.wind = value
e15030dc   Patrick Maeght   penelope work part 2
1216
        elif key == "Wind_direction":
ce470283   Jeremy   Plc simulator fin...
1217
            self.wind_dir = value
e15030dc   Patrick Maeght   penelope work part 2
1218
        elif key == "Temperature_outside":
ce470283   Jeremy   Plc simulator fin...
1219
            self.temperature = value
e15030dc   Patrick Maeght   penelope work part 2
1220
        elif key == "Humidity_outside":
ce470283   Jeremy   Plc simulator fin...
1221
            self.humidity = value
e15030dc   Patrick Maeght   penelope work part 2
1222
        elif key == "_Pressure":
ce470283   Jeremy   Plc simulator fin...
1223
1224
1225
1226
1227
            self.pressure = value
        else:
            return 1
        return 0

ddf59dd4   haribo   Remaniement :
1228
1229
1230

class WeatherWatchHistory(models.Model):
    datetime = models.DateTimeField(blank=True, null=True, auto_now_add=True)
e31b2208   theophile.puhl@epitech.eu   Severals Changes ...
1231
    humid_int = models.FloatField(blank=True, null=True)
ddf59dd4   haribo   Remaniement :
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
    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)

    class Meta:
        managed = True
        db_table = 'weatherwatchhistory'
        verbose_name_plural = "Weather watch histories"

    def __str__(self):
        return (str(self.datetime))
e31b2208   theophile.puhl@epitech.eu   Severals Changes ...

e31b2208   theophile.puhl@epitech.eu   Severals Changes ...

e6eb923f   Quentin Durand   Prototype agent t...

e6eb923f   Quentin Durand   Prototype agent t...