Skip to content

Commit

Permalink
WIP
Browse files Browse the repository at this point in the history
  • Loading branch information
gnthibault committed Aug 7, 2023
1 parent 70db961 commit ce66682
Show file tree
Hide file tree
Showing 18 changed files with 126 additions and 113 deletions.
13 changes: 8 additions & 5 deletions Manager/Manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,6 @@
from helper.IndiClient import IndiClient

# Local stuff: Service
from Service.NovaAstrometryService import NovaAstrometryService
#TODO TN TO BE FIXED
from Service.PanMessagingZMQ import PanMessagingZMQ

# Local stuff: Utils
from utils import error
Expand Down Expand Up @@ -368,6 +365,11 @@ def offset_points(self, mount, camera, guiding_camera, guider, observation, fits
observation=observation,
fits_headers=fits_headers)

def stop_tracking(self):
# Stop guiding
if self.guider is not None:
self.guider.disconnect_profile()

def initialize_tracking(self):
# start each observation by setting up the guider
try:
Expand All @@ -377,6 +379,7 @@ def initialize_tracking(self):
# TODO TN
# if self.guiding_camera is not None:
# self.guiding_camera.disable_shoot()
self.guider.connect_profile()
self.guider.guide()
self.logger.info("Guiding successfully started")
return True
Expand Down Expand Up @@ -537,7 +540,7 @@ def unpark(self):
if self.guider is not None:
self.guider.launch_server()
self.guider.connect_server()
self.guider.connect_profile()
# self.guider.connect_profile()

return True
except Exception as e:
Expand Down Expand Up @@ -742,7 +745,7 @@ def _setup_guider(self):
self.logger.info("Initializing guider")
self.guider.launch_server()
self.guider.connect_server()
self.guider.connect_profile()
# self.guider.connect_profile()
except Exception as e:
raise RuntimeError(f"Problem setting up guider: {e}")

