Blame view

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

d243a3ef   Etienne Pallier   Bugfix majordome_...
3
4
5
import time
import datetime

af5d8b11   Etienne Pallier   Nouveau shell pyr...
6
7
# from django.core.exceptions import ObjectDoesNotExist
# from django.db.models import Q
d243a3ef   Etienne Pallier   Bugfix majordome_...
8
9
from django.shortcuts import get_object_or_404
from django.conf import settings as djangosettings
ce470283   Jeremy   Plc simulator fin...
10

d243a3ef   Etienne Pallier   Bugfix majordome_...
11
import utils.Logger as L
af5d8b11   Etienne Pallier   Nouveau shell pyr...
12
13

"""
9774228b   haribo   Date: 22/06/2016
14
import observation_manager
abfb02e2   Jeremy   Device Model is n...
15
import observation_manager.tasks
ce470283   Jeremy   Plc simulator fin...
16
17
import scheduler
import scheduler.tasks as sched_task
c72eb17a   Jeremy   Update celery task
18
19
import monitoring.tasks
import alert_manager.tasks
af5d8b11   Etienne Pallier   Nouveau shell pyr...
20
21
"""
# from common.models import *
d243a3ef   Etienne Pallier   Bugfix majordome_...
22
from common.models import Config, Log, PlcDeviceStatus
6aec6155   theopuhl   Majordome algorit...
23
24
from dashboard.views import get_sunelev
from devices.TelescopeRemoteControlDefault import TelescopeRemoteControlDefault
af5d8b11   Etienne Pallier   Nouveau shell pyr...
25
26

"""
65149de7   Jeremy   Update
27
from devices.CameraNIR import NIRCameraController
ce470283   Jeremy   Plc simulator fin...
28
from devices.CameraVIS import VISCameraController
cfc9d09c   Jeremy   Added dome simula...
29
from devices.Dome import DomeController
65149de7   Jeremy   Update
30
from devices.PLC import PLCController
ce470283   Jeremy   Plc simulator fin...
31
32
from devices.Telescope import TelescopeController
from majordome.MajordomeDecorators import *
65149de7   Jeremy   Update
33
from utils.JDManipulator import *
af5d8b11   Etienne Pallier   Nouveau shell pyr...
34
"""
d51386bf   Etienne Pallier   new file majordom...
35

cfc9d09c   Jeremy   Added dome simula...
36

03814884   Etienne Pallier   launch majordome ...
37
38
from threading import Thread

ff448d43   Jeremy   Update
39
DEBUG_FILE = False
65149de7   Jeremy   Update
40
log = L.setupLogger("MajordomeTaskLogger", "Majordome")
5b5566ab   haribo   added celery
41

af5d8b11   Etienne Pallier   Nouveau shell pyr...
42
"""
05038bc8   Jeremy   Majordome logic i...
43
    Task to handle the execution of the program
65149de7   Jeremy   Update
44

4cb0ff36   Jeremy   Update
45
    check the environment status in database
05038bc8   Jeremy   Majordome logic i...
46
47
48
    check the devices status (telescope / cameras)
    check if the last schedule made has to be planned
    launch schedule's sequences
af5d8b11   Etienne Pallier   Nouveau shell pyr...
49
"""
3001ec20   Etienne Pallier   majordome small fix
50
51


af5d8b11   Etienne Pallier   Nouveau shell pyr...
52
53
54
class Majordome:
    # (EP) do this so that Majordome can be run from a thread, and called with thread.start():
    # class Majordome(Task, Thread):
d243a3ef   Etienne Pallier   Bugfix majordome_...
55
56
57

    FOR_REAL = True

65149de7   Jeremy   Update
58
59
    loop_speed = 1
    julian_div = 86400
05038bc8   Jeremy   Majordome logic i...
60
61
62
63
64
    executing_sequence = None
    next_sequence = None
    status_tel = ""
    status_nir = ""
    status_vis = ""
cfc9d09c   Jeremy   Added dome simula...
65
    status_dom = ""
ce470283   Jeremy   Plc simulator fin...
66
67
    site_status = "OK"
    weather_status = "OK"
ef60c3ec   Jeremy   Majordome and mon...
68
69
70
    timers = {}
    functions = {}
    schedule = None
c53a13e0   Jeremy   Updating a lot of...
71
    available_status = []
678838ed   Jeremy   Weather ans insid...
72
    alarm_list = []
468a79dc   Etienne Pallier   added comments
73
74

    # New variables from TP:
af5d8b11   Etienne Pallier   Nouveau shell pyr...
75

6aec6155   theopuhl   Majordome algorit...
76
    config = None
468a79dc   Etienne Pallier   added comments
77
    plc_status = None
f3534c59   Etienne Pallier   Simulators web pa...
78
    current_state = "NONE"
af5d8b11   Etienne Pallier   Nouveau shell pyr...
79

d0b663be   Etienne Pallier   refactorized majo...
80
81
    # OCS-RESTART, OCS-SHUTDOWN, or NONE (default)
    closing_mode = "NONE"
af5d8b11   Etienne Pallier   Nouveau shell pyr...
82

0ca00ebd   Etienne Pallier   refactorized and ...
83
84
85
    NEED_TO_CLOSE = False
    PLC_IS_SAFE = False

af5d8b11   Etienne Pallier   Nouveau shell pyr...
86
    """
0997e1c3   Etienne Pallier   moved main run() ...
87
88
89
90
91
92
93
94
95
        Behavior:
            Init telescope / cameras
            set night limits
            check the software version
            launch the majordome loop ///// OLD

        Main loop of Majordome
        startup everything if needed
        Loop over Majordome state
d0b663be   Etienne Pallier   refactorized majo...
96
        Change behavior with the pyros states
0997e1c3   Etienne Pallier   moved main run() ...
97
        Take suitable decision thanks to states in database
af5d8b11   Etienne Pallier   Nouveau shell pyr...
98
99
100
101
    """

    def run(self, FOR_REAL: bool = True):
        """
d243a3ef   Etienne Pallier   Bugfix majordome_...
102
            FOR_REAL: set to False if you don't want Majordome to send commands to devices
af5d8b11   Etienne Pallier   Nouveau shell pyr...
103
        """
d243a3ef   Etienne Pallier   Bugfix majordome_...
104
105

        self.FOR_REAL = FOR_REAL
af5d8b11   Etienne Pallier   Nouveau shell pyr...
106
107
108
109
110
111
        # self.createTask()
        # self.updateSoftware()
        # self.setContext()
        # self.setTime()                     /// OLD Majordome
        # self.setTasks()
        # self.loop()
0997e1c3   Etienne Pallier   moved main run() ...
112

d243a3ef   Etienne Pallier   Bugfix majordome_...
113
        print("FOR REAL ?", self.FOR_REAL)
af5d8b11   Etienne Pallier   Nouveau shell pyr...
114
        print("DB3 used is:", djangosettings.DATABASES["default"]["NAME"])
d51386bf   Etienne Pallier   new file majordom...
115

0ca00ebd   Etienne Pallier   refactorized and ...
116
        while True:
af5d8b11   Etienne Pallier   Nouveau shell pyr...
117

d0b663be   Etienne Pallier   refactorized majo...
118
            # SETUP
af5d8b11   Etienne Pallier   Nouveau shell pyr...
119
            try:
d0b663be   Etienne Pallier   refactorized majo...
120
                self.config = get_object_or_404(Config, id=1)
f3534c59   Etienne Pallier   Simulators web pa...
121
122
123
                # By default, set mode to SCHEDULER (False = REMOTE, which should never be the default)
                self.config.global_mode = True
                self.config.save()
af5d8b11   Etienne Pallier   Nouveau shell pyr...
124
125
126
127
                # self.config = Config.objects.get(pk=1)
                # self.config = Config.objects.get()[0]
                # print("maj config id is", self.config.id)
            # except Config.ObjectDoesNotExist:
