Esempio n. 1
0
def move_motors(imagetype="", obs_mode="", iodine_cell=3):

	### Check which obs mode the OR defines and move motors...

	# Check if motors are moving:
	output = get_db_values.db_connection().get_fields_site01("coude_unit", fields=["calib_mirror_pos", "iodine_pos", "filter_pos", "mirror_slide", "spectrograph_foc", "slit_pos"])

	timeout = time.time() + 20
	for motor in output:
		if float(output[motor]) == 0.0:
			time.sleep(1)
			output_motor = get_db_values.db_connection().get_fields_site01("coude_unit", fields=[motor])
			while float(output_motor[motor]) == 0.0:
				time.sleep(1)
				output_motor = get_db_values.db_connection().get_fields_site01("coude_unit", fields=[motor])
				if time.time() > timeout:
					break

	try:

		if imagetype.lower() == 'thar':
			try:
				lamp.Lamp(lamp='thar').set_on()	# Might change Lamp to LAMP at some point
				lamp.Lamp(lamp='halo').set_off()	# Might change Lamp to LAMP at some point
			except Exception,e:
				print clock.timename(), "One of the lamps was not switched correctly"
			pst.PST().move(3,2) 			# Move IODINE cell out of path
			pst.PST().move(4,3) 			# Move Calibration mirror to ThAr position

		elif imagetype.lower() == 'sun':
			try:
				lamp.Lamp(lamp='thar').set_off()	# Might change Lamp to LAMP at some point
				lamp.Lamp(lamp='halo').set_off()	# Might change Lamp to LAMP at some point
			except Exception,e:
				print clock.timename(), "One of the lamps was not switched correctly"
Esempio n. 2
0
def get_database_values(table_name, fields=[]):
    conn = psycopg2.connect(
        "host='%s' dbname='%s' user='******' password='******'" %
        (m_conf.db_c_host, m_conf.data_db, m_conf.db_user, m_conf.db_password))
    curr = conn.cursor()
    try:
        return_value = get_db_values.db_connection().get_fields(
            curr, table_name, fields)
    except Exception as e:
        conn.rollback()
        return_value = e
    curr.close()
    conn.close()
    return return_value
Esempio n. 3
0
                            print clock.timename(), e
                            send_song_mail.send_mail().sending_an_email(
                                reciever=["mads"],
                                sender="SONG_MS",
                                subject="SONGwriter problem!",
                                message=
                                "The request to start creating the master calibration files has failed.\n\nSend at: %s\n\n"
                                % clock.obstimeUT())

                calib_done_param = 1
                print "Daily evening calibration scripts done at: ", clock.obstimeUT(
                )

            tel_state_db_values = get_db_values.db_connection(
            ).get_fields_site01("tel_dome", [
                "tel_ready_state", "extra_param_1", "extra_param_2",
                "tel_motion_state"
            ])
            if daily_config.exercise_m3 == "yes" and calib_done_param == 1 and m3_exercise_performed == 0 and float(
                    tel_state_db_values["tel_ready_state"]
            ) == float(1.0) and float(
                    tel_state_db_values["extra_param_2"]) == float(0.0) and (
                        hours_from_pre_sun_set < 0.25
                        or hours_from_pre_sun_set > 23.0
                    ) and float(
                        tel_state_db_values["tel_motion_state"]) != float(11):
                print clock.obstimeUT(), "Exercising M3 %i times" % (
                    daily_config.m3_movements)
                m3_pos = [3, 12]
                tel_az_now = int(
                    round(float(gettsi.get_position_horizontal_az())))
