#! /usr/bin/env python

from guardian import GuardState, GuardStateDecorator
import cdsutils as cdu
from gpstime import gpstime
import time

request = 'HIGH_ARM_POWER'
nominal = 'HIGH_ARM_POWER'
import lscparams as lscparams

# we need to set these thresholds so that we only go to check shutter if and only if the shutter should have been triggered
arm_power_lower_thresh = 800 #at 2 Watts single arm is about 10 counts
arm_power_upper_thresh = 1100

class LOW_ARM_POWER(GuardState):
    index = 1
    def run(self):
        if ezca['LSC-TR_X_QPD_B_SUM_OUTPUT'] >=arm_power_upper_thresh and ezca['LSC-TR_Y_QPD_B_SUM_OUTPUT'] >=arm_power_upper_thresh:
            return 'HIGH_ARM_POWER'

class HIGH_ARM_POWER(GuardState):
    index = 10
    def run(self):
        if ezca['LSC-TR_X_QPD_B_SUM_OUTPUT'] <arm_power_lower_thresh and ezca['LSC-TR_Y_QPD_B_SUM_OUTPUT'] < arm_power_lower_thresh:
            return 'CHECK_SHUTTER'

class CHECK_SHUTTER(GuardState):
    index = 20
    def main(self):
        self.timenow = gpstime.tconvert('now').gps()
        self.timer['datawait'] = 5
        self.counter = 0

    def run(self):
        notify('run shutter check, then manually take to low power')
        
        if self.timer['datawait'] and self.counter == 0:
            gs13data = cdu.getdata(['H1:ISI-HAM6_BLND_GS13Z_IN1_DQ','H1:SYS-MOTION_C_SHUTTER_G_TRIGGER_VOLTS'],12,self.timenow-10)
            
            if max(gs13data[1].data) > ezca['SYS-MOTION_C_SHUTTER_G_THRESHOLD']:
                # Shutter should have been triggered, so do the check
                if max(abs(gs13data[0].data)) > 3e4:
                    log('GS13 saw a kick.  Peak GS13 signal = ' + str(max(abs(gs13data[0].data))))
                else:
                    log('No kick, but should have. Peak GS13 signal = ' + str(max(abs(gs13data[0].data))))

            else:
                # Power never got high enough at AS port to trigger the shutter.
                #   Don't bother checking, since it shouldn't have done a fast shut
                log('Power not high enough to trigger shutter.  Max trigger PD value = ' + str(max(abs(gs13data[1].data))))

            self.counter +=1


        
        
        


edges = [
    ('INIT','LOW_ARM_POWER'),
    ('LOW_ARM_POWER','HIGH_ARM_POWER'),
    ('HIGH_ARM_POWER', 'CHECK_SHUTTER')
]
