Blame view

src/majordome/tasks.py 19.7 KB
5b5566ab   haribo   added celery
1
from __future__ import absolute_import
ce470283   Jeremy   Plc simulator fin...
2

5b5566ab   haribo   added celery
3
from celery.task import Task
ce470283   Jeremy   Plc simulator fin...
4
5
6
from django.core.exceptions import ObjectDoesNotExist
from django.db.models import Q

9774228b   haribo   Date: 22/06/2016
7
import observation_manager
abfb02e2   Jeremy   Device Model is n...
8
import observation_manager.tasks
ce470283   Jeremy   Plc simulator fin...
9
10
11
12
import scheduler
import scheduler.tasks as sched_task
import utils.Logger as L
from common.models import *
65149de7   Jeremy   Update
13
from devices.CameraNIR import NIRCameraController
ce470283   Jeremy   Plc simulator fin...
14
from devices.CameraVIS import VISCameraController
cfc9d09c   Jeremy   Added dome simula...
15
from devices.Dome import DomeController
65149de7   Jeremy   Update
16
from devices.PLC import PLCController
ce470283   Jeremy   Plc simulator fin...
17
18
from devices.Telescope import TelescopeController
from majordome.MajordomeDecorators import *
65149de7   Jeremy   Update
19
from utils.JDManipulator import *
cfc9d09c   Jeremy   Added dome simula...
20

ff448d43   Jeremy   Update
21
DEBUG_FILE = False
65149de7   Jeremy   Update
22
log = L.setupLogger("MajordomeTaskLogger", "Majordome")
5b5566ab   haribo   added celery
23

65149de7   Jeremy   Update
24
'''
05038bc8   Jeremy   Majordome logic i...
25
    Task to handle the execution of the program
65149de7   Jeremy   Update
26

4cb0ff36   Jeremy   Update
27
    check the environment status in database
05038bc8   Jeremy   Majordome logic i...
28
29
30
    check the devices status (telescope / cameras)
    check if the last schedule made has to be planned
    launch schedule's sequences
65149de7   Jeremy   Update
31
32
33
34
'''
class Majordome(Task):
    loop_speed = 1
    julian_div = 86400
05038bc8   Jeremy   Majordome logic i...
35
36
37
38
39
    executing_sequence = None
    next_sequence = None
    status_tel = ""
    status_nir = ""
    status_vis = ""
cfc9d09c   Jeremy   Added dome simula...
40
    status_dom = ""
ce470283   Jeremy   Plc simulator fin...
41
42
    site_status = "OK"
    weather_status = "OK"
ef60c3ec   Jeremy   Majordome and mon...
43
44
45
    timers = {}
    functions = {}
    schedule = None
c53a13e0   Jeremy   Updating a lot of...
46
    available_status = []
ce470283   Jeremy   Plc simulator fin...
47
    current_status = "RUNNING"
678838ed   Jeremy   Weather ans insid...
48
    alarm_list = []
65149de7   Jeremy   Update
49

e8e6f017   Jeremy   Reworked devices ...
50
51
52
53
54
55
56
57
    '''
        Check if the instrument status is valid
    '''
    def isValidStatus(self, status):
        # TODO REMOVE COMMENT AND CHANGE WHEN DEFINED
        # if (status == "" or status == "ERROR" or status == "FAILED" or status == "NOT_SET"):
        #     return (False)
        return (True)
65149de7   Jeremy   Update
58
59
60
61
62
63

    def setContext(self):
        self.tel = TelescopeController()
        self.vis_camera = VISCameraController()
        self.nir_camera = NIRCameraController()
        self.plc = PLCController()
cfc9d09c   Jeremy   Added dome simula...
64
        self.dom = DomeController()
65149de7   Jeremy   Update
65
        return (0)
65149de7   Jeremy   Update
66
67
68
69
70
71
72
73
74
75
76

    '''
        Function called by celery task
        Behavior:
            Init telescope / cameras
            set night limits
            check the software version
            launch the majordome loop
    '''
    def run(self):
        self.updateSoftware()
65149de7   Jeremy   Update
77
        self.setContext()
4cb0ff36   Jeremy   Update
78
        self.setTime()