Esempio n. 4
0
class Check_Time(object):
    """
		@brief: This class handles all checks on the time of day.
	"""
    def __init__(self):
        """
			Initialization of the time checks.
		"""
        self.mon_time_value = song_monitor_config.mon_time  # 1 = do things, 0 = do nothing.
        self.sun_handle = song_star_checker.sun_pos(
            site=m_conf.song_site)  # site=1: Tenerife
        self.verbose = song_monitor_config.verbose
        self.perform_actions = mon_actions.Do_Actions()
        self.skycam_start = m_conf.start_skycam_movie
        self.local_mode = 0
        self.sms_send = 0
        self.check_ors = 0
        self.open_mirror_covers = 0
        self.bad_weather_sms = 0
        self.scheduler_val = 0
        self.local_mode_sms = 0
        self.x_mas_notify = 0

    def check_sun(self, side_port_group_1, side_port_group_2,
                  side_port_group_3, side_port_group_4, telescope_state,
                  slit_state, flap_state, mirror_cover_state, who_did_it_tel,
                  who_did_it_sp):
        """
			Checks the Suns position and returns a value corresponding to this.
		"""
        self.side_port_group_1 = side_port_group_1
        self.side_port_group_2 = side_port_group_2
        self.side_port_group_3 = side_port_group_3
        self.side_port_group_4 = side_port_group_4
        self.telescope_state = telescope_state
        self.slit_state = slit_state
        self.flap_state = flap_state
        self.mirror_cover_state = mirror_cover_state
        self.who_did_it_tel = who_did_it_tel
        self.who_did_it_sp = who_did_it_sp

        sun_alt = self.sun_handle.sun_alt()

        if str(sun_alt)[0] == "-":
            sun_alt_d = float(str(sun_alt).split(":")[0]) - float(
                str(sun_alt).split(":")[1]) / 60.0 - float(
                    str(sun_alt).split(":")[2]) / 3600.0
        elif str(sun_alt)[0] != "-":
            sun_alt_d = float(str(sun_alt).split(":")[0]) + float(
                str(sun_alt).split(":")[1]) / 60.0 + float(
                    str(sun_alt).split(":")[2]) / 3600.0

        #################################
        #### Get time to next sun set ###
        tmp_time_str2 = datetime.datetime.strptime(
            str(self.sun_handle.sun_set_next()), "%Y/%m/%d %H:%M:%S")
        time_diff = tmp_time_str2 - datetime.datetime.utcnow()
        hours_to_next_sun_set = int(
            time_diff.days) * 24. + time_diff.seconds / (24. * 3600.) * 24
        #### Get time from previous sun set ###
        tmp_time_str2 = datetime.datetime.strptime(
            str(self.sun_handle.sun_set_pre()), "%Y/%m/%d %H:%M:%S")
        time_diff2 = datetime.datetime.utcnow() - tmp_time_str2
        hours_from_pre_sun_set = int(
            time_diff2.days) * 24. + time_diff2.seconds / (24. * 3600.) * 24
        #################################

        ### GET DUST VALUE: ##############################
        try:
            conn = psycopg2.connect(
                "host='%s' dbname='%s' user='******' password='******'" %
                (m_conf.db_host, m_conf.data_db, m_conf.db_user,
                 m_conf.db_password))
            curr = conn.cursor()
            stmt = 'SELECT dust_level FROM weather_station WHERE ins_at = (SELECT max(ins_at) FROM weather_station)'
            curr.execute(stmt)
            results = curr.fetchone()
            dust_value = results[0]
        except Exception, e:
            print clock.timename(), " Could not get dust value from database!"
            dust_value = 0.011

        if song_monitor_config.mon_telescope_actions == 1:
            #### Get telescope poitning direktion ####
            tel_value = get_db_values.db_connection().get_fields_site01(
                "tel_dome", ["tel_az"])
            tel_az = tel_value["tel_az"]