03814884   Etienne Pallier   launch majordome ...
128
            except Exception as e:
f3534c59   Etienne Pallier   Simulators web pa...
129
                print("Config read (or write) exception", str(e))
d0b663be   Etienne Pallier   refactorized majo...
130
                return -1
af5d8b11   Etienne Pallier   Nouveau shell pyr...
131
132
133

            # self.config.ntc = False

d0b663be   Etienne Pallier   refactorized majo...
134
135
            # Set STATE to STARTING
            self.changeState("STARTING")
af5d8b11   Etienne Pallier   Nouveau shell pyr...
136
137

            """
d0b663be   Etienne Pallier   refactorized majo...
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
            if not self.config.majordome_restarted:
                #in order to start other agents etc....
                self.setup()
            
            # Set STATE to PASSIVE (NO PLC)
            self.changeState("Passive No PLC")
            print("Waiting for PLC connection")
            # Wait until PCL is connected
            while not self.plc_is_connected():                  
                pass           
            print("PLC is connected")
                    
            # Set STATE to PASSIVE (with PLC)
            self.changeState("Passive")
            self.config.majordome_state = "RUNNING"
    
            # MAIN LOOP: iterate on current state
            #while self.plc_is_connected() != False and self.closing_mode == "RUNNING" :          
0ca00ebd   Etienne Pallier   refactorized and ...
156
            while self.plc_is_connected() and not self.is_shuttingdown_or_restarting():          
d0b663be   Etienne Pallier   refactorized majo...
157
158
159
160
                # Call behavior for the current state and set new current state (can stay the same if no state change)
                #self.behavior[self.current_state](self)
                self.current_state = self.behavior[self.current_state](self)
                time.sleep(2)
af5d8b11   Etienne Pallier   Nouveau shell pyr...
161
            """
d0b663be   Etienne Pallier   refactorized majo...
162
            while True:
1179175f   Etienne Pallier   Majordome agent c...
163
                self.reload_config()
af5d8b11   Etienne Pallier   Nouveau shell pyr...
164
165
                if self.config.majordome_state == "STOP":
                    break
f3534c59   Etienne Pallier   Simulators web pa...
166
                if self.config.majordome_state in ("OCS-RESTART", "OCS-SHUTDOWN"):
af5d8b11   Etienne Pallier   Nouveau shell pyr...
167
168
                    if self.config.majordome_state == "OCS-SHUTDOWN":
                        self.NEED_TO_CLOSE = True
f3534c59   Etienne Pallier   Simulators web pa...
169
170
171
                    self.closing_mode = self.config.majordome_state
                    self.config.majordome_state = "RUNNING"
                    self.config.save()
af5d8b11   Etienne Pallier   Nouveau shell pyr...
172
173
174
175
                if self.current_state in ["STARTING", "PASSIVE_NO_PLC", "PASSIVE"]:
                    if self.is_shuttingdown_or_restarting() and not self.NEED_TO_CLOSE:
                        break
                """
d0b663be   Etienne Pallier   refactorized majo...
176
                if self.current_state not in ['STARTING', 'PASSIVE_NO_PLC']:
0ca00ebd   Etienne Pallier   refactorized and ...
177
                    if self.plc_is_not_auto(): self.changeState("PASSIVE")
af5d8b11   Etienne Pallier   Nouveau shell pyr...
178
                """
03814884   Etienne Pallier   launch majordome ...
179
                self.current_state = self.do_behavior_for_current_state()
af5d8b11   Etienne Pallier   Nouveau shell pyr...
180

d0b663be   Etienne Pallier   refactorized majo...
181
            # Shutdown options change by the main program
af5d8b11   Etienne Pallier   Nouveau shell pyr...
182
183
184
185
186
187
            if (
                self.config.majordome_state == "STOP"
                or self.closing_mode == "OCS-SHUTDOWN"
            ):
                if self.config.majordome_state == "STOP":
                    print("STOP Majordome agent from DB")
f3534c59   Etienne Pallier   Simulators web pa...
188
189
                self.config.majordome_state = "RUNNING"
                self.changeState("KILLED")
af5d8b11   Etienne Pallier   Nouveau shell pyr...
190
191
192
193
                # self.config.save()
                # self.shutdown()
                # self.closeBehaviour(self)
                # self.sub_behavior_closing()
0ca00ebd   Etienne Pallier   refactorized and ...
194
                break
af5d8b11   Etienne Pallier   Nouveau shell pyr...
195

0ca00ebd   Etienne Pallier   refactorized and ...
196
            if self.closing_mode == "OCS-RESTART":
d0b663be   Etienne Pallier   refactorized majo...
197
198
                self.config.majordome_restarted = True
                self.config.save()
f3534c59   Etienne Pallier   Simulators web pa...
199
200
                self.closing_mode = "NONE"

af5d8b11   Etienne Pallier   Nouveau shell pyr...
201
202
203
                # TODO: self.kill_all_agents()
                # self.send_alarm_if_not_closed()
                # self.run()
0ca00ebd   Etienne Pallier   refactorized and ...
204

af5d8b11   Etienne Pallier   Nouveau shell pyr...
205
            """    
d0b663be   Etienne Pallier   refactorized majo...
206
207
208
209
210
211
            elif not self.plc_is_connected():
                #self.config.majordome_restarted = True
                #self.config.save()
                self.changeState("Passive No PLC")
                self.send_alarm_if_not_closed()
                #self.run()
af5d8b11   Etienne Pallier   Nouveau shell pyr...
212
213
            """

0ca00ebd   Etienne Pallier   refactorized and ...
214
        self.shutdown()
af5d8b11   Etienne Pallier   Nouveau shell pyr...
215

0ca00ebd   Etienne Pallier   refactorized and ...
216
    def shutdown(self):
af5d8b11   Etienne Pallier   Nouveau shell pyr...
217
        # TODO: write shutdown code (kill agents...)
0ca00ebd   Etienne Pallier   refactorized and ...
218
        print("OCS SHUTDOWN")
af5d8b11   Etienne Pallier   Nouveau shell pyr...
219

0ca00ebd   Etienne Pallier   refactorized and ...
220
221
    def is_restarting(self):
        return self.closing_mode == "OCS-RESTART"
af5d8b11   Etienne Pallier   Nouveau shell pyr...
222

0ca00ebd   Etienne Pallier   refactorized and ...
223
224
    def is_shuttingdown(self):
        return self.closing_mode == "OCS-SHUTDOWN"
af5d8b11   Etienne Pallier   Nouveau shell pyr...
225

0ca00ebd   Etienne Pallier   refactorized and ...
226
    def is_shuttingdown_or_restarting(self):
d0b663be   Etienne Pallier   refactorized majo...
227
        return self.closing_mode != "NONE"
0997e1c3   Etienne Pallier   moved main run() ...
228

af5d8b11   Etienne Pallier   Nouveau shell pyr...
229
    """
6aec6155   theopuhl   Majordome algorit...
230
        Function called to change and save current state of pyros.
af5d8b11   Etienne Pallier   Nouveau shell pyr...
231
232
    """

6aec6155   theopuhl   Majordome algorit...
233
    def changeState(self, state):
468a79dc   Etienne Pallier   added comments
234
        # (local variable) idem self.config.pyros_state
af5d8b11   Etienne Pallier   Nouveau shell pyr...
235
236
237
        Log.objects.create(
            message="Go from " + self.current_state + " to " + state, agent="Majordome"
        )
6aec6155   theopuhl   Majordome algorit...
238
        self.current_state = state
468a79dc   Etienne Pallier   added comments
239
240

        # (in DB) PASSIVE, STANDBY, REMOTE, OPERATING
6aec6155   theopuhl   Majordome algorit...
241
242
        self.config.pyros_state = state
        self.config.save()
af5d8b11   Etienne Pallier   Nouveau shell pyr...
243