65149de7   Jeremy   Update
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
        self.loop()

    '''
        Reads the softwares versions in the settings.py, store them in the DB and send them to the IC.
    '''
    def updateSoftware(self):
        versions = settings.MODULES_VERSIONS
        for module, version in versions.items():
            same_module_versions = Version.objects.filter(module_name=module)
            if same_module_versions.count() == 0:
                Version.objects.create(module_name=module, version=version)
            elif same_module_versions.order_by("-created")[0].version != version:
                Version.objects.create(module_name=module, version=version)
        return (0)

    '''
ce470283   Jeremy   Plc simulator fin...
95
        Loop to wait for the device to be idle with the starting configurations.
65149de7   Jeremy   Update
96
97
    '''
    def waitDevices(self):
ce470283   Jeremy   Plc simulator fin...
98
99
100
101
102
        while self.status_vis == "" and self.status_tel == "" and self.status_nir == "" and self.status_dom == "":
            self.status_vis = self.vis_camera.getStatus()
            self.status_nir = self.nir_camera.getStatus()
            self.status_tel = self.tel.getStatus()
            self.status_dom = self.dom.getStatus()
65149de7   Jeremy   Update
103
104
105
106
107
108
109
110
111
112
        return (0)

    '''
        Computes the beginning and the end of the following (or current) night
    '''
    def setTime(self):
        self.night_start = getNightStart()
        self.night_end = getNightEnd()
        self.night_start_jd = secondsToJulianDate(getNightStart())
        self.night_end_jd = secondsToJulianDate(getNightEnd())
ef60c3ec   Jeremy   Majordome and mon...
113
114
        self.timer_night_start = self.night_start - getCurrentTime()
        self.timer_night_end = self.night_end - getCurrentTime()
65149de7   Jeremy   Update
115
116
117
        self.timer_status = 5
        self.timer_plc = 2
        self.timer_schedule = 1
05038bc8   Jeremy   Majordome logic i...
118
        self.timer_sequence = 1
65149de7   Jeremy   Update
119
120
121
122

        if (self.night_start - 120 > getCurrentTime()):
            self.timer_night_start = self.night_start - 120 - getCurrentTime()
        self.timer_night_end = self.night_end - getCurrentTime()
4cb0ff36   Jeremy   Update
123
124
        if (getCurrentTime() > self.night_start):
            self.adaptTimers()
65149de7   Jeremy   Update
125
126

        self.timers = {
4cb0ff36   Jeremy   Update
127
128
129
130
131
132
133
            "status": self.timer_status,
            "environment": self.timer_plc,
            "night_start": self.timer_night_start,
            "night_end": self.timer_night_end,
            "schedule": self.timer_schedule,
            "sequence": self.timer_sequence
        }
ff448d43   Jeremy   Update
134
        if (settings.DEBUG and DEBUG_FILE):
e8e6f017   Jeremy   Reworked devices ...
135
136
            log.info("Majordome started with timers : " + str(self.timers))
        # Functions called during the loop
4cb0ff36   Jeremy   Update
137
138
139
140
141
142
143
        self.functions = {
            "status": self.handleStatusTimer,
            "environment": self.handleEnvironmentTimer,
            "night_start": self.handleNightStartTimer,
            "night_end": self.handleNightEndTimer,
            "schedule": self.handleScheduleTimer,
            "sequence": self.handleSequenceTimer
65149de7   Jeremy   Update
144
        }
65149de7   Jeremy   Update
145
146
        return (0)

e8e6f017   Jeremy   Reworked devices ...
147
    # TODO adapt timers if the majordome is started during the night
4cb0ff36   Jeremy   Update
148
149
150
    def adaptTimers(self):
        pass

bca9a283   Jeremy   Reworked the sche...
151
152
153
    def logDB(self, message: str):
        Log.objects.create(agent="Majordome", message=message)

65149de7   Jeremy   Update
154
155
    '''
        Infinite loop according to the majordome behavior
65149de7   Jeremy   Update
156
157
    '''
    def loop(self):
c53a13e0   Jeremy   Updating a lot of...
158
        while (self.current_status != "SHUTDOWN"):
65149de7   Jeremy   Update
159
160
161
162
            minimal_timer = min(self.timers, key=self.timers.get)
            if (self.timers[minimal_timer] > 0):
                time.sleep(self.timers[minimal_timer])
                self.timers = {key: value - self.timers[minimal_timer] for key, value in self.timers.items()}
