Exemple #1
0
    def setUp(self):
        try:
            self.blname = os.environ['BEAMLINENAME']
            # print "beamline name=",os.environ['BEAMLINENAME']
        except:
            print "No BEAMLINENAME defined"

        self.ba1 = PyTango.DeviceProxy("id26/emotion_batest/ba1")
        self.ba2 = PyTango.DeviceProxy("id26/emotion_batest/ba2")

        self.ba1.ApplyConfig(True)
        self.ba2.ApplyConfig(True)
 def initDetector(self, adscname, limaadscname, xformstatusfile):
     try: 
        self.adscdev           = PyTango.DeviceProxy(adscname) 
        self.limaadscdev       = PyTango.DeviceProxy(limaadscname) 
        self.xformstatusfile   = xformstatusfile
     except:
        import traceback
        logging.error("<SOLEIL MultiCollect> Cannot initialize LIMA detector")
        logging.error( traceback.format_exc() )
         
     else:
        self.ready = True
Exemple #3
0
	def prepare(self, startPosSmpx, endPosSmpx, startPosSmpy, endPosSmpy, startPosPhiy, endPosPhiy, expTime, velPhi, typeOfMotor):
		"""move all motors to their start positions, calculate accelerations and velocities for motors"""
		if expTime <= 0 :
			raise Exception("Exposure time is not correct")

		self.smpx = PyTango.DeviceProxy("exp_dmy01")
		#self.velGlobSmpx = self.smpx.Velocity
		#self.accGlobSmpx = self.smpx.Acceleration
		self.smpy = PyTango.DeviceProxy("exp_dmy02")
		#self.velGlobSmpy = self.smpy.Velocity
		#self.accGlobSmpy = self.smpy.Acceleration
		self.phiy = PyTango.DeviceProxy("exp_dmy04")
		self.velGlobPhiy = self.phiy.Velocity
		self.accGlobPhiy = self.phiy.Acceleration
		self.phi = PyTango.DeviceProxy("exp_dmy05")
		self.velGlobPhi = self.phi.Velocity
		#self.accGlobPhi = self.phi.Acceleration
		self.phi.Velocity = velPhi

		"""only for sardana pseudo motors"""
		#self.accGlobSarSmpx = self.velGlobSmpx / self.accGlobSmpx
		#self.accGlobSarSmpy = self.velGlobSmpy / self.accGlobSmpy
		self.accGlobSarPhiy = self.velGlobPhiy / self.accGlobPhiy
		#self.accGlobSarPhi = velPhi / self.accGlobPhi

		self.output("Moving motors to their start positions...")
		self.smpx.Position = startPosSmpx
		self.smpy.Position = startPosSmpy
		self.phiy.Position = startPosPhiy
		while self.smpx.state() == PyTango.DevState.MOVING:
			time.sleep(0.01)
		while self.smpy.state() == PyTango.DevState.MOVING:
			time.sleep(0.01)
		while self.phiy.state() == PyTango.DevState.MOVING:
			time.sleep(0.01)
		while self.phi.state() == PyTango.DevState.MOVING:
			time.sleep(0.01)
		self.output("Motors on the start positions")

		positionsSmpx = [startPosSmpx, endPosSmpx]
		positionsSmpy = [startPosSmpy, endPosSmpy]
		positionsPhiy = [startPosPhiy, endPosPhiy]

		if typeOfMotor == 1:
			moveTime = ((self.velGlobPhiy ** 2) + self.accGlobSarPhiy * abs(startPosPhiy - endPosPhiy)) / (self.accGlobSarPhiy * self.velGlobPhiy)
			self.disPhi =  (self.accGlobSarPhi * moveTime * velPhi - (velPhi ** 2)) / self.accGlobSarPhi
		else:
			moveTime = ((self.velGlobPhiy ** 2) + self.accGlobPhiy * abs(startPosPhiy - endPosPhiy)) / (self.accGlobPhiy * self.velGlobPhiy)
			self.disPhi =  (self.accGlobPhi * moveTime * velPhi - (velPhi ** 2)) / self.accGlobPhi
		positionsPhi = [self.phi.Position, self.phi.Position + self.disPhi]
		self.f1 = interpolate.interp1d(positionsPhiy, positionsSmpx, kind = 'linear') #find equation posSmpx = f1(posPhiy)
		self.f2 = interpolate.interp1d(positionsPhiy, positionsSmpy, kind = 'linear') #find equation posSmpy = f2(posPhiy)
		self.f3 = interpolate.interp1d(positionsPhiy, positionsPhi, kind = 'linear') #find equation posPhi = f3(posPhiy)