0ca00ebd   Etienne Pallier   refactorized and ...
244
    def _plc_is_not_auto(self):
af5d8b11   Etienne Pallier   Nouveau shell pyr...
245
246
        if not self.plc_is_connected():
            return True
0ca00ebd   Etienne Pallier   refactorized and ...
247
248
        # now, self.plc_status has been updated, so check it:
        return self.plc_status.plc_mode != "AUTO"
af5d8b11   Etienne Pallier   Nouveau shell pyr...
249

0ca00ebd   Etienne Pallier   refactorized and ...
250
251
    def plc_is_auto(self):
        return not self._plc_is_not_auto()
af5d8b11   Etienne Pallier   Nouveau shell pyr...
252

0ca00ebd   Etienne Pallier   refactorized and ...
253
    def plc_is_safe(self):
af5d8b11   Etienne Pallier   Nouveau shell pyr...
254
255
        if not self.plc_is_connected():
            return False
0ca00ebd   Etienne Pallier   refactorized and ...
256
257
        # now, self.plc_status has been updated, so check it:
        return self.plc_status.is_safe
af5d8b11   Etienne Pallier   Nouveau shell pyr...
258

0ca00ebd   Etienne Pallier   refactorized and ...
259
260
    def is_night(self):
        return get_sunelev() < -10
0ca00ebd   Etienne Pallier   refactorized and ...
261

af5d8b11   Etienne Pallier   Nouveau shell pyr...
262
    """
d0b663be   Etienne Pallier   refactorized majo...
263
264
        Each function with behavior describes the behavior of a state,
        they are all contained in a dictionary called in run()
af5d8b11   Etienne Pallier   Nouveau shell pyr...
265
    """
0ca00ebd   Etienne Pallier   refactorized and ...
266

d0b663be   Etienne Pallier   refactorized majo...
267
    def behavior_starting(self):
af5d8b11   Etienne Pallier   Nouveau shell pyr...
268
269
        # print("STARTING")
        # if self.is_shuttingdown_or_restarting(): return
d0b663be   Etienne Pallier   refactorized majo...
270
        if not self.config.majordome_restarted:
af5d8b11   Etienne Pallier   Nouveau shell pyr...
271
            # TODO: Do setup things... (start agents...)
d0b663be   Etienne Pallier   refactorized majo...
272
            time.sleep(2)
af5d8b11   Etienne Pallier   Nouveau shell pyr...
273
        """
d0b663be   Etienne Pallier   refactorized majo...
274
275
276
        Cette variable sert à indiquer l'état du majordome dans la DB.
        Elle va aussi être changée par le panneau Simulator pour passer à l'état SHUTDOWN ou RESTART.
        Elle est récupérée à chaque itération par la fonction plcConnection()
af5d8b11   Etienne Pallier   Nouveau shell pyr...
277
        """
d0b663be   Etienne Pallier   refactorized majo...
278
        self.config.majordome_state = "RUNNING"
af5d8b11   Etienne Pallier   Nouveau shell pyr...
279
        # self.config.majordome_state = "NONE"
d0b663be   Etienne Pallier   refactorized majo...
280
281

        self.changeState("PASSIVE_NO_PLC")
af5d8b11   Etienne Pallier   Nouveau shell pyr...
282
        # return self.current_state
0ca00ebd   Etienne Pallier   refactorized and ...
283

d0b663be   Etienne Pallier   refactorized majo...
284
    def behavior_passive_no_plc(self):
af5d8b11   Etienne Pallier   Nouveau shell pyr...
285
286
287
        # print("PASSIVE_NO_PLC")
        # if self.is_shuttingdown_or_restarting(): return
        # self.changeState("Passive No PLC")
d0b663be   Etienne Pallier   refactorized majo...
288
289
290
        print("Waiting for PLC connection")
        # Wait until PCL is connected
        while not self.plc_is_connected():
03814884   Etienne Pallier   launch majordome ...
291
            time.sleep(3)
af5d8b11   Etienne Pallier   Nouveau shell pyr...
292
            """
0ca00ebd   Etienne Pallier   refactorized and ...
293
294
295
            if self.is_restarting():
                self.changeState("STARTING")
                return
af5d8b11   Etienne Pallier   Nouveau shell pyr...
296
            """
1179175f   Etienne Pallier   Majordome agent c...
297
            self.reload_config()
af5d8b11   Etienne Pallier   Nouveau shell pyr...
298
299
300
301
302
            if (
                self.config.majordome_state == "STOP"
                or self.is_shuttingdown_or_restarting()
            ):
                return
d0b663be   Etienne Pallier   refactorized majo...
303
304
        print("PLC is connected")
        # Set STATE to PASSIVE (with PLC)
d51386bf   Etienne Pallier   new file majordom...
305
        self.changeState("PASSIVE")
af5d8b11   Etienne Pallier   Nouveau shell pyr...
306
307
        # return self.current_state

d0b663be   Etienne Pallier   refactorized majo...
308
    def behavior_passive(self):
af5d8b11   Etienne Pallier   Nouveau shell pyr...
309
310
311
312
        # print("Passive")
        # if self.is_shuttingdown_or_restarting(): return
        # if self.plc_status.plc_mode == "AUTO":
        if not self.plc_is_connected():
0ca00ebd   Etienne Pallier   refactorized and ...
313
314
            self.changeState("PASSIVE_NO_PLC")
            return
af5d8b11   Etienne Pallier   Nouveau shell pyr...
315

0ca00ebd   Etienne Pallier   refactorized and ...
316
        if self.plc_is_auto():
af5d8b11   Etienne Pallier   Nouveau shell pyr...
317
318
319
            # if not self.config.majordome_restarted: self.config.ntc = True
            if not self.config.majordome_restarted:
                self.NEED_TO_CLOSE = True
f3534c59   Etienne Pallier   Simulators web pa...
320
            self.config.majordome_restarted = False
6aec6155   theopuhl   Majordome algorit...
321
            self.changeState("Standby")
af5d8b11   Etienne Pallier   Nouveau shell pyr...
322
323
        # return self.current_state

d0b663be   Etienne Pallier   refactorized majo...
324
    def behavior_standby(self):
af5d8b11   Etienne Pallier   Nouveau shell pyr...
325
326
        # print("Standby")
        # if self.config.ntc:
0ca00ebd   Etienne Pallier   refactorized and ...
327
328
        if self.is_shuttingdown() and not self.NEED_TO_CLOSE:
            self.NEED_TO_CLOSE = True
af5d8b11   Etienne Pallier   Nouveau shell pyr...
329

0ca00ebd   Etienne Pallier   refactorized and ...
330
        if self.NEED_TO_CLOSE:
6aec6155   theopuhl   Majordome algorit...
331
            self.changeState("Closing")
af5d8b11   Etienne Pallier   Nouveau shell pyr...
332
            # self.sub_behavior_closing()
03814884   Etienne Pallier   launch majordome ...
333
            self.do_behavior_for_current_state()
0ca00ebd   Etienne Pallier   refactorized and ...
334
            self.changeState("Standby")
af5d8b11   Etienne Pallier   Nouveau shell pyr...
335
336

        # elif self.plc_status.plc_mode != "AUTO" or self.is_shuttingdown_or_restarting():
0ca00ebd   Etienne Pallier   refactorized and ...
337
        if not self.plc_is_auto() or self.is_shuttingdown_or_restarting():
d51386bf   Etienne Pallier   new file majordom...
338
            self.changeState("PASSIVE")
0ca00ebd   Etienne Pallier   refactorized and ...
339
        elif not self.config.global_mode and not self.config.lock:
6aec6155   theopuhl   Majordome algorit...
340
            self.changeState("Remote")
6aec6155   theopuhl   Majordome algorit...
341

af5d8b11   Etienne Pallier   Nouveau shell pyr...
342
343
344
345
346
347
348
349
        elif (
            self.is_night()
            and self.plc_is_safe()
            and self.config.ack
            and not self.config.lock
        ):
            self.changeState("Startup")
        # return self.current_state