65149de7   Jeremy   Update
163
164
            for timer_name, timer_value in self.timers.items():
                if (timer_value <= 0):
4cb0ff36   Jeremy   Update
165
                    if timer_name in self.functions:
bca9a283   Jeremy   Reworked the sche...
166
                        self.logDB("Executing timer " + str(timer_name))
4cb0ff36   Jeremy   Update
167
                        self.functions[timer_name]()
65149de7   Jeremy   Update
168
                    else:
ff448d43   Jeremy   Update
169
                        if (settings.DEBUG and DEBUG_FILE):
4cb0ff36   Jeremy   Update
170
                            log.info("Timer : " + str(timer_name) + "is not known by the Majordome")
bca9a283   Jeremy   Reworked the sche...
171
                        self.logDB("Timer " + str(timer_name) + " unknown")
ff448d43   Jeremy   Update
172
                    if (settings.DEBUG and DEBUG_FILE):
e8e6f017   Jeremy   Reworked devices ...
173
                        log.info("Timer : " + str(timer_name) + " executed")
05038bc8   Jeremy   Majordome logic i...
174
175
        return (0)

4cb0ff36   Jeremy   Update
176
177
    def handleEnvironmentTimer(self):
        self.timers["environment"] = self.timer_plc
ce470283   Jeremy   Plc simulator fin...
178
        self.handlePLC()
4cb0ff36   Jeremy   Update
179
180
181
182
        return (0)

    def handleStatusTimer(self):
        self.timers["status"] = self.timer_status
ce470283   Jeremy   Plc simulator fin...
183
184
185
186
        self.status_tel = self.tel.getStatus()
        self.status_nir = self.nir_camera.getStatus()
        self.status_vis = self.vis_camera.getStatus()
        self.status_dom = self.dom.getStatus()
4cb0ff36   Jeremy   Update
187
188
189
190
191
        self.handleStatus()
        return (0)

    def handleSequenceTimer(self):
        self.timers["sequence"] = self.timer_sequence
ff448d43   Jeremy   Update
192
193
194
        if (self.executing_sequence):
            self.handleSequence(self.executing_sequence[0],
                                self.executing_sequence[1], self.executing_sequence[2])
4cb0ff36   Jeremy   Update
195
196
197
        return (0)

    def handleScheduleTimer(self):
ef60c3ec   Jeremy   Majordome and mon...
198
        self.timers["schedule"] = self.timer_schedule
4cb0ff36   Jeremy   Update
199
        if (self.isValidStatus(self.status_tel)):
ff448d43   Jeremy   Update
200
            if (self.schedule is None):
ef60c3ec   Jeremy   Majordome and mon...
201
202
203
                try:
                    self.schedule = Schedule.objects.latest('created')
                except ObjectDoesNotExist:
ff448d43   Jeremy   Update
204
                    if (settings.DEBUG and DEBUG_FILE):
ef60c3ec   Jeremy   Majordome and mon...
205
206
                        log.info("No schedule found in database")
                    return (1)
4cb0ff36   Jeremy   Update
207
            else:
ef60c3ec   Jeremy   Majordome and mon...
208
209
210
                try:
                    schedule = Schedule.objects.latest('created')
                except ObjectDoesNotExist:
ff448d43   Jeremy   Update
211
                    if (settings.DEBUG and DEBUG_FILE):
ef60c3ec   Jeremy   Majordome and mon...
212
213
                        log.info("No schedule found in database")
                    return (1)
4cb0ff36   Jeremy   Update
214
215
216
217
                if (schedule.created != self.schedule.created):
                    self.next_sequence = None
                    self.schedule = schedule
            if (self.schedule):
c53a13e0   Jeremy   Updating a lot of...
218
219
                shs_list = self.schedule.shs.filter(Q(status=Sequence.PLANNED) |
                                                    Q(status=Sequence.PENDING)).order_by('tsp')
4cb0ff36   Jeremy   Update
220
221
222
223
224
225
                self.executeSchedule(shs_list)
        else:
            self.notifyTelescopeStatus("scheduler")
        return (0)

    def handleNightEndTimer(self):
ce470283   Jeremy   Plc simulator fin...
226
        self.timers["night_end"] = getNightEnd()
