import ch.psi.pshell.epics.ControlledVariable as ControlledVariable
import ch.psi.pshell.epics.ChannelSettlingCondition as ChannelSettlingCondition
import ch.psi.pshell.device.SettlingCondition as SettlingCondition

#cam_server.start("SAROP21-PSRD103_sp1", True)
pip.start("simulation_sp")
pip.stream.waitCacheChange(-1)
i   = pip.stream.getChild("intensity")
iavg = create_averager(i, 2, interval = -1)

x=0


"""
class DCM(RegisterBase):
    def doWrite(self, value):
        print "Putting " , value 
        caput ("TESTIOC:TESTCALCOUT:Output", value)
        print "Waiting " , value 
        cawait('TESTIOC:TESTCALCOUT:Output', value, timeout = 3600.0)    
        print "Done "
        #if abs(value - self.read()) >  IN_POSITION_BAND :
        #    raise Exception("Cannot set mono")   
    def doRead(self):
        global x
        x=x+1
        return caget ("TESTIOC:TESTCALCOUT:Input") + x
        
         #return caget("SARUN03-UIND030:FELPHOTENE.VAL")

undulator = DCM()
undulator.initialize()
"""

"""
class DCM(Readable, Writable):
    def write(self, value):
        print "Putting " , value 
        caput ("TESTIOC:TESTCALCOUT:Output", value)
        print "Waiting " , value 
        cawait('TESTIOC:TESTCALCOUT:Output', value, timeout = 3600.0)    
        print "Done "
        #if abs(value - self.read()) >  IN_POSITION_BAND :
        #    raise Exception("Cannot set mono")   
    def read(self):
        global x
        x=x+1
        return caget ("TESTIOC:TESTCALCOUT:Input") + x
        
         #return caget("SARUN03-UIND030:FELPHOTENE.VAL")

undulator = DCM()
"""


class MySettlingCondition(SettlingCondition):
    def waitSettled(self):
            time.sleep(100)
            cawait('TESTIOC:TESTCALCOUT:Input', value, timeout = 3600.0)    
            

        
         #return caget("SARUN03-UIND030:FELPHOTENE.VAL")

undulator = ControlledVariable("undulator", "TESTIOC:TESTCALCOUT:Output", "TESTIOC:TESTSINUS:SinCalc")
undulator.config.resolution = float('inf') 
undulator.initialize()
undulator.setSettlingCondition(ChannelSettlingCondition("TESTIOC:TESTCALCOUT:Input", 0, None, 'i', None))

undulator.settlingCondition.latency = 100


lscan(undulator, [iavg], 1.0100, 1.18, 0.005 , latency= 0.2, range="auto")