#		if float(self.telescope_state) == float(-3.0) and self.local_mode == 0:
#			print clock.timename(), " The telescope was put in local mode"
#			if song_monitor_config.send_notifications == "yes":
#				send_song_mail.send_mail().sending_an_email(reciever=m_conf.notify_email_who,sender="SONG_MS",subject="Telescope in local mode!", message="The telescope was put in local mode!\n\nSend at: %s\n\n" % clock.obstimeUT())
#			if song_monitor_config.send_notify_sms == "yes":
#				send_song_mail.send_mail().send_sms(receiver=["Mads"], message="Someone has put the telescope into local mode")
#			self.local_mode = 1
#		elif float(self.telescope_state) == float(0.0) and self.local_mode == 1:
#			print clock.timename(), " The telescope was put back in remote mode"
#			if song_monitor_config.send_notifications == "yes":
#				send_song_mail.send_mail().sending_an_email(reciever=m_conf.notify_email_who,sender="SONG_MS", subject="Telescope back in remote mode!", message="The telescope was put back in remote mode!\n\nSend at: %s\n\n" % clock.obstimeUT())
#			self.local_mode = 0

        if float(sun_alt_d) >= (
                float(m_conf.obs_sun_alt) + 2.0
        ) and hours_to_next_sun_set >= m_conf.open_time_tel and hours_from_pre_sun_set >= m_conf.open_time_tel:

            #######################################
            #### Close dome and park telescope ####
            #######################################
            if self.skycam_start == 0:
                print clock.timename(), " Resetting skycam starting parameter"
                self.skycam_start = 1
                try:
                    self.sc2_handle.kill()
                except Exception, e:
                    print e
                    print clock.timename(
                    ), " Could not kill the skycam 2 process"

            if song_monitor_config.mon_telescope_actions == 1 and float(
                    self.telescope_state) != float(0.0) and float(
                        self.telescope_state) != float(-3.0):
                #				if float(self.slit_state) != 0.0 or float(self.flap_state) != 0.0 or float(self.mirror_cover_state) != 0.0:
                if float(self.slit_state) != 0.0 or float(
                        self.flap_state) != 0.0 or (
                            float(self.mirror_cover_state) != 0.0
                            and song_monitor_config.allow_mc_open != "yes"):

                    status_tel = self.perform_actions.shutdown_telescope()

                    if status_tel == "done":
                        self.who_did_it_tel = "time"
                        print clock.timename(
                        ), " The dome was closed due to daylight"

                    dome_check = self.perform_actions.check_shutdown()
                    if dome_check == 1:
                        print clock.timename(
                        ), " The dome was closed correctly"
                    elif dome_check == 2:
                        print clock.timename(
                        ), " The dome was closed but mirror cover open"
                        if song_monitor_config.send_notifications == "yes":
                            send_song_mail.send_mail().sending_an_email(
                                reciever=m_conf.notify_email_who,
                                sender="SONG_MS",
                                subject="Mirror covers were open!",
                                message=
                                "The dome was closed but mirror covers open!\n\nSend at: %s\n\n"
                                % clock.obstimeUT())
                    else:
                        if song_monitor_config.send_to_wake_up == "yes":
                            send_song_mail.send_mail().sending_an_email(
                                reciever=m_conf.notify_email_who,
                                sender="SONG_MS",
                                subject="Telescope Closing Error!",
                                message=
                                "The dome was not closed correctly after shutdown!\n\nSend at: %s\n\n"
                                % clock.obstimeUT())
                        if song_monitor_config.send_sms == "yes" and self.sms_send == 0:
                            send_song_mail.send_mail().send_sms(
                                receiver=m_conf.wakeup_sms_who,
                                message="The dome was not closed corretly...")
                        if song_monitor_config.send_to_support == "yes" and self.sms_send == 0:
                            send_song_mail.send_mail().sending_an_email(
                                reciever=['support'],
                                sender="SONG_MS",
                                subject="Telescope Closing Error!",
                                message=
                                "The dome was not closed correctly after shutdown!\n\nSend at: %s\n\n"
                                % clock.obstimeUT())
                            self.sms_send = 1

                    ###### Stop sigu and pugu ########
                    print clock.timename(
                    ), " Stopping the slit and pupil guiders"
                    try:
                        status_sigu_pugu = self.perform_actions.stop_sigu_and_pugu(
                        )
                    except Exception, e:
                        print clock.timename(
                        ), " Could not connect to Sigu and/or Pugu. They might be stopped already!"

                    if status_sigu_pugu != 1:
                        print clock.timename(
                        ), " Something went wrong when trying to stop sigu and pugu"

                else:
                    if self.who_did_it_tel == "free":
                        self.who_did_it_tel = "time"
                    self.time_delay_telescope = time.time() + (
                        song_checker_config.telescope_delay_time * 60)
                    ### Maybe the sms send parameter should be placed elsewhere...
                    self.sms_send = 0
