Commit 9c94cf43 authored by vertighel's avatar vertighel
Browse files

Coerenza delle 6 istanze camera: fix loop, expose, viewer Auto



devices/atik.py: _run_loop() non chiamava mai download() — il loop
scattava esposizioni ma non scriveva mai il FITS, quindi il viewer non
poteva aggiornarsi (scicam2 Loop).

devices/mako.py: l'eccezione nella fase di setup di _run_loop() spariva
senza log — il thread moriva in silenzio con looping ancora "true" in
UI (teccam2/3 Loop).

devices/{stx,atik,stl,mako}.py: log.info("... Loop started"/"stopped")
uniforme nel setter looping e a fine _run_loop(), per coerenza fra i
quattro device.

templates/snapshot_echelle.py: non esisteva (copia di
snapshot_spectro.py, camera_name default cam3) — Expose su scicam3
falliva con un 500 mai segnalato.

web/static/js/control.js:
- postExpose() ora controlla res.ok e mostra l'errore reale (showToast
  già esisteva ma non veniva mai raggiunto).
- mancava del tutto il listener per btn-echelle-expose: il bottone
  Expose di scicam3 non faceva nulla a prescindere dal template.
- i checkbox "Auto" del FITS viewer sono ora governati su due assi,
  modo (imaging/spectro/echelle) e tab Monitor (Scicam #mon-fits /
  Teccam #mon-teccam, via l'evento Bootstrap shown.bs.tab): è acceso
  solo quello del combo e del ruolo attivi, tutti gli altri sono spenti
  e disabilitati.

web/static/js/loop-toggle.js: poll ogni 5s mentre lo switch Loop è
"on", per riflettere un loop morto silenziosamente lato backend invece
di restare bloccato su "acceso" senza feedback.

web/static/js/viewer/fits-viewer.js: il costruttore inizializzava
autoUpdate sempre a true hardcoded, ignorando il .checked reale del
checkbox — dato che i FitsViewer si costruiscono in modo asincrono
dopo /api/cameras, questo disallineava lo stato visibile da quello
interno finché non arrivava un click utente reale. Ora legge lo stato
iniziale dal DOM.

Co-Authored-By: default avatarClaude Sonnet 5 <noreply@anthropic.com>
parent 9e4ff403
Loading
Loading
Loading
Loading
+4 −0
Original line number Diff line number Diff line
@@ -161,6 +161,7 @@ class Camera(BaseDevice):
        if value:
            self._loop_thread = threading.Thread(target=self._run_loop, daemon=True)
            self._loop_thread.start()
            log.info("Atik: Loop started")

    def stop_looping(self):
        """Stop the acquisition loop and wait for the in-flight frame to finish.
@@ -184,6 +185,9 @@ class Camera(BaseDevice):
            self._start(self.loop_exposure, 1)
            while self._looping and self.ready != 1:
                time.sleep(0.3)
            if self._looping:
                self.download()
        log.info("Atik: Loop stopped")

    def _start(self, duration, imagetype, datetime=None):
        """Trigger an exposure unconditionally (no loop guard).
+7 −1
Original line number Diff line number Diff line
@@ -267,6 +267,7 @@ class Guider(Mako):
        if value:
            self._loop_thread = threading.Thread(target=self._run_loop, daemon=True)
            self._loop_thread.start()
            log.info("Mako: Loop started")

    def stop_looping(self):
        """Stop the acquisition loop and wait for the in-flight frame to finish.
@@ -289,9 +290,13 @@ class Guider(Mako):
        try:
            self._set_exposure(self.loop_exposure)
            cam = self._check_connection()
        except Exception:
        except Exception as e:
            msg = f"Mako: loop setup failed: {e}"
            log.error(msg)
            self.error.append(msg)
            self._state = 5
            self._looping = False
            log.info("Mako: Loop stopped")
            return
        self._last_exptime = self.loop_exposure
        while self._looping:
@@ -307,6 +312,7 @@ class Guider(Mako):
                log.error(f"Mako loop error: {e}")
                self._state = 5
                time.sleep(1.0)
        log.info("Mako: Loop stopped")
        self._state = 0

    # --- Binning ---
+2 −0
Original line number Diff line number Diff line
@@ -518,6 +518,7 @@ class Camera(STL):
        if value:
            self._loop_thread = threading.Thread(target=self._run_loop, daemon=True)
            self._loop_thread.start()
            log.info("STL: Loop started")

    def stop_looping(self):
        """Stop the acquisition loop and wait until the camera is actually idle.
@@ -544,6 +545,7 @@ class Camera(STL):
                time.sleep(0.2)
            if self._looping:
                self.download()
        log.info("STL: Loop stopped")

    # --- Acquisition ---

+2 −0
Original line number Diff line number Diff line
@@ -199,6 +199,7 @@ class Camera(STX):
        if value:
            self._loop_thread = threading.Thread(target=self._run_loop, daemon=True)
            self._loop_thread.start()
            log.info("STX: Loop started")

    def stop_looping(self):
        """Stop the acquisition loop and wait until the camera is actually idle.
@@ -235,6 +236,7 @@ class Camera(STX):
                # before retriggering, or _start() rejects the next frame.
                while self._looping and self.state != 0:
                    time.sleep(0.1)
        log.info("STX: Loop stopped")

    def _start(self, duration, imagetype, datetime=None):
        """Trigger an exposure unconditionally (no loop guard).
+264 −0
Original line number Diff line number Diff line
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

# System modules
from time import sleep

# Third-party modules
from astropy.time import Time

# Other templates
from ..config.constants import (camera_state, filter_name, filter_number,
                                filter_state, frame_number, frame_type,
                                image_state, temp_fits, viewer_fits_path)
from .. import devices as _dev
from ..devices import dom, tel
from ..utils.coordinates import apply_offset
from ..utils.logger import log
from .basetemplate import BaseTemplate
from .fillheader import Template as FillHeader
from .lampsoff import Template as LampsOff


class Template(BaseTemplate):
    def __init__(self):
        super().__init__()
        self.name = "snapshot_echelle"
        self.description = "Observes a field with the échelle camera"

    def content(self, params):

        ########################
        ##### Params check #####
        ########################

        try:
            camera_name = params.get("camera") or "cam3"
            cam = getattr(_dev, camera_name)
            fits_file = viewer_fits_path(getattr(cam, '_viewer_key', None))

            objname = params.get("object") or "test"
            repeat = params.get("repeat") or 1
            imagetype = params.get("imagetype") or "Light"
            binning = params.get("binning") or cam.binning
            filt = params.get("filter") or (
                filter_name.get(cam.filter) if hasattr(cam, 'filter') else None)
            xystart = params.get("xystart")
            xyend = params.get("xyend")
            exptime = params["exptime"]
            self.domeslewing = params.get("domeslewing") or False
            self.recenter = params.get("recenter") or False
            self.box = params.get("box") or 300

        except KeyError as e:
            msg = f"Parameter {e} not found"
            log.error(msg)
            self.error.append(msg)
            return

        #########################################
        ##### Switch off lamps if not Flat  #####
        #########################################

        if imagetype != "Flat":
            log.info("Not a 'Flat' imagetype: switching off lamps")
            lao = LampsOff()
            lao.run({})

        if imagetype != "Light":
            log.info("Not a 'Light' imagetype: switching off recentering")
            self.recenter = False

        ########################
        ##### Camera setup #####
        ########################

        # Bringing back the camera to Idle state.
        if cam.state != 0:
            log.warning(
                f"Resetting camera from state {camera_state[cam.state]}.")
            cam.abort()
            sleep(0.1)

        log.info(f"Camera is {camera_state[cam.state]}")

        # Changing binning if not the same as the current one
        if binning != cam.binning:
            log.info(f"Changing binning to {binning}")
            cam.binning = [binning, binning]
            sleep(0.1)

        log.info(f"Camera is {camera_state[cam.state]}")

        # Changing filter if not the same as the current one (only if camera has a filter wheel)
        if filt and hasattr(cam, 'filter'):
            # On bad ctrl-c, filter can be 15 (?!)
            log.warning(f"Filter is number {cam.filter}")
            log.warning(
                f"Filter is {filter_name[cam.filter]}, we have selected {filt}")

            if filter_number[filt] != cam.filter:
                msg = f"Changing filter to {filt}, "
                msg += f"Which is number {filter_number[filt]}"
                log.info(msg)

                cam.filter = filter_number[filt]
                sleep(0.2)

                status = 1
                while status != 0:
                    self.check_pause_or_abort()

                    try:
                        status = int(cam.is_moving)
                    except ValueError as e:
                        msg = f"Error trying to contact the camera: {e}"
                        log.error(msg)
                        self.error.append(msg)

                    if status == 2:
                        msg = f"Filter {filter_state[status]}"
                        log.error(msg)
                        self.error.append(msg)
                        return
                    else:
                        log.warning(f"Filter {filter_state[status]}")
                        sleep(0.75)

        # Changing windowing (only when explicitly provided in params)
        if xystart is not None and xyend is not None:
            log.info(
                f"Changing windowing to xystart:{xystart}, xyend:{xyend}")
            cam.set_window(xystart[0],
                           xystart[1],
                           xyend[0]-xystart[0],
                           xyend[1]-xystart[1])

        #########################
        ##### Exposure loop #####
        #########################

        log.info(f"Starting {repeat} {imagetype} frames of {exptime}s")

        # Looping on the number of exposures
        for exposure in range(repeat):
            if self.check_pause_or_abort():
                return

            # RA, DEC, ALT, AZ, UTC are asked to cabinet
            # simultaneously in order to avoid latency.

            log.info(f"Asking cabinet time and coordinates")
            basic_cabinet = tel.coordinates
            gps = Time(tel.coordinates["utc"], format="unix")

            log.info(f"Starting Exposure {exposure + 1} of {repeat}")

            ##########################
            ##### Start exposure #####
            ##########################

            log.debug(frame_number[imagetype])
            try:
                cam.start(exptime,
                          frame_number[imagetype],
                          datetime=gps.isot)
            except Exception as e:
                msg = f"An error occurred : {e}"
                log.error(msg)
                self.error.append(msg)
                return

            # Some debug time counter
            now = Time.now()

            # Checking if the exposure is still running
            status = 1
            while status != 0:
                if self.check_pause_or_abort():
                    log.debug("check_pause_or_abort returned true. I'm here")
                    return

                try:
                    status = int(cam.state)
                except TypeError as e:
                    msg = f"Error trying to read camera status: {e}"
                    log.error(msg)
                    self.error.append(msg)

                if status == 5:  # i.e. error in camera
                    msg = f"Camera {camera_state[status]}"
                    log.error(msg)
                    self.error.append(msg)
                    return
                else:
                    elapsed = (Time.now() - now).sec.item()
                    msg = f"Camera {
                        camera_state[status]}, {
                        elapsed:.1f}/{exptime}s "
                    msg += f"of exposure {exposure}/{repeat - 1}"
                    log.warning(msg)
                    sleep(0.75)

            log.debug("check_pause_or_abort before the download")
            if self.check_pause_or_abort():
                log.debug("check_pause_or_abort returned true. I'm here")
                return

            ################################
            ##### Download from camera #####
            ################################

            log.info(f"Downloading frame as {temp_fits}")

            # Checking if the image is ready to be downloaded
            while cam.ready != 1:
                log.debug(f"Downloading... (cam state {image_state[cam.ready]})")
                sleep(0.5)
                if self.check_pause_or_abort():
                    log.warning(f"Buffer still {image_state[cam.ready]}")
                    return
            log.debug(f"Downloading... (cam state {image_state[cam.ready]})")

            cam.download()
            log.info(f"Elapsed {(Time.now() - now).sec.item():.2f}")

            ##################################
            ##### Update header and save #####
            ##################################

            fih_params = {
                "object": objname,
                "camera": camera_name,
                "imagetyp": imagetype,
                "fits_file": fits_file,
            }

            fih_params.update(basic_cabinet)  # radec, altaz, utc, lst

            fih = FillHeader()

            fih.run(fih_params)
            log.debug(f"observation {fih.filename}")

            self.filename = fih.filename
            self.filenames.append(fih.filename)

            log.debug(f"filenames from obs tpl {self.filenames}")

            ######################################
            ##### Calculate and apply offset #####
            ######################################

            log.info(f"Recenter is {self.recenter}")
            if self.recenter:
                log.info(f"... with box={self.box}px")

            if imagetype == "Light":
                if self.recenter:
                    try:
                        apply_offset(
                            fits_file=fits_file, box=self.box, display=False)
                    except Exception as e:
                        log.warning(f"Cannot apply offset: {e}")
        return
Loading