Exemple #4
0
    def init_device(self):
        """ Initialize device
        """
        self.set_state(PT.DevState.INIT)
        PTS.Device.init_device(self)

        # Service variables
        self._temperature = None
        self._temperature_ts = None
        self._delta = None
        self._delta_ts = None
        self._pressure = None
        self._pressure_ts = None
        self._pump_status = None
        self._pump_status_ts = None
        self._vacuum_status = None
        self._vacuum_status_ts = None
        self._compressor_status = None
        self._compressor_status_ts = None
        self._temperature_status = None
        self._temperature_status_ts = None
        self._water_status = PT.DevState.CLOSE

        # Connect to parent devices
        self.dev = PT.DeviceProxy(self.proxy)
        self.dev_lock = threading.Lock()
        self.water = PT.DeviceProxy(self.water_valve)
        self._check_water = None
        self.ws_id = self.water.subscribe_event("State",
                                                PT.EventType.CHANGE_EVENT,
                                                self.event_handler)

        # Enable change events
        self.temperature.set_change_event(True, False)
        self.delta.set_change_event(True, False)
        self.pressure.set_change_event(True, False)
        self.pump_status.set_change_event(True, False)
        self.vacuum_status.set_change_event(True, False)
        self.compressor_status.set_change_event(True, False)
        self.temperature_status.set_change_event(True, False)

        # Set polling time for State command
        self.poll_command("State", 500)

        # Start monitoring device
        self._terminate = False
        self.monitor = threading.Thread(target=self.monitor_loop)
        self.monitor.start()

        # Set device status
        self.set_state(PT.DevState.OFF)
Exemple #5
0
def test_xtreme(device, attribute, value):
    import PyTango
    i, dp = 0, PyTango.DeviceProxy(device)
    try:
        while i < value:
            i += 1
            dp.read_attribute(attribute)
            threading.Event().wait(0.01)
    except:
        print '%s.read_attribute(%s) failed after %d retries' % (device,
                                                                 attribute, i)
        print traceback.format_exc()
        PyTango.DeviceProxy(dp.adm_name()).command_inout('kill')
    return
Exemple #6
0
    def init_device(self):
        """ Initialize device
        """
        # Set INIT state
        self.set_state(PT.DevState.INIT)

        # Call parent init
        PTS.Device.init_device(self)

        # Check properties
        if self.chiller_type.lower() == "lytron":
            # Just on-off control
            self.chiller_type = self.LYTRON

        elif self.chiller_type.lower() == "polyscience":
            # High level support
            self.chiller_type = self.POLYSCIENCE

        else:
            self.fatal_stream("Found an unsupported chiller type: {0}".format(
                self.chiller_type))
            PT.Except.throw_exception(
                "Bad chiller type",
                "Unsupported chiller type {0}".format(self.chiller_type),
                "ChillerControl::init_device()")

        self.proxy_evs = []
        self.water_evs = []

        # Setup proxy
        self.dev = PT.DeviceProxy(self.proxy)
        self.dev.ping()

        # Setup water valve
        self.water = PT.DeviceProxy(self.water_valve)
        self.water.ping()

        self.attr_devstate = PT.DevState.UNKNOWN
        self.attr_temperature = math.nan
        self.attr_waterstate = PT.DevState.UNKNOWN
        self.attr_waterflow = math.nan

        # Monitoring thread
        self.monitor_th = None
        self.monitor_terminate = False
        self.monitor_running = True

        # Starting state
        self.starting = 0
    def __init__(self, integrationTime, filename):
        self.integrationTime = integrationTime
        self.filename = filename

        self.md2 = PyTango.DeviceProxy('i11-ma-cx1/ex/md2')
        self.ketek = PyTango.DeviceProxy('i11-ma-cx1/dt/dtc-mca_xmap.1')
        #self.counter = PyTango.DeviceProxy('i11-ma-c00/ca/cpt.2')
        self.obx = PyTango.DeviceProxy('i11-ma-c04/ex/obx.1')

        self.channelToeV = self.ketek.dynamicRange / len(self.ketek.channel00)

        try:
            os.mkdir(options.directory)
        except OSError as e:
            print(e)