4cb0ff36   Jeremy   Update
227
228
229
230
231
232
233
234
        if (self.isValidStatus(self.status_tel)):
            observation_manager.tasks.create_calibrations.delay()
        else:
            self.notifyTelescopeStatus("night_end")
        return (0)

    def handleNightStartTimer(self):
        self.timers["night_start"] = getNextNightStart()
ce470283   Jeremy   Plc simulator fin...
235
236
237
238
239
        scheduler.tasks.scheduling.apply_async((False, False))
        # if (self.isValidStatus(self.status_tel)):
        #     scheduler.tasks.scheduling.delay(first_schedule=False, alert=False)
        # else:
        #     self.notifyTelescopeStatus("night_start")
4cb0ff36   Jeremy   Update
240
241
        return (0)

ef60c3ec   Jeremy   Majordome and mon...
242
243
244
    def notifyTelescopeStatus(self, timer_name):
        return (self.notifyDeviceStatus("telescope", timer_name, self.status_tel))

05038bc8   Jeremy   Majordome logic i...
245
    def notifyDeviceStatus(self, device_name, timer_name, status):
ef60c3ec   Jeremy   Majordome and mon...
246
247
        Log.objects.create(agent=device_name, created=datetime.datetime.now(),
                           message="The action : " + str(timer_name) + " has been canceled : Telescope status : " + str(status))
ce470283   Jeremy   Plc simulator fin...
248
        # TODO MAYBE reset some variables and do a scheduling
65149de7   Jeremy   Update
249
250
251
252
253
254
        return (0)

    '''
        Function called when a schedule has to be executed
    '''
    def executeSchedule(self, shs_list):
bca9a283   Jeremy   Reworked the sche...
255
        self.logDB("Trying to execute a sequence from current schedule")
05038bc8   Jeremy   Majordome logic i...
256
        for shs in shs_list: # shs_list is sorted by tsp
c53a13e0   Jeremy   Updating a lot of...
257
258
259
            if (self.executableSequence(shs.sequence.status) and self.observable(shs.sequence)):
                if self.next_sequence is None:
                    self.setNextSequence(shs, shs.sequence)
678838ed   Jeremy   Weather ans insid...
260
                if self.isExecutable() and self.executing_sequence is None:
c53a13e0   Jeremy   Updating a lot of...
261
262
263
264
265
                    if self.isValidTimer(self.next_sequence[0]):
                        if self.executeSequence(self.next_sequence[0], self.next_sequence[1]) == -1:
                            return -1
                        if self.next_sequence[0] != shs and self.next_sequence[1] != shs.sequence:
                            self.setNextSequence(shs, shs.sequence)
ff448d43   Jeremy   Update
266
                        else:
c53a13e0   Jeremy   Updating a lot of...
267
                            self.next_sequence = None
ff448d43   Jeremy   Update
268
269
                    else:
                        return 0
bca9a283   Jeremy   Reworked the sche...
270
            else:
ff448d43   Jeremy   Update
271
                if (settings.DEBUG and DEBUG_FILE):
bca9a283   Jeremy   Reworked the sche...
272
                    log.info("Sequence cannot be executed : Not observable")
ff448d43   Jeremy   Update
273
274
                self.logDB("Sequence "+shs.sequence.name+" cannot be executed : Not observable")
        return 0
05038bc8   Jeremy   Majordome logic i...
275

4cb0ff36   Jeremy   Update
276
    def observable(self, sequence):
ff448d43   Jeremy   Update
277
278
279
        if (sequence.jd2 - sequence.duration - secondsToPreciseJulianDate(getPreciseCurrentTime()) <= 0):
            return 0
        return 1
4cb0ff36   Jeremy   Update
280

c53a13e0   Jeremy   Updating a lot of...
281
282
283
284
285
    def executableSequence(self, status):
        if status == Sequence.PLANNED or status == Sequence.PENDING:
            return 1
        return 0