Esempio n. 5
0
import get_db_values
import song_timeclass
import slit_module
import pupil_module
import psycopg2
import datetime
import OR_script_config as conf
import master_config as m_conf
import subprocess
import threading
import xmlrpclib

sigu = slit_module.SIGU()
pugu = pupil_module.PUGU()

collect_db_values = get_db_values.db_connection()
clock = song_timeclass.TimeClass()

# Database values:
#db_host = "192.168.66.65"	# Tenerife machine
#db_user = "******"
#db_password = ""
#db = "db_song"
#db_table = "obs_request_1"
#st_db = "db_tenerife"
#st_table = "obs_request_status_1"
# Database values:
db_host =  m_conf.db_host	# Tenerife machine
db_user =  m_conf.db_user
db_password =  m_conf.db_password
db =  m_conf.or_db
Esempio n. 6
0
import sys
import song_timeclass
import os
import song_star_checker
import string
import get_db_values
import psycopg2
import datetime
import numpy
#import barcor_song_mfa
import ephem
import master_config as m_conf

clock = song_timeclass.TimeClass()

db_handle = get_db_values.db_connection()


class MakeHeader(object):
    """
      This class will modify the header of the observed fits file to contain the relevant information
   """

    # cam is the cameraobject, ccdtemp is the temperature of the ccd just before the exposure. date_obs, jd_obs and mjd_obs is timestamps. file is the FITS file to be modified.
    def makeheader(self, cam, ccdtemp, date_obs, jd_obs, mjd_obs, fits_file,
                   hsspeed, pregain, highcap, imagetyp, object_name_1, req_no,
                   obj_ra, obj_dec, remark, used_exp_time, camera):
        """
         @brief: This function modifies, updates and fills the header of given FITS files.

         @param cam: This is the camera handle from the Andor.py wrapper.
Esempio n. 7
0
def insert_timecritical_OR(pre_obs_spec_id=""):
    ### Collect data to create the OR

    OR_data = get_star_data(pre_obs_spec_id=pre_obs_spec_id)

    starid, pre_obs_spec_id, last_observed, obs_mode, exp_time, nr_exp, nr_target_exp, nr_thar_exp, slit, project_id, read_out_mode, ra, decl, object_name, vmag, pm_ra, pm_decl, timecritical_tstart, timecritical_tend, schedule_type = OR_data
    project_data = get_project_data(project_id=project_id)

    project_name, project_id, first_name, last_name = project_data

    pi = first_name + " " + last_name

    req_prio = 99
    epoch = 2000
    imagetype = "STAR"
    observer = pi
    project_name = project_name
    project_id = project_id
    x_bin = 1
    y_bin = 1
    x_begin = 1
    y_begin = 1
    x_end = 2088
    y_end = 2048
    ang_rot_offset = 0
    adc_mode = "false"

    if obs_mode.lower() == "iodine":
        iodine_cell = 3
    elif obs_mode.lower() == "none-iodine":
        iodine_cell = 2
    elif obs_mode.lower() == 'thar':
        obs_mode = 'none-iodine'
        iodine_cell = 2
    elif obs_mode.lower() == "test-iodine":
        iodine_cell = 1
        obs_mode = "iodine"
    else:
        print obs_mode

    if nr_target_exp == None:
        nr_target_exp = 0
    if nr_thar_exp == None:
        nr_thar_exp = 0

    start_window = (
        timecritical_tstart - datetime.timedelta(seconds=float(120))
    ).strftime(
        '%Y-%m-%d %H:%M:%S'
    )  # set start_window to be 2 minutes before start of gap to account for corrections in the calculated gaps.
    stop_window = (
        timecritical_tend + datetime.timedelta(seconds=float(5 * 60))
    ).strftime(
        '%Y-%m-%d %H:%M:%S'
    )  # set stop_window to be 5 minutes after end of gap to allow observations to finish if needed.

    constraint_1 = 0
    constraint_2 = 0
    constraint_3 = 0
    constraint_4 = ""
    constraint_5 = ""
    req_chain_previous = int(
        pre_obs_spec_id)  # Now using this value for soda ID
    req_chain_next = 0
    site = 1
    ins_at = datetime.datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S')

    insert_msg = "INSERT INTO obs_request_1 (right_ascension, declination, object_name, magnitude, ra_pm, dec_pm, obs_mode, exp_time, no_exp, no_target_exp, no_thar_exp, amp_gain, readoutmode, slit, req_prio, epoch, imagetype, observer, project_name, project_id, x_bin, y_bin, x_begin, y_begin, x_end, y_end, ang_rot_offset, adc_mode, iodine_cell, start_window, stop_window, constraint_1, constraint_2, constraint_3, constraint_4, constraint_5, site, req_chain_previous, req_chain_next, ins_at) VALUES (%s, %s, '%s', %s, %s, %s, '%s', %s, %s, %s, %s, %s, %s, %s, %s, %s, '%s', '%s', '%s', %s, %s, %s, %s, %s, %s, %s, %s, '%s', %s, '%s', '%s', %s, %s, %s, '%s', '%s', %s, %s, %s, '%s' )" % (
        ra / 15., decl, object_name, vmag, pm_ra, pm_decl, obs_mode, exp_time,
        nr_exp, nr_target_exp, nr_thar_exp, 2, read_out_mode, slit, req_prio,
        epoch, imagetype, observer, project_name, project_id, x_bin, y_bin,
        x_begin, y_begin, x_end, y_end, ang_rot_offset, adc_mode, iodine_cell,
        start_window, stop_window, constraint_1, constraint_2, constraint_3,
        constraint_4, constraint_5, site, req_chain_previous, req_chain_next,
        ins_at)

    #### HERE THE OR SHOULD BE INSERTED ###

    if conf.insert_timecritical == "yes":

        try:
            conn = psycopg2.connect(
                "host='%s' dbname='%s' user='******' password='******'" %
                (m_conf.db_c_host, m_conf.or_db, m_conf.db_user,
                 m_conf.db_password))
            curr = conn.cursor()
            curr.execute(insert_msg)
            conn.commit()
            curr.close()
            conn.close()
        except Exception, e:
            print clock.timename(), " Error: ", e
        else:
            print clock.timename(), "An OR was inserted to fill the gap..."

            time.sleep(3)

            # This returns the request number of the request just inserted.
            conn = psycopg2.connect(
                "host='%s' dbname='%s' user='******' password='******'" %
                (m_conf.db_c_host, m_conf.or_db, m_conf.db_user,
                 m_conf.db_password))
            curr = conn.cursor()

            try:
                or_req_tmp = get_db_values.db_connection().get_fields(
                    curr, m_conf.or_table, fields=['req_no'])
                req_no = or_req_tmp['req_no']
            except Exception as e:
                conn.rollback()
                print clock.timename(
                ), "Could not get OR from the database. Call has been rolled back."
                return_value = e

            curr.close()
            conn.close()

            # now inserting the status of the OR....
            or_status_values = "( %i, '%s', '%s' )" % (
                int(req_no), "wait",
                datetime.datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S'))

            conn = psycopg2.connect(
                "host='%s' dbname='%s' user='******' password='******'" %
                (m_conf.db_host, m_conf.data_db, m_conf.db_user,
                 m_conf.db_password))
            curr = conn.cursor()

            params = '(req_no, status, ins_at)'
            print clock.timename(), "Now inserting status=wait for OR: ", int(
                req_no)
            try:
                stmt = "INSERT INTO obs_request_status_1 %s VALUES %s" % (
                    params, or_status_values)
                curr.execute(stmt)
            except Exception as e:
                conn.rollback()
                return_value = e
                print clock.timename(
                ), "Could not create status in the database. Changes to the status-data has been rolled back."
                raise e
            else:
                return_value = 'done'

            conn.commit()
            curr.close()
            conn.close()

            ############### UPDATE OBSERVATION PARAMETERS in the pre_obs_spec table ##################

            # Now updating the pre_obs_spec table....
            if conf.use_only_soda == "yes":
                conn = psycopg2.connect(
                    "host='%s' dbname='%s' user='******' password='******'" %
                    (m_conf.soda_host, m_conf.soda_db, m_conf.soda_user,
                     m_conf.soda_pw))
                curr = conn.cursor()

                try:
                    stmt = "UPDATE soda.projects_target_definitions SET (last_req_no, last_obs_attempt) = (%i, '%s') WHERE id = %s" % (
                        int(req_no), datetime.datetime.utcnow().strftime(
                            '%Y-%m-%d %H:%M:%S'), int(pre_obs_spec_id))
                    print stmt
                    curr.execute(stmt)
                except Exception as e:
                    conn.rollback()
                    return_value = e
                    print clock.timename(
                    ), "Could not update last_observed value. Changes to the project-data has been rolled back."
                    raise e
                else:
                    print clock.timename(
                    ), "The pre_obs_req table was updated..."
                    return_value = 'done'

                conn.commit()
                curr.close()
                conn.close()
            else:
                conn = psycopg2.connect(
                    "host='%s' dbname='%s' user='******' password='******'" %
                    (m_conf.db_c_host, m_conf.or_db, m_conf.db_user,
                     m_conf.db_password))
                curr = conn.cursor()

                try:
                    stmt = "UPDATE pre_obs_spec SET (last_ins_req_no, ins_at) = (%s, '%s') WHERE pre_obs_spec_id = %s" % (
                        int(req_no), datetime.datetime.utcnow().strftime(
                            '%Y-%m-%d %H:%M:%S'), str(pre_obs_spec_id))
                    print stmt
                    curr.execute(stmt)
                except Exception as e:
                    conn.rollback()
                    return_value = e
                    print clock.timename(
                    ), "Could not update last_observed value. Changes to the status-data has been rolled back."
                    raise e
                else:
                    print clock.timename(
                    ), "The pre_obs_spec table was updated..."
                    return_value = 'done'

                conn.commit()
                curr.close()
                conn.close()
Esempio n. 8
0
                except Exception, e:
                    print clock.timename(), " Error: ", e
                else:
                    print clock.timename(), "An OR was inserted"

                    time.sleep(3)

                    # This returns the request number of the request just inserted.
                    conn = psycopg2.connect(
                        "host='%s' dbname='%s' user='******' password='******'" %
                        (m_conf.db_c_host, m_conf.or_db, m_conf.db_user,
                         m_conf.db_password))
                    curr = conn.cursor()

                    try:
                        or_req_tmp = get_db_values.db_connection().get_fields(
                            curr, m_conf.or_table, fields=['req_no'])
                        req_no = or_req_tmp['req_no']
                    except Exception as e:
                        conn.rollback()
                        print clock.timename(
                        ), "Could not get OR from the database. Call has been rolled back."
                        return_value = e

                    curr.close()
                    conn.close()

                    # now inserting the status of the OR....
                    or_status_values = "( %i, '%s', '%s' )" % (
                        int(req_no), "wait", datetime.datetime.utcnow(
                        ).strftime('%Y-%m-%d %H:%M:%S'))