Exemple #8
0
    def __init__(self, signal, ring, axis):
        self.signal = signal
        if ring.lower() == 'r1':
            self.deviceX = PT.DeviceProxy('r1/ctl/sofb-01')
            self.deviceY = PT.DeviceProxy('r1/ctl/sofb-02')
            self.scaleFactor = 0.001  # 2019-08-12 - scale factor updated to same as for r3 after summer BPM update. Was 1000 before.
        elif ring.lower() == 'r3':
            self.deviceX = PT.DeviceProxy('r3/ctl/sofb-01')
            self.deviceY = PT.DeviceProxy('r3/ctl/sofb-02')
            self.scaleFactor = 0.001
        self.axis = axis

        #        sensorNames = list(self.deviceX.sensor_names) + list(self.deviceY.sensor_names)
        self.xDevsSize = len(self.deviceX.sensor_names)
        self.yDevsSize = len(self.deviceY.sensor_names)
Exemple #9
0
    def _saveIDConfig(self):
        if self.mag_field:
            # Implement the way to save the value in BL04
            self.phase_values = [0]

        else:
            # Implement the way to save the value in other beamlines
            id_gap = PyTango.DeviceProxy(self.scan_motor)
            self.bck_id_gap = id_gap.read_attribute('Position').value
            if self.phase_motor != 'None':
                id_phase = PyTango.DeviceProxy(self.phase_motor)
                self.bck_id_phase = id_phase.read_attribute('Position').value
            else:
                self.phase_values = [0]
                self.bck_id_phase = 0
Exemple #10
0
    def __init__(self,
                 tPixelLink=None,
                 tTrigger=None,
                 imageDir=None,
                 exptime=None):
        if tPixelLink == None:
            self.tPixelLink = PyTango.DeviceProxy(proxies.camera_pixlink)
        else:
            self.tPixelLink = tPixelLink

        if tTrigger == None:
            self.tTrigger = PyTango.DeviceProxy(proxies.dac_eh1_01)
        else:
            self.tTrigger = tTrigger

        self.CAM_Binning = 1

        time.sleep(0.2)
        if self.tPixelLink.state() == PyTango.DevState.EXTRACT:
            self.tPixelLink.command_inout('AbortAcq')
            while self.tPixelLink.state() == PyTango.DevState.EXTRACT:
                time.sleep(0.1)

        if imageDir == None:
            raise Exception('Cannot set None-type image directory!')
        else:
            self.imageDir = imageDir

        if exptime != None:
            self.exptime = exptime
        else:
            self.exptime = 0.1

        print(self.exptime)
        self.tPixelLink.write_attribute('SHUTTER', 1)
        # self.tPixelLink.write_attribute('FilePostfix', '.bin') #!!!!
        # self.tPixelLink.write_attribute('TRIGGER_SOURCE', 'EXTERNAL')
        # self.tPixelLink.write_attribute('TRIGGER_ACTIVE', 'EDGE')
        self.tPixelLink.write_attribute('FilePrefix', 'Image')
        self.tPixelLink.write_attribute('FileDirectory', self.imageDir)
        self.tPixelLink.write_attribute('FileRefNumber', 0)
        self.tPixelLink.write_attribute('SaveImageFlag', True)
        # self.tTrigger.write_attribute('Value', 0)  #!!!!
        self.tTrigger.write_attribute('Voltage', 0)  # !!!!
        time.sleep(0.2)
        self.iImage = 0

        return None