Expand Down
3 changes: 1 addition & 2 deletions ObservationPlanner/SpectralObservation.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,7 @@ def __init__(self,
Keyword Arguments:
"""
super().__init__(observing_block=observing_block,
exp_set_size=exp_set_size)
super().__init__(observing_block=observing_block)

# Important to know if corresponds to a reference acquisition or not
self.is_reference_observation = is_reference_observation
Expand Down
36 changes: 17 additions & 19 deletions ObservationPlanner/SpectroScheduler.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@

# Astrophysical informations
from astroquery.simbad import Simbad
from astroquery.mpc import MPC

# Astroplan stuff
from astroplan import FixedTarget
Expand Down Expand Up @@ -140,7 +139,7 @@ def define_target(self, target_name):

def get_best_reference_target(self, observation):
ob = observation.observing_block
maxseparation = 5 * u.deg
maxseparation = 15 * u.deg
maxebv = 1
altaz_frame = AltAz(obstime=self.serv_time.get_astropy_time_from_utc(),
location=self.obs.getAstropyEarthLocation())
Expand Down Expand Up @@ -244,7 +243,6 @@ def add_observation(self, observing_block, exp_set_size=None,
try:
observation = SpectralObservation(
observing_block=observing_block,
exp_set_size=exp_set_size,
is_reference_observation=is_reference_observation)
except Exception as e:
self.logger.warning(f"Cannot add observing_block: "
Expand Down Expand Up @@ -289,7 +287,7 @@ def get_observation(self, time=None, show_all=False,
time = self.serv_time.get_astropy_time_from_utc() # get_utc()

# dictionary where key is obs key and value is priority (aka merit)
valid_obs = {obs: 1.0 for obs in self.observations}
valid_obs = {obs: 1.0 for obs, obs_def in self.observations.items() if not obs_def.is_done}
best_obs = []

observer = self.obs.getAstroplanObserver()
Expand Down Expand Up @@ -324,21 +322,21 @@ def get_observation(self, time=None, show_all=False,
# Sort the list by highest score (reverse puts in correct order)
best_obs = sorted(valid_obs.items(), key=lambda x: x[1])[::-1]

# Check new best against current_observation
if (self.current_observation is not None and
best_obs[0][0] != self.current_observation.id):

# Favor the current observation if still doable
end_of_next_set = time + self.current_observation.set_duration
if self.observation_available(
self.current_observation,
Time([time, end_of_next_set])):

# If current is better or equal to top, add it to bestof
# but no need to update current_observation
if self.current_observation.merit >= best_obs[0][1]:
best_obs.insert(0, (self.current_observation.id,
self.current_observation.merit))
# # Check new best against current_observation
# if (self.current_observation is not None and
# best_obs[0][0] != self.current_observation.id):
#
# # Favor the current observation if still doable
# end_of_next_set = time + self.current_observation.set_duration
# if self.observation_available(
# self.current_observation,
# Time([time, end_of_next_set])):
#
# # If current is better or equal to top, add it to bestof
# # but no need to update current_observation
# if self.current_observation.merit >= best_obs[0][1]:
# best_obs.insert(0, (self.current_observation.id,
# self.current_observation.merit))

self.current_observation = self.observations[best_obs[0][0]]
self.current_observation.merit = best_obs[0][1]
Expand Down
2 changes: 1 addition & 1 deletion Service/PanMessagingMQTT.py
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,7 @@ def send_message(self, channel, message):
message = self.scrub_message(message)

msg_object = json.dumps(message, skipkeys=True)
self.logger.debug(f"PanMessaging - sending - {channel}: {message}")
# self.logger.debug(f"PanMessaging - sending - {channel}: {message}")

# Send the message
self.client.publish(
Expand Down
2 changes: 1 addition & 1 deletion Service/PanMessagingZMQ.py
Original file line number Diff line number Diff line change
Expand Up @@ -183,7 +183,7 @@ def send_message(self, channel, message):

msg_object = json.dumps(message, skipkeys=True)
full_message = f"{channel} {msg_object}"
self.logger.debug(f"PanMessaging - sending - {channel}: {message}")
# self.logger.debug(f"PanMessaging - sending - {channel}: {message}")
# Send the message
self.socket.send_string(full_message, flags=zmq.NOBLOCK)

Expand Down
16 changes: 9 additions & 7 deletions Spectro/DummySpectroController.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,23 +3,25 @@
import json
import logging

# Numerical stuff
import numpy as np
# Local utilities
from Base import Base

class IndiSpectroController:
class DummySpectroController:
"""
"""
def __init__(self, logger=None, config=None):
logger = logger or logging.getLogger(__name__)
def __init__(self,
config=None,
connect_on_create=True):

if config is None:
config = dict(
module="DummypectroController",
controller_name="dummy",
device_name="dummy",
)

logger.debug(f"Indi Spectro Controller, controller name is: {config['controller_name']}")
super().__init__()


# Finished configuring
self.logger.debug('Indi Spectro controller configured successfully')
Expand Down
17 changes: 6 additions & 11 deletions Spectro/IndiSpectroController.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,14 @@ class IndiSpectroController(IndiDevice):
"""
"""
def __init__(self, logger=None, config=None,
def __init__(self,
config=None,
connect_on_create=True):
logger = logger or logging.getLogger(__name__)

if config is None:
config = dict(
module="IndiSpectroController",
controller_name="spox",
device_name="spox",
port="/dev/ttyUSB0",
indi_client=dict(
indi_host="localhost",
Expand All @@ -30,12 +30,9 @@ def __init__(self, logger=None, config=None,

self.port = config['port']

logger.debug(f"Indi Spectro Controller, controller name is: "
f"{config['controller_name']}")

# device related intialization
IndiDevice.__init__(self,
device_name=config['controller_name'],
device_name=config['device_name'],
indi_client_config=config["indi_client"])
if connect_on_create:
self.initialize()
Expand All @@ -53,12 +50,10 @@ def set_port(self):
self.set_text("DEVICE_PORT", {"PORT": self.port})

def on_emergency(self):
self.logger.debug("Indi spectro controller: on emergency routine "
"started...")
self.logger.debug("Indi spectro controller: on emergency routine started...")
self.switch_off_spectro_light()
self.switch_off_flat_light()
self.logger.debug("Indi spectro controller: on emergency routine "
"finished")
self.logger.debug("Indi spectro controller: on emergency routine finished")

def switch_on_spectro_light(self):
self.logger("Switching-on spectro light")
Expand Down
4 changes: 4 additions & 0 deletions StateMachine/States/analyzing.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,3 +25,7 @@ def on_enter(event_data):
except Exception as e:
model.logger.error(f"Problem in analyzing: {e}")
model.next_state = 'parking'
finally:
if model.next_state not in ["observing"]:
model.manager.stop_tracking()

3 changes: 1 addition & 2 deletions StateMachine/States/parked.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,7 @@ def on_enter(event_data):
model.say(f"Going to stay parked for half an hour then will try again.")

while True:
model.sleep(delay=1800) # 30 minutes = 1800 seconds

model.sleep(delay=60) # 30 minutes = 1800 seconds
# We might have shutdown during previous sleep.
if not model.connected:
break
Expand Down
2 changes: 1 addition & 1 deletion StateMachine/States/scheduling.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ def on_enter(event_data):
# Get the next observation
try:
observation = model.manager.get_observation()
model.logger.info("Observation: {observation}")
model.logger.info(f"Observation: {observation}")
except error.NoObservation as e:
model.say("No valid observations found. Cannot schedule. "
"Going to park.")
Expand Down
2 changes: 1 addition & 1 deletion StateMachine/States/tracking.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ def on_enter(event_data):
model.next_state = 'parking'

# If we came from pointing then don't try to dither
if event_data.transition.source != 'pointing':
if event_data.transition.source not in ['pointing']:
model.logger.debug("Checking our tracking")
try:
# most likely setup dithering
Expand Down
3 changes: 3 additions & 0 deletions apps/launch_backyard_conf.sh
Original file line number Diff line number Diff line change
Expand Up @@ -13,4 +13,7 @@ indiserver indi_lx200gemini indi_canon_ccd indi_asi_ccd
# ssh -L 7625:127.0.0.1:7624 192.168.8.247
# ssh -L 8624:127.0.0.1:8624 192.168.8.247
# ssh -L 4400:127.0.0.1:4400 192.168.8.247

# export REMOTE_OBSERVATORY_CONFIG=config_backyard
# Other wise in simulation, you might want to set this variable
# export REMOTE_OBSERVATORY_IS_DARK=0
28 changes: 19 additions & 9 deletions apps/launch_remote_observatory.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
# Generic import
import logging
import argparse
import logging.config
import multiprocessing
import os
import queue
import sys
import time
import warnings
import zmq

# Astropy
from astropy import units as u
Expand Down Expand Up @@ -64,6 +63,9 @@ def __init__(
# Explicitly call the base classes in the order we want
Base.__init__(self, **kwargs)

# Check if we are running in simulation mode
self.simulation_mode = kwargs.get("simulation_mode", False)

# init
state_machine_file = state_machine_file if state_machine_file else os.path.join("conf_files", self.config[
'state_machine'])
Expand Down Expand Up @@ -301,9 +303,7 @@ def is_safe(self, no_warning=False):
is_safe_values = dict()

# Check if night time: synchronous
# TODO TN URGENT
is_safe_values['is_dark'] = True
#is_safe_values['is_dark'] = self.is_dark()
is_safe_values['is_dark'] = self.is_dark()

# Check weather: not really synchronous, checks db
is_safe_values['good_weather'] = self.is_weather_safe()
Expand Down Expand Up @@ -334,9 +334,11 @@ def is_dark(self):
"""
# See if dark
is_dark = self.manager.is_dark

self.logger.debug("Dark Check: {}".format(is_dark))
if self.simulation_mode:
is_dark = os.getenv("REMOTE_OBSERVATORY_IS_DARK", "1") == "1"
else:
is_dark = self.manager.is_dark
self.logger.debug(f"Dark Check: {is_dark}")
return is_dark

def is_weather_safe(self, stale=180):
Expand Down Expand Up @@ -567,9 +569,17 @@ def _setup_messaging(self):
# }

if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Main command to run the observatory management software')
parser.add_argument('--simulation_mode',
dest='simulation_mode',
help='Wether to run in simulation mode or not',
default=False,
action='store_true')
args = parser.parse_args()

# load the logging configuration
logging.config.fileConfig('logging.ini')
m = Manager()
r = RemoteObservatoryFSM(manager=m)
r = RemoteObservatoryFSM(manager=m, simulation_mode=args.simulation_mode)
r.initialize()
r.run()
11 changes: 11 additions & 0 deletions apps/prototyping/Spectro/test_IndiSpectroController.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
from Spectro.IndiSpectroController import IndiSpectroController

config = dict(
module="IndiSpectroController",
device_name="spox",
port="/dev/serial/by-id/usb-FTDI_FT232R_USB_UART_AD0JE0ID-if00-port0",
indi_client=dict(
indi_host="localhost",
indi_port="7625"
))
sc = IndiSpectroController(config=config)
16 changes: 8 additions & 8 deletions conf_files/config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -54,15 +54,15 @@ db:
ntp:
ntpserver: time.google.com
scheduler:
module: DefaultScheduler
# module: SpectroScheduler
target_file: targets.yaml
#target_file: spectral_targets.yaml
#module: DefaultScheduler
module: SpectroScheduler
#target_file: targets.yaml
target_file: spectral_targets.yaml
spectroscope_controller:
module: IndiSpectroController
calibration:
module: ImagingCalibration
#module: SpectralCalibration
#module: ImagingCalibration
module: SpectralCalibration
spectral_calib:
nb: 11
sec: 30
Expand All @@ -77,9 +77,9 @@ calibration:
dark_nb: 1
controller:
module: DummySpectroController
controller_name: dummy
device_name: dummy
#module: IndiSpectroController
#controller_name: spox
#device_name: spox
mount:
#module: IndiG11
#mount_name: Losmandy Gemini
Expand Down
Loading

0 comments on commit ce66682

Please sign in to comment.