678838ed   Jeremy   Weather ans insid...
286
287
288
289
290
291
292
293
294
295
296
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
326
327
328
329
330
331
332
333
334
335
336
337
    @executingSequenceExist
    def killExecutingSequence(self):
        shs = self.executing_sequence[0]
        sequence = self.executing_sequence[1]
        executing_plans = self.executing_sequence[2]

        shs.status = Sequence.CANCELLED
        sequence.status = Sequence.CANCELLED
        shs.save()
        sequence.save()
        for rev in executing_plans:
            if (not rev.failed() and not rev.successful()):
                rev.revoke(terminate=True)
        self.executing_sequence = None
        return 0

    def reset(self, type):
        if type == "WEATHER":
            self.dom.open()
            scheduler.tasks.delay((False, False))
        elif type == "INSIDE":
            scheduler.tasks.delay((False, False))


    @SameAlarmCheck
    def handleAlarm(self, type, pos=-1):
        if type == "WEATHER":
            #TODO send email
            self.dom.close()
            self.killExecutingSequence()
            self.vis_camera.park()
            self.nir_camera.park()
        elif type == "INSIDE":
            #TODO send email
            self.killExecutingSequence()
            self.vis_camera.park()
            self.nir_camera.park()
        elif type == "ENDED":
            if len(self.alarm_list) > 0 and pos != -1:
                ended = self.alarm_list[pos]
                del self.alarm_list[pos]
                self.reset(ended)
            return 0
        else:
            return 1
        self.alarm_list.append(type)
        return 0

    '''
        for now weather_status and site_status contains something different than OK if the status is critical
        Later we may have other states to handle
    '''
ce470283   Jeremy   Plc simulator fin...
338
339
340
    def isOutsideOk(self) -> bool:
        self.handlePLC()
        if self.weather_status == "OK":
678838ed   Jeremy   Weather ans insid...
341
342
            if "WEATHER" in self.alarm_list:
                self.handleAlarm("ENDED", self.alarm_list.index("WEATHER"))
ce470283   Jeremy   Plc simulator fin...
343
            return True
678838ed   Jeremy   Weather ans insid...
344
        self.handleAlarm("WEATHER")
ce470283   Jeremy   Plc simulator fin...
345
346
347
348
349
        return False

    def isInsideOk(self) -> bool:
        self.handlePLC()
        if self.site_status == "OK":
678838ed   Jeremy   Weather ans insid...
350
351
            if "INSIDE" in self.alarm_list:
                self.handleAlarm("ENDED", self.alarm_list.index("INSIDE"))
ce470283   Jeremy   Plc simulator fin...
352
            return True
678838ed   Jeremy   Weather ans insid...
353
        self.handleAlarm("INSIDE")
ce470283   Jeremy   Plc simulator fin...
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
        return False

    def isDevicesOk(self) -> bool:
        if self.isValidStatus(self.status_tel) and self.isValidStatus(self.status_dom)\
            and self.isValidStatus(self.status_vis) and self.isValidStatus(self.status_nir):
            return True
        return False

    def isExecutable(self) -> bool:
        if self.isValidStatus(self.status_tel) and self.isValidStatus(self.status_dom)\
                and self.isOutsideOk() and self.isInsideOk():
            return True
        return False

    def isValidTimer(self, shs) -> bool:
c53a13e0   Jeremy   Updating a lot of...
369
370
        current_countdown = self.getCountdown(shs)
        if (current_countdown <= JulianSeconds(5)):
c53a13e0   Jeremy   Updating a lot of...
371
372
373
            try:
                task = TaskId.objects.filter(task="scheduling")
                if not task:
ce470283   Jeremy   Plc simulator fin...
374
375
                    return True
                return False
c53a13e0   Jeremy   Updating a lot of...
376
            except:
ce470283   Jeremy   Plc simulator fin...
377
378
                return True
        return False
c53a13e0   Jeremy   Updating a lot of...
379

05038bc8   Jeremy   Majordome logic i...
380
381
382
    '''
        Launch the observation tasks associated to a sequence
    '''
c53a13e0   Jeremy   Updating a lot of...
383
    def executeSequence(self, shs, sequence):
3224f14a   Jeremy   Fixed some simula...
384
385
386
387
        shs.status = Sequence.EXECUTING
        sequence.status = Sequence.EXECUTING
        shs.save()
        sequence.save()
c53a13e0   Jeremy   Updating a lot of...
388
        log.info("Executing sequence id = " + str(sequence.pk))
bca9a283   Jeremy   Reworked the sche...
389
        self.logDB("Executing sequence")