Exemple #11
0
    def getMacroServer(cls, db, door):
        """ provides macro server of given door

        :param db: tango database
        :type db: :class:`PyTango.Database`
        :param door: given door
        :type door: :obj:`str`
        :returns: first MacroServer of the given door
        :rtype: :obj:`str`
        """
        servers = db.get_device_exported_for_class("MacroServer").value_string
        ms = ""
        sdoor = door.split("/")
        hostname = None
        if len(sdoor) > 1 and ":" in sdoor[0]:
            door = "/".join(sdoor[1:])
            hostname = sdoor[0]
        for server in servers:
            if hostname:
                mserver = "%s/%s" % (hostname, str(server))
            else:
                mserver = str(server)
            dp = PyTango.DeviceProxy(str(mserver))
            if hasattr(dp, "DoorList"):
                lst = dp.DoorList
                if lst and door in lst:
                    ms = mserver
                    break
        return ms
def run(proxy_name='arafat/lima_simulator/simulator.3-mask',
        width=1024,
        height=1024,
        roi_x=0,
        roi_width=1024 / 2,
        roi_y=0,
        roi_height=1024 / 2):
    # print arguments
    print '\nProgram inputs :\n--------------'
    print 'proxy_name\t = ', proxy_name
    print 'width\t\t = ', width
    print 'height\t\t = ', height
    print 'roi_x\t\t = ', roi_x
    print 'roi_width\t = ', roi_width
    print 'roi_y\t\t = ', roi_y
    print 'roi_height\t = ', roi_height

    width = int(width)
    height = int(height)
    roi_x = int(roi_x)
    roi_width = int(roi_width)
    roi_y = int(roi_y)
    roi_height = int(roi_height)
    mask_dev = PyTango.DeviceProxy(proxy_name)
    import numpy as np
    img_ones = np.ones((width, height), dtype='i')
    img_ones[roi_x:roi_width, roi_y:roi_height] = 0
    mask_dev.maskImage = img_ones
Exemple #13
0
    def openProxy(cls, device, counter=1000):
        """ opens device proxy of the given device

        :param device: device name
        :type device: :obj:`str`
        :returns: DeviceProxy of device
        :rtype: :class:`PyTango.DeviceProxy`
        """
        found = False
        cnt = 0
        cnfServer = PyTango.DeviceProxy(str(device))

        while not found and cnt < counter:
            if cnt > 1:
                time.sleep(0.01)
            try:
                cnfServer.ping()
                found = True
            except (PyTango.DevFailed, PyTango.Except, PyTango.DevError):
                time.sleep(0.01)
                found = False
                if cnt == counter - 1:
                    raise
            cnt += 1

        return cnfServer
    def start(self):
        path = os.path.dirname(TestServer.__file__)
        if not path:
            path = '.'

        if os.path.isfile("%s/ST" % path):
            self._psub = subprocess.call("cd %s; ./ST %s &" %
                                         (path, self.instance),
                                         stdout=None,
                                         stderr=None,
                                         shell=True)
        print "waiting for simple server",

        found = False
        cnt = 0
        while not found and cnt < 1000:
            try:
                print "\b.",
                self.dp = PyTango.DeviceProxy(self.new_device_info_writer.name)
                time.sleep(0.01)
                if self.dp.state() == PyTango.DevState.ON:
                    found = True
            except:
                found = False
            cnt += 1
        print ""
Exemple #15
0
 def _getDecodePyTangoAttr(self, attr_name, cfg):
     """Helper for decode the PyTango attribute infoex
     """
     dev = PyTango.DeviceProxy(self.DEV_NAME)
     infoex = dev.get_attribute_config_ex(attr_name)[0]
     unit = unit_from_tango(infoex.unit)
     if cfg in ['range', 'alarms', 'warnings']:
         if cfg == 'range':
             low = infoex.min_value
             high = infoex.max_value
         elif cfg == 'alarms':
             low = infoex.alarms.min_alarm
             high = infoex.alarms.max_alarm
         elif cfg == 'warnings':
             low = infoex.alarms.min_warning
             high = infoex.alarms.max_warning
         if low == 'Not specified':
             low = '-inf'
         if high == 'Not specified':
             high = 'inf'
         return [Quantity(float(low), unit), Quantity(float(high), unit)]
     elif cfg == 'label':
         return infoex.label
     else:
         return None
