tasks.py 17.1 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 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 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444
from __future__ import absolute_import
from common.models import *
from django.core.exceptions import ObjectDoesNotExist
import scheduler
import scheduler.tasks
from celery.task import Task
from celery import app
import observation_manager
import observation_manager.tasks
from devices.Telescope import TelescopeController
from devices.CameraVIS import VISCameraController
from devices.CameraNIR import NIRCameraController
from devices.Dome import DomeController
from devices.PLC import PLCController
from django.conf import settings
from utils.JDManipulator import *
import utils.Logger as L

DEBUG_FILE = False
log = L.setupLogger("MajordomeTaskLogger", "Majordome")

'''
    Task to handle the execution of the program

    check the environment status in database
    check the devices status (telescope / cameras)
    check if the last schedule made has to be planned
    launch schedule's sequences
'''
class Majordome(Task):
    loop_speed = 1
    julian_div = 86400
    executing_sequence = None
    next_sequence = None
    status_tel = ""
    status_nir = ""
    status_vis = ""
    status_dom = ""
    timers = {}
    functions = {}
    schedule = None
    majordome_status = "STARTING"

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

    def setContext(self):
        self.tel = TelescopeController()
        self.vis_camera = VISCameraController()
        self.nir_camera = NIRCameraController()
        self.plc = PLCController()
        self.dom = DomeController()
        return (0)

    '''
        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()
        self.setContext()
        self.setTime()
        self.majordome_status = "EXECUTING"
        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)

    '''
        Loop to wait for the device to be idle avec the starting configurations.
    '''
    def waitDevices(self):
        # TODO Maybe remove comment if we need to wait the devices connection / valid status
        # while self.status_vis == "" and self.status_tel == "" and self.status_nir == "" and self.status_dom == "":
        self.status_vis = self.vis_camera.get("STATUS")
        self.status_nir = self.nir_camera.get("STATUS")
        self.status_tel = self.tel.get("STATUS")
        self.status_dom = self.dom.get("STATUS")
        print("Devices ready !")
        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())
        self.timer_night_start = self.night_start - getCurrentTime()
        self.timer_night_end = self.night_end - getCurrentTime()
        self.timer_status = 5
        self.timer_plc = 2
        self.timer_schedule = 1
        self.timer_sequence = 1

        if (self.night_start - 120 > getCurrentTime()):
            self.timer_night_start = self.night_start - 120 - getCurrentTime()
        self.timer_night_end = self.night_end - getCurrentTime()
        if (getCurrentTime() > self.night_start):
            self.adaptTimers()

        self.timers = {
            "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
        }
        if (settings.DEBUG and DEBUG_FILE):
            log.info("Majordome started with timers : " + str(self.timers))
        # Functions called during the loop
        self.functions = {
            "status": self.handleStatusTimer,
            "environment": self.handleEnvironmentTimer,
            "night_start": self.handleNightStartTimer,
            "night_end": self.handleNightEndTimer,
            "schedule": self.handleScheduleTimer,
            "sequence": self.handleSequenceTimer
        }
        return (0)

    # TODO adapt timers if the majordome is started during the night
    def adaptTimers(self):
        pass

    def logDB(self, message: str):
        Log.objects.create(agent="Majordome", message=message)

    '''
        Infinite loop according to the majordome behavior
    '''
    def loop(self):
        while (self.majordome_status != "SHUTDOWN"):
            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()}
            for timer_name, timer_value in self.timers.items():
                if (timer_value <= 0):
                    if timer_name in self.functions:
                        self.logDB("Executing timer " + str(timer_name))
                        self.functions[timer_name]()
                    else:
                        if (settings.DEBUG and DEBUG_FILE):
                            log.info("Timer : " + str(timer_name) + "is not known by the Majordome")
                        self.logDB("Timer " + str(timer_name) + " unknown")
                    if (settings.DEBUG and DEBUG_FILE):
                        log.info("Timer : " + str(timer_name) + " executed")
        return (0)

    def handleEnvironmentTimer(self):
        self.timers["environment"] = self.timer_plc
        try:
            site_status = SiteWatch.objects.latest('updated')
            weather_status = WeatherWatch.objects.latest('updated')
        except ObjectDoesNotExist:
            if (settings.DEBUG and DEBUG_FILE):
                log.info("No site_status or weather_status found in database")
            return (1)
        self.handlePLC(site_status, weather_status)
        return (0)

    def handleStatusTimer(self):
        self.timers["status"] = self.timer_status
        self.status_tel = self.tel.get("STATUS")
        self.status_nir = self.nir_camera.get("STATUS")
        self.status_vis = self.vis_camera.get("STATUS")
        self.status_dom = self.dom.get("STATUS")
        self.handleStatus()
        return (0)

    def handleSequenceTimer(self):
        self.timers["sequence"] = self.timer_sequence
        if (self.executing_sequence):
            self.handleSequence(self.executing_sequence[0],
                                self.executing_sequence[1], self.executing_sequence[2])
        return (0)

    def handleScheduleTimer(self):
        self.timers["schedule"] = self.timer_schedule
        if (self.isValidStatus(self.status_tel)):
            if (self.schedule is None):
                try:
                    self.schedule = Schedule.objects.latest('created')
                except ObjectDoesNotExist:
                    if (settings.DEBUG and DEBUG_FILE):
                        log.info("No schedule found in database")
                    return (1)
            else:
                try:
                    schedule = Schedule.objects.latest('created')
                except ObjectDoesNotExist:
                    if (settings.DEBUG and DEBUG_FILE):
                        log.info("No schedule found in database")
                    return (1)
                if (schedule.created != self.schedule.created):
                    self.next_sequence = None
                    self.schedule = schedule
            if (self.schedule):
                shs_list = self.schedule.shs.filter(status=Sequence.PENDING).order_by('tsp')
                self.executeSchedule(shs_list)
        else:
            self.notifyTelescopeStatus("scheduler")
        return (0)

    def handleNightEndTimer(self):
        self.timers["night_end"] = getNextNightEnd()
        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()
        if (self.isValidStatus(self.status_tel)):
            scheduler.tasks.scheduling.delay(first_schedule=False, alert=False)
        else:
            self.notifyTelescopeStatus("night_start")
        return (0)

    def notifyTelescopeStatus(self, timer_name):
        return (self.notifyDeviceStatus("telescope", timer_name, self.status_tel))

    def notifyDeviceStatus(self, device_name, timer_name, status):
        Log.objects.create(agent=device_name, created=datetime.datetime.now(),
                           message="The action : " + str(timer_name) + " has been canceled : Telescope status : " + str(status))
        # maybe reset some variables and do a scheduling
        return (0)

    '''
        Function called when a schedule has to be executed
    '''
    def executeSchedule(self, shs_list):
        is_prev_planned = False
        self.logDB("Trying to execute a sequence from current schedule")
        for shs in shs_list: # shs_list is sorted by tsp
            if (shs.sequence.status == Sequence.PLANNED and self.observable(shs.sequence)):
                countdown = self.getCountdown(shs)
                # if (countdown <= 6):
                #     TODO CHECK IF OBSERVABLE ELSE RESCHEDULE
                if countdown <= JulianSeconds(5):
                    if self.executing_sequence is None:
                        if self.switchSequence():
                            self.executeSequence(shs, shs.sequence, countdown)
                        else:
                            self.setNextSequence(shs, shs.sequence, countdown)
                    elif self.next_sequence is None:
                        self.setNextSequence(shs, shs.sequence, countdown)
                    else:
                        return 0
                elif self.next_sequence is None:
                    self.setNextSequence(shs, shs.sequence, countdown)
            else:
                if (settings.DEBUG and DEBUG_FILE):
                    log.info("Sequence cannot be executed : Not observable")
                self.logDB("Sequence "+shs.sequence.name+" cannot be executed : Not observable")
        return 0

    def observable(self, sequence):
        if (sequence.jd2 - sequence.duration - secondsToPreciseJulianDate(getPreciseCurrentTime()) <= 0):
            return 0
        return 1

    '''
        Launch the observation tasks associated to a sequence
    '''
    def executeSequence(self, shs, sequence, countdown):
        if (countdown > JulianSeconds(5)):
            if self.next_sequence and self.next_sequence[1].status == Sequence.PENDING:
                self.next_sequence[1].status = Sequence.PLANNED
                self.next_sequence[1].save()
            return 0
        if self.next_sequence and self.next_sequence[1].status == Sequence.PLANNED:
            self.next_sequence[1].status = Sequence.PENDING
            self.next_sequence[1].save()

        self.logDB("Executing sequence")
        plans_results = []
        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():
                    res = observation_manager.tasks.execute_plan_nir.apply_async((plan.id, float(countdown)))
                    TaskId.objects.create(task_id=res.id, task="execute_plan")
                    plans_results.append(res)
            else:
                self.notifyDeviceStatus("Cagire", "Sequence execution", self.status_nir)
                sequence.status = Sequence.DEVICE_ERROR
                sequence.save()
                return (1)
        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():
                    res = observation_manager.tasks.execute_plan_vis.apply_async((plan.id, float(countdown)))
                    TaskId.objects.create(task_id=res.id, task="execute_plan")
                    plans_results.append(res)
            else:
                self.notifyDeviceStatus("Camera visible", "Sequence execution", self.status_vis)
                sequence.status = Sequence.DEVICE_ERROR
                sequence.save()
                return (1)
        shs.status = Sequence.EXECUTING
        sequence.status = Sequence.EXECUTING
        shs.save()
        sequence.save()
        self.executing_sequence = [shs, sequence, plans_results]
        return (0)

    '''
        Set the next sequence
    '''
    def setNextSequence(self, shs, sequence, countdown):
        sequence.status = Sequence.PENDING
        self.next_sequence = [shs, sequence, countdown]
        sequence.save()
        return (0)

    '''
        Switch sequences
    '''
    def switchSequence(self):
        self.executing_sequence = None
        if (self.next_sequence is not None):
            self.executeSequence(self.next_sequence[0],
                                 self.next_sequence[1], self.next_sequence[2])
            self.next_sequence = None
        else:
            return 1
        return (0)

    '''
        Check if the current sequence is finished
    '''
    def handleSequence(self, shs, sequence, executing_plans):
        finished = False
        error = False

        for plan in executing_plans:
            try:
                if plan.ready() == False:
                    finished = True
            except Exception as e:
                error = True
                shs.status = Sequence.CANCELLED
                sequence.status = Sequence.CANCELLED
                shs.save()
                sequence.save()
                for rev in executing_plans:
                    if (not rev.failed() and rev.ready() != True):
                        app.control.revoke(rev.id)
                self.switchSequence()
                return (-1)
        if (finished):
            sequence.status = Sequence.EXECUTED
            shs.status = Sequence.EXECUTED
            sequence.save()
            shs.save()
            message = "Finished sequence " + str(sequence.pk) + " execution"
            Log.objects.create(agent="Majordome", message=message)
            self.switchSequence()
        return (0)

    '''
        Function called to do an action with the devices status
    '''
    def handleStatus(self):
        # TODO switch majordome state according to devices status
        telescope = Telescope.objects.first()
        camera_nir = Detector.objects.get(name="Cagire")
        camera_vis = Detector.objects.get(name="Visible camera")
        # TODO Dome in database
        # dome = ???.objects.get(name="Dome")
        # dome.status = self.status_dom
        # dome.save()
        # TODO adapt the status (must be short)
        telescope.status = self.status_tel
        camera_nir.status = self.status_nir
        camera_vis.status = self.status_vis
        # TODO Uncomment when prev todo id done
        # telescope.save()
        # camera_nir.save()
        # camera_vis.save()
        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))
        return (0)

    '''
        Put the system in Pause
    '''
    def systemPause(self, duration, cause: str):
        self.logDB("System in pause for " + str(duration))
        time.sleep(duration)
        scheduler.tasks.scheduling.delay(first_schedule=False, alert=False)
        self.setTime()
        print("system has been paused. Cause : " + cause)
        return (0)

    '''
        Function called to do an action with the site status and the wheather status
    '''
    def handlePLC(self, site_status, weather_status):
        return (0)

    '''
        Gets the time before the expected start of the execution.
    '''
    def getCountdown(self, shs):
        # TODO start sequence as soon as possible (a lot of verifications must be done there)
        current_time = secondsToPreciseJulianDate(getPreciseCurrentTime())
        countdown = shs.tsp - current_time
        return countdown

    '''
        Change observation conditions
    '''
    def changeObsConditions(self):
        print("change_obs_conditions")
        pass

if (__name__ == "__main__"):
    m = Majordome()
    m.run()