05038bc8   Jeremy   Majordome logic i...
390
        plans_results = []
05038bc8   Jeremy   Majordome logic i...
391
392
393
        if sequence.albums.filter(detector__name="Cagire").exists():
            if (self.isValidStatus(self.status_nir)):
                for plan in sequence.albums.get(detector__name="Cagire").plans.all():
c53a13e0   Jeremy   Updating a lot of...
394
395
396
397
                    res = observation_manager.tasks.execute_plan_nir.apply_async(
                        (plan.id, float(self.getCountdown(shs))))
                    # JB TODO : is it still usefull ?
                    # TaskId.objects.create(task_id=res.id, task="execute_plan")
05038bc8   Jeremy   Majordome logic i...
398
                    plans_results.append(res)
ff448d43   Jeremy   Update
399
400
            else:
                self.notifyDeviceStatus("Cagire", "Sequence execution", self.status_nir)
c53a13e0   Jeremy   Updating a lot of...
401
402
403
                sequence.status = Sequence.CANCELLED
                shs.status = Sequence.CANCELLED
                shs.save()
ff448d43   Jeremy   Update
404
405
                sequence.save()
                return (1)
05038bc8   Jeremy   Majordome logic i...
406
407
408
        if sequence.albums.filter(detector__name="Visible camera").exists():
            if (self.isValidStatus(self.status_vis)):
                for plan in sequence.albums.get(detector__name="Visible camera").plans.all():
c53a13e0   Jeremy   Updating a lot of...
409
410
                    res = observation_manager.tasks.execute_plan_vis.apply_async(
                        (plan.id, float(self.getCountdown(shs))))
05038bc8   Jeremy   Majordome logic i...
411
412
413
                    plans_results.append(res)
            else:
                self.notifyDeviceStatus("Camera visible", "Sequence execution", self.status_vis)
c53a13e0   Jeremy   Updating a lot of...
414
415
416
                sequence.status = Sequence.CANCELLED
                shs.status = Sequence.CANCELLED
                shs.save()
05038bc8   Jeremy   Majordome logic i...
417
418
                sequence.save()
                return (1)
05038bc8   Jeremy   Majordome logic i...
419
        self.executing_sequence = [shs, sequence, plans_results]
05038bc8   Jeremy   Majordome logic i...
420
421
422
423
424
        return (0)

    '''
        Set the next sequence
    '''
c53a13e0   Jeremy   Updating a lot of...
425
    def setNextSequence(self, shs, sequence):
ff448d43   Jeremy   Update
426
        sequence.status = Sequence.PENDING
c53a13e0   Jeremy   Updating a lot of...
427
428
        shs.status = Sequence.PENDING
        self.next_sequence = [shs, sequence]
ff448d43   Jeremy   Update
429
        sequence.save()
c53a13e0   Jeremy   Updating a lot of...
430
        shs.save()
05038bc8   Jeremy   Majordome logic i...
431
432
433
434
435
436
        return (0)

    '''
        Check if the current sequence is finished
    '''
    def handleSequence(self, shs, sequence, executing_plans):
c53a13e0   Jeremy   Updating a lot of...
437
        count = 0
c53a13e0   Jeremy   Updating a lot of...
438
        for res in executing_plans:
05038bc8   Jeremy   Majordome logic i...
439
            try:
c53a13e0   Jeremy   Updating a lot of...
440
441
                if res.successful() or res.failed():
                    count += 1
05038bc8   Jeremy   Majordome logic i...
442
            except Exception as e:
678838ed   Jeremy   Weather ans insid...
443
444
                if DEBUG_FILE and settings.DEBUG:
                    log.info(str(e))
05038bc8   Jeremy   Majordome logic i...
445
446
447
448
449
                shs.status = Sequence.CANCELLED
                sequence.status = Sequence.CANCELLED
                shs.save()
                sequence.save()
                for rev in executing_plans:
c53a13e0   Jeremy   Updating a lot of...
450
451
452
                    if (not rev.failed() and not rev.successful()):
                        rev.revoke(terminate=True)
                self.executing_sequence = None
05038bc8   Jeremy   Majordome logic i...
453
                return (-1)
c53a13e0   Jeremy   Updating a lot of...
454
        if count >= len(executing_plans):