Exemple #16
0
 def get_station_state(self):
     """ This commands returns a summary of the state of each TPM in the station.
     
     :param : 
     :type: PyTango.DevVoid
     :return: A pickled string storing the state of each TPM in the station.
     :rtype: PyTango.DevString """
     self.debug_stream("In get_station_state()")
     argout = ''
     # ----- PROTECTED REGION ID(Station_DS.get_station_state) ENABLED START -----#
     state_ok = self.check_state_flow(inspect.stack()[0][3])
     if state_ok:
         try:
             states = {}
             for device_proxy_name in self.tpm_dict:
                 self.info_stream("Retrieving state from: %s" % device_proxy_name)
                 tpm_instance = PyTango.DeviceProxy(device_proxy_name)
                 tpm_state = tpm_instance.read_attribute("board_state")
                 self.debug_stream("State: %s" % tpm_state.value)
                 states[device_proxy_name] = tpm_state.value
             argout = pickle.dumps(states)
         except DevFailed as df:
             self.debug_stream("Failed to report station board states: %s" % df)
             argout = ''
     else:
         self.debug_stream("Invalid state")
     # ----- PROTECTED REGION END -----#	//	Station_DS.get_station_state
     return argout
Exemple #17
0
    def __init__(self, inst, props, *args, **kwargs):
        CounterTimerController.__init__(self, inst, props, *args, **kwargs)
        self._log.debug("__init__(%s, %s): Entering...", repr(inst),
                        repr(props))

        self.master = None
        self.integrationTime = 0.0
        self.avSamplesMax = 1000
        self.channels = []
        # @todo: this is not a good idea, better change it.
        # Maybe avoid ReadAll?
        self.measures = ['0', '0', '0', '0']

        self.lastvalues = []
        self.contAcqChannels = {}
        self.acqchannels = []
        self.state = None
        self.ranges = ['', '', '', '']
        self.filters = ['', '', '', '']
        self.dinversions = ['', '', '', '']
        self.offsets = ['', '', '', '']
        self.sampleRate = 0.0
        try:
            self.AemDevice = PyTango.DeviceProxy(self.Albaemname)
            self.state = self.AemDevice.getEmState()

        except Exception as e:
            self._log.error(
                "__init__(): Could not create a device from "
                "following device name: %s.\nException: %s", self.Albaemname,
                e)
    def openWriter(self, fname, xml, json=None):
        tdw = PyTango.DeviceProxy(self._sv.new_device_info_writer.name)
        self.assertTrue(ProxyHelper.wait(tdw, 10000))
        self.setProp(tdw, "writer", "h5cpp")

        tdw.FileName = fname
        self.assertEqual(tdw.state(), PyTango.DevState.ON)
        self.assertEqual(tdw.status(), self.__status[tdw.state()])

        tdw.OpenFile()

        self.assertEqual(tdw.state(), PyTango.DevState.OPEN)
        self.assertEqual(tdw.status(), self.__status[tdw.state()])

        tdw.XMLSettings = xml
        self.assertEqual(tdw.state(), PyTango.DevState.OPEN)
        self.assertEqual(tdw.status(), self.__status[tdw.state()])
        if json:
            tdw.JSONRecord = json
        self.assertEqual(tdw.status(), self.__status[tdw.state()])
        self.assertEqual(tdw.state(), PyTango.DevState.OPEN)
        tdw.OpenEntryAsynch()
        self.assertTrue(ProxyHelper.wait(tdw, 10000))
        self.assertEqual(tdw.status(), self.__status[tdw.state()])
        self.assertEqual(tdw.state(), PyTango.DevState.EXTRACT)
        return tdw