0ca00ebd   Etienne Pallier   refactorized and ...
350

d0b663be   Etienne Pallier   refactorized majo...
351
    def behavior_remote(self):
af5d8b11   Etienne Pallier   Nouveau shell pyr...
352
353
354
355
356
357
358
        # print("Remote")
        if (
            self.config.global_mode
            or self.is_shuttingdown_or_restarting()
            or not self.plc_is_auto()
            or self.config.lock
        ):
0ca00ebd   Etienne Pallier   refactorized and ...
359
            if not self.plc_is_auto() or self.config.lock or self.is_shuttingdown():
af5d8b11   Etienne Pallier   Nouveau shell pyr...
360
                self.NEED_TO_CLOSE = True
6aec6155   theopuhl   Majordome algorit...
361
            self.changeState("Standby")
0ca00ebd   Etienne Pallier   refactorized and ...
362
            return
af5d8b11   Etienne Pallier   Nouveau shell pyr...
363
364

        # TODO: get shutter state from db status (then wait until close/open)
0ca00ebd   Etienne Pallier   refactorized and ...
365
366
        if not self.plc_is_safe() and self.PLC_IS_SAFE:
            PLC_IS_SAFE = False
af5d8b11   Etienne Pallier   Nouveau shell pyr...
367
368
369
370
            if self.FOR_REAL:
                response = TelescopeRemoteControlDefault(
                    "DOME SHUTTER CLOSE", expert_mode=True
                ).exec_command()
0ca00ebd   Etienne Pallier   refactorized and ...
371
372
        if self.plc_is_safe() and not self.PLC_IS_SAFE:
            PLC_IS_SAFE = True
af5d8b11   Etienne Pallier   Nouveau shell pyr...
373
374
375
376
377
            if self.FOR_REAL:
                response = TelescopeRemoteControlDefault(
                    "DOME SHUTTER OPEN", expert_mode=True
                ).exec_command()
        # return self.current_state
0ca00ebd   Etienne Pallier   refactorized and ...
378

d0b663be   Etienne Pallier   refactorized majo...
379
    def behavior_startup(self):
af5d8b11   Etienne Pallier   Nouveau shell pyr...
380
        # print("Startup")
0ca00ebd   Etienne Pallier   refactorized and ...
381
        if self.config.lock or not self.plc_is_auto():
af5d8b11   Etienne Pallier   Nouveau shell pyr...
382
            self.NEED_TO_CLOSE = True
6aec6155   theopuhl   Majordome algorit...
383
            self.changeState("Standby")
0ca00ebd   Etienne Pallier   refactorized and ...
384
            return
af5d8b11   Etienne Pallier   Nouveau shell pyr...
385
386

        # TODO: get shutter and telescope from db status
0ca00ebd   Etienne Pallier   refactorized and ...
387
        time.sleep(5)
af5d8b11   Etienne Pallier   Nouveau shell pyr...
388
        """
0ca00ebd   Etienne Pallier   refactorized and ...
389
390
391
        if not (dome_shutter == Open and telescope == Ready)
            TelescopeRemoteControlDefault("DO DOME SHUTTER OPEN", expert_mode=True).exec_command()
            TelescopeRemoteControlDefault("DO START", expert_mode=True).exec_command()
af5d8b11   Etienne Pallier   Nouveau shell pyr...
392
        """
0ca00ebd   Etienne Pallier   refactorized and ...
393
        self.changeState("Scheduler")
af5d8b11   Etienne Pallier   Nouveau shell pyr...
394
        # return self.current_state
6aec6155   theopuhl   Majordome algorit...
395

d0b663be   Etienne Pallier   refactorized majo...
396
    def behavior_scheduler(self):
af5d8b11   Etienne Pallier   Nouveau shell pyr...
397
398
399
400
401
402
403
404
405
406
407
        # print("Scheduler")
        if (
            not self.is_night()
            or not self.plc_status.is_safe
            or self.config.lock
            or not self.plc_is_auto()
            or not self.config.global_mode
            or self.is_shuttingdown_or_restarting()
        ):
            if not (not self.config.global_mode or self.is_restarting()):
                self.NEED_TO_CLOSE = True
6aec6155   theopuhl   Majordome algorit...
408
            self.changeState("Standby")
af5d8b11   Etienne Pallier   Nouveau shell pyr...
409
        # return self.current_state
0ca00ebd   Etienne Pallier   refactorized and ...
410
411

    def sub_behavior_closing(self):
af5d8b11   Etienne Pallier   Nouveau shell pyr...
412
413
414
        # print("CURRENT OCS (MAJORDOME) STATE: "+ self.current_state)
        # print("Closing")
        # self.config.save()
0ca00ebd   Etienne Pallier   refactorized and ...
415
416
417
        if not self.plc_is_auto():
            # PLC not AUTO => we can do nothing, so only send email if dome not closed...
            self.send_alarm_if_not_closed()
af5d8b11   Etienne Pallier   Nouveau shell pyr...
418
        else:
d243a3ef   Etienne Pallier   Bugfix majordome_...
419
420
            if self.FOR_REAL:
                # These commands should do nothing if instruments are already closed/parked...
af5d8b11   Etienne Pallier   Nouveau shell pyr...
421
422
423
424
425
426
427
428
429
                response = TelescopeRemoteControlDefault(
                    "DO DOME SHUTTER CLOSE", expert_mode=True
                ).exec_command()
                response = TelescopeRemoteControlDefault(
                    "DO DOME PARK", expert_mode=True
                ).exec_command()
                response = TelescopeRemoteControlDefault(
                    "DO TELESCOPE PARK", expert_mode=True
                ).exec_command()
0ca00ebd   Etienne Pallier   refactorized and ...
430
431
432

        self.NEED_TO_CLOSE = False

af5d8b11   Etienne Pallier   Nouveau shell pyr...
433
434
        # self.changeState("Standby")
        # return self.current_state
d0b663be   Etienne Pallier   refactorized majo...
435
436
437
438

    behavior = {
        "STARTING": behavior_starting,
        "PASSIVE_NO_PLC": behavior_passive_no_plc,
d51386bf   Etienne Pallier   new file majordom...
439
        "PASSIVE": behavior_passive,
d0b663be   Etienne Pallier   refactorized majo...
440
441
442
443
        "Standby": behavior_standby,
        "Remote": behavior_remote,
        "Startup": behavior_startup,
        "Scheduler": behavior_scheduler,
af5d8b11   Etienne Pallier   Nouveau shell pyr...
444
        # "Closing": sub_behavior_closing,
d0b663be   Etienne Pallier   refactorized majo...
445
    }
af5d8b11   Etienne Pallier   Nouveau shell pyr...
446

03814884   Etienne Pallier   launch majordome ...
447
448
    def do_behavior_for_current_state(self) -> str:
        print("CURRENT OCS (MAJORDOME) STATE: " + self.current_state)
0ca00ebd   Etienne Pallier   refactorized and ...
449
        time.sleep(2)
d0b663be   Etienne Pallier   refactorized majo...
450
        # EXIT if PLC not connected
af5d8b11   Etienne Pallier   Nouveau shell pyr...
451
        # if not self.plc_is_connected(): return
d0b663be   Etienne Pallier   refactorized majo...
452
        # EXIT if closing or restarting
af5d8b11   Etienne Pallier   Nouveau shell pyr...
453
        # if self.is_shuttingdown_or_restarting(): return
d0b663be   Etienne Pallier   refactorized majo...
454
        # run behavior for this state
af5d8b11   Etienne Pallier   Nouveau shell pyr...
455
456
        # self.behavior[current_state](self)
        if self.current_state == "Closing":
0ca00ebd   Etienne Pallier   refactorized and ...
457
458
            self.sub_behavior_closing()
        else:
03814884   Etienne Pallier   launch majordome ...
459
460
            self.behavior[self.current_state](self)
        return self.current_state
468a79dc   Etienne Pallier   added comments
461

af5d8b11   Etienne Pallier   Nouveau shell pyr...
462
    """
6aec6155   theopuhl   Majordome algorit...
463
        Function called to send alarms is the site isn't closed (Empty for the moment)
af5d8b11   Etienne Pallier   Nouveau shell pyr...
464
465
    """

d0b663be   Etienne Pallier   refactorized majo...
466
    def send_alarm_if_not_closed(self):
6aec6155   theopuhl   Majordome algorit...
467
468
        pass

af5d8b11   Etienne Pallier   Nouveau shell pyr...
469
    """
6aec6155   theopuhl   Majordome algorit...
470
471
        Function called by run to wait for PLC connection before and during the loop
        (also gathering needed info)
af5d8b11   Etienne Pallier   Nouveau shell pyr...
472
473
    """

d0b663be   Etienne Pallier   refactorized majo...
474
    def plc_is_connected(self):
af5d8b11   Etienne Pallier   Nouveau shell pyr...
475
        try:
6aec6155   theopuhl   Majordome algorit...
476
            self.config = Config.objects.get(pk=1)
af5d8b11   Etienne Pallier   Nouveau shell pyr...
477
478
479
480
481
482
            self.plc_status = PlcDeviceStatus.objects.exclude(plc_mode=None).latest(
                "created"
            )
            timeout = (
                datetime.datetime.now() - self.plc_status.created
            ).total_seconds()
d0b663be   Etienne Pallier   refactorized majo...
483
            if timeout >= self.config.plc_timeout_seconds:
af5d8b11   Etienne Pallier   Nouveau shell pyr...
484
485
                return False
            return True
6aec6155   theopuhl   Majordome algorit...
486

af5d8b11   Etienne Pallier   Nouveau shell pyr...
487
488
        except Config.DoesNotExist or PlcDeviceStatus.DoesNotExist:
            return False
6aec6155   theopuhl   Majordome algorit...
489

1179175f   Etienne Pallier   Majordome agent c...
490
491
    def reload_config(self):
        self.config = Config.objects.get(pk=1)
af5d8b11   Etienne Pallier   Nouveau shell pyr...
492
        """
1179175f   Etienne Pallier   Majordome agent c...
493
494
495
496
497
        try :
            self.config = Config.objects.get(pk=1)
        except Config.DoesNotExist:
            return (False)
        return self.config
af5d8b11   Etienne Pallier   Nouveau shell pyr...
498
        """
1179175f   Etienne Pallier   Majordome agent c...
499
500
501