05038bc8   Jeremy   Majordome logic i...
455
456
457
458
459
            sequence.status = Sequence.EXECUTED
            shs.status = Sequence.EXECUTED
            sequence.save()
            shs.save()
            message = "Finished sequence " + str(sequence.pk) + " execution"
05038bc8   Jeremy   Majordome logic i...
460
            Log.objects.create(agent="Majordome", message=message)
c53a13e0   Jeremy   Updating a lot of...
461
            self.executing_sequence = None
05038bc8   Jeremy   Majordome logic i...
462
        return (0)
65149de7   Jeremy   Update
463
464
465
466

    '''
        Function called to do an action with the devices status
    '''
05038bc8   Jeremy   Majordome logic i...
467
    def handleStatus(self):
05038bc8   Jeremy   Majordome logic i...
468
469
470
        telescope = Telescope.objects.first()
        camera_nir = Detector.objects.get(name="Cagire")
        camera_vis = Detector.objects.get(name="Visible camera")
ce470283   Jeremy   Plc simulator fin...
471
472
473
        dome = Dome.objects.get(name="Dome")

        dome.status = self.status_dom
05038bc8   Jeremy   Majordome logic i...
474
475
476
        telescope.status = self.status_tel
        camera_nir.status = self.status_nir
        camera_vis.status = self.status_vis
ce470283   Jeremy   Plc simulator fin...
477
478
479
480
481

        dome.save()
        telescope.save()
        camera_nir.save()
        camera_vis.save()
bca9a283   Jeremy   Reworked the sche...
482
483
        self.logDB("Instrument status : dome  = " + str(self.status_dom) + ", telescope = " + str(self.status_tel)
                   + ", camera_nir = " + str(self.status_nir) + ", camera_vis" + str(self.status_vis))
65149de7   Jeremy   Update
484
485
486
        return (0)

    '''
3224f14a   Jeremy   Fixed some simula...
487
        Put the majordome in pause
4cb0ff36   Jeremy   Update
488
    '''
4cb0ff36   Jeremy   Update
489
    def systemPause(self, duration, cause: str):
bca9a283   Jeremy   Reworked the sche...
490
        self.logDB("System in pause for " + str(duration))
4cb0ff36   Jeremy   Update
491
492
493
494
495
496
497
        time.sleep(duration)
        scheduler.tasks.scheduling.delay(first_schedule=False, alert=False)
        self.setTime()
        print("system has been paused. Cause : " + cause)
        return (0)

    '''
65149de7   Jeremy   Update
498
499
        Function called to do an action with the site status and the wheather status
    '''
ce470283   Jeremy   Plc simulator fin...
500
501
502
503
504
505
506
507
508
509
510
    def handlePLC(self):
        try:
            site_status = SiteWatch.objects.latest('updated')
            weather_status = WeatherWatch.objects.latest('updated')
            self.weather_status = weather_status.global_status
            self.site_status = site_status.global_status
        except ObjectDoesNotExist as e:
            if (settings.DEBUG and DEBUG_FILE):
                log.info("No site_status or weather_status found in database : " + str(e))
            # TODO shutdown everything
            return 1
3224f14a   Jeremy   Fixed some simula...
511
        return 0
5b5566ab   haribo   added celery
512

4cb0ff36   Jeremy   Update
513
    '''
05038bc8   Jeremy   Majordome logic i...
514
        Gets the time before the expected start of the execution.
4cb0ff36   Jeremy   Update
515
    '''
05038bc8   Jeremy   Majordome logic i...
516
517
    def getCountdown(self, shs):
        # TODO start sequence as soon as possible (a lot of verifications must be done there)
ff448d43   Jeremy   Update
518
        current_time = secondsToPreciseJulianDate(getPreciseCurrentTime())
05038bc8   Jeremy   Majordome logic i...
519
        countdown = shs.tsp - current_time
9774228b   haribo   Date: 22/06/2016
520
        return countdown
7a79e25b   haribo   Date: 19/05/2016
521

4cb0ff36   Jeremy   Update
522
523
524
525
    '''
        Change observation conditions
    '''
    def changeObsConditions(self):
5b5566ab   haribo   added celery
526
        print("change_obs_conditions")
4cb0ff36   Jeremy   Update
527
        pass