Exemple #19
0
    def __init__(self, server, command, finalState, args=None):
        """constructor

        :param server: Tango server implementation
        :type server: :class:`PyTango.Device_4Impl`
        :param command: Thread command
        :type command: :obj:`str`
        :param finalState: Final State Code
        :type finalState: :class:`PyTango.DevState`
        :param args: List of command arguments
        :type args: :obj:`list` <:obj:`str`>
        """
        Thread.__init__(self)
        #: (:class:`PyTango.Device_4Impl`) tango server
        self.server = server
        #: (:obj:`__callable__`) command
        self.command = getattr(server.tdw, command)
        #: (:class:`PyTango.DevState`) final state
        self.fstate = finalState
        #: (:class:`PyTango.DevState`) error state
        self.estate = PyTango.DevState.FAULT
        #: (:obj:`list` <:obj:`str`>) command arguments
        self.args = args if isinstance(args, list) else []
        self.dp = PyTango.DeviceProxy(self.server.get_name())
        self.dp.set_source(PyTango.DevSource.DEV)
    def configureMotorsWidget(self):
        '''
        we received a scanInfo block indicating that a new scan has started
        now we configure the motors widget using information from the scanInfo block
        '''

        length = len(self.scanInfo['motors'])
        if length == 0 or length > 3:
            QtGui.QMessageBox.about(
                None, 'Info Box',
                "pyspMonitorClass: # of motors == 0 or > 3: %d " % length)
            return

        motorArr = self.scanInfo['motors']
        for i in range(3):
            if i < length:
                self.motorNameButtons[i].setText(motorArr[i]['name'])
                #
                # invode TngGui for all motors
                #
                self.motorNameButtons[i].clicked.connect(
                    self.makeMotorCb(motorArr[i]))
                self.motProxies[i] = PyTango.DeviceProxy(motorArr[i]['name'])
                self.motorNameButtons[i].show()
                self.motPosLabels[i].show()
            else:
                self.motorNameButtons[i].hide()
                self.motPosLabels[i].hide()

        self.nMotor = length
Exemple #21
0
    def __init__(self, parent):
        # Parent constructor
        threading.Thread.__init__(self)

        # Init variables
        self._parent = parent
        self._polling = float(parent.polling) / 1000.0
        self._axis = parent.axis
        self._terminate = False
        self._pos_value = 0
        self._vel_value = 0
        self._acc_value = 0.0

        # Connect to proxy
        try:
            self.dev = PT.DeviceProxy(self._parent.proxy)
            self.dev.ping()
        except PT.DevFailed as e:
            PT.Except.re_throw_exception(
                e, "Proxy not available",
                "Proxy device is offline or not reachable",
                "MicosPollux::init_device()")

        # Read position, velocity and acceleration
        self._pos_value = self.__get_pos()
        self._vel_value = self.__get_vel()
        self._acc_value = self.__get_acc()

        # Start thread
        self.start()
Exemple #22
0
 def run(self, mca):
     name = mca.getName()
     tango_device_name = mca.TangoDevice
     tango_proxy = PyTango.DeviceProxy(tango_device_name)
     tango_proxy.Clear()
     o = "Clearing " + name
     self.output(o)
Exemple #23
0
    def connect_tpm(self, argin):
        """ Instructs a particular TPM to connect.
        
        :param argin: Tango device proxy name of TPM.
        :type: PyTango.DevString
        :return: Returns true if operation is successful, false otherwise.
        :rtype: PyTango.DevBoolean """
        self.debug_stream("In connect_tpm()")
        argout = False
        # ----- PROTECTED REGION ID(Station_DS.connect_tpm) ENABLED START -----#
        state_ok = self.check_state_flow(inspect.stack()[0][3])
        if state_ok:
            try:
                device_name = argin
                sub_dict = self.tpm_dict[device_name]

                # setup device
                tpm_instance = PyTango.DeviceProxy(device_name)
                tpm_instance.ip_address = sub_dict['ip']
                tpm_instance.port = sub_dict['port']

                # Connect to device
                if not tpm_instance.is_connected:
                    tpm_instance.command_inout("connect")
                    self.info_stream("Connected: %s" % device_name)

                argout = True
            except DevFailed as df:
                self.debug_stream("Failed to connect to all station devices: %s" % df)
                argout = ''
        else:
            self.debug_stream("Invalid state")
        # ----- PROTECTED REGION END -----#	//	Station_DS.connect_tpm
        return argout