""" OLD MAJORDOME CODE
6aec6155   theopuhl   Majordome algorit...
502
503


e8e6f017   Jeremy   Reworked devices ...
504
505
506
507
508
509
510
511
    '''
        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
512
513
514
515
516
517

    def setContext(self):
        self.tel = TelescopeController()
        self.vis_camera = VISCameraController()
        self.nir_camera = NIRCameraController()
        self.plc = PLCController()
cfc9d09c   Jeremy   Added dome simula...
518
        self.dom = DomeController()
65149de7   Jeremy   Update
519
        return (0)
65149de7   Jeremy   Update
520

c72eb17a   Jeremy   Update celery task
521
522
    def createTask(self):
        try:
1a2dc19f   Etienne Pallier   nombreux bugfixes...
523
524
525
            # (EP) NO find() method available from Django ORM !!!! 
            #TaskId.objects.find(task="majordome").delete()
            TaskId.objects.filter(task="majordome").delete()
c72eb17a   Jeremy   Update celery task
526
527
528
529
530
531
532
533
534
535
536
537
538
539
        except Exception as e:
            log.info(str(e))
            return 1
        TaskId.objects.create(task_id=self.request.id, task="majordome")
        return 0

    def setTasks(self):
        try:
            self.monitoring_task = TaskId.objects.get(task="monitoring")
            self.alert_task = TaskId.objects.get(task="alert_manager")
        except Exception as e:
            self.monitoring_task = None
            self.alert_task = None
        return 0
65149de7   Jeremy   Update
540
541
542
543
544
545
546
547
548
549
550
551
552
553
    '''
        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...
554
        Loop to wait for the device to be idle with the starting configurations.
65149de7   Jeremy   Update
555
556
    '''
    def waitDevices(self):
ce470283   Jeremy   Plc simulator fin...
557
558
559
560
561
        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
562
563
564
565
        return (0)

    '''
        Computes the beginning and the end of the following (or current) night
257abe9b   Jeremy   Added comments
566
        set the timers -> maybe put timers in a config file ?
65149de7   Jeremy   Update
567
568
569
570
571
572
    '''
    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...
573
574
        self.timer_night_start = self.night_start - getCurrentTime()
        self.timer_night_end = self.night_end - getCurrentTime()
65149de7   Jeremy   Update
575
        self.timer_status = 5
c72eb17a   Jeremy   Update celery task
576
        self.tasks_timer = 5
65149de7   Jeremy   Update
577
        self.timer_plc = 2
1aed430d   jeremy   Alert handled + k...
578
        self.alert_timer = 1
65149de7   Jeremy   Update
579
        self.timer_schedule = 1
05038bc8   Jeremy   Majordome logic i...
580
        self.timer_sequence = 1
65149de7   Jeremy   Update
581
582
583
584

        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
585
586
        if (getCurrentTime() > self.night_start):
            self.adaptTimers()
65149de7   Jeremy   Update
587
588

        self.timers = {
4cb0ff36   Jeremy   Update
589
590
591
592
593
            "status": self.timer_status,
            "environment": self.timer_plc,
            "night_start": self.timer_night_start,
            "night_end": self.timer_night_end,
            "schedule": self.timer_schedule,
c72eb17a   Jeremy   Update celery task
594
595
            "sequence": self.timer_sequence,
            "tasks": self.tasks_timer
4cb0ff36   Jeremy   Update
596
        }
ff448d43   Jeremy   Update
597
        if (settings.DEBUG and DEBUG_FILE):
e8e6f017   Jeremy   Reworked devices ...
598
599
            log.info("Majordome started with timers : " + str(self.timers))
        # Functions called during the loop
4cb0ff36   Jeremy   Update
600
601
602
603
604
605
        self.functions = {
            "status": self.handleStatusTimer,
            "environment": self.handleEnvironmentTimer,
            "night_start": self.handleNightStartTimer,
            "night_end": self.handleNightEndTimer,
            "schedule": self.handleScheduleTimer,
c72eb17a   Jeremy   Update celery task
606
607
            "sequence": self.handleSequenceTimer,
            "tasks": self.handleTasks
65149de7   Jeremy   Update
608
        }
65149de7   Jeremy   Update
609
610
        return (0)

257abe9b   Jeremy   Added comments
611
612
613
    '''
        Function called by the main loop to handle the task event (check monitoring and alert_manager)
    '''
c72eb17a   Jeremy   Update celery task
614
    def handleTasks(self):
5e45ba9f   Etienne Pallier   Bye Bye Celery (f...
615
        return 0
05bdcc44   Etienne Pallier   BIG DEMO tests (s...
616

c72eb17a   Jeremy   Update celery task
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
        self.timers["tasks"] = self.tasks_timer
        if self.monitoring_task is None:
            try:
                self.monitoring_task = TaskId.objects.get(task="monitoring")
            except Exception as e:
                monitoring.tasks.Monitoring.apply_async()
                if settings.DEBUG and DEBUG_FILE:
                    log.info(str(e))
        if self.alert_task is None:
            try:
                self.alert_task = TaskId.objects.get(task="alert_manager")
            except Exception as e:
                alert_manager.tasks.AlertListener.apply_async()
                if settings.DEBUG and DEBUG_FILE:
                    log.info(str(e))
        return 0

    # TODO adapt timers if the majordome is started during the night or not ?
4cb0ff36   Jeremy   Update
635
636
637
    def adaptTimers(self):
        pass

bca9a283   Jeremy   Reworked the sche...
638
639
640
    def logDB(self, message: str):
        Log.objects.create(agent="Majordome", message=message)

65149de7   Jeremy   Update
641
642
    '''
        Infinite loop according to the majordome behavior
65149de7   Jeremy   Update
643
644
    '''
    def loop(self):
d0b663be   Etienne Pallier   refactorized majo...
645
        while (self.closing_mode != "OCS-SHUTDOWN"):
b4e8963c   Etienne Pallier   Each agent (envmo...
646
            print("(MAJOR): start new iteration")
65149de7   Jeremy   Update
647
648
649
650
            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
651
652
            for timer_name, timer_value in self.timers.items():
                if (timer_value <= 0):
4cb0ff36   Jeremy   Update
653
                    if timer_name in self.functions:
bca9a283   Jeremy   Reworked the sche...
654
                        self.logDB("Executing timer " + str(timer_name))
4cb0ff36   Jeremy   Update
655
                        self.functions[timer_name]()
65149de7   Jeremy   Update
656
                    else:
ff448d43   Jeremy   Update
657
                        if (settings.DEBUG and DEBUG_FILE):
4cb0ff36   Jeremy   Update
658
                            log.info("Timer : " + str(timer_name) + "is not known by the Majordome")
bca9a283   Jeremy   Reworked the sche...
659
                        self.logDB("Timer " + str(timer_name) + " unknown")
ff448d43   Jeremy   Update
660
                    if (settings.DEBUG and DEBUG_FILE):
e8e6f017   Jeremy   Reworked devices ...
661
                        log.info("Timer : " + str(timer_name) + " executed")
075082e1   Etienne Pallier   added start of ag...
662
            # EP added because loop is too quick (without CELERY)
5e45ba9f   Etienne Pallier   Bye Bye Celery (f...
663
            time.sleep(2)
05038bc8   Jeremy   Majordome logic i...
664
665
        return (0)

257abe9b   Jeremy   Added comments
666
667
668
    '''
        Function called by the main loop to handle environment event (PLC info)
    '''
4cb0ff36   Jeremy   Update
669
670
    def handleEnvironmentTimer(self):
        self.timers["environment"] = self.timer_plc
ce470283   Jeremy   Plc simulator fin...
671
        self.handlePLC()
4cb0ff36   Jeremy   Update
672
673
        return (0)

257abe9b   Jeremy   Added comments
674
675
676
    '''
        Function called by the main loop to handle the devices status
    '''
4cb0ff36   Jeremy   Update
677
678
    def handleStatusTimer(self):
        self.timers["status"] = self.timer_status
ce470283   Jeremy   Plc simulator fin...
679
680
681
682
        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
683
        self.handleStatus()
c72eb17a   Jeremy   Update celery task
684
        return 0
4cb0ff36   Jeremy   Update
685

257abe9b   Jeremy   Added comments
686
687
688
    '''
        Function called by the main loop to check if the executing sequence is finished
    '''
4cb0ff36   Jeremy   Update
689
690
    def handleSequenceTimer(self):
        self.timers["sequence"] = self.timer_sequence
ff448d43   Jeremy   Update
691
692
693
        if (self.executing_sequence):
            self.handleSequence(self.executing_sequence[0],
                                self.executing_sequence[1], self.executing_sequence[2])
4cb0ff36   Jeremy   Update
694
695
        return (0)

257abe9b   Jeremy   Added comments
696
697
698
    '''
        Function called by the main loop to check if there is a new schedule and to execute its sequences
    '''
4cb0ff36   Jeremy   Update
699
    def handleScheduleTimer(self):
ef60c3ec   Jeremy   Majordome and mon...
700
        self.timers["schedule"] = self.timer_schedule
4cb0ff36   Jeremy   Update
701
        if (self.isValidStatus(self.status_tel)):
ff448d43   Jeremy   Update
702
            if (self.schedule is None):
ef60c3ec   Jeremy   Majordome and mon...
703
704
705
                try:
                    self.schedule = Schedule.objects.latest('created')
                except ObjectDoesNotExist:
ff448d43   Jeremy   Update
706
                    if (settings.DEBUG and DEBUG_FILE):
ef60c3ec   Jeremy   Majordome and mon...
707
708
                        log.info("No schedule found in database")
                    return (1)
4cb0ff36   Jeremy   Update
709
            else:
ef60c3ec   Jeremy   Majordome and mon...
710
711
712
                try:
                    schedule = Schedule.objects.latest('created')
                except ObjectDoesNotExist:
ff448d43   Jeremy   Update
713
                    if (settings.DEBUG and DEBUG_FILE):
ef60c3ec   Jeremy   Majordome and mon...
714
715
                        log.info("No schedule found in database")
                    return (1)
4cb0ff36   Jeremy   Update
716
717
718
                if (schedule.created != self.schedule.created):
                    self.next_sequence = None
                    self.schedule = schedule
1aed430d   jeremy   Alert handled + k...
719
                    self.firstSequenceIsAlert()
4cb0ff36   Jeremy   Update
720
            if (self.schedule):
c53a13e0   Jeremy   Updating a lot of...
721
722
                shs_list = self.schedule.shs.filter(Q(status=Sequence.PLANNED) |
                                                    Q(status=Sequence.PENDING)).order_by('tsp')
4cb0ff36   Jeremy   Update
723
724
725
726
727
                self.executeSchedule(shs_list)
        else:
            self.notifyTelescopeStatus("scheduler")
        return (0)

257abe9b   Jeremy   Added comments
728
    '''
1aed430d   jeremy   Alert handled + k...
729
730
731
732
733
734
735
736
737
738
739
740
741
742
        Function called by handleScheduleTimer, the purpose is to kill the executing sequence if the
        first sequence in the new planning is from an alert
    '''
    @executingSequenceExist
    def firstSequenceIsAlert(self):
        shs_list = self.schedule.shs.filter(Q(status=Sequence.PLANNED) |
                                            Q(status=Sequence.PENDING)).order_by('tsp')
        if shs_list and shs_list[0].sequence.is_alert:
            if shs_list[0].sequence.created.date() >= (datetime.datetime.now() - datetime.timedelta(seconds=10)).date():
                self.killExecutingSequence()
                return 1
        return 0

    '''
257abe9b   Jeremy   Added comments
743
744
        Function called by the main loop to handle the end of a night
    '''
4cb0ff36   Jeremy   Update
745
    def handleNightEndTimer(self):
ce470283   Jeremy   Plc simulator fin...
746
        self.timers["night_end"] = getNightEnd()
4cb0ff36   Jeremy   Update
747
        if (self.isValidStatus(self.status_tel)):
05bdcc44   Etienne Pallier   BIG DEMO tests (s...
748
            #observation_manager.tasks.night_calibrations.apply_async()
5e45ba9f   Etienne Pallier   Bye Bye Celery (f...
749
750
            print("MJ: call observation_manager WITHOUT CELERY")
            observation_manager.tasks.night_calibrations().run()
05bdcc44   Etienne Pallier   BIG DEMO tests (s...
751

4cb0ff36   Jeremy   Update
752
753
754
755
        else:
            self.notifyTelescopeStatus("night_end")
        return (0)

257abe9b   Jeremy   Added comments
756
    '''
ed1bf194   Etienne Pallier   bugfix task major...
757
        Function called by the main loop to handle the beginning of a night
257abe9b   Jeremy   Added comments
758
    '''
4cb0ff36   Jeremy   Update
759
760
    def handleNightStartTimer(self):
        self.timers["night_start"] = getNextNightStart()
c72eb17a   Jeremy   Update celery task
761
762
763
764
        if self.isOutsideOk():
            self.dom.open()
            self.vis_camera.open_shutter()
            self.nir_camera.open_shutter()
05bdcc44   Etienne Pallier   BIG DEMO tests (s...
765
        #scheduler.tasks.scheduling.apply_async((False, False))
5e45ba9f   Etienne Pallier   Bye Bye Celery (f...
766
767
        print("MJ: call schedule WITHOUT CELERY")
        scheduler.tasks.scheduling().run((False, False))
05bdcc44   Etienne Pallier   BIG DEMO tests (s...
768

4cb0ff36   Jeremy   Update
769
770
        return (0)

ef60c3ec   Jeremy   Majordome and mon...
771
772
773
    def notifyTelescopeStatus(self, timer_name):
        return (self.notifyDeviceStatus("telescope", timer_name, self.status_tel))

05038bc8   Jeremy   Majordome logic i...
774
    def notifyDeviceStatus(self, device_name, timer_name, status):
ef60c3ec   Jeremy   Majordome and mon...
775
776
        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...
777
        # TODO MAYBE reset some variables and do a scheduling
65149de7   Jeremy   Update
778
779
780
        return (0)

    '''
257abe9b   Jeremy   Added comments
781
        Execute a schedule
65149de7   Jeremy   Update
782
783
    '''
    def executeSchedule(self, shs_list):
c72eb17a   Jeremy   Update celery task
784
        for shs in shs_list:  # shs_list is sorted by tsp
c53a13e0   Jeremy   Updating a lot of...
785
786
787
            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...
788
                if self.isExecutable() and self.executing_sequence is None:
c53a13e0   Jeremy   Updating a lot of...
789
790
791
792
793
                    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
794
                        else:
c53a13e0   Jeremy   Updating a lot of...
795
                            self.next_sequence = None
ff448d43   Jeremy   Update
796
797
                    else:
                        return 0
bca9a283   Jeremy   Reworked the sche...
798
            else:
ff448d43   Jeremy   Update
799
                if (settings.DEBUG and DEBUG_FILE):
bca9a283   Jeremy   Reworked the sche...
800
                    log.info("Sequence cannot be executed : Not observable")
ff448d43   Jeremy   Update
801
802
                self.logDB("Sequence "+shs.sequence.name+" cannot be executed : Not observable")
        return 0
05038bc8   Jeremy   Majordome logic i...
803

4cb0ff36   Jeremy   Update
804
    def observable(self, sequence):
ff448d43   Jeremy   Update
805
806
807
        if (sequence.jd2 - sequence.duration - secondsToPreciseJulianDate(getPreciseCurrentTime()) <= 0):
            return 0
        return 1
4cb0ff36   Jeremy   Update
808

c53a13e0   Jeremy   Updating a lot of...
809
810
811
812
813
    def executableSequence(self, status):
        if status == Sequence.PLANNED or status == Sequence.PENDING:
            return 1
        return 0

257abe9b   Jeremy   Added comments
814
815
816
    '''
        Kill the executing sequence and set its state to cancelled
    '''
678838ed   Jeremy   Weather ans insid...
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
    @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()
05bdcc44   Etienne Pallier   BIG DEMO tests (s...
836
            #scheduler.tasks.scheduling.delay((False, False))
5e45ba9f   Etienne Pallier   Bye Bye Celery (f...
837
838
            print("MJ: call schedule WITHOUT CELERY")
            scheduler.tasks.scheduling().run((False, False))
05bdcc44   Etienne Pallier   BIG DEMO tests (s...
839

678838ed   Jeremy   Weather ans insid...
840
        elif type == "INSIDE":
05bdcc44   Etienne Pallier   BIG DEMO tests (s...
841
            #scheduler.tasks.scheduling.delay((False, False))
5e45ba9f   Etienne Pallier   Bye Bye Celery (f...
842
843
            print("MJ: call schedule WITHOUT CELERY")
            scheduler.tasks.scheduling().run((False, False))
678838ed   Jeremy   Weather ans insid...
844

257abe9b   Jeremy   Added comments
845
846
847
    '''
        Handle a new alarm (called by isInsideOk or isWeatherOk)
    '''
678838ed   Jeremy   Weather ans insid...
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
    @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...
876
877
878
    def isOutsideOk(self) -> bool:
        self.handlePLC()
        if self.weather_status == "OK":
678838ed   Jeremy   Weather ans insid...
879
880
            if "WEATHER" in self.alarm_list:
                self.handleAlarm("ENDED", self.alarm_list.index("WEATHER"))
ce470283   Jeremy   Plc simulator fin...
881
            return True
678838ed   Jeremy   Weather ans insid...
882
        self.handleAlarm("WEATHER")
ce470283   Jeremy   Plc simulator fin...
883
884
        return False

257abe9b   Jeremy   Added comments
885
886
887
    '''
        Check the telescope inside status
    '''
ce470283   Jeremy   Plc simulator fin...
888
889
890
    def isInsideOk(self) -> bool:
        self.handlePLC()
        if self.site_status == "OK":
678838ed   Jeremy   Weather ans insid...
891
892
            if "INSIDE" in self.alarm_list:
                self.handleAlarm("ENDED", self.alarm_list.index("INSIDE"))
ce470283   Jeremy   Plc simulator fin...
893
            return True
678838ed   Jeremy   Weather ans insid...
894
        self.handleAlarm("INSIDE")
ce470283   Jeremy   Plc simulator fin...
895
896
897
898
899
900
901
902
903
904
905
906
907
908
        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

257abe9b   Jeremy   Added comments
909
910
911
    '''
        check if the sequence timer is valid for execution, also check if there is a scheduling task running
    '''
ce470283   Jeremy   Plc simulator fin...
912
    def isValidTimer(self, shs) -> bool:
c53a13e0   Jeremy   Updating a lot of...
913
914
        current_countdown = self.getCountdown(shs)
        if (current_countdown <= JulianSeconds(5)):
c53a13e0   Jeremy   Updating a lot of...
915
916
917
            try:
                task = TaskId.objects.filter(task="scheduling")
                if not task:
ce470283   Jeremy   Plc simulator fin...
918
919
                    return True
                return False
c53a13e0   Jeremy   Updating a lot of...
920
            except:
ce470283   Jeremy   Plc simulator fin...
921
922
                return True
        return False
c53a13e0   Jeremy   Updating a lot of...
923

05038bc8   Jeremy   Majordome logic i...
924
    '''
257abe9b   Jeremy   Added comments
925
        Launch the observation tasks NIR and VIS associated to a sequence
05038bc8   Jeremy   Majordome logic i...
926
    '''
c53a13e0   Jeremy   Updating a lot of...
927
    def executeSequence(self, shs, sequence):
3224f14a   Jeremy   Fixed some simula...
928
929
930
931
        shs.status = Sequence.EXECUTING
        sequence.status = Sequence.EXECUTING
        shs.save()
        sequence.save()
c53a13e0   Jeremy   Updating a lot of...
932
        log.info("Executing sequence id = " + str(sequence.pk))
bca9a283   Jeremy   Reworked the sche...
933
        self.logDB("Executing sequence")
05038bc8   Jeremy   Majordome logic i...
934
        plans_results = []
05038bc8   Jeremy   Majordome logic i...
935
936
937
        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():
05bdcc44   Etienne Pallier   BIG DEMO tests (s...
938
                    #res = observation_manager.tasks.execute_plan_nir.apply_async((plan.id, float(self.getCountdown(shs))))
5e45ba9f   Etienne Pallier   Bye Bye Celery (f...
939
940
941
                    print("MJ: call observation_manager WITHOUT CELERY")
                    res = observation_manager.tasks.execute_plan_nir().run(
                        (plan.id, float(self.getCountdown(shs))))
05bdcc44   Etienne Pallier   BIG DEMO tests (s...
942

c53a13e0   Jeremy   Updating a lot of...
943
944
                    # JB TODO : is it still usefull ?
                    # TaskId.objects.create(task_id=res.id, task="execute_plan")
05038bc8   Jeremy   Majordome logic i...
945
                    plans_results.append(res)
ff448d43   Jeremy   Update
946
947
            else:
                self.notifyDeviceStatus("Cagire", "Sequence execution", self.status_nir)
c53a13e0   Jeremy   Updating a lot of...
948
949
950
                sequence.status = Sequence.CANCELLED
                shs.status = Sequence.CANCELLED
                shs.save()
ff448d43   Jeremy   Update
951
952
                sequence.save()
                return (1)
05038bc8   Jeremy   Majordome logic i...
953
954
955
        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():
05bdcc44   Etienne Pallier   BIG DEMO tests (s...
956
                    #res = observation_manager.tasks.execute_plan_vis.apply_async((plan.id, float(self.getCountdown(shs))))
5e45ba9f   Etienne Pallier   Bye Bye Celery (f...
957
958
                    print("MJ: call observation_manager WITHOUT CELERY")
                    res = observation_manager.tasks.execute_plan_vis().run((plan.id, float(self.getCountdown(shs))))
05bdcc44   Etienne Pallier   BIG DEMO tests (s...
959

05038bc8   Jeremy   Majordome logic i...
960
961
962
                    plans_results.append(res)
            else:
                self.notifyDeviceStatus("Camera visible", "Sequence execution", self.status_vis)
c53a13e0   Jeremy   Updating a lot of...
963
964
965
                sequence.status = Sequence.CANCELLED
                shs.status = Sequence.CANCELLED
                shs.save()
05038bc8   Jeremy   Majordome logic i...
966
967
                sequence.save()
                return (1)
05038bc8   Jeremy   Majordome logic i...
968
        self.executing_sequence = [shs, sequence, plans_results]
05038bc8   Jeremy   Majordome logic i...
969
970
971
972
973
        return (0)

    '''
        Set the next sequence
    '''
c53a13e0   Jeremy   Updating a lot of...
974
    def setNextSequence(self, shs, sequence):
ff448d43   Jeremy   Update
975
        sequence.status = Sequence.PENDING
c53a13e0   Jeremy   Updating a lot of...
976
977
        shs.status = Sequence.PENDING
        self.next_sequence = [shs, sequence]
ff448d43   Jeremy   Update
978
        sequence.save()
c53a13e0   Jeremy   Updating a lot of...
979
        shs.save()
05038bc8   Jeremy   Majordome logic i...
980
981
982
983
984
985
        return (0)

    '''
        Check if the current sequence is finished
    '''
    def handleSequence(self, shs, sequence, executing_plans):
c53a13e0   Jeremy   Updating a lot of...
986
        count = 0
c53a13e0   Jeremy   Updating a lot of...
987
        for res in executing_plans:
05038bc8   Jeremy   Majordome logic i...
988
            try:
c53a13e0   Jeremy   Updating a lot of...
989
990
                if res.successful() or res.failed():
                    count += 1
05038bc8   Jeremy   Majordome logic i...
991
            except Exception as e:
678838ed   Jeremy   Weather ans insid...
992
993
                if DEBUG_FILE and settings.DEBUG:
                    log.info(str(e))
05038bc8   Jeremy   Majordome logic i...
994
995
996
997
998
                shs.status = Sequence.CANCELLED
                sequence.status = Sequence.CANCELLED
                shs.save()
                sequence.save()
                for rev in executing_plans:
c53a13e0   Jeremy   Updating a lot of...
999
1000
1001
                    if (not rev.failed() and not rev.successful()):
                        rev.revoke(terminate=True)
                self.executing_sequence = None
05038bc8   Jeremy   Majordome logic i...
1002
                return (-1)
c53a13e0   Jeremy   Updating a lot of...
1003
        if count >= len(executing_plans):
05038bc8   Jeremy   Majordome logic i...
1004
1005
1006
1007
1008
            sequence.status = Sequence.EXECUTED
            shs.status = Sequence.EXECUTED
            sequence.save()
            shs.save()
            message = "Finished sequence " + str(sequence.pk) + " execution"
05038bc8   Jeremy   Majordome logic i...
1009
            Log.objects.create(agent="Majordome", message=message)
c53a13e0   Jeremy   Updating a lot of...
1010
            self.executing_sequence = None
05038bc8   Jeremy   Majordome logic i...
1011
        return (0)
65149de7   Jeremy   Update
1012
1013
1014
1015

    '''
        Function called to do an action with the devices status
    '''
05038bc8   Jeremy   Majordome logic i...
1016
    def handleStatus(self):
05038bc8   Jeremy   Majordome logic i...
1017
1018
1019
        telescope = Telescope.objects.first()
        camera_nir = Detector.objects.get(name="Cagire")
        camera_vis = Detector.objects.get(name="Visible camera")
ce470283   Jeremy   Plc simulator fin...
1020
1021
1022
        dome = Dome.objects.get(name="Dome")

        dome.status = self.status_dom
05038bc8   Jeremy   Majordome logic i...
1023
1024
1025
        telescope.status = self.status_tel
        camera_nir.status = self.status_nir
        camera_vis.status = self.status_vis
ce470283   Jeremy   Plc simulator fin...
1026
1027
1028
1029
1030

        dome.save()
        telescope.save()
        camera_nir.save()
        camera_vis.save()
bca9a283   Jeremy   Reworked the sche...
1031
1032
        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
1033
1034
1035
        return (0)

    '''
3224f14a   Jeremy   Fixed some simula...
1036
        Put the majordome in pause
4cb0ff36   Jeremy   Update
1037
    '''
4cb0ff36   Jeremy   Update
1038
    def systemPause(self, duration, cause: str):
bca9a283   Jeremy   Reworked the sche...
1039
        self.logDB("System in pause for " + str(duration))
4cb0ff36   Jeremy   Update
1040
        time.sleep(duration)
05bdcc44   Etienne Pallier   BIG DEMO tests (s...
1041
        #scheduler.tasks.scheduling.apply_async(first_schedule=False, alert=False)
5e45ba9f   Etienne Pallier   Bye Bye Celery (f...
1042
1043
        print("MJ: call schedule WITHOUT CELERY")
        scheduler.tasks.scheduling().run(first_schedule=False, alert=False)
05bdcc44   Etienne Pallier   BIG DEMO tests (s...
1044

4cb0ff36   Jeremy   Update
1045
1046
1047
1048
1049
        self.setTime()
        print("system has been paused. Cause : " + cause)
        return (0)

    '''
65149de7   Jeremy   Update
1050
1051
        Function called to do an action with the site status and the wheather status
    '''
ce470283   Jeremy   Plc simulator fin...
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
    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...
1063
        return 0
5b5566ab   haribo   added celery
1064

4cb0ff36   Jeremy   Update
1065
    '''
05038bc8   Jeremy   Majordome logic i...
1066
        Gets the time before the expected start of the execution.
4cb0ff36   Jeremy   Update
1067
    '''
05038bc8   Jeremy   Majordome logic i...
1068
1069
    def getCountdown(self, shs):
        # TODO start sequence as soon as possible (a lot of verifications must be done there)
ff448d43   Jeremy   Update
1070
        current_time = secondsToPreciseJulianDate(getPreciseCurrentTime())
05038bc8   Jeremy   Majordome logic i...
1071
        countdown = shs.tsp - current_time
9774228b   haribo   Date: 22/06/2016
1072
        return countdown
7a79e25b   haribo   Date: 19/05/2016
1073

4cb0ff36   Jeremy   Update
1074
1075
1076
1077
    '''
        Change observation conditions
    '''
    def changeObsConditions(self):
5b5566ab   haribo   added celery
1078
        print("change_obs_conditions")
1179175f   Etienne Pallier   Majordome agent c...
1079
1080
        pass

af5d8b11   Etienne Pallier   Nouveau shell pyr...
1081
"""