Exemple #24
0
 def __init__(self, door_name=None):
     super(TangoMacroExecutor, self).__init__()
     if door_name == None:
         door_name = getattr(sardanacustomsettings, 'UNITTEST_DOOR_NAME')
     self._door = PyTango.DeviceProxy(door_name)
     self._done_event = None
     self._started_event = None
Exemple #25
0
    def updateQuadSelected(self):
        self.quad_selected = self.ui.quadSelectionCombobox.currentText()
        quadDevice = pt.DeviceProxy(str(self.quad_selected))

        current_quad_circuit = quadDevice.get_property(
            'CircuitProxies')['CircuitProxies'][0]
        current_quad_circuit_dev = pt.DeviceProxy(current_quad_circuit)
        current_quad_powersupply = current_quad_circuit_dev.get_property(
            'PowerSupplyProxy')['PowerSupplyProxy'][0]

        self.quadCircuitDev = pt.DeviceProxy(current_quad_powersupply)
        self.quad_current_initial = self.quadCircuitDev.read_attribute(
            'Current').value
        self.ui.quadMinSpinbox.setValue(0.2 + self.quad_current_initial)
        self.ui.quadMaxSpinbox.setValue(-0.2 + self.quad_current_initial)
        self.ui.quadReadValue.setText(str(self.quad_current_initial))
Exemple #26
0
 def configure_motors(self, motor_names):
     # TODO: workaround for bug with velocity<base_rate: Sdn#38
     for name in motor_names:
         mot = PyTango.DeviceProxy(name)
         mot.write_attribute('acceleration', 0.1)
         mot.write_attribute('base_rate', 0)
         mot.write_attribute('deceleration', 0.1)
    def start(self):
        path = os.path.dirname(TestServer.__file__)
        if not path:
            path = '.'

        self._psub = subprocess.call("cd %s;  python ./TestServer.py %s &" %
                                     (path, self.instance),
                                     stdout=None,
                                     stderr=None,
                                     shell=True)
        print "waiting for simple server",

        found = False
        cnt = 0
        devices = self.ts.values()
        while not found and cnt < 1000:
            try:
                print "\b.",
                dpcnt = 0
                for dv in devices:
                    self.dps[dv.name] = PyTango.DeviceProxy(dv.name)
                    time.sleep(0.01)
                    if self.dps[dv.name].state() == PyTango.DevState.ON:
                        dpcnt += 1
                if dpcnt == len(devices):
                    found = True
            except Exception as e:
                found = False
            cnt += 1
        print ""
 def snap(self):
     if self.contextid == None:
         try:
             attributes = []
             device = PyTango.DeviceProxy(self.model)
             attr_infos = device.attribute_list_query()
             for attr_info in attr_infos:
                 attributes.append(self.model + '/' + attr_info.name)
             if self.useWizardForContext:
                 self.author = self.getUserInput(self.author, "Author")
                 self.name = self.getUserInput(self.name, "Name")
                 self.reason = self.getUserInput(self.reason, "Reason")
                 self.description = self.getUserInput(self.description, "Description")
             self.snapapi.create_context(self.author,self.name,self.reason,self.description,attributes)
             print "context ok" 
             self.contextid = self.snapapi.contexts.keys()[len(self.snapapi.contexts.items())-1]
         except Exception:
             fandango.qt.QExceptionMessage()
             return
     try:
         if self.useInputForComment == True:
             self.comment = self.getUserInput(self.comment, "Comment")
         ctx=self.snapapi.get_context(self.contextid)
         ctx.take_snapshot(str(self.comment))
     except Exception:
         fandango.qt.QExceptionMessage()
         return
def run(proxy_name = 'arafat/lima_simu/simu.1', exposure_time = 100, latency_time = 0, wait_first_image_extra_time = 200):
    # print arguments
    print '\nProgram inputs :\n--------------'
    print 'proxy_name\t\t\t = ', proxy_name
    print 'exposure_time\t\t\t =  %s (ms)' %(exposure_time)
    print 'latency_time\t\t\t =  %s (ms)' %(latency_time)
    print 'wait_first_image_extra_time\t =  %s (ms)' %(wait_first_image_extra_time)
    exposure_time = float(exposure_time) 
    latency_time = float(latency_time)
    wait_first_image_extra_time = float(wait_first_image_extra_time)    

    #Configure the device
    print '\nConfigure the Device :\n--------------'
    timeBegin = datetime.datetime.now()
    print '\r',timeBegin.isoformat(), " - Create a DeviceProxy to Device ", proxy_name
    proxy = PyTango.DeviceProxy(proxy_name)
    timeBegin = datetime.datetime.now()
    print '\r',timeBegin.isoformat(), " - Ping proxy(\"",proxy_name,"\") ",proxy.ping()," us"

    timeBegin = datetime.datetime.now()
    print '\r',timeBegin.isoformat(), " - State = ",proxy.state();
    print '--> Stop()'
    proxy.Stop()
    timeBegin = datetime.datetime.now()
    print '\r',timeBegin.isoformat(), " - State = ",proxy.state();
    
    print 'write exposureTime = ', exposure_time    
    proxy.exposureTime = float(exposure_time)

    print 'write latencyTime = ', latency_time    
    proxy.latencyTime = float(latency_time)
        
    timeBegin = datetime.datetime.now()
    print '\r',timeBegin.isoformat(), " - State = ",proxy.state();        
    print '--> Start()'
    proxy.Start()

    #Loop while state is RUNNING (prepare in progress...)
    while proxy.state() != PyTango.DevState.RUNNING:
        pass
    timeBegin = datetime.datetime.now()
    print '\r',timeBegin.isoformat(), " - State = ",proxy.state();
    
    wait_first_image = proxy.exposureTime + proxy.latencyTime + wait_first_image_extra_time

    time.sleep(wait_first_image/1000)#to ensure that the first image is ready
        
    ar = None
    try:
        while True:
            if ar is None:
                ar = pyplot.imshow(proxy.image)
            else:
                ar.set_data(proxy.image)            
            pyplot.draw()
            
    except Exception as err:
	    print >>sys.stderr, '--------------\nERROR :\n--------------\n%s' % err
    except KeyboardInterrupt:
        print 'properly stopped'
 def init_device(self):
     self.debug_stream("In init_device()")
     self.get_device_properties(self.get_device_class())
     self.attr_DeflX_read = 0.0
     self.attr_DeflY_read = 0.0
     self.attr_Stig2a_read = 0.0
     self.attr_Stig2b_read = 0.0
     self.attr_Stig4_read = 0.0
     self.attr_Offset_read = 0.0
     self.attr_Angle_read = 0.0
     self.attr_Status_oct_read = False
     self.attr_VoltageOutput_read = False
     self.attr_Setting_Valid_read = False
     #----- PROTECTED REGION ID(Stigmator2.init_device) ENABLED START -----#         
     self.DX  = 0.0 # values which are used for calculation
     self.DY  = 0.0
     self.S2a = 0.0
     self.S2b = 0.0
     self.S4  = 0.0
     self.A   = 0.0
     self.OFF = 0.0
     
     self.ISEG=PyTango.DeviceProxy("ktof/logic/lens1")
     self.DevStat = [False for i in range(8)]
     self.DevStat_check = [True for i in range(8)]
     if not 'pingthread' in dir(self):
         self.pingthread = threading.Thread(target=self.check_voltages)
         self.pingthread.setDaemon(True)
         self.pingthread.start()