コード例 #1
0
ファイル: main.py プロジェクト: PawelPamula/geosynoptic
    def show_device_info(self, device):
        """
        Displays basic device attribute properties (status, state, etc.). It creates
        QWidget with GridLayout.
        """
        #czyszczenie grida
        for i in reversed(range(self.grid.count())):
            self.grid.itemAt(i).widget().setParent(None)

        t = DeviceProxy(device)

        try:
            attr_list = t.get_attribute_list()

            i = 0

            attr_device = [t.read_attribute(j) for j in attr_list]
            attr_device = [x for x in attr_device if x.data_format == PyTango._PyTango.AttrDataFormat.SCALAR]

            for p in self.pos:
                if not attr_device:
                    break
                else:
                    name = attr_device[0].name
                    value = attr_device[0].value
                    del attr_device[0]
                    l = QtGui.QLabel("%s : %s" % (name, value))
                    l.setAlignment(QtCore.Qt.AlignCenter)
                    self.grid.addWidget(l, p[0], p[1])

        except DevFailed:
            ret = QtGui.QMessageBox.warning(self.centralwidget,
                                            "Warning",
                                            '''Retrieving attribute list failed''',
                                            QtGui.QMessageBox.Ok)
コード例 #2
0
ファイル: beamline.py プロジェクト: MartinSavko/align
def wavelength(x = None):
    mono = DeviceProxy('i11-ma-c03/op/mono1')
    
    if x == None:
        return mono.Lambda
        
    mono.Lambda = x
コード例 #3
0
ファイル: beamline.py プロジェクト: MartinSavko/align
def distance(x = None):
    '''Read or set the detector distance'''
    ts = DeviceProxy('i11-ma-cx1/dt/dtc_ccd.1-mt_ts')
    
    if x == None:
        return ts.position
    
    ts.position = x
コード例 #4
0
ファイル: beamline.py プロジェクト: MartinSavko/align
def energy(x = None):
    '''Read or set the energy of the beamline'''
    ble  = DeviceProxy('i11-ma-c00/ex/beamlineenergy')
    
    if x == None:
        return ble.energy
    
    ble.energy = x
コード例 #5
0
ファイル: PX2MultiCollect.py プロジェクト: SOLEILPX/mxcube
class PX2MultiCollect(SOLEILMultiCollect):
    def __init__(self, name):

        SOLEILMultiCollect.__init__(self, name, LimaAdscDetector(), TunableEnergy())
        #SOLEILMultiCollect.__init__(self, name, DummyDetector(), TunableEnergy())

    def init(self):

        logging.info("headername is %s" % self.headername )

        self.headerdev     = DeviceProxy( self.headername )
        self.mono1dev      = DeviceProxy( self.mono1name )
        self.det_mt_ts_dev = DeviceProxy( self.detmttsname )
        self.det_mt_tx_dev = DeviceProxy( self.detmttxname )
        self.det_mt_tz_dev = DeviceProxy( self.detmttzname )

        self._detector.prepareHeader = self.prepareHeader
        SOLEILMultiCollect.init(self)
       
    def prepareHeader(self):
        '''Will set up header given the actual values of beamline energy, mono and detector distance'''
        X, Y = self.beamCenter()

        BeamCenterX = str(round(X, 3))
        BeamCenterY = str(round(Y, 3))
        head = self.headerdev.read_attribute('header').value
        head = re.sub('BEAM_CENTER_X=\d\d\d\.\d', 'BEAM_CENTER_X=' + BeamCenterX, head)
        head = re.sub('BEAM_CENTER_Y=\d\d\d\.\d', 'BEAM_CENTER_Y=' + BeamCenterY, head)
        return head

    def beamCenter(self):
        '''Will calculate beam center coordinates'''

        # Useful values
        tz_ref = -6.5     # reference tz position for linear regression
        tx_ref = -17.0    # reference tx position for linear regression
        q = 0.102592  # pixel size in milimeters

        wavelength = self.mono1dev.read_attribute('lambda').value
        distance   = self.det_mt_ts_dev.read_attribute('position').value
        tx         = self.det_mt_tx_dev.read_attribute('position').value
        tz         = self.det_mt_tz_dev.read_attribute('position').value

        zcor = tz - tz_ref
        xcor = tx - tx_ref

        Theta = numpy.matrix([[1.55557116e+03,  1.43720063e+03],
                              [-8.51067454e-02, -1.84118001e-03],
                              [-1.99919592e-01,  3.57937064e+00]])  # values from 16.05.2013

        X = numpy.matrix([1., distance, wavelength])

        Origin = Theta.T * X.T
        Origin = Origin * q

        return Origin[1] + zcor, Origin[0] + xcor
コード例 #6
0
ファイル: beamline.py プロジェクト: MartinSavko/align
def detectorPosition(x = None):
    '''Read or set the detector position'''
    ts = DeviceProxy('i11-ma-cx1/dt/dtc_ccd.1-mt_ts')
    tx = DeviceProxy('i11-ma-cx1/dt/dtc_ccd.1-mt_tx')
    tz = DeviceProxy('i11-ma-cx1/dt/dtc_ccd.1-mt_tz')
    
    if x == None:
        return ts.position, tx.position, tz.position
        
    ts.position, tx.position, tz.position = x
コード例 #7
0
ファイル: BLEnergy.py プロジェクト: jan-meyer/HardwareObjects
    def init(self):
        
        self.moving = None
        self.deviceOk = True
        self.prev_state = None
        self.doBacklashCompensation = False

        # Channel and commands for monochormator pitch.
        #    it will be used here to make sure it is on before moving energy (PX2)
        #    not needed on PX1
        self.mono_mt_rx_statech = None
        self.mono_mt_rx_oncmd = None
        
        # Connect to device BLEnergy defined "tangoname" in the xml file 
        try :
            self.BLEnergydevice = DeviceProxy(self.getProperty("tangoname"))
        except :
            self.errorDeviceInstance(self.getProperty("tangoname"))
            
        # Connect to device mono defined "tangoname2" in the xml file 
        # used for conversion in wavelength
        try :    
            self.monodevice = DeviceProxy(self.getProperty("tangoname2"))
        except :    
            self.errorDeviceInstance(self.getProperty("tangoname2"))

        # Nom du device bivu (Energy to gap) : necessaire pour amelioration du positionnement de l'onduleur (Backlash)
        try :    
#            self.U20Energydevice = DeviceProxy(self.getProperty("tangoname3"), movingState="RUNNING")
# Modif suite a changement par ICA de l etat du device U20 RUNNING devient MOVING
            self.U20Energydevice = DeviceProxy(self.getProperty("tangoname3"))
        except :    
            self.errorDeviceInstance(self.getProperty("tangoname3"))
            
        self.doBacklashCompensation = self.getProperty("backlash")
#        print self.doBacklashCompensation

        try:
            self.mono_mt_rx_statech = self.getChannelObject("mono_mt_rx_state")
            self.mono_mt_rx_oncmd = self.getCommandObject("mono_mt_rx_on")
        except KeyError:
            logging.info("Beware that mt_rx control is not properly defined for BLEnergy")
 
        
        # parameters for polling     
        if self.deviceOk :
            self.is_connected()
            self.prev_state = str( self.BLEnergydevice.State() )

            energyChan = self.getChannelObject("energy") 
            energyChan.connectSignal("update", self.energyChanged)

            stateChan = self.getChannelObject("state") # utile seulement si statechan n'est pas defini dans le code
            stateChan.connectSignal("update", self.stateChanged)
コード例 #8
0
ファイル: PX2MultiCollect.py プロジェクト: SOLEILPX/mxcube
    def init(self):

        logging.info("headername is %s" % self.headername )

        self.headerdev     = DeviceProxy( self.headername )
        self.mono1dev      = DeviceProxy( self.mono1name )
        self.det_mt_ts_dev = DeviceProxy( self.detmttsname )
        self.det_mt_tx_dev = DeviceProxy( self.detmttxname )
        self.det_mt_tz_dev = DeviceProxy( self.detmttzname )

        self._detector.prepareHeader = self.prepareHeader
        SOLEILMultiCollect.init(self)
コード例 #9
0
    def init_device(self, cl=None, name=None):
        PS.PowerSupply.init_device(self, cl, name)

        # cache contains what the DS considers to be the current read values
        # of each attribute, updated from UpdateState
        self.cache = {}
        # initializes internal modbus data to fill pattern
        self.ALL = [ USHORT_FILL ] * NREGISTER
        # all bits are False, neither power on nor off
        self.ALL[ADDR_STATE] = 0

        self._next_read_time = time() #< when next read might be attempted
        self._pend_oo(None)

        # initializes connection
        self.modbus = DeviceProxy(self.ModbusDevice)
        self.modbus.set_timeout_millis(self.ModbusTimeout)

        # checks type property
        if not self.Type:
            self.Type = self.get_name().rpartition('/')[-1][0]
            self.log.info('guessing Type is %r' % self.Type)

        pctype = TYPE_TRANS[self.Type.lower()]

        msg,mask,xi = PSTYPE_INFO[pctype]

        #  customize external interlock messages
        msg[1] = copy(msg[1])
        for i,x in enumerate(xi):
            msg[1][x] = getattr(self, "Interlock%d" % (i+1) )
        self.STAT = IocasteStateLogic(self, msg, mask)
        self.STAT.INITIALIZED()
コード例 #10
0
    def _init(self):
        self.positionValue = 0.0
        self.stateValue    = 'UNKNOWN'

        threshold      = self.getProperty("threshold")
        self.threshold = 0.0018   # default value. change it with property threshold in xml

        self.old_value = 0.
        self.tangoname = self.getProperty("tangoname")
        self.motor_name = self.getProperty("motor_name")
        self.ho = DeviceProxy(self.tangoname)
        
        try:
            self.dataType    = self.getProperty("datatype")
            if self.dataType is None:
                self.dataType    = "float"
        except:
            self.dataType    = "float"

        if threshold is not None:
            try:
               self.threshold = float(threshold)
            except:
               pass

        self.setIsReady(True)
        try:
            self.limitsCommand = self.getCommandObject("limits")
        except KeyError:
            self.limitsCommand = None
        self.positionChan = self.getChannelObject("position") # utile seulement si positionchan n'est pas defini dans le code
        self.stateChan    = self.getChannelObject("state")    # utile seulement si statechan n'est pas defini dans le code

        self.positionChan.connectSignal("update", self.positionChanged) 
        self.stateChan.connectSignal("update", self.motorStateChanged)   
コード例 #11
0
ファイル: Tango.py プロジェクト: vrey01/HardwareRepository
    def continue_init(self, _):
        # self.init_poller.stop()

        if isinstance(self.polling, types.IntType):
            self.raw_device = RawDeviceProxy(self.deviceName)
            Poller.poll(
                self.poll,
                polling_period=self.polling,
                value_changed_callback=self.update,
                error_callback=self.pollFailed,
            )
        else:
            if self.polling == "events":
                # try to register event
                try:
                    self.pollingEvents = True
                    # logging.getLogger("HWR").debug("subscribing to CHANGE event for %s", self.attributeName)
                    self.device.subscribe_event(
                        self.attributeName,
                        PyTango.EventType.CHANGE_EVENT,
                        self,
                        [],
                        True,
                    )
                    # except PyTango.EventSystemFailed:
                    #   pass
                except BaseException:
                    logging.getLogger("HWR").exception("could not subscribe event")
        self._device_initialized.set()
コード例 #12
0
 def _init(self):
     self.currentResolution = None
     self.currentDistance = None
     self.currentWavelength = None
     self.currentEnergy = None
     self.connect("equipmentReady", self.equipmentReady)
     self.connect("equipmentNotReady", self.equipmentNotReady)
     #self.device = SimpleDevice(self.getProperty("tangoname"), waitMoves = False, verbose=False)
     self.device = DeviceProxy(self.getProperty("tangoname"))
     #self.device.timeout = 3000 # Setting timeout to 3 sec
     
     #self.monodevice = SimpleDevice(self.getProperty("tangoname2"), waitMoves = False, verbose=False)
     self.blenergyHOname = self.getProperty("BLEnergy")
     if self.blenergyHOname is None:
         logging.getLogger("HWR").error('TangoResolution: you must specify the %s hardware object' % self.blenergyHOname)
         hobj=None
         self.configOk=False
     else:
         hobj=HardwareRepository.HardwareRepository().getHardwareObject(self.blenergyHOname)
         if hobj is None:
             logging.getLogger("HWR").error('TangoResolution: invalid %s hardware object' % self.blenergyHOname)
             self.configOk=False
         self.blenergyHO=hobj
         self.connect(self.blenergyHO,qt.PYSIGNAL('energyChanged'), self.energyChanged)
     # creer un chanel sur l'energy: pour faire un update 
     positChan = self.getChannelObject("position") # utile seulement si statechan n'est pas defini dans le code
     positChan.connectSignal("update", self.positionChanged)
     stateChan = self.getChannelObject("state") # utile seulement si statechan n'est pas defini dans le code
     stateChan.connectSignal("update", self.stateChanged)
     
     self.currentDistance = self.device.position
     self.currentEnergy = self.blenergyHO.get_current_energy()
     self.currentWavelength = self.blenergyHO.get_current_wavelength()
     return BaseHardwareObjects.Equipment._init(self)
コード例 #13
0
ファイル: MotorWidget.py プロジェクト: daneos/motorwidget
	def __init__(self, model, parent=None):
		QWidget.__init__(self, parent)
		uic.loadUi("MotorWidget.ui", self)

		self.connect(self.configButton, SIGNAL("clicked()"), self.openConfig)
		self.connect(self.goButton, SIGNAL("clicked()"), self.go)
		self.connect(self.moveNegButton, SIGNAL("clicked()"), self.moveNeg)
		self.connect(self.movePosButton, SIGNAL("clicked()"), self.movePos)
		self.connect(self.disableButton, SIGNAL("toggled(bool)"), self.disable)

		self.stateLabel.setModel("%s/state" % model)
		self.positionLCD.setModel("%s/position" % model)

		self.motor = DeviceProxy(str(model))
		try:
			self.nameLabel.setText(self.motor.alias())
		except Exception:
			match = re.search(r"((?:[^/]+/){2}[^/]+)$", model)
			if not match:
				self.nameLabel.setText(model)
			else:
				self.nameLabel.setText(match.group(1))

		pos = AttributeProxy("%s/position" % model)
		try:
			self.unitLabel.setText(pos.get_config().unit)
		except Exception:
			self.unitLabel.setText("")

		self.absMotionEdit.setText(str(self.motor.position))
コード例 #14
0
ファイル: beamline.py プロジェクト: MartinSavko/align
def transmission(x = None):
    '''Get or set the transmission'''
    Fp   = DeviceProxy('i11-ma-c00/ex/fp_parser')
    if x == None:
        return Fp.TrueTrans_FP
        
    Ps_h         = DeviceProxy('i11-ma-c02/ex/fent_h.1')
    Ps_v         = DeviceProxy('i11-ma-c02/ex/fent_v.1')
    Const        = DeviceProxy('i11-ma-c00/ex/fpconstparser')
    
    truevalue = (2.0 - math.sqrt(4 - 0.04 * x)) / 0.02

    newGapFP_H = math.sqrt( (truevalue / 100.0) * Const.FP_Area_FWHM / Const.Ratio_FP_Gap )
    newGapFP_V = newGapFP_H * Const.Ratio_FP_Gap
    
    Ps_h.gap = newGapFP_H
    Ps_v.gap = newGapFP_V
コード例 #15
0
ファイル: PX2MultiCollect.py プロジェクト: MartinSavko/align
    def init(self):

        logging.info("headername is %s" % self.headername )

        self.headerdev     = DeviceProxy( self.headername )
        self.mono1dev      = DeviceProxy( self.mono1name )
        self.det_mt_ts_dev = DeviceProxy( self.detmttsname )
        self.det_mt_tx_dev = DeviceProxy( self.detmttxname )
        self.det_mt_tz_dev = DeviceProxy( self.detmttzname )
        
        self.helical = False
        self.linear = False
        self.grid = False
        self.translational = False
        
        self._detector.prepareHeader = self.prepareHeader
        SOLEILMultiCollect.init(self)
コード例 #16
0
ファイル: beamline.py プロジェクト: MartinSavko/align
def resolution(x = None):
    '''Read or set the resolution'''
    
    ts = DeviceProxy('i11-ma-cx1/dt/dtc_ccd.1-mt_ts')
    
    diameter = 315. # detector diameter in mm
    radius = diameter / 2.
    distance = ts.position
    wavelen = wavelength()
    
    if x == None:
        theta = math.atan(radius / distance)
        resolution = 0.5 * wavelen / math.sin(theta / 2.)
        return resolution
    
    theta = math.asin(wavelen / 2. / x)
    distance = radius / math.tan(2. * theta)
    ts.position = distance
コード例 #17
0
ファイル: HabitatMonitor.py プロジェクト: casyazmon/mars_city
 def init_graph(self):
     temp = str(self.itemText).split(' - ')
     self.ui.hour_label.show()
     self.ui.hour_value.show()
     self.ui.minutes_label.show()
     self.ui.minutes_value.show()
     if len(temp) > 1:
         self.attr = temp[1]
         with open('graph_config', 'r') as fin:
             graph_nodes = json.loads(fin.read())
             current_graph_node = graph_nodes[str(self.itemText)]
             total_graph_values = int(
                 current_graph_node['total_graph_values'])
             graph_updation_time = int(
                 current_graph_node['graph_updation_time'])
             print "----init_graph----"
             print "total_graph_values:", total_graph_values
             print "graph_updation_time:", graph_updation_time
     elif len(temp) == 1:
         self.attr = str(self.ui.childrenBox.currentText())
         with open('graph_config', 'r') as fin:
             graph_nodes = json.loads(fin.read())
             current_graph_node = graph_nodes[str(self.itemText)]
             self.total_graph_values = int(
                 current_graph_node['total_graph_values'])
             graph_updation_time = int(
                 current_graph_node['graph_updation_time'])
             print "----init_graph----"
             print "total_graph_values:", self.total_graph_values
             print "graph_updation_time:", graph_updation_time
         self.branch_time_array = []
         self.branch_axis_counter = 0
     pg.setConfigOptions(antialias=True)
     self.ui.graphicsView.clear()
     self.curve = self.ui.graphicsView.plot(pen='y')
     try:
         self.l.scene().removeItem(self.l)
     except AttributeError:
         pass
     self.l = pg.LegendItem((100, 60), offset=(70, 30))
     self.l.setParentItem(self.ui.graphicsView.graphicsItem())
     self.l.addItem(self.curve, self.attr)
     self.data = []
     self.ptr = 0
     if len(temp) > 1:
         self.proxy = DeviceProxy(temp[0])
         params = json.dumps({'period': 1})
         data = json.loads(self.proxy.get_data(params))
         data = data[self.attr]
         data_len = len(data)
         self.data_period = total_graph_values / data_len
     else:
         self.proxy = ''
     self.graphTimer.stop()
     self.graphTimer.timeout.connect(self.update_plot)
     self.graphTimer.start(graph_updation_time)
コード例 #18
0
    def init(self):
        
        self.moving = None
        self.deviceOk = True
        self.prev_state = None
        self.doBacklashCompensation = True
        
        # Connect to device BLEnergy defined "tangoname" in the xml file 
        try :
            self.BLEnergydevice = DeviceProxy(self.getProperty("tangoname"))
        except :
            self.errorDeviceInstance(self.getProperty("tangoname"))
            
        # Connect to device mono defined "tangoname2" in the xml file 
        # used for conversion in wavelength
        try :    
            self.monodevice = DeviceProxy(self.getProperty("tangoname2"))
        except :    
            self.errorDeviceInstance(self.getProperty("tangoname2"))

        # Nom du device bivu (Energy to gap) : necessaire pour amelioration du positionnement de l'onduleur (Backlash)
        try :    
#            self.U20Energydevice = DeviceProxy(self.getProperty("tangoname3"), movingState="RUNNING")
# Modif suite a changement par ICA de l etat du device U20 RUNNING devient MOVING
            self.U20Energydevice = DeviceProxy(self.getProperty("tangoname3"))
        except :    
            self.errorDeviceInstance(self.getProperty("tangoname3"))
            
        self.doBacklashCompensation = self.getProperty("backlash")
#        print self.doBacklashCompensation
            
        # parameters for polling     
        if self.deviceOk :
            self.sConnected()
            self.prev_state = str( self.BLEnergydevice.State() )
            energyChan = self.getChannelObject("energy") 
            energyChan.connectSignal("update", self.energyChanged)
            stateChan = self.getChannelObject("state") # utile seulement si statechan n'est pas defini dans le code
            stateChan.connectSignal("update", self.stateChanged)
コード例 #19
0
    def get_device_properties(self, device_pattern):
        """
        Function retrieves properties of devices consistent with device_pattern

        :param device_pattern: server name pattern (* available)
        :type  device_pattern: string

        :return:    dictionary with devices as keys and lists of properties as values
        :rtype:     dict
        """
        device_properties = {}
        device_list = self.get_device_list(device_pattern)
        for device in device_list:
            device_proxy = DeviceProxy(device)
            
            properties_list = []
            for d in device_proxy.get_property_list('*'):
                x = device_proxy.get_property(d)
                properties_list.extend(x.items())
            if device not in device_properties:
                device_properties[device] = properties_list
        
        return device_properties    
コード例 #20
0
ファイル: Xanes.py プロジェクト: JieNanMAXIV/HardwareObjects
 def attenuation(self, x=None):
     '''Read or set the attenuation'''
     if self.test: return 0
     from PyTango import DeviceProxy
     Attenuator = DeviceProxy('i11-ma-c05/ex/att.1')
     labels = ['00 None',
               '01 Carbon 200um',
               '02 Carbon 250um',
               '03 Carbon 300um',
               '04 Carbon 500um',
               '05 Carbon 1mm',
               '06 Carbon 2mm',
               '07 Carbon 3mm',
               '10 Ref Fe 5um',
               '11 Ref Pt 5um']
     if x == None:
         status = Attenuator.Status()
         print 'status', status
         status = status[:status.index(':')]
         value = status
         return value
     NumToLabel = dict([(int(l.split()[0]), l) for l in labels])
     Attenuator.write_attribute(NumToLabel[x], True)
     self.wait(Attenuator)
コード例 #21
0
ファイル: beamline.py プロジェクト: MartinSavko/align
def attenuation(x = None):
    '''Read or set the attenuation'''
    Attenuator = DeviceProxy('i11-ma-c05/ex/att.1')
    labels = [  
                '00 Extract', 
                '01 Carbon 200um', 
                '02 Carbon 250um', 
                '03 Carbon 300um', 
                '04 Carbon 500um', 
                '05 Carbon 1mm', 
                '06 Carbon 2mm', 
                '07 Carbon 3mm', 
                '10 Ref Fe 5um', 
                '11 Ref Pt 5um'
             ]

    if x == None:
        status = Attenuator.Status()
        status = status[:status.index(':')]
        value = status
        return value
        
    NumToLabel = dict([(int(l.split()[0]), l) for l in labels])
    Attenuator.write_attribute(NumToLabel[x], True)
コード例 #22
0
ファイル: HabitatMonitor.py プロジェクト: casyazmon/mars_city
 def populate_startup_nodes(self):
     nodes = self.db.nodes
     print dt.now(), ":", 'populating leaves'
     for i in nodes.find({'type': 'leaf'}):
         device = i['name'] + " - " + i['attr']
         if device in self.checkedLeaves:
             continue
         proxy = DeviceProxy(i['name'])
         deviceFlag = 1
         while deviceFlag:
             try:
                 proxy.ping()
                 deviceFlag = 0
                 t = threading.Thread(target=self.aggregate_data,
                                      args=([device]))
                 t.start()
                 self.update_tree(self.dataSourcesTreeItem, i['name'],
                                  i['attr'])
                 self.checkedLeaves.append(device)
             except Exception as ex:
                 QtGui.QMessageBox.critical(self, "Warning",
                                            "Start the device server " + device)
     print dt.now(), ":", 'populating branches'
     for i in nodes.find({'type': 'branch'}):
         device = i['name']
         treeBranch = QtGui.QTreeWidgetItem(self.ui.treeWidget)
         treeBranch.setText(0, device)
         for j in i['children']:
             if '-' in j:
                 temp = j.split(' - ')
                 self.update_tree(treeBranch, temp[0], temp[1])
             else:
                 self.update_tree(treeBranch, j, "")
         t = threading.Thread(
             target=self.aggregate_branch_data, args=([device]))
         t.start()
コード例 #23
0
    def init(self):
        #cmdToggle = self.getCommandObject('toggle')
        #cmdToggle.connectSignal('connected', self.connected)
        #cmdToggle.connectSignal('disconnected', self.disconnected)
        
        # Connect to device Attenuator defined "tangoname" in the xml file 
        try :
            #self.Attenuatordevice = SimpleDevice(self.getProperty("tangoname"), verbose=False)
            self.Attenuatordevice = DeviceProxy(self.getProperty("tangoname"))
            self.Attenuatordevice.waitMoves = False
            self.Attenuatordevice.timeout = 5000

        except :
            self.errorDeviceInstance(self.getProperty("tangoname"))

        if self.deviceOk:
            #self.connected()
            #self.chanAttState = self.getChannelObject('State')
            #print "self.chanAttState : ", self.chanAttState
            #self.chanAttState.connectSignal('update', self.attStateChanged)
            ##self.chanAttFactor = self.getChannelObject('appliedTransmission')
            ##self.chanAttFactor = self.getChannelObject('computedTransmission')
            ##self.chanAttFactor.connectSignal('update', self.attFactorChanged)
            
            ##self.chanAttToggle = self.getChannelObject('filtersCombination')
            ##self.chanAttToggle.connectSignal('update', self.attToggleChanged)
            
            #self.getAtteConfig()
            
            self.connected()
            self.chanAttState = self.getChannelObject('State')
            print "self.chanAttState : ", self.chanAttState
            self.chanAttState.connectSignal('update', self.attStateChanged)
            #self.chanAttFactor = self.getChannelObject('appliedTransmission')
            
            self.chanAttFactor = self.getChannelObject('Status')
            self.chanAttFactor.connectSignal('update', self.attFactorChanged)
            
            self.chanAttToggle = self.getChannelObject('State')
            self.chanAttToggle.connectSignal('update', self.attToggleChanged)
            
            self.getAtteConfig()
            
        logging.getLogger().debug("AttenuatorsPX2: self.labels, self.bits, self.attno, %s, %s, %s" %( self.labels, self.bits, self.attno))
コード例 #24
0
    def _init(self):
        
        self.MOVESTARTED = 0
        self.NOTINITIALIZED = 0
        self.UNUSABLE = 0
        self.READY = 2
        self.MOVING = 4
        self.ONLIMITS = 1

        self.device = DeviceProxy(self.getProperty("tangoname")) #, verbose=False)
        self.device.timeout = 6000 # Setting timeout to 6 sec
        self.device.waitMoves = False
        logging.getLogger("HWR").info("TangoMotor._init of device %s" % self.device.name)
        self.setIsReady(True)
        print "TangoMotor._init of device %s" % self.device.name
        positionChan = self.getChannelObject("position") # utile seulement si statechan n'est pas defini dans le code
        positionChan.connectSignal("update", self.positionChanged) 
        stateChan = self.getChannelObject("state") # utile seulement si statechan n'est pas defini dans le code
        stateChan.connectSignal("update", self.motor_state_changed) 
コード例 #25
0
    def _init(self):
        self.currentResolution = None
        self.currentDistance = None
        self.currentWavelength = None
        self.currentEnergy = None
        self.connect("equipmentReady", self.equipmentReady)
        self.connect("equipmentNotReady", self.equipmentNotReady)
        #self.device = SimpleDevice(self.getProperty("tangoname"), waitMoves = False, verbose=False)
        self.device = DeviceProxy(self.getProperty("tangoname"))
        #self.device.timeout = 3000 # Setting timeout to 3 sec
        
        #self.monodevice = SimpleDevice(self.getProperty("tangoname2"), waitMoves = False, verbose=False)

        hobj = self.getProperty("BLEnergy")
        logging.getLogger("HWR").debug('TangoResolution: load specify the %s hardware object' % hobj)
        self.blenergyHO = None
        if hobj is not None:
            try:
                self.blenergyHO=HardwareRepository.HardwareRepository().getHardwareObject(hobj)
            except:
                logging.getLogger("HWR").error('TangoResolutionComplex: BLEnergy is not defined in resolution equipment %s', str(self.name()))
       
        if self.blenergyHO is not None:
            #self.connect(self.blenergyHO, "energyChanged",self.energyChanged)
            self.blenergyHO.connect("energyChanged",self.energyChanged)
        else:
            logging.info('TANGORESOLUTION : BLENERGY is not defined in TangoResolution equipment %s', str(self.name()))

        #self.connect(self.blenergyHO,, "energyChanged",self.energyChanged)
        #self.connect(self.beam_info_hwobj, 
        #                 "beamPosChanged", 
        #                 self.beam_position_changed)
            #self.blenergyHO.connectSignal('energyChanged', self.energyChanged)
        # creer un chanel sur l'energy: pour faire un update 
        positChan = self.getChannelObject("position") # utile seulement si statechan n'est pas defini dans le code
        positChan.connectSignal("update", self.positionChanged)
        stateChan = self.getChannelObject("state") # utile seulement si statechan n'est pas defini dans le code
        stateChan.connectSignal("update", self.stateChanged)
        
        self.currentDistance = self.device.position
        self.currentEnergy = self.blenergyHO.getCurrentEnergy()
        self.currentWavelength = self.blenergyHO.getCurrentWavelength()
        return BaseHardwareObjects.Equipment._init(self)
コード例 #26
0
    def _init(self):
        
        self.MOVESTARTED = 0
        self.NOTINITIALIZED = 0
        self.UNUSABLE = 0
        self.READY = 2
        self.MOVING = 4
        self.ONLIMITS = 1

        self.device = DeviceProxy(self.getProperty("tangoname"))
        self.device.waitMoves = False
        self.setIsReady(True)
        print "TangoMotor._init of device %s" % self.device.name

        self.positionChan = self.getChannelObject("attributeName") # utile seulement si statechan n'est pas defini dans le code
        self.positionChan.connectSignal("update", self.positionChanged) 

        self.stateChan = self.getChannelObject("state") # utile seulement si statechan n'est pas defini dans le code
        self.stateChan.connectSignal("update", self.stateChanged) 
コード例 #27
0
ファイル: HabitatMonitor.py プロジェクト: casyazmon/mars_city
 def add_device(self):
     self.ui.tabWidget.hide()
     self.ui.functionButton.setText("Add Summary")
     print "Add new device"
     devName, ok = QtGui.QInputDialog.getText(self, 'Input Dialog',
                                              'Enter Device Address:')
     devName = str(devName)
     self.devName = devName
     nodes = self.db.nodes
     if ok:
         try:
             self.sourceType = "leaf"
             self.proxy = DeviceProxy(devName)
             msgBox = QtGui.QMessageBox()
             msgBox.setText('Device added successfully')
             msgBox.addButton(QtGui.QPushButton('Ok'),
                              QtGui.QMessageBox.YesRole)
             ret = msgBox.exec_()
             dev_attrs = self.proxy.get_attribute_list()
             self.ui.comboBox.clear()
             for i in dev_attrs:
                 flag = 0
                 if nodes.find_one({'name': devName, 'attr': i}) != None:
                     flag = 1
                 if i == "State" or i == "Status" or flag == 1:
                     continue
                 self.ui.comboBox.addItem(i)
             self.ui.groupBox.show()
             self.ui.comboBox.show()
             self.ui.attrLabel.show()
             self.ui.timeLabel.show()
             self.ui.timeLineEdit.show()
             self.ui.minutesLabel.show()
             self.ui.treeWidget.setEnabled(False)
         except Exception as ex:
             print ex
             QtGui.QErrorMessage(self).showMessage(
                 "Incorrect Device Address")
     else:
         QtGui.QMessageBox.critical(self, "Warning",
                                    "Device not added")
コード例 #28
0
 def parse(self, device_url):
     device = DeviceProxy(device_url)
     result = Documentation()
     result.name = device.info().dev_class
     result.description = device.description()
     # FIXME: perhaps need to query the database about the propertiess
     propertyNames = device.get_property_list('*')
     for propertyName in propertyNames:
         result.addproperty(propertyName, 'TODO description', 'TODO type name', 'TODO default')
     attributeInfos = device.attribute_list_query()
     for attributeInfo in attributeInfos:
         result.addattribute(attributeInfo.name, attributeInfo.description, self.translate(attributeInfo.data_type, attributeInfo.data_format))
     commandInfos = device.command_list_query()
     for commandInfo in commandInfos:
         result.addcommand(
             commandInfo.cmd_name,
             'TODO command description',
             self.translate_command_argument(commandInfo.in_type),
             commandInfo.in_type_desc,
             self.translate_command_argument(commandInfo.out_type),
             commandInfo.out_type_desc)
     return [result]
コード例 #29
0
class Blender():
    def __init__(self):
        client = MongoClient('localhost', 27017)
        self.db = client.habitatdb
        self.threads = []
        self.nodeTimers = []
        self.isModified = False
        self.addingSummary = False
        self.summaryNode = None
        nodes = self.db.nodes
        self.checkedLeaves = []
        try:  #code to connect to client and recieve first few data items
            self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            self.sock.bind((TCP_IP, TCP_PORT))
            self.sock.listen(1)
            self.conn, self.addr = self.sock.accept()
            print 'Connection ESTAblished successfully to BlenderLeap Client'
            time.sleep(3)
            response = "".encode()
            try:
                data = self.conn.recv(BUFFER_SIZE)
                print data
                if not data:
                    print "no data"
                if data == "add" or data == "Add":
                    try:
                        data = self.conn.recv(BUFFER_SIZE)
                        response += data
                        data_arr = json.loads(response)
                        self.devName = data_arr[0]
                        self.attrname = data_arr[1]
                        self.summary_type = data_arr[2]
                        self.summ_time = data_arr[3]
                    except:
                        print "error in sending data"
                    self.populate_startup_nodes()
                    self.add_device()

                else:
                    try:
                        data = self.conn.recv(BUFFER_SIZE)
                        response += data
                        data_arr = json.loads(
                            response
                        )  #to recieve data as an array of strings from client
                        self.devName = data_arr[0]
                        self.attrname = data_arr[1]
                        self.delete_node()
                        self.populate_startup_nodes()
                    except:
                        print "delete error"
            except:
                print "Receiving error"
        except:
            print "connection couldn't be established to BlenderLeap Client"
            self.sock.close()
            sys.exit()
            pass

    def populate_startup_nodes(self):
        nodes = self.db.nodes
        print dt.now(), ":", 'populating leaves'
        for i in nodes.find({'type': 'leaf'}):
            device = i['name'] + " - " + i['attr']
            if device in self.checkedLeaves:
                continue
            proxy = DeviceProxy(i['name'])
            deviceFlag = 1
            while deviceFlag:
                try:
                    proxy.ping()
                    deviceFlag = 0
                    t = threading.Thread(target=self.aggregate_data,
                                         args=([device]))
                    t.start()
                    self.checkedLeaves.append(device)
                except Exception as ex:
                    print "Warning" + "Start the device server" + device

    def fetch_data(self, devName):
        temp = devName.split(" - ")
        dName = temp[0]
        dAttr = temp[1]
        proxy = DeviceProxy(dName)
        nodes = self.db.nodes
        node = nodes.find_one({'name': dName, 'attr': dAttr})
        temp = proxy[dAttr].value
        if node != None:
            try:
                max_len = node['max_len']
                if len(list(node['data'])) >= max_len:
                    nodes.update({
                        'name': dName,
                        'attr': dAttr
                    }, {'$pop': {
                        'data': -1
                    }})
                nodes.update({
                    'name': dName,
                    'attr': dAttr
                }, {'$push': {
                    'data': temp
                }})
                node = nodes.find_one({'name': dName, 'attr': dAttr})
                summary_data = self.find_summary(list(node['data']),
                                                 node['function'])
                nodes.update({
                    'name': dName,
                    'attr': dAttr
                }, {'$set': {
                    'summary_data': summary_data
                }})
                response = dName + "," + dAttr + "," + node[
                    'function'] + "," + str(node['summary_data'])
                summary_value = str(node['summary_data'])
                try:
                    self.conn.send(response.encode())
                except:
                    print "could send please check connection"
                    self.sock.close()
                    sys.exit()
                    pass
                print response
                threading.Timer(4, self.fetch_data, [devName]).start()
            except Exception as ex:
                print ex
                print node
        else:
            print devName, "deleted"

    def aggregate_data(self, devName):
        timer = threading.Timer(3, self.fetch_data, [devName])
        timer.start()

    def add_summary(self):
        summaryTime = ""
        max_len = 0
        attrname = self.attrname
        summary_type = self.summary_type
        summ_time = self.summ_time
        children = ""
        attr = ""
        summary_children = {}
        nodes = self.db.nodes
        summary = summary_type
        pattern = re.compile("^[0-9][0-9]:[0-9][0-9]:[0-9][0-9]$")
        sourceType = self.sourceType
        print "logging:", sourceType
        if sourceType == "leaf":
            timeField = summ_time
            if len(timeField) == 0:
                print "Time Field is required"
                return
            if not pattern.match(timeField):
                print "Please enter time in the correct format -- hh:mm:ss"
                return
            l = timeField.split(":")
            attr = attrname
            summaryTime = int(l[0]) * 3600 + int(l[1]) * 60 + int(l[2])
            max_len = (summaryTime * 60) / 2
            nodeName = self.devName
            summary_data = 0.0
        node = {
            'name': nodeName,
            'type': sourceType,
            'attr': attr,
            'function': summary,
            'time': summaryTime,
            'children': children,
            'max_len': max_len,
            'data': [],
            'summary_data': summary_data,
            'summary_children': summary_children
        }
        node_id = nodes.insert_one(node).inserted_id
        if sourceType == "leaf":
            t = threading.Thread(target=self.aggregate_data,
                                 args=([self.devName + " - " + attr]))
            try:
                t.start()
            except (KeyboardInterrupt, SystemExit):
                cleanup_stop_thread()
                sys.exit()

    def delete_node(self):
        #Delte a particular node when requested
        print "reached"
        if 1:
            nodes = self.db.nodes
            mdNode = self.devName
            mdAttr = self.attrname
            node = nodes.find_one({'name': mdNode, 'attr': mdAttr})
            if node:
                nodes.remove({'name': mdNode, 'attr': mdAttr})
            else:
                print "Cannot delete. Invalid device name or attribute"

    def find_summary(self, data, function):
        #Function to return the required value
        if function == "Minimum":
            return min(data)
        elif function == "Maximum":
            return max(data)
        elif function == "Average":
            try:
                value = float(sum(data)) / len(data)
            except ZeroDivisionError:
                value = 0
            return value

    def add_device(self):
        # This Function is called to add a device with the given device name and address to get the required value
        print "Add new device"
        devName = self.devName
        attrname = self.attrname
        self.devName = devName
        nodes = self.db.nodes
        if 1:
            try:
                self.sourceType = "leaf"
                self.proxy = DeviceProxy(devName)
                print "Device added success"
                dev_attrs = self.proxy.get_attribute_list()
                if nodes.find_one({'name': devName, 'attr': attrname}) != None:
                    print " attribute already added before sorry"
                else:
                    self.add_summary()
            except Exception as ex:
                print ex
                print "Incorrect Device Address"
        else:
            print "Warning" + "Device not added"
コード例 #30
0
    def connectTangoDevices(self):
        try :
            self.BLEnergydevice = DeviceProxy(self.getProperty("blenergy")) #, verbose=False)
            self.BLEnergydevice.waitMoves = True
            self.BLEnergydevice.timeout = 30000
        except :
            logging.getLogger("HWR").error("%s not found" %(self.getProperty("blenergy")))
            self.canScan = False
            
        # Connect to device mono defined "tangoname2" in the xml file 
        # used for conversion in wavelength
        try :    
            self.monodevice = DeviceProxy(self.getProperty("mono")) #, verbose=False)
            self.monodevice.waitMoves = True
            self.monodevice.timeout = 6000
        except :    
            logging.getLogger("HWR").error("%s not found" %(self.getProperty("mono")))
            self.canScan = False
        #mono_mt_rx
        try :    
            self.mono_mt_rx_device = DeviceProxy(self.getProperty("mono_mt_rx")) #, verbose=False)
            #self.monodevice.waitMoves = True
            self.mono_mt_rx_device.timeout = 6000
        except :    
            logging.getLogger("HWR").error("%s not found" %(self.getProperty("mono_mt_rx")))
            self.canScan = False
        # Nom du device bivu (Energy to gap) : necessaire pour amelioration du positionnement de l'onduleur (Backlash)
        try :    
            self.U20Energydevice = DeviceProxy(self.getProperty("U24Energy")) #, movingState="MOVING")
            self.U20Energydevice.timeout = 30000
        except :    
            logging.getLogger("HWR").error("%s not found" %(self.getProperty("U24Energy")))
            self.canScan = False
            
        try :
            self.fluodetdevice = DeviceProxy(self.getProperty("ketek")) #, verbose=False)
            self.fluodetdevice.timeout = 1000
        except :
            logging.getLogger("HWR").error("%s not found" %(self.getProperty("ketek")))
            self.canScan = False
            
        try :    
            self.counterdevice = DeviceProxy(self.getProperty("counter")) #, verbose=False)
            self.counterdevice.timeout = 1000
        except :    
            logging.getLogger("HWR").error("%s not found" %(self.getProperty("counter")))
            self.canScan = False

        try :    
            self.xbpmdevice = DeviceProxy(self.getProperty("xbpm")) #, verbose=False)
            self.xbpmdevice.timeout = 30000
        except :    
            logging.getLogger("HWR").error("%s not found" %(self.getProperty("xbpm")))
            self.canScan = False
       
        try :    
            self.attdevice = DeviceProxy(self.getProperty("attenuator")) #, verbose=False)
            self.attdevice.timeout = 6000
        except :    
            logging.getLogger("HWR").error("%s not found" %(self.getProperty("attenuator")))
            self.canScan = False
        
#        try :    
#            self.md2device = DeviceProxy(self.getProperty("md2")) #, verbose=False)
#            self.md2device.timeout = 2000
#        except :    
#            logging.getLogger("HWR").error("%s not found" %(self.getProperty("md2")))
#            self.canScan = False
        
        try:
            self.lightdevice = DeviceProxy(self.getProperty("lightextract")) #, verbose=False)
            self.lightdevice.timeout = 2000
        except :    
            logging.getLogger("HWR").error("%s not found" %(self.getProperty("lightextract")))
            self.canScan = False

        try:
            self.bstdevice = DeviceProxy(self.getProperty("bst")) #, verbose=False)
            self.bstdevice.timeout = 2000
        except :    
            logging.getLogger("HWR").error("%s not found" %(self.getProperty("bst")))
            self.canScan = False

        try:
            self.ketekinsertdevice = DeviceProxy(self.getProperty("ketekinsert")) #, verbose=False)
            self.ketekinsertdevice.timeout = 2000
        except :    
            logging.getLogger("HWR").error("%s not found" %(self.getProperty("ketekinsert")))
            self.canScan = False

        try:
            self.fastshutterdevice = DeviceProxy(self.getProperty("fastshutter")) #, verbose=False)
            self.fastshutterdevice.timeout = 2000
        except :    
            logging.getLogger("HWR").error("%s not found" %(self.getProperty("fastshutter")))
            self.canScan = False
コード例 #31
0
    def run(self, energy):

        if energy == -999:
            self.output("Usage:")
            self.output("me <energy>")
            self.output("Move energy. Diffractometer wavelength is set")
            return

        try:
            energyfmb_device = self.getObj("mnchrmtr")
            energyfmb_device_name = "mnchrmtr"
        except Exception:
            self.warning("mnchrmtr device does not exist.")
            self.warning("Trying to get the fmb device name from the "
                         "EnergyFMB environment variable")
            try:
                energyfmb_device_name = self.getEnv('EnergyFMB')
            except Exception:
                self.error("EnergyFMB not defined. Macro exiting")
                return
            try:
                energyfmb_device = self.getObj(energyfmb_device_name)
            except Exception:
                self.error("Unable to get fmb device %s. Macro exiting" %
                           energyfmb_device_name)
                return

        try:
            energy_device = self.getObj("mnchrmtr")
            energy_device_name = "mnchrmtr"
        except Exception:
            self.warning("mnchrmtr device does not exist.")
            self.warning("Trying to get the energy device name from the "
                         "EnergyDevice environment variable")
            try:
                energy_device_name = self.getEnv('EnergyDevice')
            except Exception:
                self.error("EnergyDevice not defined. Macro exiting")
                return
            try:
                energy_device = self.getObj(energy_device_name)
            except Exception:
                self.error("Unable to get energy device %s. Macro exiting" %
                           energy_device_name)
                return

        fmb_tango_device = DeviceProxy(energyfmb_device.TangoDevice)
        try:
            fmb_tango_device.write_attribute("PseudoChannelCutMode", 0)
        except Exception:
            pass

        flag_diffrac = 0
        try:
            diffrac_name = self.getEnv('DiffracDevice')
            diffrac_device = self.getDevice(diffrac_name)

            initial_autoenergy = diffrac_device.read_attribute(
                "autoenergyupdate").value
            diffrac_device.write_attribute("autoenergyupdate", 0)

            flag_diffrac = 1

            lambda_to_e = 12398.424  # Amstrong * eV
            wavelength = lambda_to_e / energy
            diffrac_device.write_attribute("wavelength", wavelength)
        except Exception:
            pass

        self.execMacro("mv", [[energy_device, energy]])

        if flag_diffrac:
            diffrac_device.write_attribute("autoenergyupdate",
                                           initial_autoenergy)
コード例 #32
0
    def init(self):      

        self.cats_device = DeviceProxy(self.tangoname)

        try:
            self.cats_model = self.cats_device.read_attribute("CatsModel").value
        except:
            self.cats_model = "CATS"

        if self.is_isara():
            self.nb_of_lids = 1
        else:
            self.nb_of_lids = 3

        self._chnState = self.addChannel({ "type": "tango", 
            "name": "_chnState", "tangoname": self.tangoname, 
            "polling": 1000, }, "State")

        self._chnPathRunning = self.addChannel({ "type": "tango", 
            "name": "_chnPathRunning", "tangoname": self.tangoname, 
            "polling": 1000, }, "PathRunning")
        self._chnPowered = self.addChannel({ "type": "tango", 
            "name": "_chnPowered", "tangoname": self.tangoname, 
            "polling": 1000, }, "Powered")
        self._chnMessage = self.addChannel({ "type": "tango", 
            "name": "_chnMessage", "tangoname": self.tangoname, 
            "polling": 1000, }, "Message")
        self._chnToolOpenClose = self.addChannel({ "type": "tango", 
            "name": "_chnToolOpenClose", "tangoname": self.tangoname, 
            "polling": 1000, }, "di_ToolOpen")
        self._chnLN2Regulation = self.addChannel({ "type": "tango", 
            "name": "_chnLN2Regulation", "tangoname": self.tangoname, 
            "polling": 1000, }, "LN2Regulating")
        self._chnBarcode = self.addChannel({ "type": "tango", 
            "name": "_chnBarcode", "tangoname": self.tangoname, 
            "polling": 1000, }, "Barcode")

        self._chnLid1State = self.addChannel({ "type": "tango", 
            "name": "_chnLid1State", "tangoname": self.tangoname, 
            "polling": 1000, }, "di_Lid1Open")
        self._chnLid1State.connectSignal("update", self._updateLid1State)

        if self.nb_of_lids > 1:
            self._chnLid2State = self.addChannel({ "type": "tango", 
                "name": "_chnLid2State", "tangoname": self.tangoname, 
                "polling": 1000, }, "di_Lid2Open")
            self._chnLid2State.connectSignal("update", self._updateLid2State)

        if self.nb_of_lids > 2:
            self._chnLid3State = self.addChannel({ "type": "tango", 
                "name": "_chnLid3State", "tangoname": self.tangoname, 
                "polling": 1000, }, "di_Lid3Open")
            self._chnLid3State.connectSignal("update", self._updateLid3State)

        self._chnState.connectSignal("update", self._updateState)
        self._chnPathRunning.connectSignal("update", self._updateRunningState)
        self._chnPowered.connectSignal("update", self._updatePoweredState)
        self._chnToolOpenClose.connectSignal("update", self._updateToolState)
        self._chnMessage.connectSignal("update", self._updateMessage)
        self._chnLN2Regulation.connectSignal("update", self._updateRegulationState)
        self._chnBarcode.connectSignal("update", self._updateBarcode)
           
        self._chnCurrentTool = self.addChannel({ "type": "tango", 
            "name": "_chnCurrentTool", "tangoname": self.tangoname }, "Tool")
        # 
        self._cmdPowerOn = self.addCommand({ "type": "tango", 
            "name": "_cmdPowerOn", "tangoname": self.tangoname, }, "powerOn")
        self._cmdPowerOff = self.addCommand({ "type": "tango", 
            "name": "_cmdPowerOff", "tangoname": self.tangoname, }, "powerOff")
        self._cmdOpenTool = self.addCommand({ "type": "tango", 
            "name": "_cmdOpenTool", "tangoname": self.tangoname, }, "opentool")
        self._cmdCloseTool = self.addCommand({ "type": "tango", 
            "name": "_cmdCloseTool", "tangoname": self.tangoname, }, "closetool")
        self._cmdMagnetOn = self.addCommand({ "type": "tango", 
            "name": "_cmdMagnetOn", "tangoname": self.tangoname, }, "magnetOn")
        self._cmdMagnetOff = self.addCommand({ "type": "tango", 
            "name": "_cmdMagnetOff", "tangoname": self.tangoname, }, "magnetOff")

        # LIDs
        self._cmdOpenLid1 = self.addCommand({ "type": "tango", 
            "name": "_cmdOpenLid1", "tangoname": self.tangoname, }, "openlid1")
        self._cmdCloseLid1 = self.addCommand({ "type": "tango", 
            "name": "_cmdCloseLid1", "tangoname": self.tangoname, }, "closelid1")

        if self.nb_of_lids > 1:
            self._cmdOpenLid2 = self.addCommand({ "type": "tango", 
                "name": "_cmdOpenLid1", "tangoname": self.tangoname, }, "openlid2")
            self._cmdCloseLid2 = self.addCommand({ "type": "tango", 
                "name": "_cmdCloseLid1", "tangoname": self.tangoname, }, "closelid2")

        if self.nb_of_lids > 2:
            self._cmdOpenLid3 = self.addCommand({ "type": "tango", 
                "name": "_cmdOpenLid1", "tangoname": self.tangoname, }, "openlid3")
            self._cmdCloseLid3 = self.addCommand({ "type": "tango", 
                "name": "_cmdCloseLid1", "tangoname": self.tangoname, }, "closelid3")

        self._cmdRegulOn = self.addCommand({ "type": "tango", 
            "name": "_cmdRegulOn", "tangoname": self.tangoname, }, "regulon")
        self._cmdRegulOff = self.addCommand({ "type": "tango", 
            "name": "_cmdRegulOff", "tangoname": self.tangoname, }, "reguloff")

        self._cmdToolOpen = self.addCommand({ "type": "tango", 
            "name": "_cmdToolOpen", "tangoname": self.tangoname, }, "opentool")
        self._cmdToolClose = self.addCommand({ "type": "tango", 
            "name": "_cmdToolClose", "tangoname": self.tangoname, }, "closetool")

        # Paths
        self._cmdAbort = self.addCommand({ "type": "tango", 
            "name": "_cmdAbort", "tangoname": self.tangoname, }, "abort")
        self._cmdDry = self.addCommand({ "type": "tango", 
            "name": "_cmdDry", "tangoname": self.tangoname, }, "dry")
        self._cmdSafe = self.addCommand({ "type": "tango", 
            "name": "_cmdSafe", "tangoname": self.tangoname, }, "safe")
        self._cmdHome = self.addCommand({ "type": "tango", 
            "name": "_cmdHome", "tangoname": self.tangoname, }, "home")
        self._cmdSoak = self.addCommand({ "type": "tango", 
            "name": "_cmdSoak", "tangoname": self.tangoname, }, "soak")
        self._cmdBack = self.addCommand({ "type": "tango", 
            "name": "_cmdBack", "tangoname": self.tangoname, }, "back")
        self._cmdCalibration = self.addCommand({ "type": "tango", 
            "name": "_cmdCalibration", "tangoname": self.tangoname, }, "toolcalibration")

        self._cmdClearMemory = self.addCommand({ "type": "tango", 
            "name": "_cmdClearMemory", "tangoname": self.tangoname, }, "clear_memory")
        self._cmdReset = self.addCommand({ "type": "tango", 
            "name": "_cmdReset", "tangoname": self.tangoname, }, "reset")
        self._cmdResetParameters = self.addCommand({ "type": "tango", 
            "name": "_cmdResetParameters", "tangoname": self.tangoname, }, "reset_parameters")

        self._cmdRecoverFailure = self.addCommand({ "type": "tango", 
            "name": "_cmdRecoverFailure", "tangoname": self.tangoname, }, "recoverFailure")

        self._cmdResetMotion = self.addCommand({ "type": "tango", 
            "name": "_cmdResetMotion", "tangoname": self.tangoname, }, "resetmotion")

        self._cmdSetOnDiff = self.addCommand({ "type": "tango", 
            "name": "_cmdSetOnDiff", "tangoname": self.tangoname, }, "setondiff")
        self._cmdSetOnTool = self.addCommand({ "type": "tango", 
            "name": "_cmdSetOnTool", "tangoname": self.tangoname, }, "settool")
        self._cmdSetOnTool2 = self.addCommand({ "type": "tango", 
            "name": "_cmdSetOnTool2", "tangoname": self.tangoname, }, "settool2")

        self.state_actions = {
             "power": {"in_open": self._cmdPowerOn, "out_close": self._cmdPowerOff, 
                       "state": self._chnPowered},
        }
コード例 #33
0
class EnergyScanPX1(Equipment):
    
    MANDATORY_HO={"BLEnergy":"BLEnergy"}
    
    
    def init(self):
        self.scanning = None
#        self.moving = None
        self.scanThread = None
        self.pk = None
        self.ip = None
        self.roiwidth = 0.35 # en keV largeur de la roi 
        self.before = 0.10  #  en keV Ecart par rapport au seuil pour le point de depart du scan
        self.after = 0.20   # en keV Ecart par rapport au seuil pour le dernier point du scan
        self.canScan = True
        self.nbsteps = 100 #
        self.integrationtime = 5.0
        self.directoryPrefix = None

        self.directoryPrefix=self.getProperty("directoryprefix")
        if self.directoryPrefix is None:
            logging.getLogger("HWR").error("EnergyScan: you must specify the directory prefix property")
        else :
            logging.getLogger("HWR").info("EnergyScan: directoryPrefix : %s" %(self.directoryPrefix))
            
                    # Load mandatory hardware objects
#         for ho in EnergyScan.MANDATORY_HO:
#             desc=EnergyScan.MANDATORY_HO[ho]
#             name=self.getProperty(ho)
#             if name is None:
#                  logging.getLogger("HWR").error('EnergyScan: you must specify the %s hardware object' % desc)
#                  hobj=None
#                  self.configOk=False
#             else:
#                  hobj=HardwareRepository.HardwareRepository().getHardwareObject(name)
#                  if hobj is None:
#                      logging.getLogger("HWR").error('EnergyScan: invalid %s hardware object' % desc)
#                      self.configOk=False
#             exec("self.%sHO=hobj" % ho)
# 
#         print "BLEnergyHO : ", self.BLEnergyHO
        
        paramscan = self["scan"]   
        self.roiwidth = paramscan.roiwidth
        self.before = paramscan.before
        self.after = paramscan.after
        self.nbsteps = paramscan.nbsteps
        self.integrationTime = paramscan.integrationtime
      
      
        print("self.roiwidth :", self.roiwidth)
        print("self.before :", self.before)
        print("self.after :", self.after)
        print("self.nbsteps :", self.nbsteps)
        print("self.integrationtime :", self.integrationtime)
        

        self.dbConnection=self.getObjectByRole("dbserver")
        if self.dbConnection is None:
            logging.getLogger("HWR").warning('EnergyScan: you should specify the database hardware object')
        self.scanInfo=None

        if self.isSpecConnected():
            self.sConnected()
            
    def connectTangoDevices(self):
        try :
            self.BLEnergydevice = DeviceProxy(self.getProperty("blenergy")) #, verbose=False)
            self.BLEnergydevice.waitMoves = True
            self.BLEnergydevice.timeout = 30000
        except :
            logging.getLogger("HWR").error("%s not found" %(self.getProperty("blenergy")))
            self.canScan = False
            
        # Connect to device mono defined "tangoname2" in the xml file 
        # used for conversion in wavelength
        try :    
            self.monodevice = DeviceProxy(self.getProperty("mono")) #, verbose=False)
            self.monodevice.waitMoves = True
            self.monodevice.timeout = 6000
        except :    
            logging.getLogger("HWR").error("%s not found" %(self.getProperty("mono")))
            self.canScan = False
        #mono_mt_rx
        try :    
            self.mono_mt_rx_device = DeviceProxy(self.getProperty("mono_mt_rx")) #, verbose=False)
            #self.monodevice.waitMoves = True
            self.mono_mt_rx_device.timeout = 6000
        except :    
            logging.getLogger("HWR").error("%s not found" %(self.getProperty("mono_mt_rx")))
            self.canScan = False
        # Nom du device bivu (Energy to gap) : necessaire pour amelioration du positionnement de l'onduleur (Backlash)
        try :    
            self.U20Energydevice = DeviceProxy(self.getProperty("U24Energy")) #, movingState="MOVING")
            self.U20Energydevice.timeout = 30000
        except :    
            logging.getLogger("HWR").error("%s not found" %(self.getProperty("U24Energy")))
            self.canScan = False
            
        try :
            self.fluodetdevice = DeviceProxy(self.getProperty("ketek")) #, verbose=False)
            self.fluodetdevice.timeout = 1000
        except :
            logging.getLogger("HWR").error("%s not found" %(self.getProperty("ketek")))
            self.canScan = False
            
        try :    
            self.counterdevice = DeviceProxy(self.getProperty("counter")) #, verbose=False)
            self.counterdevice.timeout = 1000
        except :    
            logging.getLogger("HWR").error("%s not found" %(self.getProperty("counter")))
            self.canScan = False

        try :    
            self.xbpmdevice = DeviceProxy(self.getProperty("xbpm")) #, verbose=False)
            self.xbpmdevice.timeout = 30000
        except :    
            logging.getLogger("HWR").error("%s not found" %(self.getProperty("xbpm")))
            self.canScan = False
       
        try :    
            self.attdevice = DeviceProxy(self.getProperty("attenuator")) #, verbose=False)
            self.attdevice.timeout = 6000
        except :    
            logging.getLogger("HWR").error("%s not found" %(self.getProperty("attenuator")))
            self.canScan = False
        
#        try :    
#            self.md2device = DeviceProxy(self.getProperty("md2")) #, verbose=False)
#            self.md2device.timeout = 2000
#        except :    
#            logging.getLogger("HWR").error("%s not found" %(self.getProperty("md2")))
#            self.canScan = False
        
        try:
            self.lightdevice = DeviceProxy(self.getProperty("lightextract")) #, verbose=False)
            self.lightdevice.timeout = 2000
        except :    
            logging.getLogger("HWR").error("%s not found" %(self.getProperty("lightextract")))
            self.canScan = False

        try:
            self.bstdevice = DeviceProxy(self.getProperty("bst")) #, verbose=False)
            self.bstdevice.timeout = 2000
        except :    
            logging.getLogger("HWR").error("%s not found" %(self.getProperty("bst")))
            self.canScan = False

        try:
            self.ketekinsertdevice = DeviceProxy(self.getProperty("ketekinsert")) #, verbose=False)
            self.ketekinsertdevice.timeout = 2000
        except :    
            logging.getLogger("HWR").error("%s not found" %(self.getProperty("ketekinsert")))
            self.canScan = False

        try:
            self.fastshutterdevice = DeviceProxy(self.getProperty("fastshutter")) #, verbose=False)
            self.fastshutterdevice.timeout = 2000
        except :    
            logging.getLogger("HWR").error("%s not found" %(self.getProperty("fastshutter")))
            self.canScan = False
        
                            
    def isConnected(self):
        return self.isSpecConnected()
        
    def isSpecConnected(self):
        logging.getLogger("HWR").debug('EnergyScan:isSpecConnected')
        return True

    # Handler for spec connection
    def sConnected(self):
        logging.getLogger("HWR").debug('EnergyScan:sConnected')
        self.emit('connected', ())
        self.emit('setDirectory', (self.directoryPrefix,))


    # Handler for spec disconnection
    def sDisconnected(self):
        logging.getLogger("HWR").debug('EnergyScan:sDisconnected')
        self.emit('disconnected', ())

    # Energy scan commands
    def canScanEnergy(self):
        logging.getLogger("HWR").debug('EnergyScan:canScanEnergy : %s' %(str(self.canScan)))
        return self.canScan

 
#        return self.doEnergyScan is not None
	
    def startEnergyScan(self, 
                        element, 
                        edge, 
                        directory, 
                        prefix, 
                        session_id = None, 
                        blsample_id = None):
        
        logging.getLogger("HWR").debug('EnergyScan:startEnergyScan')
        print('edge', edge)
        print('element', element)
        print('directory', directory)
        print('prefix', prefix)
        #logging.getLogger("HWR").debug('EnergyScan:edge', edge)
        #logging.getLogger("HWR").debug('EnergyScan:element', element)
        #logging.getLogger("HWR").debug('EnergyScan:directory', directory)
        #logging.getLogger("HWR").debug('EnergyScan:prefix', prefix)
        #logging.getLogger("HWR").debug('EnergyScan:edge', edge)
        self.scanInfo={"sessionId":session_id,
                       "blSampleId":blsample_id,
                       "element":element,
                       "edgeEnergy":edge}
#        if self.fluodetectorHO is not None:
#            self.scanInfo['fluorescenceDetector']=self.fluodetectorHO.userName()
        if not os.path.isdir(directory):
            logging.getLogger("HWR").debug("EnergyScan: creating directory %s" % directory)
            try:
                os.makedirs(directory)
            except OSError as diag:
                logging.getLogger("HWR").error("EnergyScan: error creating directory %s (%s)" % (directory,str(diag)))
                self.emit('scanStatusChanged', ("Error creating directory",))
                return False
        self.doEnergyScan(element, edge, directory, prefix)
        return True
        
    def cancelEnergyScan(self):
        logging.getLogger("HWR").debug('EnergyScan:cancelEnergyScan')
        if self.scanning:
            self.scanning = False
            
    def scanCommandReady(self):
        logging.getLogger("HWR").debug('EnergyScan:scanCommandReady')
        if not self.scanning:
            self.emit('energyScanReady', (True,))
            
    def scanCommandNotReady(self):
        logging.getLogger("HWR").debug('EnergyScan:scanCommandNotReady')
        if not self.scanning:
            self.emit('energyScanReady', (False,))
            
    def scanCommandStarted(self):
        logging.getLogger("HWR").debug('EnergyScan:scanCommandStarted')

        self.scanInfo['startTime']=time.strftime("%Y-%m-%d %H:%M:%S")
        self.scanning = True
        self.emit('energyScanStarted', ())
    
    def scanCommandFailed(self):
        logging.getLogger("HWR").debug('EnergyScan:scanCommandFailed')
        self.scanInfo['endTime']=time.strftime("%Y-%m-%d %H:%M:%S")
        self.scanning = False
        self.storeEnergyScan()
        self.emit('energyScanFailed', ())
        
    def scanCommandAborted(self):
        logging.getLogger("HWR").debug('EnergyScan:scanCommandAborted')
    
    def scanCommandFinished(self,result):
        logging.getLogger("HWR").debug("EnergyScan: energy scan result is %s" % result)
        self.scanInfo['endTime']=time.strftime("%Y-%m-%d %H:%M:%S")
        self.scanning = False
        if result==-1:
            self.storeEnergyScan()
            self.emit('scanStatusChanged', ("Scan aborted",))
            self.emit('energyScanFailed', ())
            return

        self.storeEnergyScan()
        self.emit('energyScanFinished', (self.scanInfo,))
        self.scanInfo=None
        
    def doChooch(self, scanObject, scanDesc):
                 #elt, 
                 #edge):
                 #scanArchiveFilePrefix = 'scanArchiveFilePrefix', 
                 #scanFilePrefix = 'scanFilePrefix'):
                     
        logging.getLogger().info("EnergyScan: doChooch")
        print('scanObject', scanObject)
        print('scanDesc', scanDesc)
        #archiveRawScanFile=os.path.extsep.join((scanArchiveFilePrefix, "raw"))
        #rawScanFile=os.path.extsep.join((scanFilePrefix, "raw"))
        #scanFile=os.path.extsep.join((scanFilePrefix, "efs"))
      
        #if not os.path.exists(os.path.dirname(scanArchiveFilePrefix)):
            #os.mkdir(os.path.dirname(scanArchiveFilePrefix))
        
        #try:
            #f=open(rawScanFile, "w")
            #pyarch_f=open(archiveRawScanFile, "w")
        #except:
            #logging.getLogger("HWR").exception("could not create raw scan files")
            #self.storeEnergyScan()
            #self.emit("energyScanFailed", ())
            #return
        #else:
            #scanData = []
            #for i in range(len(scanObject.x)):
                    #x = float(scanObject.x[i])
                    #x = x < 1000 and x*1000.0 or x 
                    #y = float(scanObject.y[i])
                    #scanData.append((x, y))
                    #f.write("%f,%f\r\n" % (x, y))
                    #pyarch_f.write("%f,%f\r\n"% (x, y)) 
            #f.close()
            #pyarch_f.close()
            #self.scanInfo["scanFileFullPath"]=str(archiveRawScanFile)
        
        filenameIn = self.filenameIn
        filenameOut = filenameIn[:-3] + 'efs'
        scanData = []
        
        contents = file(filenameIn).readlines()
        file(filenameIn).close()
        
        for value in contents:
          if value[0] != '#' :
              vals = value.split()
              x = float(vals[0])
              x = x < 1000 and x*1000.0 or x #This is rather cryptic but seems to work (MS 11.03.13)
              y = float(vals[1])
              #if y == 0.0:
                  #self.scanCommandFailed()
                  #self.scanStatus.setText("data not valid for chooch")
                  #print "data not valid for chooch"
                  #return
              scanData.append((x, y))
              
        elt = scanDesc['element']
        edge = scanDesc['edgeEnergy']
        
        try:
            pk, fppPeak, fpPeak, ip, fppInfl, fpInfl, chooch_graph_data = PyChooch.calc(scanData,
                                                                                    elt, 
                                                                                    edge, 
                                                                                    filenameOut)
        except:
            pk = self.thEdge
            rm = (pk + 50.) / 1000.0
            savpk = pk
            ip = pk - 5. / 1000.0
            logging.getLogger("HWR").info("Chooch failed badly")
            #, fppPeak, fpPeak, ip, fppInfl, fpInfl, chooch_graph_data = self.thEdge, 
            
        rm = (pk + 50.) / 1000.0
        pk = pk / 1000.0
        savpk = pk
        ip = ip / 1000.0
        comm = ""
        logging.getLogger("HWR").info("th. Edge %s ; chooch results are pk=%f, ip=%f, rm=%f" % (self.thEdge,  pk, ip, rm))

        if math.fabs(self.thEdge - ip) > 0.01:
            pk = 0
            ip = 0
            rm = self.thEdge + 0.05
            comm = 'Calculated peak (%f) is more that 10eV away from the theoretical value (%f). Please check your scan' % (savpk, self.thEdge)
    
            logging.getLogger("HWR").warning('EnergyScan: calculated peak (%f) is more that 10eV %s the theoretical value (%f). Please check your scan and choose the energies manually' % (savpk, (self.thEdge - ip) > 0.01 and "below" or "above", self.thEdge))
        
        scanFile = filenameIn
        archiveEfsFile = filenameOut #os.path.extsep.join((scanArchiveFilePrefix, "efs"))
        try:
            fi = open(scanFile)
            fo = open(archiveEfsFile, "w")
        except:
            self.storeEnergyScan()
            self.emit("energyScanFailed", ())
            return
        else:
            fo.write(fi.read())
            fi.close()
            fo.close()

        self.scanInfo["peakEnergy"]=pk
        self.scanInfo["inflectionEnergy"]=ip
        self.scanInfo["remoteEnergy"]=rm
        self.scanInfo["peakFPrime"]=fpPeak
        self.scanInfo["peakFDoublePrime"]=fppPeak
        self.scanInfo["inflectionFPrime"]=fpInfl
        self.scanInfo["inflectionFDoublePrime"]=fppInfl
        self.scanInfo["comments"] = comm

        chooch_graph_x, chooch_graph_y1, chooch_graph_y2 = list(zip(*chooch_graph_data))
        chooch_graph_x = list(chooch_graph_x)
        for i in range(len(chooch_graph_x)):
          chooch_graph_x[i]=chooch_graph_x[i]/1000.0

        logging.getLogger("HWR").info("<chooch> Saving png" )
        # prepare to save png files
        title="%10s  %6s  %6s\n%10s  %6.2f  %6.2f\n%10s  %6.2f  %6.2f" % ("energy", "f'", "f''", pk, fpPeak, fppPeak, ip, fpInfl, fppInfl) 
        fig=Figure(figsize=(15, 11))
        ax=fig.add_subplot(211)
        ax.set_title("%s\n%s" % (scanFile, title))
        ax.grid(True)
        ax.plot(*(list(zip(*scanData))), **{"color":'black'})
        ax.set_xlabel("Energy")
        ax.set_ylabel("MCA counts")
        ax2=fig.add_subplot(212)
        ax2.grid(True)
        ax2.set_xlabel("Energy")
        ax2.set_ylabel("")
        handles = []
        handles.append(ax2.plot(chooch_graph_x, chooch_graph_y1, color='blue'))
        handles.append(ax2.plot(chooch_graph_x, chooch_graph_y2, color='red'))
        canvas=FigureCanvasAgg(fig)

        escan_png = filenameOut[:-3] + 'png' #.replace('.esf', '.png') #os.path.extsep.join((scanFilePrefix, "png"))
        escan_archivepng = filenameOut[:-4] + '_archive.png'  #os.path.extsep.join((scanArchiveFilePrefix, "png")) 
        self.scanInfo["jpegChoochFileFullPath"]=str(escan_archivepng)
        try:
            logging.getLogger("HWR").info("Rendering energy scan and Chooch graphs to PNG file : %s", escan_png)
            canvas.print_figure(escan_png, dpi=80)
        except:
            logging.getLogger("HWR").exception("could not print figure")
        try:
            logging.getLogger("HWR").info("Saving energy scan to archive directory for ISPyB : %s", escan_archivepng)
            canvas.print_figure(escan_archivepng, dpi=80)
        except:
            logging.getLogger("HWR").exception("could not save figure")

        self.storeEnergyScan()
        self.scanInfo=None

        logging.getLogger("HWR").info("<chooch> returning" )
        return pk, fppPeak, fpPeak, ip, fppInfl, fpInfl, rm, chooch_graph_x, chooch_graph_y1, chooch_graph_y2, title
    
    def scanStatusChanged(self,status):
        logging.getLogger("HWR").debug('EnergyScan:scanStatusChanged')
        self.emit('scanStatusChanged', (status,))
        
    def storeEnergyScan(self):
        logging.getLogger("HWR").debug('EnergyScan:storeEnergyScan')
        #if self.dbConnection is None:
            #return
        #try:
            #session_id=int(self.scanInfo['sessionId'])
        #except:
            #return
        return
        
    def updateEnergyScan(self, scan_id, jpeg_scan_filename):
        logging.getLogger("HWR").debug('EnergyScan:updateEnergyScan')

    # Elements commands
    def getElements(self):
        logging.getLogger("HWR").debug('EnergyScan:getElements')
        elements=[]
        try:
            for el in self["elements"]:
                elements.append({"symbol":el.symbol, "energy":el.energy})
        except IndexError:
            pass
        return elements

    # Mad energies commands
    def getDefaultMadEnergies(self):
        logging.getLogger("HWR").debug('EnergyScan:getDefaultMadEnergies')
        energies=[]
        try:
            for el in self["mad"]:
                energies.append([float(el.energy), el.directory])
        except IndexError:
            pass
        return energies
        
    def getFilename(self, directory, filename, element, edge):
        filenameIn = os.path.join(directory, filename)
        filenameIn += "_" + element + "_" + "_".join(edge) + ".dat"
        return filenameIn
    
    def doEnergyScan(self, element, edge, directory, filename):
        logging.getLogger("HWR").info('EnergyScan: Element:%s Edge:%s' %(element,edge))    	

        e_edge, roi_center = self.getEdgefromXabs(element, edge)
        self.thEdge = e_edge
        self.element = element
        self.edge = edge
        
        print('e_edge = %5.4f , roi_center = %5.4f' %(e_edge, roi_center)) 
        
        filenameIn = self.getFilename(directory, filename, element, edge) # filenameIn
        self.filenameIn = filenameIn
        
        # Demarrage du thread de scan
        self.scanCommandStarted()
        self.pk = None
        self.ip = None
        self.scanThread = EnergyScanThread(self,
                                           e_edge,
                                           roi_center,
                                           filenameIn)
        self.scanThread.start()

    def getEdgefromXabs(self, el, edge):
        edge = string.upper(edge)
        roi_center = McMaster[el]['edgeEnergies'][edge + '-alpha']
        if edge == 'L':
            edge = 'L3'
        e_edge = McMaster[el]['edgeEnergies'][edge]
        return (e_edge, roi_center)    
        
    def newPoint(self, x, y):
        logging.getLogger("HWR").debug('EnergyScan:newPoint')
        print('newPoint', x, y)
        self.emit('addNewPoint', (x, y))
    
    def newScan(self,scanParameters):
        logging.getLogger("HWR").debug('EnergyScan:newScan')
        self.emit('newScan', (scanParameters,))
        
    def startMoveEnergy(self, value):   # Copie du code ecrit dans BLEnergy.py pour gestion du backlash onduleur.
   
        # MODIFICATION DE CETTE FONCTION POUR COMPENSER LE PROBLEME D'HYSTERESIS DE L"ONDULEUR
        # PAR CETTE METHODE ON APPLIQUE TOUJOURS UN GAP CROISSANT
        backlash = 0.1 # en mmte
        gaplimite = 5.5  # en mm
        self.doBacklashCompensation = False # True #MS 2013-05-21
#        self.mono_mt_rx_device.On()
        #time.sleep(5)
        
        if (str(self.BLEnergydevice.State()) != "MOVING") :# MS .State -> .State() 06.03.2013
            if self.doBacklashCompensation :
                try : 
                    # Recuperation de la valeur de gap correspondant a l'energie souhaitee
                    self.U20Energydevice.autoApplyComputedParameters = False
                    self.U20Energydevice.energy = value
                    newgap = self.U20Energydevice.computedGap
                    actualgap = self.U20Energydevice.gap

                    self.U20Energydevice.autoApplyComputedParameters = True
                
                    # On applique le backlash que si on doit descendre en gap	    
                    if newgap < actualgap + backlash:
                        # Envoi a un gap juste en dessous (backlash)    
                        if newgap-backlash > gaplimite :
                            self.U20Energydevice.gap = newgap - backlash
                        else :
                            self.U20Energydevice.gap = gaplimite
                            self.U20Energydevice.gap = newgap + backlash
                        time.sleep(1)
                except :           
                    logging.getLogger("HWR").error("%s: Cannot move undulator U20 : State device = %s", self.name(), self.U20Energydevice.State())

            try :
                # Envoi a l'energie desiree    
                self.BLEnergydevice.energy = value
            except :           
                logging.getLogger("HWR").error("%s: Cannot move BLEnergy : State device = %s", self.name(), self.BLEnergydevice.State())
        
        else : 
            statusBLEnergydevice = self.BLEnergydevice.Status()
            logging.getLogger("HWR").error("%s: Cannot move : State device = %s", self.name(), self.BLEnergydevice.State())

            for i in statusBLEnergydevice.split("\n") :
                logging.getLogger().error("\t%s\n" % i)
            logging.getLogger().error("\tCheck devices")
                # Envoi a l'energie desiree    
#        self.BLEnergydevice.energy = value
    def getChoochValue(self, pk, ip) :
        logging.getLogger("HWR").debug('EnergyScan:getChoochValue')
        self.pk = pk
        self.ip = ip
コード例 #34
0
    def init(self, config, collect_obj):
        self.config = config
        self.collect_obj = collect_obj
        self.header = dict()

        lima_device = config.getProperty("lima_device")
        pilatus_device = config.getProperty("pilatus_device")
        if None in (lima_device, pilatus_device):
            return

        for channel_name in ("acq_status", "acq_trigger_mode", "saving_mode",
                             "acq_nb_frames", "acq_expo_time",
                             "saving_directory", "saving_prefix",
                             "saving_suffix", "saving_next_number",
                             "saving_index_format", "saving_format",
                             "saving_overwrite_policy",
                             "saving_header_delimiter", "last_image_saved"):
            self.addChannel(
                {
                    "type": "tango",
                    "name": channel_name,
                    "tangoname": lima_device
                }, channel_name)

        for channel_name in ("fill_mode", "threshold"):
            self.addChannel(
                {
                    "type": "tango",
                    "name": channel_name,
                    "tangoname": pilatus_device
                }, channel_name)

        pilatus_tg_device = DeviceProxy(pilatus_device)
        if hasattr(pilatus_tg_device, "working_energy"):
            self.addChannel(
                {
                    "type": "tango",
                    "name": "energy_threshold",
                    "tangoname": pilatus_device
                }, "working_energy")
        else:
            self.addChannel(
                {
                    "type": "tango",
                    "name": "energy_threshold",
                    "tangoname": pilatus_device
                }, "energy_threshold")

        self.addCommand(
            {
                "type": "tango",
                "name": "prepare_acq",
                "tangoname": lima_device
            }, "prepareAcq")
        self.addCommand(
            {
                "type": "tango",
                "name": "start_acq",
                "tangoname": lima_device
            }, "startAcq")
        self.addCommand(
            {
                "type": "tango",
                "name": "stop_acq",
                "tangoname": lima_device
            }, "stopAcq")
        self.addCommand(
            {
                "type": "tango",
                "name": "reset",
                "tangoname": lima_device
            }, "reset")
        self.addCommand(
            {
                "type": "tango",
                "name": "set_image_header",
                "tangoname": lima_device
            }, "SetImageHeader")
コード例 #35
0
class TangoChannel(ChannelObject):
    _tangoEventsQueue = Queue()
    _eventReceivers = {}
    _tangoEventsProcessingTimer = gevent.get_hub().loop.async_()

    # start Tango events processing timer
    _tangoEventsProcessingTimer.start(processTangoEvents)

    def __init__(self,
                 name,
                 attribute_name,
                 tangoname=None,
                 username=None,
                 polling=None,
                 timeout=10000,
                 **kwargs):
        ChannelObject.__init__(self, name, username, **kwargs)

        self.attributeName = attribute_name
        self.deviceName = tangoname
        self.device = None
        self.value = Poller.NotInitializedValue
        self.polling = polling
        self.pollingTimer = None
        self.pollingEvents = False
        self.timeout = int(timeout)
        self.read_as_str = kwargs.get("read_as_str", False)
        self._device_initialized = Event()
        logging.getLogger("HWR").debug(
            "creating Tango attribute %s/%s, polling=%s, timeout=%d",
            self.deviceName,
            self.attributeName,
            polling,
            self.timeout,
        )
        self.init_device()
        self.continue_init(None)
        """
        self.init_poller = Poller.poll(self.init_device,
                                       polling_period = 3000,
                                       value_changed_callback = self.continue_init,
                                       error_callback = self.init_poll_failed,
                                       start_delay=100)
        """

    def init_poll_failed(self, e, poller_id):
        self._device_initialized.clear()
        logging.warning(
            "%s/%s (%s): could not complete init. (hint: device server is not running, or has to be restarted)",
            self.deviceName,
            self.attributeName,
            self.name(),
        )
        self.init_poller = self.init_poller.restart(3000)

    def continue_init(self, _):
        # self.init_poller.stop()

        if isinstance(self.polling, int):
            self.raw_device = RawDeviceProxy(self.deviceName)
            Poller.poll(
                self.poll,
                polling_period=self.polling,
                value_changed_callback=self.update,
                error_callback=self.pollFailed,
            )
        else:
            if self.polling == "events":
                # try to register event
                try:
                    self.pollingEvents = True
                    # logging.getLogger("HWR").debug("subscribing to CHANGE event for %s", self.attributeName)
                    self.device.subscribe_event(
                        self.attributeName,
                        PyTango.EventType.CHANGE_EVENT,
                        self,
                        [],
                        True,
                    )
                    # except PyTango.EventSystemFailed:
                    #   pass
                except Exception:
                    logging.getLogger("HWR").exception(
                        "could not subscribe event")
        self._device_initialized.set()

    def init_device(self):
        try:
            self.device = DeviceProxy(self.deviceName)
        except PyTango.DevFailed as traceback:
            self.imported = False
            last_error = traceback[-1]
            logging.getLogger("HWR").error("%s: %s", str(self.name()),
                                           last_error["desc"])
        else:
            self.imported = True
            try:
                self.device.ping()
            except PyTango.ConnectionFailed:
                self.device = None
                raise ConnectionError
            else:
                self.device.set_timeout_millis(self.timeout)

                # check that the attribute exists (to avoid Abort in PyTango grrr)
                if not self.attributeName.lower() in [
                        attr.name.lower()
                        for attr in self.device.attribute_list_query()
                ]:
                    logging.getLogger("HWR").error(
                        "no attribute %s in Tango device %s",
                        self.attributeName,
                        self.deviceName,
                    )
                    self.device = None

    def push_event(self, event):
        # logging.getLogger("HWR").debug("%s | attr_value=%s, event.errors=%s, quality=%s", self.name(), event.attr_value, event.errors,event.attr_value is None and "N/A" or event.attr_value.quality)
        if (event.attr_value is None or event.err
                or event.attr_value.quality != PyTango.AttrQuality.ATTR_VALID):
            # logging.getLogger("HWR").debug("%s, receving BAD event... attr_value=%s, event.errors=%s, quality=%s", self.name(), event.attr_value, event.errors, event.attr_value is None and "N/A" or event.attr_value.quality)
            return
        else:
            pass
            # logging.getLogger("HWR").debug("%s, receiving good event", self.name())
        ev = E(event)
        TangoChannel._eventReceivers[id(ev)] = saferef.safe_ref(self.update)
        TangoChannel._tangoEventsQueue.put(ev)
        TangoChannel._tangoEventsProcessingTimer.send()

    def poll(self):
        if self.read_as_str:
            value = self.raw_device.read_attribute(
                self.attributeName,
                PyTango.DeviceAttribute.ExtractAs.String).value
            # value = self.device.read_attribute_as_str(self.attributeName).value
        else:
            value = self.raw_device.read_attribute(self.attributeName).value
        self.emit("update", value)
        return value

    def pollFailed(self, e, poller_id):
        self.emit("update", None)
        """
        emit_update = True
        if self.value is None:
          emit_update = False
        else:
          self.value = None

        try:
            self.init_device()
        except:
            pass

        poller = Poller.get_poller(poller_id)
        if poller is not None:
            poller.restart(1000)

        try:
          raise e
        except:
          logging.exception("%s: Exception happened while polling %s", self.name(), self.attributeName)

        if emit_update:
          # emit at the end => can raise exceptions in callbacks
          self.emit('update', None)
        """

    def getInfo(self):
        self._device_initialized.wait(timeout=3)
        return self.device.get_attribute_config(self.attributeName)

    def update(self, value=Poller.NotInitializedValue):
        if value == Poller.NotInitializedValue:
            value = self.getValue()
        if isinstance(value, types.TupleType):
            value = list(value)

        self.value = value
        self.emit("update", value)

    def getValue(self):
        self._device_initialized.wait(timeout=3)

        if self.read_as_str:
            value = self.device.read_attribute(
                self.attributeName,
                PyTango.DeviceAttribute.ExtractAs.String).value
        else:
            value = self.device.read_attribute(self.attributeName).value

        return value

    def setValue(self, newValue):
        self.device.write_attribute(self.attributeName, newValue)
        # attr = PyTango.AttributeProxy(self.deviceName + "/" + self.attributeName)
        # a = attr.read()
        # a.value = newValue
        # attr.write(a)

    def isConnected(self):
        return self.device is not None
コード例 #36
0
from flask import Flask, request, session, g, redirect, url_for, abort, \
     render_template, flash
import click
from PyTango import DeviceProxy
from PyTango import EventType
from datetime import datetime


def callback(event):
    print("callback called:" + str(datetime.now()))
    if (event.err != "False"):
        print(event.attr_value.value)


app = Flask(__name__)  # create the application instance :)
app.config.from_envvar('FLASKR_SETTINGS', silent=True)
tango_test = DeviceProxy("sys/tg_test/1")
event_id = tango_test.subscribe_event("Status", EventType.CHANGE_EVENT,
                                      callback, [], True)


@app.route('/')
def getRoot():
    print("in getRoot ")
    return "hello world"
コード例 #37
0
class AttenuatorsPX2(Device):
    stateAttenuator = {
        'ALARM': 0,
        'EXTRACT': 1,
        'INSERT': 1,
        'UNKNOWN': 3,
        'ALARM': 'error',
        'OFF': 'error',
        'RUNNING': 'moving',
        'MOVING': 'moving',
        'STANDBY': 'ready',
        'UNKNOWN': 'changed',
        'EXTRACT': 'outlimits'
    }

    def __init__(self, name):
        Device.__init__(self, name)

        self.labels = []
        self.bits = []
        self.attno = 0
        self.deviceOk = True
        self.NumToLabel = {}

    def init(self):
        #cmdToggle = self.getCommandObject('toggle')
        #cmdToggle.connectSignal('connected', self.connected)
        #cmdToggle.connectSignal('disconnected', self.disconnected)

        # Connect to device Attenuator defined "tangoname" in the xml file
        try:
            #self.Attenuatordevice = SimpleDevice(self.getProperty("tangoname"), verbose=False)
            self.Attenuatordevice = DeviceProxy(self.getProperty("tangoname"))
            self.Attenuatordevice.waitMoves = False
            self.Attenuatordevice.timeout = 5000

        except:
            self.errorDeviceInstance(self.getProperty("tangoname"))

        if self.deviceOk:
            #self.connected()
            #self.chanAttState = self.getChannelObject('State')
            #print "self.chanAttState : ", self.chanAttState
            #self.chanAttState.connectSignal('update', self.attStateChanged)
            ##self.chanAttFactor = self.getChannelObject('appliedTransmission')
            ##self.chanAttFactor = self.getChannelObject('computedTransmission')
            ##self.chanAttFactor.connectSignal('update', self.attFactorChanged)

            ##self.chanAttToggle = self.getChannelObject('filtersCombination')
            ##self.chanAttToggle.connectSignal('update', self.attToggleChanged)

            #self.getAtteConfig()

            self.connected()
            self.chanAttState = self.getChannelObject('State')
            print("self.chanAttState : ", self.chanAttState)
            self.chanAttState.connectSignal('update', self.attStateChanged)
            #self.chanAttFactor = self.getChannelObject('appliedTransmission')

            self.chanAttFactor = self.getChannelObject('Status')
            self.chanAttFactor.connectSignal('update', self.attFactorChanged)

            self.chanAttToggle = self.getChannelObject('State')
            self.chanAttToggle.connectSignal('update', self.attToggleChanged)

            self.getAtteConfig()

        logging.getLogger().debug(
            "AttenuatorsPX2: self.labels, self.bits, self.attno, %s, %s, %s" %
            (self.labels, self.bits, self.attno))

    def getAtteConfig(self):
        pass

    def getAtteConfig_OLD(self):
        logging.getLogger().debug("HOS Attenuator: passe dans getAtteConfig")
        self.attno = len(self['atte'])

        for att_i in range(self.attno):
            obj = self['atte'][att_i]
            self.labels.append(obj.label)
            self.bits.append(obj.bits)
        self.NumToLabel = dict([(int(l.split()[0]), l) for l in self.labels])

    def getAttState(self):
        logging.getLogger().debug("HOS Attenuator: passe dans getAttState")
        logging.getLogger().debug("Attenuator state read from the device %s",
                                  self.Attenuatordevice.State().name)
        try:
            #print "HEYO", self.Attenuatordevice.StatefiltersCombination
            print(self.Attenuatordevice.Status())
            value = AttenuatorsPX2.stateAttenuator[
                self.Attenuatordevice.State().name]
        except:
            logging.getLogger("HWR").error(
                '%s: received value on channel is not a integer value',
                str(self.name()))
            value = None
        return value

    def getAttFactor(self):
        logging.getLogger().debug("HOS Attenuator: passe dans getAttFactor")
        print('self.Attenuatordevice.Status()', self.Attenuatordevice.Status())
        try:
            #value = float(self.Attenuatordevice.appliedTransmission)
            status = self.Attenuatordevice.Status()
            status = status[:status.index(':')]
            print('status', status)
            value = status  #self.Attenuatordevice.Status() #1. #float(self.Attenuatordevice.computedTransmission)
        except:
            logging.getLogger("HWR").error(
                '%s: received value on channel is not a float value',
                str(self.name()))
            value = None
        return value

    def connected(self):
        self.setIsReady(True)

    def disconnected(self):
        self.setIsReady(False)

    def attStateChanged(self, channelValue):
        logging.getLogger("HWR").debug(
            "%s: AttenuatorsPX2.attStateChanged: %s", self.name(),
            channelValue)
        self.emit('attStateChanged',
                  (AttenuatorsPX2.stateAttenuator[str(channelValue)], ))

    def attFactorChanged(self, channelValue):
        print('attFactorChanged', channelValue)
        print('self.Attenuatordevice.Status()', self.Attenuatordevice.Status())
        try:
            status = self.Attenuatordevice.Status()
            status = status[:status.index(':')]
            print('status', status)
            value = status
            #value = float(channelValue)
        except:
            logging.getLogger("HWR").error(
                '%s: received value on channel is not a float value',
                str(self.name()))
        else:
            logging.getLogger("HWR").info(
                '%s: AttenuatorsPX2, received value on channel',
                str(self.name()))
            self.emit('attFactorChanged', (value, ))

    def attToggleChanged(self, channelValue):
        #        print "Dans attToggleChanged  channelValue = %s" %channelValue
        logging.getLogger().debug(
            "HOS Attenuator: passe dans attToggleChanged")
        try:
            value = int(channelValue)
        except:
            logging.getLogger("HWR").error(
                '%s: received value on channel is not a float value',
                str(self.name()))
        else:
            self.emit('toggleFilter', (value, ))

    def setTransmission(self, value):
        logging.getLogger("HWR").debug(
            "%s: AttenuatorsPX2.setTransmission: %s", self.name(), value)
        print(value)
        self.Attenuatordevice.write_attribute(
            self.NumToLabel[value],
            True)  #.computedAttenuation = 1.0/(value/100.0)
        #try:
        #self.Attenuatordevice.write_attribute(value, True) #.computedAttenuation = 1.0/(value/100.0)
        #except:
        #logging.getLogger("HWR").error('%s: received value on channel is not valid', str(self.name()))
        #value=None
        return value

    def toggle(self, value):
        print("Toggle value = %s" % value)
        logging.getLogger().debug("HOS Attenuator: passe dans toggle")
        self.Attenuatordevice.write_attribute(value, True)

        #        old_value = self.Attenuatordevice.filtersCombination
        #        try:
        #            self.Attenuatordevice.filtersCombination = old_value "sys/database/dbds1")+ (2**(value-1))
        #        except:
        #            logging.getLogger("HWR").error('%s: the filter doesn\'t exist', str(self.name()))
        #            value=None
        return value

    def errorDeviceInstance(self, device):
        #db = SimpleDevice("sys/database/dbds1")
        db = DeviceProxy("sys/database/dbds1")
        logging.getLogger().error("Check Instance of Device server %s" %
                                  db.DbGetDeviceInfo(device)[1][3])
        self.sDisconnected()
コード例 #38
0
class Agilent4UHV(Dev4Tango):
    def __init__(self, cl, name):
        self.call__init__(Dev4Tango, cl, name)
        self.lg = fandango.Logger('test')
        self.init_device()

    def delete_device(self):
        try:
            self.thread.stop()
        except:
            traceback.print_exc()

    def init_device(self):
        self.lg.info("init_device()")
        self.get_device_properties(self.get_device_class())
        self.info('LogLevel = %s' % self.getLogLevel())
        self.set_state(DevState.ON)
        self.last_comm = 0
        self.exception = ''
        self.serial = DeviceProxy(self.SerialLine)
        self.thread = ThreadDict(
            read_method=self.send_command,
            write_method=self.send_command,
            timewait=self.TimeWait,
        )

        self.dyn_attr()
        self.thread.start()
        self.info("Ready to accept request ...")
        self.info('-' * 80)

    @catched
    def dyn_attr(self):
        self.dyn_attrs = getattr(self, 'dyn_attrs', [])
        self.info('dyn_attr(%s)' % self.dyn_attrs)
        for l, n in product('VPI', '1234'):

            if l + n not in self.dyn_attrs:
                self.info('Adding attribute: %s' % (l + n))
                unit, frmt = {
                    'V': ('V', '%d'),
                    'P': ('mbar', '%g'),
                    'I': ('mA', '%g')
                }[l]
                attrib = PyTango.Attr(l + n, PyTango.DevDouble,
                                      PyTango.AttrWriteType.READ)
                props = PyTango.UserDefaultAttrProp()
                props.set_format(frmt), props.set_unit(unit)
                attrib.set_default_properties(props)
                self.add_attribute(attrib, self.read_dyn_attr, None,
                                   self.is_Attr_allowed)

            self.thread.append(l + n, period=self.Refresh)

        for a in ('Model', 'ErrorCode', 'ModeLocal'):
            self.info('Adding attribute (%d s): %s' % (self.Refresh * 5, a))
            attrib = PyTango.Attr(a, PyTango.DevString,
                                  PyTango.AttrWriteType.READ)
            self.add_attribute(attrib, self.read_dyn_attr, None,
                               self.is_Attr_allowed)
            self.thread.append(a, period=self.Refresh * 5)

    def always_executed_hook(self):
        self.state_machine()

    #############################################################################

    #@catched
    def send_command(self, comm, value=None, throw=False):
        r, s = '', ''
        try:
            data = WP.pack_window_message(comm, value)
            (self.info if throw else self.debug)('send_command(%s,%s) => %s' %
                                                 (comm, value, data))
            [self.serial.DevSerWriteChar([t]) for t in data]
            wait(self.TimeWait)
            r = self.serial.DevSerReadRaw()
            assert r, 'NothingReceived!'
            self.last_comm = now()
            self.exception = ''
        except Exception, e:
            self.error('send_command(%s):\n %s' %
                       (comm, traceback.format_exc()))
            self.exception = str(e)
            if throw:
                raise e
                #PyTango.Except.throw_exception("Agilent4UHV Exception",str(e),str(e))
            return r

        try:
            s = WP.unpack_window_message(r).data
            s = ''.join(s) if isSequence(map(str, s)) else str(s)
        except Exception, e:
            traceback.print_exc()
            raise e
コード例 #39
0
 def _createHWObject(self):
     try:
         return DeviceProxy(self.getFullName())
     except DevFailed as e:
         self.warning('Could not create HW object: %s' % (e.args[0].desc))
         self.traceback()
コード例 #40
0
ファイル: client.py プロジェクト: cpascual/PyTango
class _DeviceHelper(object):

    __CMD_FILTER = set(("init", "state", "status"))
    __ATTR_FILTER = set(("state", "status"))

    def __init__(self, dev_name, *args, **kwargs):
        self.dev_name = dev_name
        self.device = Device(dev_name, *args, **kwargs)
        self.slots = weakref.WeakKeyDictionary()

    def connect(self, signal, slot, event_type=PyTango.EventType.CHANGE_EVENT):
        i = self.device.subscribe_event(signal, event_type, slot)
        self.slots[slot] = i
        return i

    def disconnect(self, signal, slot):
        i = self.slots.pop(slot)
        self.device.unsubscribe_event(i)

    def get_attr_cache(self, refresh=False):
        try:
            cache = self.__attr_cache
            if not cache:
                refresh = True
        except AttributeError:
            refresh = True
        if refresh:
            cache = {}
            dev = self.device
            try:
                for attr_info in dev.attribute_list_query_ex():
                    attr_name = attr_info.name
                    if attr_name.lower() in self.__ATTR_FILTER:
                        continue
                    cache[attr_name] = attr_info
            except PyTango.DevFailed:
                pass
            self.__attr_cache = cache
        return cache

    def get_attr_info(self, name):
        cache = self.get_attr_cache()
        result = cache.get(name)
        if result:
            return result
        else:
            cache = self.get_attr_cache(refresh=True)
            return cache.get(name)

    def get_cmd_cache(self, refresh=False):
        try:
            cache = self.__cmd_cache
            if not cache:
                refresh = True
        except AttributeError:
            refresh = True
        if refresh:
            cache = {}
            dev = self.device
            try:
                for cmd_info in dev.command_list_query():
                    cmd_name = cmd_info.cmd_name
                    if cmd_name.lower() in self.__CMD_FILTER:
                        continue
                    cmd_func = functools.partial(_command, dev, cmd_info)
                    cmd_func.__name__ = cmd_name
                    cmd_func.__doc__ = cmd_info.in_type_desc
                    cmd_info.func = cmd_func
                    cache[cmd_name] = cmd_info
            except PyTango.DevFailed:
                pass
            self.__cmd_cache = cache
        return cache

    def get_cmd_info(self, name):
        cache = self.get_cmd_cache()
        result = cache.get(name)
        if result:
            return result
        else:
            cache = self.get_cmd_cache(refresh=True)
            return cache.get(name)

    def is_cmd(self, name):
        return name.lower() in self.get_cmd_cache()

    def members(self):
        result = self.get_attr_cache().keys()
        result.extend(self.get_cmd_cache().keys())
        return result

    def get(self, name):
        dev = self.device
        result = self.get_attr_info(name)
        if result:
            result = dev.read_attribute(name)
            value = result.value
            if result.type == PyTango.DevEncoded:
                result = loads(*value)
            else:
                result = value
            return result
        result = self.get_cmd_info(name)
        if result is None:
            raise KeyError("Unknown %s" % name)
        return result

    def set(self, name, value):
        result = self.get_attr_info(name)
        if result is None:
            raise KeyError("Unknown attribute %s" % name)
        if result.data_type == PyTango.DevEncoded:
            self.device.write_attribute(name, dumps(value))
        else:
            self.device.write_attribute(name, value)

    def get_info(self):
        try:
            return self.__info
        except AttributeError:
            pass
        try:
            info = self.device.info()
            self.__dict__["__info"] = info
            return info
        except PyTango.DevFailed:
            return None

    def __str__(self):
        return self.dstr()

    def __repr__(self):
        return str(self)

    def dstr(self):
        info = self.get_info()
        klass = "Device"
        if info:
            klass = info.dev_class
        return "{0}({1})".format(klass, self.dev_name)
コード例 #41
0
def ping_to_device():
    print('server asked to ping from device')
    p = DeviceProxy("sys/tg_test/1")
    elapsed_time = p.ping()
    emit("pong from device", {'elapsed': elapsed_time})
    print('client ponged from device')
コード例 #42
0
class TangoKeithleyPhotonFlux(Equipment):
    def __init__(self, *args, **kwargs):
        Equipment.__init__(self, *args, **kwargs)

    def init(self):
        self.getObjectByRole("controller")
        self.shutter = self.getDeviceByRole("shutter")
        self.aperture = self.getObjectByRole("aperture")
        self.factor = self.getProperty("current_photons_factor")

        self.shutter.connect("shutterStateChanged", self.shutterStateChanged)

        self.tg_device = DeviceProxy(self.getProperty("tango_device"))
        self.counts_reading_task = self._read_counts_task(wait=False)

    @task
    def _read_counts_task(self):
        old_counts = None
        while True:
            counts = self._get_counts()
            if counts != old_counts:
                old_counts = counts
                self.countsUpdated(counts)
            time.sleep(1)

    def _get_counts(self):
        self.tg_device.MeasureSingle()
        counts = abs(self.tg_device.ReadData) * 1e6
        if self.aperture:
            try:
                aperture_coef = self.aperture.getApertureCoef()
            except Exception:
                aperture_coef = 1
        else:
            aperture_coef = 1

        counts *= aperture_coef
        return counts

    def connectNotify(self, signal):
        if signal == "valueChanged":
            self.emitValueChanged()

    def shutterStateChanged(self, _):
        self.countsUpdated(self._get_counts())

    def updateFlux(self, _):
        self.countsUpdated(self._get_counts(), ignore_shutter_state=True)

    def countsUpdated(self, counts, ignore_shutter_state=False):
        if not ignore_shutter_state and self.shutter.getShutterState(
        ) != "opened":
            self.emitValueChanged(0)
            return
        flux = counts * self.factor
        self.emitValueChanged("%1.3g" % flux)

    def get_value(self):
        return self.current_flux

    def emitValueChanged(self, flux=None):
        self.current_flux = flux

        if flux is None:
            self.emit("valueChanged", ("?", ))
        else:
            self.emit("valueChanged", (self.current_flux, ))
コード例 #43
0
class BLEnergy(Device):

    stateEnergy = {
        'ALARM': 'error',
        'FAULT': 'error',
        'RUNNING': 'moving',
        'MOVING': 'moving',
        'STANDBY': 'ready',
        'UNKNOWN': 'unknown',
        'EXTRACT': 'outlimits'
    }

    def init(self):

        self.moving = None
        self.deviceOk = True
        self.prev_state = None
        self.doBacklashCompensation = False

        # Channel and commands for monochormator pitch.
        #    it will be used here to make sure it is on before moving energy (PX2)
        #    not needed on PX1
        self.mono_mt_rx_statech = None
        self.mono_mt_rx_oncmd = None

        # Connect to device BLEnergy defined "tangoname" in the xml file
        try:
            self.BLEnergydevice = DeviceProxy(self.getProperty("tangoname"))
        except:
            self.errorDeviceInstance(self.getProperty("tangoname"))

        # Connect to device mono defined "tangoname2" in the xml file
        # used for conversion in wavelength
        try:
            self.monodevice = DeviceProxy(self.getProperty("tangoname2"))
        except:
            self.errorDeviceInstance(self.getProperty("tangoname2"))

        # Nom du device bivu (Energy to gap) : necessaire pour amelioration du positionnement de l'onduleur (Backlash)
        try:
            #            self.U20Energydevice = DeviceProxy(self.getProperty("tangoname3"), movingState="RUNNING")
            # Modif suite a changement par ICA de l etat du device U20 RUNNING devient MOVING
            self.U20Energydevice = DeviceProxy(self.getProperty("tangoname3"))
        except:
            self.errorDeviceInstance(self.getProperty("tangoname3"))

        self.doBacklashCompensation = self.getProperty("backlash")
        #        print self.doBacklashCompensation

        try:
            self.mono_mt_rx_statech = self.getChannelObject("mono_mt_rx_state")
            self.mono_mt_rx_oncmd = self.getCommandObject("mono_mt_rx_on")
        except KeyError:
            logging.info(
                "Beware that mt_rx control is not properly defined for BLEnergy"
            )

        # parameters for polling
        if self.deviceOk:
            self.isConnected()
            self.prev_state = str(self.BLEnergydevice.State())

            energyChan = self.getChannelObject("energy")
            energyChan.connectSignal("update", self.energyChanged)

            stateChan = self.getChannelObject(
                "state"
            )  # utile seulement si statechan n'est pas defini dans le code
            stateChan.connectSignal("update", self.stateChanged)

    def stateChanged(self, value):
        if (str(value) == 'MOVING'):
            self.moveEnergyCmdStarted()
        if self.prev_state == 'MOVING' or self.moving == True:
            if str(value) != 'MOVING':
                self.moveEnergyCmdFinished()

        self.prev_state = str(value)

        self.emit('stateChanged', BLEnergy.stateEnergy[str(value)])

    # function called during polling
    def energyChanged(self, value):
        #logging.getLogger("HWR").debug("%s: BLEnergy.energyChanged: %.3f", self.name(), value)
        wav = self.monodevice.read_attribute("lambda").value
        if wav is not None:
            self.emit('energyChanged', (value, wav))

    def connectNotify(self, signal):
        #logging.getLogger("HWR").info("%s: BLEnergy.connectNotify, : %s", self.name(), signal)
        if signal == 'energyChanged':
            self.energyChanged(self.BLEnergydevice.energy)
        if signal == 'stateChanged':
            self.stateChanged(str(self.BLEnergydevice.State()))
        self.setIsReady(True)

    # called by brick : not useful
    def isSpecConnected(self):
        logging.getLogger("HWR").debug("%s: BLEnergy.isSpecConnected",
                                       self.name())
        return True

    def isConnected(self):
        logging.getLogger("HWR").debug("%s: BLEnergy.isConnected", self.name())
        return True

    def sConnected(self):
        logging.getLogger("HWR").debug("%s: BLEnergy.sConnected", self.name())
        self.deviceOk = True
        self.emit('connected', ())

    def sDisconnected(self):
        logging.getLogger("HWR").debug("%s: BLEnergy.sDisconnected",
                                       self.name())
        self.deviceOk = False
        self.emit('disconnected', ())

    def isDisconnected(self):
        logging.getLogger("HWR").debug("%s: BLEnergy.isDisconnected",
                                       self.name())
        return True

    # Definit si la beamline est a energie fixe ou variable
    def canMoveEnergy(self):
        logging.getLogger("HWR").debug("%s: BLEnergy.canMoveEnergy",
                                       self.name())
        return True

    def getPosition(self):
        return self.getCurrentEnergy()

    def getCurrentEnergy(self):
        if self.deviceOk:
            return self.BLEnergydevice.energy
        else:
            return None

    def getState(self):
        return self.BLEnergydevice.State().name

    def getEnergyComputedFromCurrentGap(self):
        #logging.getLogger("HWR").debug("%s: BLEnergy.getCurrentEnergy", self.name())
        if self.deviceOk:
            # PL. Rq: if the device is not redy, it send a NaN...
            return self.U20Energydevice.energy
        else:
            return None

    def getCurrentUndulatorGap(self):
        logging.getLogger("HWR").debug("%s: BLEnergy.getCurrentEnergy",
                                       self.name())
        if self.deviceOk:
            return self.U20Energydevice.gap
        else:
            return None

    def getCurrentWavelength(self):
        #logging.getLogger("HWR").debug("%s: BLEnergy.getCurrentWavelength", self.name())
        # Pb with the attribute name "lamdda" which is a keyword for python
        if self.deviceOk:
            # using calculation of the device mono
            return self.monodevice.read_attribute("lambda").value
        else:
            return None

    def getEnergyLimits(self):
        logging.getLogger("HWR").debug("%s: BLEnergy.getEnergyLimits",
                                       self.name())
        if self.deviceOk:
            # limits defined in tango
            enconfig = self.BLEnergydevice.get_attribute_config("energy")
            max = float(enconfig.max_value)
            min = float(enconfig.min_value)
            lims = (min, max)

            logging.getLogger("HWR").info("HOS : energy Limits: %.4f %.4f" %
                                          lims)
            return lims
        else:
            return None

    def getWavelengthLimits(self):
        logging.getLogger("HWR").debug("%s: BLEnergy.getWavelengthLimits",
                                       self.name())
        if self.deviceOk:
            lims = []
            # Recuperation des limites en energie
            energylims = self.getEnergyLimits()
            # Conversion de la limite inferieure en wavelength superieure (Utilisation des fonctions de conversion du device mono)
            self.monodevice.simEnergy = energylims[1]
            lims.append(self.monodevice.simLambda)
            # Conversion de la limite superieure en wavelength inferieure (Utilisation des fonctions de conversion du device mono)
            self.monodevice.simEnergy = energylims[0]
            lims.append(self.monodevice.simLambda)
            #        logging.getLogger("HWR").info("HOS : wavelength Limits: %.4f %.4f" % lims)
            logging.getLogger("HWR").info("HOS : wavelength Limits: %s" % lims)
            return lims
        else:
            return None

    def startMoveEnergy(self, value, wait=False):
        logging.getLogger("HWR").debug("%s: BLEnergy.startMoveEnergy: %.3f",
                                       self.name(), float(value))

        # MODIFICATION DE CETTE FONCTION POUR COMPENSER LE PROBLEME D'HYSTERESIS DE L"ONDULEUR
        # PAR CETTE METHODE ON APPLIQUE TOUJOURS UN GAP CROISSANT
        backlash = 0.1  # en mm
        gaplimite = 5.5  # en mm

        if self.mono_mt_rx_statech is not None and self.mono_mt_rx_oncmd is not None:
            while str(self.mono_mt_rx_statech.getValue()) == 'OFF':
                logging.getLogger("HWR").info(
                    "BLEnergy : turning mono1-mt_rx on")
                self.mono_mt_rx_oncmd()
                time.sleep(0.2)

        if (str(self.BLEnergydevice.State()) != "MOVING" and self.deviceOk):
            if self.doBacklashCompensation:
                try:
                    # Recuperation de la valeur de gap correspondant a l'energie souhaitee
                    self.U20Energydevice.autoApplyComputedParameters = False
                    self.U20Energydevice.energy = value
                    newgap = self.U20Energydevice.computedGap
                    actualgap = self.U20Energydevice.gap

                    self.U20Energydevice.autoApplyComputedParameters = True

                    # On applique le backlash que si on doit descendre en gap
                    if newgap < actualgap + backlash:
                        # Envoi a un gap juste en dessous (backlash)
                        if newgap - backlash > gaplimite:
                            self.U20Energydevice.gap = newgap - backlash
                        else:
                            self.U20Energydevice.gap = gaplimite
                            self.U20Energydevice.gap = newgap + backlash
                        time.sleep(1)
                except:
                    logging.getLogger("HWR").error(
                        "%s: Cannot move undulator U20 : State device = %s",
                        self.name(), str(self.U20Energydevice.State()))

            try:
                # Envoi a l'energie desiree
                self.BLEnergydevice.energy = value
            except:
                logging.getLogger("HWR").error(
                    "%s: Cannot move BLEnergy : State device = %s",
                    self.name(), str(self.BLEnergydevice.State()))

        else:
            statusBLEnergydevice = self.BLEnergydevice.Status()
            logging.getLogger("HWR").error(
                "%s: Cannot move : State device = %s", self.name(),
                str(self.BLEnergydevice.State()))

            for i in statusBLEnergydevice.split("\n"):
                logging.getLogger().error("\t%s\n" % i)
            logging.getLogger().error("\tCheck devices")

    def startMoveWavelength(self, value, wait=False):
        logging.getLogger("HWR").debug(
            "%s: BLEnergy.startMoveWavelength: %.3f", self.name(), value)
        self.monodevice.simLambda = value
        self.startMoveEnergy(self.monodevice.simEnergy)


#        return self.startMoveEnergy(energy_val)

    def cancelMoveEnergy(self):
        logging.getLogger("HWR").debug("%s: BLEnergy.cancelMoveEnergy",
                                       self.name())
        self.BLEnergydevice.Stop()
        self.moving = False

    def energyLimitsChanged(self, limits):
        logging.getLogger("HWR").debug(
            "%s: BLEnergy.energyLimitsChanged: %.3f", self.name(), value)
        self.monodevice.simEnergy = limits[0]
        wav_limits.append[self.monodevice.simLambda]
        self.monodevice.simEnergy = limits[1]
        wav_limits.append[self.monodevice.simLambda]
        self.emit('energyLimitsChanged', (limits, ))
        if wav_limits[0] != None and wav_limits[1] != None:
            self.emit('wavelengthLimitsChanged', (wav_limits, ))
        else:
            self.emit('wavelengthLimitsChanged', (None, ))

    def moveEnergyCmdReady(self):
        logging.getLogger("HWR").debug("%s: BLEnergy.moveEnergyCmdReady",
                                       self.name())
        if not self.moving:
            self.emit('moveEnergyReady', (True, ))

    def moveEnergyCmdNotReady(self):
        logging.getLogger("HWR").debug("%s: BLEnergy.moveEnergyCmdNotReady",
                                       self.name())
        if not self.moving:
            self.emit('moveEnergyReady', (False, ))

    def moveEnergyCmdStarted(self):
        logging.getLogger("HWR").debug("%s: BLEnergy.moveEnergyCmdStarted",
                                       self.name())
        self.moving = True
        #self.emit('moveEnergyStarted',(BLEnergy.stateEnergy[str(self.BLEnergydevice.State())]))
        self.emit('moveEnergyStarted', ())

    def moveEnergyCmdFailed(self):
        logging.getLogger("HWR").debug("%s: BLEnergy.moveEnergyCmdFailed",
                                       self.name())
        self.moving = False
        self.emit('moveEnergyFailed', ())

    def moveEnergyCmdAborted(self):
        self.moving = False
        logging.getLogger("HWR").debug("%s: BLEnergy.moveEnergyCmdAborted",
                                       self.name())

    def moveEnergyCmdFinished(self):
        logging.getLogger("HWR").debug("%s: BLEnergy.moveEnergyCmdFinished",
                                       self.name())
        self.moving = False
        print('moveEnergyFinished')
        #self.emit('moveEnergyFinished',(BLEnergy.stateEnergy[str(self.BLEnergydevice.State())]))
        self.emit('moveEnergyFinished', ())

    def getPreviousResolution(self):
        logging.getLogger("HWR").debug("%s: BLEnergy.getPreviousResolution",
                                       self.name())
        return (None, None)

    def restoreResolution(self):
        logging.getLogger("HWR").debug("%s: BLEnergy.restoreResolution",
                                       self.name())
        return (False, "Resolution motor not defined")

    def errorDeviceInstance(self, device):
        logging.getLogger("HWR").debug("%s: BLEnergy.errorDeviceInstance: %s",
                                       self.name(), device)
        db = DeviceProxy("sys/database/dbds1")
        logging.getLogger().error("Check Instance of Device server %s" %
                                  db.DbGetDeviceInfo(device)[1][3])
        self.sDisconnected()
コード例 #44
0
ファイル: devices.py プロジェクト: lorcat/Raman-Revolver
class TangoDevice(object):
    """
    Wrapper for basic Tango device.
    It provides registering device, halting device and executing commands
    """
    POLL_STATE_TIME = 0.5
    TEST_MODE = False

    def __init__(self, devicePath=None):
        """
        Class constructor
        @type devicePath: String
        """
        self.devicePath = devicePath
        self.maxValue = False
        self.minValue = False
        self.name = "Generic device"
        self.output = {}
        self.profiling = False
        self.deviceError = False
        self.defaultClass = self.__class__

        # state change marker
        self._bstate_changed = False
        self.old_state = None

        self.__thread = None

        try:
            self.__device_init()
        except:
            logging.error(
                str("Device %s could not be connected" % self.devicePath))
            self.name = self.devicePath
            if config.DEVICE_ALLOW_RETRY:
                self._retry_device()
                #raise Exception(str("Device %s could not be connected" % self.devicePath))
                # logging.error(str("Device %s could not be connected" % self.devicePath))
                #else:

                #raise Exception(str("Device %s could not be connected" % self.devicePath))

    def __postInit__(self):
        pass

    def __device_init(self):
        self.device = DeviceProxy(self.devicePath)
        info = self.device.import_info()
        self.name = info.name

        if (self.name in DEVICE_NAMES):
            self.name = DEVICE_NAMES[self.name]

        self.deviceError = False
        self.__postInit__()

    def _retry_device(self, callback=None):
        self.deviceError = True
        thread = Thread(target=self.__retry_routine, args=([callback]))
        threads.add_thread(thread)
        thread.start()
        self.__class__ = DummyDevice

    def __retry_routine(self, callback):
        retrySleep = [True]
        while (retrySleep[0] and threads.THREAD_KEEP_ALIVE):
            try:
                DeviceProxy(self.devicePath).state()
                logging.error("Device online: %s" % (self.devicePath))
                retrySleep = [False]
            except:
                logging.error("Device offline, retrying: %s" %
                              (self.devicePath))
            threads.thread_sleep(config.DEVICE_RETRY_INTERVAL,
                                 sleepFlags=retrySleep)
        if threads.THREAD_KEEP_ALIVE == True:
            self.__class__ = self.defaultClass
            self.__device_init()
            if callback: callback()
        return True

    def isDeviceError(self):
        return self.deviceError

    def halt(self, callBack=None):
        """
        Stop device
        """
        pass

    def running_remove(self, *args):
        """
        Remove device from all running devices set
        """
        try:
            if (not stopDevices):
                runningDevices.remove(self)
        except:
            pass

    def running_add(self):
        """
        Add device to all runing devices set
        """
        global runningDevices
        runningDevices.add(self)

    def is_connected(self):
        """
        Return true if device is connected
        @rtype: bool
        """
        if self.device is None: return False
        else: return True

    def read_attributes(self, attributes):
        try:
            return self.device.read_attributes(attributes)
        except:
            logging.error("Device read attribute error: retrying device")
            if not config.DEVICE_ALLOW_RETRY:
                raise Exception(
                    str("Device %s could not be connected" % self.devicePath))
            else:
                self._retry_device()
                return self.read_attributes(attributes)

    def read_attribute(self, attribute):
        try:
            return self.device.read_attribute(attribute)
        except:
            if not config.DEVICE_ALLOW_RETRY:
                raise Exception(
                    str("Device %s could not be connected" % self.devicePath))
            else:
                self._retry_device()
                return self.read_attribute(attribute)

    def write_attributes(self, attributes):
        """
        Write attribute to device
        @type attributes: list
        @rtype: String
        """
        res = None
        if self.device:
            for attribute in attributes:
                logging.info("Attribute: %s wrote on device: %s", attribute[0],
                             self.devicePath)

            try:
                self.device.state()
                res = self.device.write_attributes(attributes)
            except (DevFailed, AttributeError) as e:
                pass
        return res

    def write_attributes_async(self, attributes, callback=None):
        res = None
        if self.device:
            for attribute in attributes:
                logging.info("Attribute: %s wrote on device: %s", attribute[0],
                             self.devicePath)

            try:
                self.device.state()
                res = self.device.write_attributes_asynch(attributes, callback)
            except (DevFailed, AttributeError) as e:
                pass
        return res

    def execute_command(self, commandName, commandParam=None):
        """
        Execute command on device
        @type commandName: String
        @type commandParam: String
        @rtype: String
        """
        try:
            if self.device:
                return self.device.command_inout(commandName, commandParam)
        except:
            if not config.DEVICE_ALLOW_RETRY:
                raise Exception(
                    str("Device %s could not be connected" % self.devicePath))
            else:
                self._retry_device()
                return self.execute_command(commandName, commandParam)

    def wait_for_state(self, state, callback=None):
        """
        Wait for state
        @type state: DevState.state
        """
        if self.device:
            while (self.device.state() == state):
                sleep(self.POLL_STATE_TIME)
            if not (callback is None): callback(self)

    def wait_seconds(self, duration=1):
        """
        Wait for a time duration
        @type duration: float if not config.DEVICE_ALLOW_RETRY: 
                raise Exception(str("Device %s could not be connected" % self.devicePath))
            else: 
                self._retry_device()
                return self.execute_command(commandName, commandParam)
        """
        if self.device:
            sleep(duration)

    def poll(self,
             commandName,
             duration=0.1,
             commandResult=True,
             callback=None,
             commandParam=None):
        """
        Poll device with command
        @type commandName: String
        @type duration: float
        @type callback: fun
        @type commandParam: String  
        """
        while (self.execute_command(commandName, commandParam) == commandResult
               and threads.THREAD_KEEP_ALIVE):
            self.wait_seconds(duration)
        if not (callback is None): callback(self)

    def poll_attribute(self,
                       attrName,
                       duration=0.1,
                       attributeResult=True,
                       callback=None,
                       commandParam=None):
        """
        Poll device with command
        @type attrName: String
        @type duration: float
        @type callback: fun
        @type commandParam: String
        """
        while (self.read_attribute(attrName).value == attributeResult
               and threads.THREAD_KEEP_ALIVE):
            self.wait_seconds(duration)
        if not (callback is None): callback(self)

    def check_idle(self):
        """
        Check if device id idle
        """
        pass

    def is_idle(self):
        """
        Return True if is idle, False if not and None if unknown 
        """
        return None

    def start_profiling(self):
        if self.profiling: return False
        self.profiling = True
        logging.info("Profiling of device %s started" % self.devicePath)
        return True

    def stop_profiling(self):
        self.profiling = False
        self.cleanup_thread()

    def current_value(self, value):
        return self.read_attribute(value).value

    def __profiling_routine(self):
        pass

    @property
    def thread(self):
        return self.__thread

    def start_external_profiling(self, func):
        """
        Starts profiling with an external function
        """
        self.profiling = True

        if self.__thread is None:
            thread = threads.threading.Thread(target=func, args=([self]))
            threads.add_thread(thread)
            thread.start()

            self.__thread = thread

    def cleanup_thread(self):
        if self.__thread is not None:
            self.profiling = False
            threads.join_thread(self.__thread)
            self.__thread = None

    def state(self):
        """
        Overload of the state function to keep track of old states
        :return:
        """
        state = None
        try:
            state = DeviceProxy(self.devicePath).state()

            self._bstate_changed = False
            if state != self.old_state:
                self.old_state = state
                self._bstate_changed = True
        except DevFailed:
            pass
        return state

    def is_state_changed(self):
        return self._bstate_changed
コード例 #45
0
class Ps_attenuatorPX1(Device):
    stateAttenuator = {
        'ALARM': 'error',
        'OFF': 'error',
        'RUNNING': 'moving',
        'MOVING': 'moving',
        'STANDBY': 'ready',
        'UNKNOWN': 'changed',
        'EXTRACT': 'outlimits'
    }

    def __init__(self, name):
        Device.__init__(self, name)

        self.labels = []
        self.attno = 0
        self.deviceOk = True

    def init(self):
        #         cmdToggle = self.getCommandObject('toggle')
        #         cmdToggle.connectSignal('connected', self.connected)
        #         cmdToggle.connectSignal('disconnected', self.disconnected)

        # Connect to device FP_Parser defined "tangoname" in the xml file
        try:
            self.Attenuatordevice = DeviceProxy(self.getProperty("tangoname"))
        except:
            self.errorDeviceInstance(self.getProperty("tangoname"))

        if self.deviceOk:
            self.connected()

            self.chanAttState = self.getChannelObject('State')
            self.chanAttState.connectSignal('update', self.attStateChanged)

            self.chanAttFactor = self.getChannelObject('TrueTrans_FP')
            self.chanAttFactor.connectSignal('update', self.attFactorChanged)

    def getAttState(self):
        logging.getLogger().info("HOS Attenuator: passe dans getAttState")
        try:
            value = Ps_attenuatorPX1.stateAttenuator[
                self.Attenuatordevice.State().name]
            print(
                'State Ps_Attenuator : ', Ps_attenuatorPX1.stateAttenuator[
                    self.Attenuatordevice.State().name])
            logging.getLogger().debug(
                "Attenuator state read from the device %s", value)
        except:
            logging.getLogger("HWR").error(
                '%s getAttState : received value on channel is not a integer value',
                str(self.name()))
            value = None
        return value

    def attStateChanged(self, channelValue):
        logging.getLogger().info("HOS Attenuator: passe dans attStateChanged")
        value = self.getAttState()
        self.emit('attStateChanged', (value, ))

    def getAttFactor(self):
        logging.getLogger().info("HOS Attenuator: passe dans getAttFactor")

        try:
            #            if self.Attenuatordevice.TrueTrans_FP  <= 100.0 :
            #                value = float(self.Attenuatordevice.TrueTrans_FP)
            #            else :
            #                value = float(self.Attenuatordevice.T)
            value = float(self.Attenuatordevice.TrueTrans_FP)
        except:
            logging.getLogger("HWR").error(
                '%s getAttFactor : received value on channel is not a float value',
                str(self.name()))
            value = None
        return value

    def connected(self):
        self.setIsReady(True)

    def disconnected(self):
        self.setIsReady(False)

    def attFactorChanged(self, channelValue):
        try:
            print("Dans attFactorChanged channelValue = %f" % channelValue)
            #  	    value = float(channelValue)
            value = self.getAttFactor()
        except:
            logging.getLogger("HWR").error(
                '%s attFactorChanged : received value on channel is not a float value',
                str(self.name()))
        else:
            self.emit('attFactorChanged', (value, ))

    def attToggleChanged(self, channelValue):
        #        print "Dans attToggleChanged  channelValue = %s" %channelValue
        #        logging.getLogger().debug("HOS Attenuator: passe dans attToggleChanged")
        try:
            value = int(channelValue)
        except:
            logging.getLogger("HWR").error(
                '%s attToggleChanged : received value on channel is not a float value',
                str(self.name()))
        else:
            self.emit('toggleFilter', (value, ))

    def setTransmission(self, value):
        logging.getLogger().debug("HOS Attenuator: passe dans setTransmission")
        try:
            self.Attenuatordevice.TrueTrans_FP = value
        except:
            logging.getLogger("HWR").error(
                '%s set Transmission : received value on channel is not valid',
                str(self.name()))
            value = None
        return value

    def toggle(self, value):
        logging.getLogger().debug("HOS Attenuator: passe dans toggle")
        return value

    def errorDeviceInstance(self, device):
        db = DeviceProxy("sys/database/dbds1")
        logging.getLogger().error("Check Instance of Device server %s" %
                                  db.DbGetDeviceInfo(device)[1][3])
        self.sDisconnected()
コード例 #46
0
class TangoDCMotor(Device):

    MOVESTARTED = 0
    NOTINITIALIZED = 0
    UNUSABLE = 0
    READY = 2
    MOVING = 4
    ONLIMIT = 1

    stateDict = {
        "UNKNOWN": 0,
        "OFF": 0,
        "ALARM": 1,
        "FAULT": 1,
        "STANDBY": 2,
        "RUNNING": 4,
        "MOVING": 4,
        "ON": 2,
    }

    def __init__(self, name):

        # State values as expected by Motor bricks

        Device.__init__(self, name)
        self.GUIstep = 0.1
        self.motor_states = MotorStates()

    def _init(self):
        self.positionValue = 0.0
        self.stateValue = "UNKNOWN"

        threshold = self.get_property("threshold")
        self.threshold = (
            0.0018  # default value. change it with property threshold in xml
        )

        self.old_value = 0.0
        self.tangoname = self.get_property("tangoname")
        self.motor_name = self.get_property("motor_name")
        self.ho = DeviceProxy(self.tangoname)

        try:
            self.dataType = self.get_property("datatype")
            if self.dataType is None:
                self.dataType = "float"
        except Exception:
            self.dataType = "float"

        if threshold is not None:
            try:
                self.threshold = float(threshold)
            except Exception:
                pass

        self.set_is_ready(True)
        try:
            self.limitsCommand = self.get_command_object("limits")
        except KeyError:
            self.limitsCommand = None
        self.positionChan = self.get_channel_object(
            "position"
        )  # utile seulement si positionchan n'est pas defini dans le code
        self.stateChan = self.get_channel_object(
            "state"
        )  # utile seulement si statechan n'est pas defini dans le code

        self.positionChan.connect_signal("update", self.positionChanged)
        self.stateChan.connect_signal("update", self.motorStateChanged)

    def positionChanged(self, value):
        self.positionValue = value
        if abs(float(value) - self.old_value) > self.threshold:
            try:
                # logging.getLogger("HWR").error("%s: TangoDCMotor new position  , %s", self.name(), value)
                self.emit("valueChanged", (value,))
                self.old_value = value
            except Exception:
                logging.getLogger("HWR").error(
                    "%s: TangoDCMotor not responding, %s", self.name(), ""
                )
                self.old_value = value

    def is_ready(self):
        return self.stateValue == "STANDBY"

    def connect_notify(self, signal):
        if signal == "hardware_object_name,stateChanged":
            self.motorStateChanged(TangoDCMotor.stateDict[self.stateValue])
        elif signal == "limitsChanged":
            self.motorLimitsChanged()
        elif signal == "valueChanged":
            self.motor_positions_changed(self.positionValue)
        self.set_is_ready(True)

    def motorState(self):
        return TangoDCMotor.stateDict[self.stateValue]

    def motorStateChanged(self, state):
        self.stateValue = str(state)
        self.set_is_ready(True)
        logging.info("motor state changed. it is %s " % self.stateValue)
        self.emit("stateChanged", (TangoDCMotor.stateDict[self.stateValue],))

    def get_state(self):
        return TangoDCMotor.stateDict[self.stateValue]

    def get_limits(self):
        try:
            logging.getLogger("HWR").info(
                "TangoDCMotor.get_limits: trying to get limits for motor_name %s "
                % (self.motor_name)
            )
            limits = self.ho.getMotorLimits(
                self.motor_name
            )  # limitsCommand() # self.ho.getMotorLimits(self.motor_name)
            logging.getLogger("HWR").info(
                "TangoDCMotor.get_limits: Getting limits for %s -- %s "
                % (self.motor_name, str(limits))
            )
            if numpy.inf in limits:
                limits = numpy.array([-10000, 10000])
        except Exception:
            # import traceback
            # logging.getLogger("HWR").info("TangoDCMotor.get_limits: Cannot get limits for %s.\nException %s " % (self.motor_name, traceback.print_exc()))
            if self.motor_name in [
                "detector_distance",
                "detector_horizontal",
                "detector_vertical",
            ]:
                info = self.positionChan.getInfo()
                limits = [float(info.min_value), float(info.max_value)]
            # if self.motor_name == 'detector_ts':
            # limits = [96, 1100]
            # elif self.motor_name == 'detector_tx':
            # limits =
            elif self.motor_name == "exposure":
                limits = [float(self.min_value), float(self.max_value)]

        if limits is None:
            try:
                limits = self.get_property("min"), self.get_property("max")
                logging.getLogger("HWR").info(
                    "TangoDCMotor.get_limits: %.4f ***** %.4f" % limits
                )
                limits = numpy.array(limits)
            except Exception:
                # logging.getLogger("HWR").info("TangoDCMotor.get_limits: Cannot get limits for %s" % self.name())
                limits = None
        return limits

    def motorLimitsChanged(self):
        self.emit("limitsChanged", (self.get_limits(),))

    def motorIsMoving(self):
        return self.stateValue == "RUNNING" or self.stateValue == "MOVING"

    def motorMoveDone(self, channelValue):
        if self.stateValue == "STANDBY":
            self.emit("moveDone", (self.tangoname, "tango"))

    def motor_positions_changed(self, absolutePosition):
        self.emit("valueChanged", (absolutePosition,))

    def syncQuestionAnswer(self, specSteps, controllerSteps):
        return (
            "0"  # This is only for spec motors. 0 means do not change anything on sync
        )

    def get_value(self):
        return self.positionChan.get_value()

    def convertValue(self, value):
        logging.info("TangoDCMotor: converting value to %s " % str(self.dataType))
        retvalue = value
        if self.dataType in ["short", "int", "long"]:
            retvalue = int(value)
        return retvalue

    def get_motor_mnemonic(self):
        return self.name()

    def _set_value(self, value):
        """Move the motor to the required position

        Arguments:
        absolutePosition -- position to move to
        """
        logging.getLogger("TangoClient").info(
            "TangoDCMotor move (%s). Trying to go to %s: type '%s'",
            self.motor_name,
            value,
            type(value),
        )
        value = float(value)
        if not isinstance(value, float) and not isinstance(value, int):
            logging.getLogger("TangoClient").error(
                "Cannot move %s: position '%s' is not a number. It is a %s",
                self.tangoname,
                value,
                type(value),
            )
        logging.info("TangoDCMotor: move. motor will go to %s " % str(value))
        logging.getLogger("HWR").info(
            "TangoDCMotor.move to absolute position: %.3f" % value
        )
        logging.getLogger("TangoClient").info(
            "TangoDCMotor move. Trying to go to %s: that is a '%s'", value, type(value),
        )
        # if abs(self.get_value() - value) > epsilon:
        #     logging.info(
        #         "TangoDCMotor: difference larger then epsilon (%s), executing the move "
        #         % str(epsilon)
        #     )
        self.positionChan.set_value(self.convertValue(value))
        # else:
        #     logging.info(
        #         "TangoDCMotor: not moving really as epsilon is large %s " % str(epsilon)
        #     )
        #     logging.info("TangoDCMotor: self.get_value() %s " % str(self.get_value()))
        #     logging.info("TangoDCMotor: value %s " % str(value))

    def stop(self):
        logging.getLogger("HWR").info("TangoDCMotor.stop")
        stopcmd = self.get_command_object("Stop")()
        if not stopcmd:
            stopcmd = TangoCommand("stopcmd", "Stop", self.tangoname)
        stopcmd()

    def isSpecConnected(self):
        logging.getLogger().debug("%s: TangoDCMotor.isSpecConnected()" % self.name())
        return (Truehardware_object_name,)
コード例 #47
0
 def errorDeviceInstance(self, device):
     db = DeviceProxy("sys/database/dbds1")
     logging.getLogger().error("Check Instance of Device server %s" %
                               db.DbGetDeviceInfo(device)[1][3])
     self.sDisconnected()
コード例 #48
0
ファイル: client.py プロジェクト: cpascual/PyTango
 def __init__(self, dev_name, *args, **kwargs):
     self.dev_name = dev_name
     self.device = Device(dev_name, *args, **kwargs)
     self.slots = weakref.WeakKeyDictionary()
コード例 #49
0
    def init(self):

        self.collectServer = DeviceProxy(self.getProperty("collectname"))
        self.pilatusServer = DeviceProxy(self.getProperty("pilatusname"))

        self.setControlObjects(
            diffractometer=self.getObjectByRole("diffractometer"),
            sample_changer=self.getObjectByRole("sample_changer"),
            lims=self.getObjectByRole("dbserver"),
            fast_shutter=self.getObjectByRole("fast_shutter"),
            safety_shutter=self.getObjectByRole("safety_shutter"),
            machine_current=self.getObjectByRole("machine_current"),
            cryo_stream=self.getObjectByRole("cryo_stream"),
            energy=self.getObjectByRole("energy"),
            resolution=self.getObjectByRole("resolution"),
            detector_distance=self.getObjectByRole("detector_distance"),
            transmission=self.getObjectByRole("transmission"),
            undulators=self.getObjectByRole("undulators"),
            flux=self.getObjectByRole("flux"))

        kappa_hwo = self.getObjectByRole("kappa")
        phi_hwo = self.getObjectByRole("phi")
        omega_hwo = self.getObjectByRole("omega")
        mxlocalHO = self.getObjectByRole("beamline_configuration")

        bcm_pars = mxlocalHO["BCM_PARS"]
        spec_pars = mxlocalHO["SPEC_PARS"]

        try:
            undulators = bcm_pars["undulator"]
        except IndexError:
            undulators = []

        self.setBeamlineConfiguration(
            directory_prefix=self.getProperty("directory_prefix"),
            default_exposure_time=bcm_pars.getProperty(
                "default_exposure_time"),
            default_number_of_passes=bcm_pars.getProperty(
                "default_number_of_passes"),
            maximum_radiation_exposure=bcm_pars.getProperty(
                "maximum_radiation_exposure"),
            nominal_beam_intensity=bcm_pars.getProperty(
                "nominal_beam_intensity"),
            minimum_exposure_time=bcm_pars.getProperty(
                "minimum_exposure_time"),
            minimum_phi_speed=bcm_pars.getProperty("minimum_phi_speed"),
            minimum_phi_oscillation=bcm_pars.getProperty(
                "minimum_phi_oscillation"),
            maximum_phi_speed=bcm_pars.getProperty("maximum_phi_speed"),
            detector_fileext=bcm_pars.getProperty("FileSuffix"),
            detector_type=bcm_pars["detector"].getProperty("type"),
            detector_mode=spec_pars["detector"].getProperty("binning"),
            detector_manufacturer=bcm_pars["detector"].getProperty(
                "manufacturer"),
            detector_model=bcm_pars["detector"].getProperty("model"),
            detector_px=bcm_pars["detector"].getProperty("px"),
            detector_py=bcm_pars["detector"].getProperty("py"),
            beam_ax=spec_pars["beam"].getProperty("ax"),
            beam_ay=spec_pars["beam"].getProperty("ay"),
            beam_bx=spec_pars["beam"].getProperty("bx"),
            beam_by=spec_pars["beam"].getProperty("by"),
            undulators=undulators,
            focusing_optic=bcm_pars.getProperty('focusing_optic'),
            monochromator_type=bcm_pars.getProperty('monochromator'),
            beam_divergence_vertical=bcm_pars.getProperty(
                'beam_divergence_vertical'),
            beam_divergence_horizontal=bcm_pars.getProperty(
                'beam_divergence_horizontal'),
            polarisation=bcm_pars.getProperty('polarisation'),
            auto_processing_server=None,
            input_files_server=None)

        self.oscaxis = self.getProperty("oscaxis")

        self._detector.collectServer = self.collectServer
        self._detector.pilatusServer = self.pilatusServer
        self._detector.bl_control = self.bl_control
        self._detector.bl_config = self.bl_config
        self._detector.kappa_hwo = kappa_hwo
        self._detector.phi_hwo = phi_hwo
        self._detector.omega_hwo = omega_hwo
        self._detector.oscaxis = self.oscaxis

        #self._detector.getCommandObject = self.getCommandObject
        #self._detector.getChannelObject = self.getChannelObject
        #self._detector.execute_command = self.execute_command

        self._tunable_bl.bl_control = self.bl_control

        self.emit("collectConnected", (True, ))
        self.emit("collectReady", (True, ))
コード例 #50
0
class TangoMotorZoomPX2(Device):

    stateDict = {
        "UNKNOWN": 0,
        "ALARM": 1,
        "FAULT": 1,
        "STANDBY": 2,
        "RUNNING": 4,
        "MOVING": 4,
        "ON": 2,
        '2': 2
    }

    def __init__(self, name):
        Device.__init__(self, name)
        self.GUIstep = 0.1

    def _init(self):

        self.MOVESTARTED = 0
        self.NOTINITIALIZED = 0
        self.UNUSABLE = 0
        self.READY = 2
        self.MOVING = 4
        self.ONLIMITS = 1

        #self.device = SimpleDevice(self.getProperty("tangoname"), verbose=False)
        #self.device.timeout = 6000 # Setting timeout to 6 sec
        self.device = DeviceProxy(self.getProperty("tangoname"))
        self.device.waitMoves = False
        logging.getLogger("HWR").info("TangoMotorZoomPX2._init of device %s" %
                                      self.device.name)
        self.setIsReady(True)
        print("TangoMotorZoomPX2._init of device %s" % self.device.name)
        positionChan = self.getChannelObject(
            "position"
        )  # utile seulement si statechan n'est pas defini dans le code
        positionChan.connectSignal("update", self.positionChanged)
        #focus_positionChan = self.getChannelObject("focus_position")
        #focus_positionChan.connectSignal("update", self.positionChanged)
        stateChan = self.getChannelObject(
            "state"
        )  # utile seulement si statechan n'est pas defini dans le code
        stateChan.connectSignal("update", self.motorStateChanged)

        #logging.getLogger("HWR").info("%s: TangoMotorZoomPX2._init, %s", self.name(), '')

    def positionChanged(self, value):
        try:
            logging.getLogger("HWR").info(
                "%s: TangoMotorZoomPX2.positionChanged: %.3f", self.name(),
                value)
        except:
            logging.getLogger("HWR").error("%s: TangoMotor not responding, %s",
                                           self.name(), '')

        self.emit('positionChanged', (value, ))

    def isReady(self):
        #logging.getLogger("HWR").info("%s: TangoMotorZoomPX2.isReady", self.name())
        return str(self.device.State()) == 'STANDBY'

    def connectNotify(self, signal):
        #logging.getLogger("HWR").info("%s: TangoMotorZoomPX2.connectNotify, : %s", self.name(), signal)
        if signal == 'hardwareObjectName,stateChanged':
            self.motorStateChanged(TangoMotorZoomPX2.stateDict[str(
                self.device.State())])
        elif signal == 'limitsChanged':
            self.motorLimitsChanged()
            #print "Not implemented yet."PhiTableXAxisPosition

        elif signal == 'positionChanged':
            #self.motorPositionChanged(self.device.position)
            print('MS debug 18.10.2012')
            #print self.device
            print(self.device.read_attribute("ZoomLevel").value)
            self.motorPositionChanged(
                self.device.read_attribute(
                    "ZoomLevel").value)  #MS debug 18.10.2012

        self.setIsReady(True)

    def motorState(self):
        return TangoMotorZoomPX2.stateDict[str(self.device.State())]

    def motorStateChanged(self, state):
        #logging.getLogger("HWR").info("%s: TangoMotorZoomPX2.motorStateChanged, %s", self.name(), state)
        #self.setIsReady(state == 'STANDBY')
        self.setIsReady(True)
        #print "motorStateChanged", str(state)
        self.emit('stateChanged',
                  (TangoMotorZoomPX2.stateDict[str(self.device.State())], ))

    def getState(self):
        state = str(self.device.State())
        #logging.getLogger("HWR").info("%s: TangoMotorZoomPX2.getState, %s", self.name(), state)
        return TangoMotorZoomPX2.stateDict[str(self.device.State())]

    def getLimits(self):
        #limits = self.device.getLimits("positiopositionChan.connectSignal("update", self.positionChanged)n")
        # MS 18.09.2012 adapted for use without SimpleDevice
        position_info = self.device.attribute_query("ZoomLevel")
        rlow = 1  # position_info.min_value
        rhigh = 10  #position_info.max_value
        #logging.getLogger("HWR").info("TangoMotorZoomPX2.getLimits: %.4f %.4f" % limits)
        return rlow, rhigh

    def motorLimitsChanged(self):
        #self.emit('limitsChanged', (self.getLimits(), ))
        #logging.getLogger("HWR").info("%s: TangoMotorZoomPX2.limitsChanged", self.name())
        self.emit('limitsChanged', (self.getLimits(), ))

    def motorMoveDone(self, channelValue):
        #SpecMotorA.motorMoveDone(self, channelValue)
        #logging.getLogger("HWR").info("TangoMotorZoomPX2.motorMoveDone")
        if str(self.device.State()) == 'STANDBY':

            #self.emit('moveDone', (self.specversion, self.specname, ))
            self.emit('moveDone', ("EH3", "toto"))

    def motorPositionChanged(self, absolutePosition):
        self.emit('positionChanged', (absolutePosition, ))

    def syncQuestionAnswer(self, specSteps, controllerSteps):
        return '0'  #NO ('1' means YES)

    def getPosition(self):
        pos = self.device.read_attribute(
            "ZoomLevel").value  #self.device.position
        #logging.getLogger("HWR").info("%s: TangoMotorZoomPX2.getPosition, pos = %.3f", self.name(), pos)
        return pos

    def syncMove(self, position):
        #print 'about to start moving', self.motorState
        t0 = time.time()
        prev_position = self.getPosition()
        self.device.position = position

        print('move started from %s to %s, state is %s' %
              (prev_position, position, str(self.device.State())))

        while str(self.device.State()) == "RUNNING" or str(
                self.device.State()
        ) == "MOVING":  # or str(self.device.State()) == SpecMotor.MOVESTARTED:
            #print 'processing events...', self.motorState
            qApp.processEvents(100)

        print('move done (%s s), state is %s' %
              (time.time() - t0, str(self.device.State())))

    def moveRelative(self, position):
        old_pos = self.device.position
        self.device.position = old_pos + position
        #self.moveRelahardwareObjectName,tive(position)

        while str(self.device.State()) == "RUNNING" or str(
                self.device.State()) == "MOVING":
            qApp.processEvents(100)

    def syncMoveRelative(self, position):
        old_pos = self.device.position
        self.device.position = old_pos + position
        #self.moveRelahardwareObjectName,tive(position)

        while str(self.device.State()) == "RUNNING" or str(
                self.device.State()) == "MOVING":
            qApp.processEvents(100)

    def getMotorMnemonic(self):
        return self.specName

    def move(self, absolutePosition):
        """Move the motor to the required position

        Arguments:
        absolutePosition -- position to move to
        """
        if type(absolutePosition) != float and type(absolutePosition) != int:
            logging.getLogger("TangoClient").error(
                "Cannot move %s: position '%s' is not a number",
                self.device.name, absolutePosition)

        #self.__changeMotorState(MOVESTARTED)

        #c = self.connection.getChannel(self.chanNamePrefix % 'start_one')
        logging.getLogger("HWR").info(
            "TangoMotorZoomPX2.move to absolute position: %.3f" %
            absolutePosition)
        self.device.position = absolutePosition

    def stop(self):
        logging.getLogger("HWR").info("TangoMotorZoomPX2.stop")
        self.device.Stop()

    def isSpecConnected(self):
        logging.getLogger().debug("%s: TangoMotorZoomPX2.isSpecConnected()" %
                                  self.name())
        return TruehardwareObjectName,
コード例 #51
0
class TangoResolution(BaseHardwareObjects.Equipment):
#     resoState = {
#         None: 'unknown',
#         'UNKNOWN': 'unknown',
#         'CLOSE': 'closed',
#         'OPEN': 'opened',
#         'MOVING': 'moving',
#         'FAULT': 'fault',
#         'DISABLE': 'disabled',
#         'OFF': 'fault',
#         'ON': 'unknown'
#         }
        
    stateDict = {
         "UNKNOWN": 0,
         "ALARM":   1,
         "STANDBY": 2,
         "RUNNING": 4,
         "MOVING":  4,
         "1":       1,
         "2":       2}
   
    
    def _init(self):
        self.currentResolution = None
        self.currentDistance = None
        self.currentWavelength = None
        self.currentEnergy = None
        self.connect("equipmentReady", self.equipmentReady)
        self.connect("equipmentNotReady", self.equipmentNotReady)
        self.device = DeviceProxy( self.getProperty("tangoname") )
        
        #self.monodevice = SimpleDevice(self.getProperty("tangoname2"), waitMoves = False, verbose=False)
        self.blenergyHOname = self.getProperty("BLEnergy")
        if self.blenergyHOname is None:
            logging.getLogger("HWR").error('TangoResolution: you must specify the %s hardware object' % self.blenergyHOname)
            hobj=None
            self.configOk=False
        else:
            hobj=HardwareRepository.HardwareRepository().getHardwareObject(self.blenergyHOname)
            if hobj is None:
                logging.getLogger("HWR").error('TangoResolution: invalid %s hardware object' % self.blenergyHOname)
                self.configOk=False
            self.blenergyHO=hobj
            self.connect(self.blenergyHO,qt.PYSIGNAL('energyChanged'), self.energyChanged)
        # creer un chanel sur l'energy: pour faire un update 
        positChan = self.getChannelObject("position") # utile seulement si statechan n'est pas defini dans le code
        positChan.connectSignal("update", self.positionChanged)
        stateChan = self.getChannelObject("state") # utile seulement si statechan n'est pas defini dans le code
        stateChan.connectSignal("update", self.stateChanged)
        
        self.currentDistance = self.device.position
        self.currentEnergy = self.blenergyHO.getCurrentEnergy()
        self.currentWavelength = self.blenergyHO.getCurrentWavelength()
        return BaseHardwareObjects.Equipment._init(self)

        
    def init(self):
        #self.detm = self.getDeviceByRole("detm")
        #self.dtox = self.getDeviceByRole("dtox")
        #self.dist2res = self.getCommandObject("dist2res")
        #self.res2dist = self.getCommandObject("res2dist")
        self.__resLimitsCallback = None
        
        
        self.__resLimitsErrCallback = None
        self.__resLimits = {}

        #self.connect(self.device, "stateChanged", self.detmStateChanged)
        #self.dist2res.connectSignal("commandReplyArrived", self.newResolution)
        #self.res2dist.connectSignal("commandReplyArrived", self.newDistance)
    
    def positionChanged(self, value):
        res = self.dist2res(value)
        self.emit('positionChanged', (res,))

    
    def getState(self):
        return TangoResolution.stateDict[str( self.device.State() )] 

                
    def equipmentReady(self):
        self.emit("deviceReady")


    def equipmentNotReady(self):
        self.emit("deviceNotReady")
        

    def getPosition(self):
        if self.currentResolution is None:
            self.recalculateResolution()
        return self.currentResolution

    def energyChanged(self, energy):
        if self.currentEnergy is None:
            self.currentEnergy = energy
        if type(energy) is not float:
            logging.getLogger("HWR").error("%s: TangoResolution Energy not a float: %s", energy, '')
            return
        if abs(self.currentEnergy - energy) > 0.0002:
            self.currentEnergy = energy # self.blenergyHO.getCurrentEnergy()
            self.wavelengthChanged(self.blenergyHO.getCurrentWavelength())
        
    def wavelengthChanged(self, wavelength):
        self.currentWavelength = wavelength
        self.recalculateResolution()
        
    def recalculateResolution(self):
        self.currentDistance = self.device.position
        self.currentResolution = self.dist2res(self.currentDistance)
        if self.currentResolution is None:
            return
        self.newResolution(self.currentResolution) 

    def newResolution(self, res):      
        if self.currentResolution is None:
            self.currentResolution = self.recalculateResolution()
        self.currentResolution = res
        self.emit("positionChanged", (res, ))
    
    def connectNotify(self, signal):
        #logging.getLogger("HWR").debug("%s: TangoResolution.connectNotify, : %s", \
        #                                                  self.name(), signal)
        if signal == "stateChanged":
            self.stateChanged(TangoResolution.stateDict[self.device.State])
        
        elif signal == 'positionChanged':
            self.positionChanged(self.device.position)

    def stateChanged(self, state):
        self.emit('stateChanged', (TangoResolution.stateDict[str(state)], ))


    def getLimits(self, callback=None, error_callback=None):

        positionChan = self.getChannelObject("position")
        info = positionChan.getInfo()

        high = float(info.max_value)
        low  = float(info.min_value)

        #logging.getLogger("HWR").debug("%s: DetectorDistance.getLimits: [%.2f - %.2f]" % (self.name(), low, high))
        
        if isinstance(callback, collections.Callable):
            #logging.getLogger("HWR").debug("getLimits with callback: %s" % callback)

            self.__resLimitsCallback = callback
            self.__resLimitsErrCallback = error_callback

            self.__resLimits = {}
            rlow = self.dist2res(low, callback=self.__resLowLimitCallback, \
                                   error_callback=self.__resLimitsErrCallback)
            rhigh = self.dist2res(high, callback=self.__resHighLimitCallback,\
                                   error_callback=self.__resLimitsErrCallback)
        else:
            #logging.getLogger("HWR").debug("getLimits with no callback")
            rhigh  = self.dist2res(low)
            rlow   = self.dist2res(high)
        
        #logging.getLogger("HWR").debug("%s: TangoResolution.getLimits: [%.3f - %.3f]"\
                                                     #% (self.name(), rlow, rhigh))
        return (rlow, rhigh)


    def isSpecConnected(self):
        #logging.getLogger().debug("%s: TangoResolution.isSpecConnected()" % self.name())
        return True
    
    def __resLowLimitCallback(self, rlow):
        self.__resLimits["low"]=float(rlow)

        if len(self.__resLimits) == 2:
            if isinstance(self.__resLimitsCallback, collections.Callable):
              self.__resLimitsCallback((self.__resLimits["low"], self.__resLimits["high"]))
            self.__resLimitsCallback = None
            self.__dist2resA1 = None
            self.__dist2resA2 = None


    def __resHighLimitCallback(self, rhigh):
        self.__resLimits["high"]=float(rhigh)

        if len(self.__resLimits) == 2:
            if isinstance(self.__resLimitsCallback, collections.Callable):
              self.__resLimitsCallback((self.__resLimits["low"], self.__resLimits["high"]))
            self.__resLimitsCallback = None
            self.__dist2resA1 = None
            self.__dist2resA2 = None
            

    def __resLimitsErrCallback(self):
        if isinstance(self.__resLimitsErrCallback, collections.Callable):
            self.__resLimitsErrCallback()
            self.__resLimitsErrCallback = None
            self.__dist2resA1 = None
            self.__dist2resA2 = None


    def move(self, res):
        self.currentWavelength = self.blenergyHO.getCurrentWavelength()
        self.device.position = self.res2dist(res)

    def newDistance(self, dist):
        self.device.position = dist


    def stop(self):
        try:
            self.device.Stop()
        except:
            logging.getLogger("HWR").err("%s: TangoResolution.stop: error while trying to stop!", self.name())
            pass
        
    def dist2res(self, Distance, callback=None, error_callback=None):

        Distance = float(Distance)
        try:
            #Wavelength = self.monodevice._SimpleDevice__DevProxy.read_attribute("lambda").value
            if self.currentWavelength is None:
                self.currentWavelength = self.blenergyHO.getCurrentWavelength()
            thetaangle2 = math.atan(DETECTOR_DIAMETER/2./Distance)
            Resolution = 0.5*self.currentWavelength /math.sin(thetaangle2/2.)
            if isinstance(callback, collections.Callable):
                callback(Resolution)
            return Resolution
        except:
            if isinstance(error_callback, collections.Callable):
                error_callback()

    
    def res2dist(self, Resolution):
        #print "********* In res2dist with ", Resolution
        Resolution = float(Resolution)
        #Wavelength = self.monodevice._SimpleDevice__DevProxy.read_attribute("lambda").value
        if self.currentWavelength is None:
            self.currentWavelength = self.blenergyHO.getCurrentWavelength()
        thetaangle=math.asin(self.currentWavelength / 2. / Resolution)
        Distance=DETECTOR_DIAMETER/2./math.tan(2.*thetaangle)
        #print "********* Distance ", Distance
        return Distance
コード例 #52
0
class TangoMotor3(Device):

    stateDict = {
        "UNKNOWN": 0,
        "ALARM": 1,
        "FAULT": 1,
        "STANDBY": 2,
        "RUNNING": 4,
        "MOVING": 4,
        "ON": 2,
        '2': 2
    }

    def __init__(self, name):
        Device.__init__(self, name)
        self.GUIstep = 0.1

    def _init(self):

        self.MOVESTARTED = 0
        self.NOTINITIALIZED = 0
        self.UNUSABLE = 0
        self.READY = 2
        self.MOVING = 4
        self.ONLIMITS = 1

        self.device = DeviceProxy(self.getProperty("tangoname"))
        self.device.waitMoves = False
        self.setIsReady(True)
        print "TangoMotor._init of device %s" % self.device.name

        self.positionChan = self.getChannelObject(
            "attributeName"
        )  # utile seulement si statechan n'est pas defini dans le code
        self.positionChan.connectSignal("update", self.positionChanged)

        self.stateChan = self.getChannelObject(
            "state"
        )  # utile seulement si statechan n'est pas defini dans le code
        self.stateChan.connectSignal("update", self.stateChanged)
#
#        logging.getLogger("HWR").info("%s: TangoMotor._init, %s", self.name(), '')

    def positionChanged(self, value):
        try:
            logging.getLogger("HWR").info(
                "%s: TangoMotor.positionChanged: %.3f", self.name(), value)
        except:
            logging.getLogger("HWR").error("%s: TangoMotor not responding, %s",
                                           self.name(), '')

        self.emit('positionChanged', (value, ))

    def isReady(self):
        #logging.getLogger("HWR").info("%s: TangoMotor.isReady", self.name())
        return self.motorState() == TangoMotor3.stateDict["STANDBY"]

    def connectNotify(self, signal):
        #logging.getLogger("HWR").info("%s: TangoMotor.connectNotify, : %s", \
        #                                                  self.name(), signal)
        if signal == 'hardwareObjectName,stateChanged':
            self.motorStateChanged(self.motorState())
        elif signal == 'limitsChanged':
            self.motorLimitsChanged()
            #print "Not implemented yet."

        elif signal == 'positionChanged':
            self.motorPositionChanged(self.positionChan.getValue())

        self.setIsReady(True)

    def motorState(self):
        return self.getState()

    def stateChanged(self, state):
        logging.getLogger("HWR").info("State Changed, %s / %s" %
                                      (self.name(), str(state)))
        self.motorStateChanged(state)

    def motorStateChanged(self, state):
        logging.getLogger("HWR").info("%s: TangoMotor.motorStateChanged, %s",
                                      self.name(), state)
        #self.setIsReady(state == 'STANDBY')
        self.setIsReady(True)
        print "motorStateChanged", str(state), self.motorState()
        self.emit('stateChanged', (self.motorState(), ))

    def getState(self):
        state = str(self.device.State())
        #logging.getLogger("HWR").info("%s: TangoMotor.getState, %s", self.name(), state)
        #return self.motorState()
        return TangoMotor3.stateDict[state]

    def getLimits(self):
        #limits = self.device.getLimits(str(self.positionChan.attributeName))
        try:
            atprops = self.device.attribute_query(
                str(self.positionChan.attributeName))
            limits = map(float, [atprops.min_value, atprops.max_value])
            logging.getLogger("HWR").info(
                "TangoMotor3 getLimits returning %.4f %.4f" %
                (limits[0], limits[1]))
            return limits
        except IndexError:
            logging.getLogger("HWR").info(
                "TangoMotor3 cannot getLimits returning -1,1")
            return (-1, 1)

    def motorLimitsChanged(self):
        #self.emit('limitsChanged', (self.getLimits(), ))
        #logging.getLogger("HWR").info("%s: TangoMotor.limitsChanged", self.name())
        self.emit('limitsChanged', (self.getLimits(), ))

    def motorMoveDone(self, channelValue):
        #SpecMotorA.motorMoveDone(self, channelValue)
        #logging.getLogger("HWR").info("TangoMotor.motorMoveDone")
        if str(self.device.State()) == 'STANDBY':

            #self.emit('moveDone', (self.specversion, self.specname, ))
            self.emit('moveDone', ("EH3", "toto"))

    def motorPositionChanged(self, absolutePosition):
        self.motorStateChanged(self.device.State())
        self.emit('positionChanged', (absolutePosition, ))

    def syncQuestionAnswer(self, specSteps, controllerSteps):
        return '0'  #NO ('1' means YES)

    def getPosition(self):
        pos = self.positionChan.getValue()
        #logging.getLogger("HWR").info("%s: TangoMotor.getPosition, pos = %.3f", self.name(), pos)
        return pos

    def syncMove(self, position):
        #print 'about to start moving', self.motorState
        import time
        t0 = time.time()
        prev_position = self.getPosition()
        self.positionChan.value = position

        print 'move started from %s to %s, state is %s' % (
            prev_position, position, self.getState())

        while self.getState() == "RUNNING" or self.getState(
        ) == "MOVING":  # or str(self.device.State()) == SpecMotor.MOVESTARTED:
            #print 'processing events...', self.motorState
            qApp.processEvents(100)

        print 'move done (%s s), state is %s' % (time.time() - t0,
                                                 str(self.device.State()))

    def syncMoveRelative(self, position):
        old_pos = self.positionChan.getValue()
        self.positionChan.value = old_pos + position
        #self.moveRelahardwareObjectName,tive(position)

        while self.getState() == "RUNNING" or self.getState() == "MOVING":
            qApp.processEvents(100)

    def moveRelative(self, position):
        old_pos = self.positionChan.getValue()
        self.positionChan.value = old_pos + position
        #self.moveRelahardwareObjectName,tive(position)
        self.syncMove(self.positionChan.value)

    def getMotorMnemonic(self):
        return self.specName

    def move(self, absolutePosition):
        """Move the motor to the required position

        Arguments:
        absolutePosition -- position to move to
        """
        if type(absolutePosition) != float and type(absolutePosition) != int:
            logging.getLogger("TangoClient").error(
                "Cannot move %s: position '%s' is not a number",
                self.device.name, absolutePosition)

        #self.__changeMotorState(MOVESTARTED)

        #c = self.connection.getChannel(self.chanNamePrefix % 'start_one')
        logging.getLogger("HWR").info(
            "TangoMotor.move to absolute position: %.3f" % absolutePosition)
        self.positionChan.value = absolutePosition
        print self.positionChan.value
        nom_attribut = self.positionChan.attributeName
        setattr(self.device, nom_attribut, absolutePosition)
        self.motorPositionChanged(absolutePosition)

    def stop(self):
        logging.getLogger("HWR").info("TangoMotor.stop")
        self.device.Stop()

    def isSpecConnected(self):
        logging.getLogger().debug("%s: TangoMotor.isSpecConnected()" %
                                  self.name())
        return TruehardwareObjectName,
コード例 #53
0
                        action="store_true",
                        default=False,
                        help="Return output as json")

    args = parser.parse_args()
    domain = config["domain"]
    servers = _get_servers(config)

    log = logging.getLogger('aavs.ctl')
    if args.use_json:
        log.disabled = True

    # TODO move prints to logging, output to json for all branches
    hostname = platform.uname()[1]
    starter = "tango/admin/" + hostname
    starter_dp = DeviceProxy(starter)

    if args.status:
        status(args.use_json)
        exit()
    elif args.stop:
        kill_everything(starter_dp, servers)
        exit()
    elif args.config or args.run:
        kill_everything(starter_dp, servers)
        # Setup all configuration
        setup_tango_config(config)

        if args.use_json:
            exit()
        else:
コード例 #54
0
class CatsMaint(Equipment):

    __TYPE__ = "CATS"    
    NO_OF_LIDS = 3

    """
    Actual implementation of the CATS Sample Changer, MAINTENANCE COMMANDS ONLY
    BESSY BL14.1 installation with 3 lids
    """    
    def __init__(self, *args, **kwargs):
        Equipment.__init__(self, *args, **kwargs)

        self._state = None
        self._running = None
        self._powered = None
        self._toolopen = None
        self._message = None
        self._regulating = None
        self._lid1state = None
        self._lid2state = None
        self._lid3state = None
        self._charging = None
            
    def init(self):      

        self.cats_device = DeviceProxy(self.tangoname)

        try:
            self.cats_model = self.cats_device.read_attribute("CatsModel").value
        except:
            self.cats_model = "CATS"

        if self.is_isara():
            self.nb_of_lids = 1
        else:
            self.nb_of_lids = 3

        self._chnState = self.addChannel({ "type": "tango", 
            "name": "_chnState", "tangoname": self.tangoname, 
            "polling": 1000, }, "State")

        self._chnPathRunning = self.addChannel({ "type": "tango", 
            "name": "_chnPathRunning", "tangoname": self.tangoname, 
            "polling": 1000, }, "PathRunning")
        self._chnPowered = self.addChannel({ "type": "tango", 
            "name": "_chnPowered", "tangoname": self.tangoname, 
            "polling": 1000, }, "Powered")
        self._chnMessage = self.addChannel({ "type": "tango", 
            "name": "_chnMessage", "tangoname": self.tangoname, 
            "polling": 1000, }, "Message")
        self._chnToolOpenClose = self.addChannel({ "type": "tango", 
            "name": "_chnToolOpenClose", "tangoname": self.tangoname, 
            "polling": 1000, }, "di_ToolOpen")
        self._chnLN2Regulation = self.addChannel({ "type": "tango", 
            "name": "_chnLN2Regulation", "tangoname": self.tangoname, 
            "polling": 1000, }, "LN2Regulating")
        self._chnBarcode = self.addChannel({ "type": "tango", 
            "name": "_chnBarcode", "tangoname": self.tangoname, 
            "polling": 1000, }, "Barcode")

        self._chnLid1State = self.addChannel({ "type": "tango", 
            "name": "_chnLid1State", "tangoname": self.tangoname, 
            "polling": 1000, }, "di_Lid1Open")
        self._chnLid1State.connectSignal("update", self._updateLid1State)

        if self.nb_of_lids > 1:
            self._chnLid2State = self.addChannel({ "type": "tango", 
                "name": "_chnLid2State", "tangoname": self.tangoname, 
                "polling": 1000, }, "di_Lid2Open")
            self._chnLid2State.connectSignal("update", self._updateLid2State)

        if self.nb_of_lids > 2:
            self._chnLid3State = self.addChannel({ "type": "tango", 
                "name": "_chnLid3State", "tangoname": self.tangoname, 
                "polling": 1000, }, "di_Lid3Open")
            self._chnLid3State.connectSignal("update", self._updateLid3State)

        self._chnState.connectSignal("update", self._updateState)
        self._chnPathRunning.connectSignal("update", self._updateRunningState)
        self._chnPowered.connectSignal("update", self._updatePoweredState)
        self._chnToolOpenClose.connectSignal("update", self._updateToolState)
        self._chnMessage.connectSignal("update", self._updateMessage)
        self._chnLN2Regulation.connectSignal("update", self._updateRegulationState)
        self._chnBarcode.connectSignal("update", self._updateBarcode)
           
        self._chnCurrentTool = self.addChannel({ "type": "tango", 
            "name": "_chnCurrentTool", "tangoname": self.tangoname }, "Tool")
        # 
        self._cmdPowerOn = self.addCommand({ "type": "tango", 
            "name": "_cmdPowerOn", "tangoname": self.tangoname, }, "powerOn")
        self._cmdPowerOff = self.addCommand({ "type": "tango", 
            "name": "_cmdPowerOff", "tangoname": self.tangoname, }, "powerOff")
        self._cmdOpenTool = self.addCommand({ "type": "tango", 
            "name": "_cmdOpenTool", "tangoname": self.tangoname, }, "opentool")
        self._cmdCloseTool = self.addCommand({ "type": "tango", 
            "name": "_cmdCloseTool", "tangoname": self.tangoname, }, "closetool")
        self._cmdMagnetOn = self.addCommand({ "type": "tango", 
            "name": "_cmdMagnetOn", "tangoname": self.tangoname, }, "magnetOn")
        self._cmdMagnetOff = self.addCommand({ "type": "tango", 
            "name": "_cmdMagnetOff", "tangoname": self.tangoname, }, "magnetOff")

        # LIDs
        self._cmdOpenLid1 = self.addCommand({ "type": "tango", 
            "name": "_cmdOpenLid1", "tangoname": self.tangoname, }, "openlid1")
        self._cmdCloseLid1 = self.addCommand({ "type": "tango", 
            "name": "_cmdCloseLid1", "tangoname": self.tangoname, }, "closelid1")

        if self.nb_of_lids > 1:
            self._cmdOpenLid2 = self.addCommand({ "type": "tango", 
                "name": "_cmdOpenLid1", "tangoname": self.tangoname, }, "openlid2")
            self._cmdCloseLid2 = self.addCommand({ "type": "tango", 
                "name": "_cmdCloseLid1", "tangoname": self.tangoname, }, "closelid2")

        if self.nb_of_lids > 2:
            self._cmdOpenLid3 = self.addCommand({ "type": "tango", 
                "name": "_cmdOpenLid1", "tangoname": self.tangoname, }, "openlid3")
            self._cmdCloseLid3 = self.addCommand({ "type": "tango", 
                "name": "_cmdCloseLid1", "tangoname": self.tangoname, }, "closelid3")

        self._cmdRegulOn = self.addCommand({ "type": "tango", 
            "name": "_cmdRegulOn", "tangoname": self.tangoname, }, "regulon")
        self._cmdRegulOff = self.addCommand({ "type": "tango", 
            "name": "_cmdRegulOff", "tangoname": self.tangoname, }, "reguloff")

        self._cmdToolOpen = self.addCommand({ "type": "tango", 
            "name": "_cmdToolOpen", "tangoname": self.tangoname, }, "opentool")
        self._cmdToolClose = self.addCommand({ "type": "tango", 
            "name": "_cmdToolClose", "tangoname": self.tangoname, }, "closetool")

        # Paths
        self._cmdAbort = self.addCommand({ "type": "tango", 
            "name": "_cmdAbort", "tangoname": self.tangoname, }, "abort")
        self._cmdDry = self.addCommand({ "type": "tango", 
            "name": "_cmdDry", "tangoname": self.tangoname, }, "dry")
        self._cmdSafe = self.addCommand({ "type": "tango", 
            "name": "_cmdSafe", "tangoname": self.tangoname, }, "safe")
        self._cmdHome = self.addCommand({ "type": "tango", 
            "name": "_cmdHome", "tangoname": self.tangoname, }, "home")
        self._cmdSoak = self.addCommand({ "type": "tango", 
            "name": "_cmdSoak", "tangoname": self.tangoname, }, "soak")
        self._cmdBack = self.addCommand({ "type": "tango", 
            "name": "_cmdBack", "tangoname": self.tangoname, }, "back")
        self._cmdCalibration = self.addCommand({ "type": "tango", 
            "name": "_cmdCalibration", "tangoname": self.tangoname, }, "toolcalibration")

        self._cmdClearMemory = self.addCommand({ "type": "tango", 
            "name": "_cmdClearMemory", "tangoname": self.tangoname, }, "clear_memory")
        self._cmdReset = self.addCommand({ "type": "tango", 
            "name": "_cmdReset", "tangoname": self.tangoname, }, "reset")
        self._cmdResetParameters = self.addCommand({ "type": "tango", 
            "name": "_cmdResetParameters", "tangoname": self.tangoname, }, "reset_parameters")

        self._cmdRecoverFailure = self.addCommand({ "type": "tango", 
            "name": "_cmdRecoverFailure", "tangoname": self.tangoname, }, "recoverFailure")

        self._cmdResetMotion = self.addCommand({ "type": "tango", 
            "name": "_cmdResetMotion", "tangoname": self.tangoname, }, "resetmotion")

        self._cmdSetOnDiff = self.addCommand({ "type": "tango", 
            "name": "_cmdSetOnDiff", "tangoname": self.tangoname, }, "setondiff")
        self._cmdSetOnTool = self.addCommand({ "type": "tango", 
            "name": "_cmdSetOnTool", "tangoname": self.tangoname, }, "settool")
        self._cmdSetOnTool2 = self.addCommand({ "type": "tango", 
            "name": "_cmdSetOnTool2", "tangoname": self.tangoname, }, "settool2")

        self.state_actions = {
             "power": {"in_open": self._cmdPowerOn, "out_close": self._cmdPowerOff, 
                       "state": self._chnPowered},
        }

    def is_isara(self):
        return self.cats_model == "ISARA"

    def is_cats(self):
        return self.cats_model != "ISARA"

    def get_current_tool(self):
        current_value = self._chnCurrentTool.getValue()

        tool = TOOL_TO_STR.get(current_value, None)

        return tool

    ################################################################################

    def backTraj(self):    
        """
        Moves a sample from the gripper back into the dewar to its logged position.
        """    
        return self._executeTask(False,self._doBack)     

    def safeTraj(self):    
        """
        Safely Moves the robot arm and the gripper to the home position
        """    
        return self._executeTask(False,self._doSafe)     

    def _doAbort(self):
        """
        Launch the "abort" trajectory on the CATS Tango DS

        :returns: None
        :rtype: None
        """
        self._cmdAbort()            

    def _doHome(self):
        """
        Launch the "abort" trajectory on the CATS Tango DS

        :returns: None
        :rtype: None
        """
        tool = self.get_current_tool()
        self._cmdHome(tool)            

    def _doReset(self):
        """
        Launch the "reset" command on the CATS Tango DS

        :returns: None
        :rtype: None
        """
        logging.getLogger("HWR").debug("CatsMaint. doing reset")
        return
        self._cmdReset()

    def _doResetMemory(self):
        """
        Launch the "reset memory" command on the CATS Tango DS

        :returns: None
        :rtype: None
        """
        self._cmdClearMemory()
        time.sleep(1)
        self._cmdResetParameters()
        time.sleep(1)

    def _doResetMotion(self):
        """
        Launch the "reset_motion" command on the CATS Tango DS

        :returns: None
        :rtype: None
        """
        self._cmdResetMotion()

    def _doRecoverFailure(self):
        """
        Launch the "recoverFailure" command on the CATS Tango DS

        :returns: None
        :rtype: None
        """
        self._cmdRecoverFailure()

    def _doCalibration(self):
        """
        Launch the "toolcalibration" command on the CATS Tango DS

        :returns: None
        :rtype: None
        """
        tool = self.get_current_tool()
        self._cmdCalibration(tool)

    def _doOpenTool(self):
        """
        Launch the "opentool" command on the CATS Tango DS

        :returns: None
        :rtype: None
        """
        self._cmdOpenTool()
 
    def _doCloseTool(self):
        """
        Launch the "closetool" command on the CATS Tango DS

        :returns: None
        :rtype: None
        """
        self._cmdCloseTool()

    def _doDryGripper(self):
        """
        Launch the "dry" command on the CATS Tango DS

        :returns: None
        :rtype: None
        """
        tool = self.get_current_tool()
        self._cmdDry(tool)

    def _doSetOnDiff(self, sample):
        """
        Launch the "setondiff" command on the CATS Tango DS, an example of sample value is 2:05

        :returns: None
        :rtype: None
        """

        if sample is None:
            raise Exception ("No sample selected")
        else:
            str_tmp=str(sample)
            sample_tmp=str_tmp.split(":")
            # calculate CATS specific lid/sample number
            lid = (int(sample_tmp[0]) - 1) / 3 + 1
            puc_pos = ((int(sample_tmp[0]) - 1) % 3) * 10 + int(sample_tmp[1])
            argin = [ str(lid), str(puc_pos), "0"]
            logging.getLogger().info("to SetOnDiff %s", argin)
            self._executeServerTask(self._cmdSetOnDiff,argin)

    def _doBack(self):
        """
        Launch the "back" trajectory on the CATS Tango DS

        :returns: None
        :rtype: None
        """
        tool = self.get_current_tool()
        argin = [str(tool), "0"] # to send string array with two arg...
        self._executeServerTask(self._cmdBack, argin)

    def _doSafe(self):
        """
        Launch the "safe" trajectory on the CATS Tango DS

        :returns: None
        :rtype: None
        """
        argin = self.get_current_tool()
        self._executeServerTask(self._cmdSafe, argin)

    def _doPowerState(self, state=False):
        """
        Switch on CATS power if >state< == True, power off otherwise

        :returns: None
        :rtype: None
        """
        logging.getLogger("HWR").debug("   running power state command ")
        if state:
            self._cmdPowerOn()
        else:
            self._cmdPowerOff()

        self.do_state_action("power",state)

    def _doEnableRegulation(self):
        """
        Switch on CATS regulation

        :returns: None
        :rtype: None
        """
        self._cmdRegulOn()

    def _doDisableRegulation(self):
        """
        Switch off CATS regulation

        :returns: None
        :rtype: None
        """
        self._cmdRegulOff()

    def _doLid1State(self, state = True):
        """
        Opens lid 1 if >state< == True, closes the lid otherwise

        :returns: None
        :rtype: None
        """
        if state:
            self._executeServerTask(self._cmdOpenLid1)
        else:
            self._executeServerTask(self._cmdCloseLid1)
           
    def _doLid2State(self, state = True):
        """
        Opens lid 2 if >state< == True, closes the lid otherwise

        :returns: None
        :rtype: None
        """
        if state:
            self._executeServerTask(self._cmdOpenLid2)
        else:
            self._executeServerTask(self._cmdCloseLid2)
           
    def _doLid3State(self, state = True):
        """
        Opens lid 3 if >state< == True, closes the lid otherwise

        :returns: None
        :rtype: None
        """
        if state:
            self._executeServerTask(self._cmdOpenLid3)
        else:
            self._executeServerTask(self._cmdCloseLid3)
           
    def _doMagnetOn(self):
        self._executeServerTask(self._cmdMagnetOn)
    def _doMagnetOff(self):
        self._executeServerTask(self._cmdMagnetOff)
       
    def _doToolOpen(self):
        self._executeServerTask(self._cmdToolOpen)
    def _doToolClose(self):
        self._executeServerTask(self._cmdToolClose)

    #########################          PROTECTED          #########################        

    def _executeTask(self,wait,method,*args):        
        ret= self._run(method,wait=False,*args)
        if (wait):                        
            return ret.get()
        else:
            return ret    
        
    @task
    def _run(self,method,*args):
        exception=None
        ret=None    
        try:            
            ret=method(*args)
        except Exception as ex:        
            exception=ex
        if exception is not None:
            raise exception
        return ret

    #########################           PRIVATE           #########################        

    def _updateRunningState(self, value):
        self._running = value
        self.emit('runningStateChanged', (value, ))
        self._updateGlobalState()

    def _updatePoweredState(self, value):
        self._powered = value
        self.emit('powerStateChanged', (value, ))
        self._updateGlobalState()
    
    def _updateToolState(self,value):
        self._toolopen = value
        self.emit('toolStateChanged', (value, ))
        self._updateGlobalState()

    def _updateMessage(self, value):
        self._message = value
        self.emit('messageChanged', (value, ))
        self._updateGlobalState()

    def _updateRegulationState(self, value):
        self._regulating = value
        self.emit('regulationStateChanged', (value, ))
        self._updateGlobalState()

    def _updateBarcode(self, value):
        self._barcode = value
        self.emit('barcodeChanged', (value, ))

    def _updateState(self, value):
        self._state = value
        self._updateGlobalState()

    def _updateLid1State(self, value):
        self._lid1state = value
        self.emit('lid1StateChanged', (value, ))
        self._updateGlobalState()

    def _updateLid2State(self, value):
        self._lid2state = value
        self.emit('lid2StateChanged', (value, ))
        self._updateGlobalState()

    def _updateLid3State(self, value):
        self._lid3state = value
        self.emit('lid3StateChanged', (value, ))
        self._updateGlobalState()

    def _updateOperationMode(self, value):
        self._charging = not value

    def _updateGlobalState(self):
        state_dict, cmd_state, message = self.get_global_state()
        self.emit('globalStateChanged', (state_dict, cmd_state, message))

    def get_global_state(self):
        """
           Update clients with a global state that
           contains different: 

           - first param (state_dict):
               collection of state bits

           - second param (cmd_state):
               list of command identifiers and the
               status of each of them True/False 
               representing whether the command is 
               currently available or not

           - message
               a message describing current state information
               as a string
        """
        _ready = str(self._state) in ("READY", "ON")

        if self._running: 
            state_str = "MOVING"
        elif not (self._powered) and _ready:
            state_str = "DISABLED"
        elif _ready:
            state_str = "READY"
        else:
            state_str = str(self._state)

        state_dict = {
           "toolopen": self._toolopen,
           "powered": self._powered,
           "running": self._running,
           "regulating": self._regulating,
           "lid1": self._lid1state,
           "lid2": self._lid2state,
           "lid3": self._lid3state,
           "state": state_str,
        }


        cmd_state = {
           "powerOn": (not self._powered) and _ready, 
           "powerOff": (self._powered) and _ready,
           "regulon": (not self._regulating) and _ready,
           "openlid1": (not self._lid1state) and self._powered and _ready,
           "closelid1": self._lid1state and self._powered and _ready,
           "dry": (not self._running) and self._powered and _ready,
           "soak": (not self._running) and self._powered and _ready,
           "home": (not self._running) and self._powered and _ready,
           "back": (not self._running) and self._powered and _ready,
           "safe": (not self._running) and self._powered and _ready,
           "clear_memory": True,
           "reset": True,
           "abort": True,
        }

        message = self._message

        return state_dict, cmd_state, message

    def get_cmd_info(self):
        """ return information about existing commands for this object 
           the information is organized as a list 
           with each element contains
           [ cmd_name,  display_name, category ]
        """
        """ [cmd_id, cmd_display_name, nb_args, cmd_category, description ] """
        cmd_list = [ 
              ["Power", [
                   ["powerOn", "PowerOn", "Switch Power On"], 
                   ["powerOff", "PowerOff", "Switch Power Off"], 
                   ["regulon", "Regulation On", "Swich LN2 Regulation On"], 
                 ] 
              ], 
              ["Lid", [
                   ["openlid1", "Open Lid", "Open Lid"], 
                   ["closelid1", "Close Lid", "Close Lid"], 
                 ]
              ], 
              ["Actions",  [
                   ["home", "Home", "Actions", "Home (trajectory)"], 
                   ["dry", "Dry", "Actions", "Dry (trajectory)"], 
                   ["soak", "Soak", "Actions", "Soak (trajectory)"], 
                 ] 
              ], 
              ["Recovery",  [
                   ["clear_memory", "Clear Memory", 
                       "Clear Info in Robot Memory "
                       " (includes info about sample on Diffr)"], 
                   ["reset", "Reset Message", "Reset Cats State" ], 
                   ["back", "Back", "Reset Cats State" ], 
                   ["safe", "Safe", "Reset Cats State" ], 
                 ]
              ], 
              ["Abort", [
                    ["abort", "Abort", "Abort Execution of Command"], 
                 ]
              ], 
           ]
        return cmd_list
        
    def _executeServerTask(self, method, *args):
        task_id = method(*args)
        ret=None
        # introduced wait because it takes some time before the attribute PathRunning is set
        # after launching a transfer
        # after setting refresh in the Tango DS to 0.1 s a wait of 1s is enough
        time.sleep(1.0)
        while str(self._chnPathRunning.getValue()).lower() == 'true': 
            gevent.sleep(0.1)            
        ret = True
        return ret

    def send_command(self, cmdname, args=None):

        # 
        lid = 1
        toolcal = 0
        tool = self.get_current_tool()

        if cmdname in ["dry", "safe", "home"]:
           if tool is not None:
               args = [tool]
           else:
               raise Exception ("Cannot detect type of TOOL in Cats. Command ignored")

        if cmdname == "soak":
           if tool in [TOOL_DOUBLE, TOOL_UNIPUCK]:
               args = [str(tool), str(lid)]
           else:
               raise Exception ("Can SOAK only when UNIPUCK tool is mounted")

        if cmdname == "back":
           if tool is not None:
               args = [tool, toolcal]
           else:
               raise Exception ("Cannot detect type of TOOL in Cats. Command ignored")

        cmd = getattr(self.cats_device, cmdname)

        try:
            if args is not None:
                if len(args) > 1:
                    ret = cmd(map(str,args))
                else:
                    ret = cmd(*args)
            else:
                ret = cmd()
            return ret
        except Exception,exc:
            import traceback
            traceback.print_exc()
            msg = exc[0].desc
            raise Exception (msg)
コード例 #55
0
class EnergyScanThread(QThread):
    def __init__(self, parent, e_edge, roi_center, filenameIn):

        QThread.__init__(self)

        self.parent = parent
        self.e_edge = e_edge
        self.roi_center = roi_center
        self.filenameIn = filenameIn
        self.mrtx = DeviceProxy('i11-ma-c03/op/mono1-mt_rx')
        self.miniSteps = 1  #30
        self.integrationTime = 1.

        self.resultValues = {
            'transmissionFactor': None,
            'exposureTime': None,
            'startEnergy': None,
            'endEnergy': None,
            'beamSizeHorizontal': None,
            'beamSizeVertical': None,
            'theoreticalEdge': None,
        }

    def wait(self, device):
        while device.state().name == 'MOVING':
            time.sleep(.1)

        while device.state().name == 'RUNNING':
            time.sleep(.1)

    def run(self):
        self.result = -1
        logging.getLogger("HWR").debug('EnergyScanThread:run')
        #        	mono = SimpleDevice("i10-c-c02/op/mono1")
        #         qbpm1 = SimpleDevice("i10-c-c02/dt/xbpm_diode.1")
        #         counter = SimpleDevice("i10-c-c00/ca/bai.1144-pci.1h-cpt.1")
        #        if self.parent.BLEnergyHO is not None:
        #            self.parent.connect(self.parent.BLEnergyHO,qt.PYSIGNAL('setEnergy'),self.energyChanged)
        #             self.parent.BLEnergyHO.setEnergy(7.0)

        self.prepare4EScan()
        logging.getLogger("HWR").debug(
            'EnergyScanThread: starting Scan (fileName %s)' % self.filenameIn)
        self.scan(
            ((self.parent.counterdevice, "counter1"),
             (self.parent.xbpmdevice, "intensity")),  # sSensors
            (self.parent.monodevice, "energy"),  # sMotor
            self.e_edge - self.parent.before,  # sStart
            self.e_edge + self.parent.after,  # sEnd
            self.parent.nbsteps,  # nbSteps
            sFileName=self.filenameIn,  # sFileName 
            integrationTime=self.integrationTime /
            self.miniSteps)  #integrationTime=self.parent.integrationtime

        logging.getLogger("HWR").debug('EnergyScanThread: Scan finished %s' %
                                       str(self.result))
        self.parent.scanCommandFinished(self.result)
        self.afterScan()

    def optimizeTransmission(self):
        import XfeCollect
        logging.info('EnergyScanPX2 optimizeTransmission')
        logging.getLogger("HWR").debug('EnergyScanPX2 optimizeTransmission')
        self.xfe = XfeCollect.XfeCollect(directory='/tmp/opt_test')
        self.xfe.optimizeTransmission(self.parent.element, self.parent.edge)

    def prepare4EScan(self):
        logging.getLogger("HWR").debug('EnergyScanThread:prepare4EScan')
        self.mrtx.On()
        logging.getLogger("HWR").debug('EnergyScanThread:prepare4EScan (2)')

        self.parent.connectTangoDevices()
        if not self.parent.canScan:
            return
        # Rontec configuration
        if self.parent.fluodetdevice.State().name == "RUNNING":
            self.parent.fluodetdevice.Abort()
            while self.parent.fluodetdevice.State().name != 'STANDBY':
                pass
        #self.parent.fluodetdevice.energyMode = 1
        #time.sleep(0.5)
        #self.parent.fluodetdevice.readDataSpectrum = 0
        #time.sleep(0.5)
        #self.parent.fluodetdevice.SetSpeedAndResolutionConfiguration(0)
        #time.sleep(0.5)
        self.parent.fluodetdevice.presettype = 1
        self.parent.fluodetdevice.peakingtime = 2.5  #2.1
        self.parent.fluodetdevice.presetvalue = 0.64  #1.

        #conversion factor: 2048 channels correspond to 20,000 eV hence we have approx 10eV per channel
        #channelToeV = self.parent.fluodetdevice.dynamicRange / len(self.parent.fluodetdevice.channel00)
        channelToeV = 10.  #MS 2013-05-23

        roi_debut = 1000.0 * (self.roi_center - self.parent.roiwidth / 2.0
                              )  #values set in eV
        roi_fin = 1000.0 * (self.roi_center + self.parent.roiwidth / 2.0
                            )  #values set in eV
        print('roi_debut', roi_debut)
        print('roi_fin', roi_fin)

        channel_debut = int(roi_debut / channelToeV) + 7
        channel_fin = int(roi_fin / channelToeV) + 7
        print('channel_debut', channel_debut)
        print('channel_fin', channel_fin)

        # just for testing MS 07.03.2013, has to be removed for production
        ##### remove for production ####
        #roi_debut = 1120.
        #roi_fin = 1124.
        ##### remove for production ####

        try:
            #self.xfe.setROI(channel_debut, channel_fin)
            self.parent.fluodetdevice.SetROIs(
                numpy.array((channel_debut, channel_fin)))
            time.sleep(0.1)
        except:
            import traceback
            traceback.print_exc()
            time.sleep(1)

        self.optimizeTransmission()
        #self.parent.fluodetdevice.integrationTime = 0

        # Beamline Energy Positioning and Attenuation setting
        #self.parent.startMoveEnergy(self.e_edge - (self.parent.before - self.parent.after)/2.0)
        self.parent.startMoveEnergy(self.e_edge +
                                    (self.parent.after - self.parent.before) /
                                    2.0)

        #self.parent.attdevice.computedAttenuation = currentAtt

        # Positioning Light, BST, Rontec
        #self.parent.lightdevice.Extract()
        self.parent.md2device.write_attribute('BackLightIsOn', False)
        time.sleep(1)
        #self.parent.bstdevice.Insert()
        #self.parent.rontecinsertdevice.Insert()
        self.parent.md2device.write_attribute('FluoDetectorBack', 0)
        time.sleep(4)
        self.parent.safetyshutterdevice.Open()
        while self.parent.md2device.State(
        ).name == "MOVING" or self.parent.BLEnergydevice.State(
        ).name == "MOVING":
            time.sleep(1)

    def scan(self,
             sSensors,
             sMotor,
             sStart,
             sEnd,
             nbSteps=100,
             sStepSize=None,
             sFileName=None,
             stabilisationTime=0.1,
             interactive=False,
             wait_beamline_status=True,
             integrationTime=0.25,
             mono_mt_rx=None):

        logging.getLogger("HWR").debug('EnergyScanThread:scan')
        print('sSensors', sSensors)
        print('sMotor', sMotor)
        #self.mrtx.On()
        time.sleep(1)

        if not self.parent.canScan:
            return

        # initialising
        sData = []
        sSensorDevices = []
        sMotorDevice = sMotor[0]
        print("sStepSize:", sStepSize)

        if not sStepSize:
            sStepSize = float(sEnd - sStart) / nbSteps
            nbSteps += 1
        else:
            nbSteps = int(
                1 + ((sEnd - sStart) / sStepionTime)
            )  #__setattr__("integrationTime", integrationTime)Size))
        print("nbsteps:", nbSteps)

        print("Starting new scan using:")
        sSensorDevices = sSensors
        nbSensors = len(sSensorDevices)
        doIntegrationTime = False

        # Rechercher les sensors compteur car besoin d'integrer avant de lire la valeur
        sSensorCounters = []
        for sSensor in sSensorDevices:
            try:
                sSensor[0].__getattr__("integrationTime")
            except:
                pass
            else:
                doIntegrationTime = True
                if sSensor[0].State == "RUNNING":
                    sSennsor[0].Stop()
                sSensor[0].write_attribute(
                    "integrationTime", integrationTime
                )  #__setattr__("integrationTime", integrationTime)
                sSensorCounters.append(sSensor[0])
        print("sSensorDevices", sSensorDevices)
        print("nbSensors = ", nbSensors)
        print("Motor  = %s" % sMotorDevice.name())
        logging.debug( "Scanning %s from %f to %f by steps of %f (nsteps = %d)" % \
                    (sMotorDevice.name(),sStart, sEnd, sStepSize, nbSteps))

        t = time.localtime()
        sDate = "%02d/%02d/%d - %02d:%02d:%02d" % (t[2], t[1], t[0], t[3],
                                                   t[4], t[5])
        sTitle = 'EScan - %s ' % (sDate)

        # Parametrage du SoleilPlotBrick
        scanParameter = {}
        scanParameter['title'] = sTitle
        scanParameter['xlabel'] = "Energy in keV"
        scanParameter['ylabel'] = "Normalized counts"
        self.parent.newScan(scanParameter)

        # Pre-positioning the motor
        if not self.parent.scanning:
            return
        try:
            while str(sMotorDevice.State()) == 'MOVING':
                time.sleep(1)
            sMotorDevice.write_attribute(sMotor[1], sStart)
        except:
            print("probleme sMotor")
            self.parent.scanCommandFailed()
        # while (sMotorDevice.State == 'MOVING')

        # complete record of the collect MS 23.05.2013
        # How to represent a fluorescence emission spectra record
        # Element, Edge, DateTime, Total accumulation time per data point, Number of recordings per data point
        # DataPoints: Undulator energy, Mono energy, ROI counts, InCounts, OutCounts, Transmission, XBPM1 intensity, counts for all Channels
        #collectRecord = {}
        #time_format = "%04d-%02d-%02d - %02d:%02d:%02d"
        #DateTime = time_format % (t[0], t[1], t[2], t[3], t[4], t[5])

        #collectRecord['DateTime'] = DateTime
        #collectRecord['Edge'] = self.parent.edge
        #collectRecord['Element'] = self.parent.element
        #collectRecord['TheoreticalEdge'] = self.parent.thEdge
        #collectRecord['ROIwidth'] = self.parent.roiwidth
        #collectRecord['ROIcenter'] = self.roi_center
        #collectRecord['ROIStartsEnds'] = self.roisStartsEnds
        #collectRecord['IntegrationTime'] = integrationTime
        #collectRecord['StabilisationTime'] = stabilisationTime
        #collectRecord['Transmission'] = ''c
        #collectRecord['Filter'] = ''
        #collectRecord['DataPoints'] = {}

        # Ecriture de l'entete du fichier
        logging.debug("    energy scan thread saving data to %s " % sFileName)
        try:
            f = open(sFileName, "w")
        except:
            print("probleme ouverture fichier")
            self.parent.scanCommandFailed()
            return

        f.write("# %s\n" % (sTitle))
        f.write("# Motor  = %s\n" % sMotorDevice.name())
        # On insere les valeurs normalisees dans le deuxieme colonne
        f.write("# Normalized value\n")

        for sSensor in sSensorDevices:
            print("type(sSensor) = ", type(sSensor))
            f.write("# %s\n" % (sSensor[0].name()))

        f.write("# Counts on the fluorescence detector: all channels")
        f.write(
            "# Counts on the fluorescence detector: channels up to end of ROI")

        tDebut = time.time()

        # On ajoute un sensor pour la valeur normalisee (specifique au EScan)
        nbSensors = nbSensors + 1
        fmt_f = "%12.4e" + (nbSensors + 2) * "%12.4e" + "\n"
        _ln = 0

        channel_debut, channel_end = self.parent.fluodetdevice.roisStartsEnds
        # Entering the Scan loop
        measurement = 0
        for sI in range(
                nbSteps
        ):  #range(nbSteps): MS. 11.03.2013 lower the number for quick tests
            print('Step sI', sI, 'of', nbSteps)
            # test sur l utilisateur n a pas demande un stop
            if not self.parent.scanning:
                break
            pos_i = sStart + (sI * sStepSize)

            # positionnement du moteur
            while str(sMotorDevice.State()) == 'MOVING':
                time.sleep(1)
            sMotorDevice.write_attribute(
                sMotor[1], pos_i)  #sMotorDevice.__setattr__(sMotor[1], pos_i)

            # opening the fast shutter
            # self.parent.fastshutterdevice.Open()
            self.wait(self.parent.md2device)
            self.parent.md2device.OpenFastShutter(
            )  #write_attribute('FastShutterIsOpen', 1)

            self.parent.fast_shutter_hwo.openShutter()

            #while self.parent.md2device.read_attribute('FastShutterIsOpen') != 1:
            #time.nsleep(0.05)

            # Attente de stabilisation
            #time.sleep(stabilisationTime)

            # starting the measurement for the energy step
            #miniSteps = 3
            roiCounts = 0
            intensity = 0
            eventsInRun = 0
            eventsInRun_upToROI = 0
            for mS in range(self.miniSteps):
                measurement += 1
                self.parent.fluodetdevice.Start()
                #self.parent.counterdevice.Start()
                #time.sleep(integrationTime/self.miniSteps)
                #while self.parent.counterdevice.State().name != 'STANDBY':
                #pass
                #self.parent.fluodetdevice.Abort()
                while self.parent.fluodetdevice.State().name != 'STANDBY':
                    pass
                roiCounts += self.parent.fluodetdevice.roi00_01
                intensity += self.parent.xbpmdevice.intensity
                eventsInRun += self.parent.fluodetdevice.eventsInRun00
                #print 5*'\n'
                #print 'realTime00', self.parent.fluodetdevice.realTime00
                #print 5*'\n'
                eventsInRun_upToROI += sum(
                    self.parent.fluodetdevice.channel00[channel_end + 10:]
                )  #elastic peak normalization
                #collectRecord['DataPoints'][measurement] = {}
                #collectRecord['DataPoints'][measurement]['MonoEnergy'] = pos_i
                #collectRecord['DataPoints'][measurement]['ROICounts']  = self.parent.fluodetdevice.roi00_01

            #Lecture de la position du moteur
            pos_readed = sMotorDevice.read_attribute(
                sMotor[1]).value  #__getattr__(sMotor[1])

            # On laisse une place pour mettre la valeur normalisee (specifique au EScan)
            measures = [pos_readed, -1.0]
            print("Position: %12.4e   Measures: " % pos_readed)

            # Lecture des differents sensors
            measures.append(
                roiCounts
            )  #(self.parent.fluodetdevice.roi00_01) #eventsInRun00)
            measures.append(intensity)  #(self.parent.xbpmdevice.intensity)
            measures.append(
                eventsInRun)  #(self.parent.fluodetdevice.eventsInRun00)
            measures.append(eventsInRun_upToROI)
            # closing the fastshutter
            #self.parent.fastshutterdevice.Close()
            self.wait(self.parent.md2device)
            #self.parent.md2device.CloseFastShutter() #write_attribute('FastShutterIsOpen', 0)
            self.parent.fast_shutter_hwo.closeShutter()
            #while self.parent.md2device.read_attribute('FastShutterIsOpen') != 0:
            #time.sleep(0.05)

            # Valeur normalisee specifique au EScan
            #(Oblige an mettre le sensor compteur en premier et le xbpm en deuxieme dans le liste des sensors)
            try:
                measures[1] = measures[2] / measures[5]  #measures[3]
            except ZeroDivisionError as e:
                print(e)
                print('Please verify that the safety shutter is open.')
                measures[1] = 0.0

            # Demande de mise a jour du SoleilPlotBrick
            #if sI % 5 == 0:
            self.parent.newPoint(measures[0], measures[1])

            #Ecriture des mesures dans le fichier
            f.write(fmt_f % tuple(measures))

            _ln += 1
            if not _ln % 10:
                f.flush()  # flush the buffer every 10 lines

        # Exiting the Scan loop
        #self.parent.fastshutterdevice.Close()
        #while self.parent.fastshutterdevice.State != "CLOSE":
        #time.sleep(0.1)
        #self.parent.md2device.CloseFastShutter()
        self.parent.fast_shutter_hwo.closeShutter()
        #while self.parent.md2device.read_attribute('FastShutterIsOpen') != 0:
        #time.sleep(0.05)

        self.parent.fluodetdevice.Abort()

        self.parent.md2device.write_attribute('FluoDetectorBack', 1)
        time.sleep(2)
        #self.parent.mono_mt_rx_device.On()
        if not self.parent.scanning:
            self.result = -1
        else:
            self.result = 1

        tScanTotal = time.time() - tDebut
        print("Time taken for the scan = %.2f sec" % (tScanTotal))
        f.write("# Duration = %.2f sec\n" % (tScanTotal))
        f.close()

    def afterScan(self):
        logging.getLogger("HWR").debug('EnergyScanThread:afterScan')
        self.parent.safetyshutterdevice.Close()
        if self.parent.pk:
            self.parent.startMoveEnergy(self.parent.pk)
コード例 #56
0
 def __init__(self, connector=None, uri=None, updateInterval = 0.02):
     Motor.__init__(self)
     self.uri = uri
     self.type = "Simulation"
     attributes = {}
     attributes["AerotechEnsemble"] = [ \
             {"attr": "Position", "delta": 0.1},
             {"attr": "Velocity"},
             {"attr": "Acceleration"},
             {"attr": "SoftLimitCcw", "name": "soft_limit_min"},
             {"attr": "SoftLimitCw", "name": "soft_limit_max"},
             {"attr": "CcwSoftLimitFault", "name": "soft_limit_min_fault"},
             {"attr": "CwSoftLimitFault", "name": "soft_limit_max_fault"},
             {"attr": "CcwLimitFault", "name": "hard_limit_min_fault"},
             {"attr": "CwLimitFault", "name": "hard_limit_max_fault"},
             {"attr": "AbortMove", "name": "stop", "mode": "execute"},
             {"attr": "Calibrate", "mode": "execute"},
     ]
     attributes["GalilDMCMotor"] = [ \
             {"attr": "Position", "delta": 0.1},
             {"attr": "Velocity"},
             {"attr": "Acceleration"},
             {"attr": "SoftCcwLimit", "name": "soft_limit_min"},
             {"attr": "SoftCwLimit", "name": "soft_limit_max"},
             {"attr": "SoftCcwLimitFault", "name": "soft_limit_min_fault"},
             {"attr": "SoftCwLimitFault", "name": "soft_limit_max_fault"},
             {"attr": "Stop", "name": "stop", "mode": "execute"},
             {"attr": "Calibrate", "mode": "execute"},
     ]
     attributes["OmsMaxV"] = [ \
             {"attr": "Position", "delta": 0.1},
             {"attr": "VelocityUnits", "name": "velocity"},
             {"attr": "AccelerationUnits"},
             {"attr": "SoftLimitMinUnits", "name": "soft_limit_min"},
             {"attr": "SoftLimitMaxUnits", "name": "soft_limit_max"},
             {"attr": "FlagCcwLimit", "name": "hard_limit_min_fault"},
             {"attr": "FlagCwLimit", "name": "hard_limit_max_fault"},
             {"attr": "AbortMove", "name": "stop", "mode": "execute"},
             {"attr": "Calibrate", "mode": "execute"},
             {"attr": "PIDactive", "name": "pid_active"},
     ]
     attributes["OmsVme58"] = [ \
             {"attr": "Position"},
             {"attr": "SlewRate", "name": "velocity"},
             {"attr": "Acceleration"},
             {"attr": "UnitLimitMin", "name": "soft_limit_min"},
             {"attr": "UnitLimitMax", "name": "soft_limit_max"},
             {"attr": "CcwLimit", "name": "hard_limit_min_fault"},
             {"attr": "CwLimit", "name": "hard_limit_max_fault"},
             {"attr": "StopMove", "name": "stop", "mode": "execute"},
             {"attr": "Calibrate", "mode": "execute"},
             {"attr": "Conversion"},
     ]
     attributes["PowerPMAC_Motor"] = [ \
             {"attr": "Position", "delta": 0.1},
             {"attr": "Velocity"},
             {"attr": "Acceleration"},
             {"attr": "SoftCcwLimit", "name": "soft_limit_min"},
             {"attr": "SoftCwLimit", "name": "soft_limit_max"},
             {"attr": "SoftCcwLimitFault", "name": "soft_limit_min_fault"},
             {"attr": "SoftCwLimitFault", "name": "soft_limit_max_fault"},
             {"attr": "CcwLimitFault", "name": "hard_limit_min_fault"},
             {"attr": "CwLimitFault", "name": "hard_limit_max_fault"},
             {"attr": "Stop", "name": "stop", "mode": "execute"},
             {"attr": "Calibrate", "mode": "execute"},
     ]
     attributes["Simulation"] = [ \
             {"attr": "Position"},
             {"attr": "Velocity"},
             {"attr": "Acceleration"},
             {"attr": "Soft_Limit_Min"},
             {"attr": "Soft_Limit_Max"},
             {"attr": "Stop", "mode": "execute"},
             {"attr": "Calibrate", "mode": "execute"},
     ]
     self.connector = None
     if connector == "tango":
         try:
             proxy = DeviceProxy(uri)
             type = proxy.info().dev_class
             self.type = type
             if self.type == "GalilDMCMotor" and "CwLimitFault" in \
                     proxy.get_attribute_list():
                 attributes["GalilDMCMotor"].append(
                         {"attr": "CcwLimitFault", "name": "hard_limit_min_fault"},
                         {"attr": "CwLimitFault", "name": "hard_limit_max_fault"},
                     )
         except Exception as e:
             self.janus.utils["logger"].error(
                 "TangoMotor({}).__init__() connection failed".format(self.uri))
             self.janus.utils["logger"].debug("", exc_info=True)
         if self.type in attributes:
             self.connector = TangoConnector(uri, attributes[self.type], interval=updateInterval)
     if connector == "simulation" or self.connector is None:
         self.connector = SimulationConnector(uri, attributes["Simulation"])
         self.connector.write("state", State.ON)
         if connector != "simulation":
             self.connector.write("state", State.UNKNOWN)
         self.connector.write("position", 0)
         self.connector.write("velocity", 1000)
         self.connector.write("acceleration", 1000)
         self.connector.write("soft_limit_min", 0)
         self.connector.write("soft_limit_max", 0)
     self.last_soft_limit_min_fault = \
             self.soft_limit_min_fault(refresh=True)
     self.last_soft_limit_max_fault = \
             self.soft_limit_max_fault(refresh=True)
     self.last_state = self.connector.read("state", refresh=True)
     if self.type in ["OmsMaxV", "OmsVme58", "Simulation"]:
         self.connector.value_changed.connect(self.on_value_changed)
     else:
         self.connector.value_changed.connect(self.value_changed.emit)
コード例 #57
0
class TangoMotorZoomPX2(Device):
    
    stateDict = {
         "UNKNOWN": 0,
         "ALARM":   1,
         "FAULT":   1,
         "STANDBY": 2,
         "RUNNING": 4,
         "MOVING":  4,
         "ON": 2,
         '2':         2}


    def __init__(self, name):
        Device.__init__(self, name)
        self.GUIstep = 0.1

    def _init(self):
        
        self.MOVESTARTED = 0
        self.NOTINITIALIZED = 0
        self.UNUSABLE = 0
        self.READY = 2
        self.MOVING = 4
        self.ONLIMIT = 1

        #self.device = SimpleDevice(self.getProperty("tangoname"), verbose=False)
        #self.device.timeout = 6000 # Setting timeout to 6 sec
        self.device = DeviceProxy(self.getProperty("tangoname"))
        self.device.waitMoves = False
        logging.getLogger("HWR").info("TangoMotorZoomPX2._init of device %s" % self.device.name)
        self.setIsReady(True)
        print "TangoMotorZoomPX2._init of device %s" % self.device.name
        positionChan = self.getChannelObject("position") # utile seulement si statechan n'est pas defini dans le code
        positionChan.connectSignal("update", self.positionChanged) 
        #focus_positionChan = self.getChannelObject("focus_position")
        #focus_positionChan.connectSignal("update", self.positionChanged)
        stateChan = self.getChannelObject("state") # utile seulement si statechan n'est pas defini dans le code
        stateChan.connectSignal("update", self.motorStateChanged) 
        
        #logging.getLogger("HWR").info("%s: TangoMotorZoomPX2._init, %s", self.name(), '')
        

    def positionChanged(self, value):
        try:
            logging.getLogger("HWR").info("%s: TangoMotorZoomPX2.positionChanged: %.3f", self.name(), value)
        except:
            logging.getLogger("HWR").error("%s: TangoMotor not responding, %s", self.name(), '')
        
        self.emit('positionChanged', (value,))
    
    def isReady(self):
        #logging.getLogger("HWR").info("%s: TangoMotorZoomPX2.isReady", self.name())
        return str(self.device.State()) == 'STANDBY'
        
        
    def connectNotify(self, signal):
        #logging.getLogger("HWR").info("%s: TangoMotorZoomPX2.connectNotify, : %s", self.name(), signal)
        if signal == 'hardwareObjectName,stateChanged':
            self.motorStateChanged(TangoMotorZoomPX2.stateDict[str(self.device.State())])
        elif signal == 'limitsChanged':
            self.motorLimitsChanged()
            #print "Not implemented yet."PhiTableXAxisPosition
            
        elif signal == 'positionChanged':
            #self.motorPositionChanged(self.device.position)
            print 'MS debug 18.10.2012'
            #print self.device
            print self.device.read_attribute("ZoomLevel").value
            self.motorPositionChanged(self.device.read_attribute("ZoomLevel").value) #MS debug 18.10.2012
            
        self.setIsReady(True)
    
    def motorState(self):
        return TangoMotorZoomPX2.stateDict[str(self.device.State())]
    
    def motorStateChanged(self, state):
        #logging.getLogger("HWR").info("%s: TangoMotorZoomPX2.motorStateChanged, %s", self.name(), state)
        #self.setIsReady(state == 'STANDBY')
        self.setIsReady(True)
        #print "motorStateChanged", str(state)
        self.emit('stateChanged', (TangoMotorZoomPX2.stateDict[str(self.device.State())], ))
        
    def getState(self):
        state = str(self.device.State())
        #logging.getLogger("HWR").info("%s: TangoMotorZoomPX2.getState, %s", self.name(), state)
        return TangoMotorZoomPX2.stateDict[str(self.device.State())]
    
    def getLimits(self):
        #limits = self.device.getLimits("positiopositionChan.connectSignal("update", self.positionChanged)n")
        # MS 18.09.2012 adapted for use without SimpleDevice
        position_info = self.device.attribute_query("ZoomLevel")
        rlow  = 1 # position_info.min_value
        rhigh = 10 #position_info.max_value
        #logging.getLogger("HWR").info("TangoMotorZoomPX2.getLimits: %.4f %.4f" % limits)
        return rlow, rhigh
        
    def motorLimitsChanged(self):
        #self.emit('limitsChanged', (self.getLimits(), ))
        #logging.getLogger("HWR").info("%s: TangoMotorZoomPX2.limitsChanged", self.name())
        self.emit('limitsChanged', (self.getLimits(), )) 
                      
    def motorMoveDone(self, channelValue):
       #SpecMotorA.motorMoveDone(self, channelValue)
       #logging.getLogger("HWR").info("TangoMotorZoomPX2.motorMoveDone")
       if str(self.device.State()) == 'STANDBY':
           
          #self.emit('moveDone', (self.specversion, self.specname, ))
          self.emit('moveDone', ("EH3","toto" ))
          
    def motorPositionChanged(self, absolutePosition):
        self.emit('positionChanged', (absolutePosition, ))

    def syncQuestionAnswer(self, specSteps, controllerSteps):
        return '0' #NO ('1' means YES)
    
    def getPosition(self):
        pos = self.device.read_attribute("ZoomLevel").value #self.device.position
        #logging.getLogger("HWR").info("%s: TangoMotorZoomPX2.getPosition, pos = %.3f", self.name(), pos)
        return pos
    
    def syncMove(self, position):
        #print 'about to start moving', self.motorState
        t0 = time.time()
        prev_position =  self.getPosition()
        self.device.position = position

        print 'move started from %s to %s, state is %s' % (prev_position, position, str(self.device.State()))
        
        while str(self.device.State()) == "RUNNING" or str(self.device.State()) == "MOVING": # or str(self.device.State()) == SpecMotor.MOVESTARTED:
            #print 'processing events...', self.motorState
            qApp.processEvents(100)

        print 'move done (%s s), state is %s' % (time.time()-t0,  str(self.device.State()))
        
    def moveRelative(self, position):
        old_pos = self.device.position
        self.device.position = old_pos + position
        #self.moveRelahardwareObjectName,tive(position)

        while str(self.device.State()) == "RUNNING" or str(self.device.State()) == "MOVING":
            qApp.processEvents(100)
        
    def syncMoveRelative(self, position):
        old_pos = self.device.position
        self.device.position = old_pos + position
        #self.moveRelahardwareObjectName,tive(position)

        while str(self.device.State()) == "RUNNING" or str(self.device.State()) == "MOVING":
            qApp.processEvents(100)
        

    def getMotorMnemonic(self):
        return self.specName

    def move(self, absolutePosition):
        """Move the motor to the required position

        Arguments:
        absolutePosition -- position to move to
        """
        if type(absolutePosition) != float and type(absolutePosition) != int:
            logging.getLogger("TangoClient").error("Cannot move %s: position '%s' is not a number", self.device.name, absolutePosition)
            
        #self.__changeMotorState(MOVESTARTED)

        #c = self.connection.getChannel(self.chanNamePrefix % 'start_one')
        logging.getLogger("HWR").info("TangoMotorZoomPX2.move to absolute position: %.3f" % absolutePosition)
        self.device.position = absolutePosition
        
    def stop(self):
        logging.getLogger("HWR").info("TangoMotorZoomPX2.stop")
        self.device.Stop()

    def isSpecConnected(self):
        logging.getLogger().debug("%s: TangoMotorZoomPX2.isSpecConnected()" % self.name())
        return TruehardwareObjectName,
import sys
import time
import contextlib
import numpy as np
from PyTango import DeviceProxy

dev_name = 'id00/slsdetector/eiger500k'

if len(sys.argv) > 1:
    dev_name = sys.argv[1]

eiger_dev = DeviceProxy(dev_name)
data = []

ref = eiger_dev.fpga_frame_ptr_diff
nb_hosts = len(ref)
zeros = np.zeros((nb_hosts, ), 'uint32')
if (ref != zeros).any():
    raise RuntimeError(f'Invalid reference: {ref}')

max_val = np.array(zeros)
max_i = np.array(zeros)
t0 = None
print('Ready')
while True:
    i = len(data)
    d = eiger_dev.fpga_frame_ptr_diff
    d > max_val
    if (d != ref).all():
        t = time.time()
        if t0 is None:
コード例 #59
0
class AttenuatorsPX2(Device):
    stateAttenuator = {'ALARM' : 0,'EXTRACT' : 1,'INSERT' : 1,'UNKNOWN' : 3, 'ALARM' : 'error','OFF' : 'error', 'RUNNING' : 'moving','MOVING' : 'moving', 'STANDBY' : 'ready', 'UNKNOWN': 'changed', 'EXTRACT': 'outlimits'}
    
    def __init__(self, name):
        Device.__init__(self, name)

        self.labels  = []
        self.bits    = []
        self.attno   = 0
        self.deviceOk = True
        self.NumToLabel = {}
        

    def init(self):
        #cmdToggle = self.getCommandObject('toggle')
        #cmdToggle.connectSignal('connected', self.connected)
        #cmdToggle.connectSignal('disconnected', self.disconnected)
        
        # Connect to device Attenuator defined "tangoname" in the xml file 
        try :
            #self.Attenuatordevice = SimpleDevice(self.getProperty("tangoname"), verbose=False)
            self.Attenuatordevice = DeviceProxy(self.getProperty("tangoname"))
            self.Attenuatordevice.waitMoves = False
            self.Attenuatordevice.timeout = 5000

        except :
            self.errorDeviceInstance(self.getProperty("tangoname"))

        if self.deviceOk:
            #self.connected()
            #self.chanAttState = self.getChannelObject('State')
            #print "self.chanAttState : ", self.chanAttState
            #self.chanAttState.connectSignal('update', self.attStateChanged)
            ##self.chanAttFactor = self.getChannelObject('appliedTransmission')
            ##self.chanAttFactor = self.getChannelObject('computedTransmission')
            ##self.chanAttFactor.connectSignal('update', self.attFactorChanged)
            
            ##self.chanAttToggle = self.getChannelObject('filtersCombination')
            ##self.chanAttToggle.connectSignal('update', self.attToggleChanged)
            
            #self.getAtteConfig()
            
            self.connected()
            self.chanAttState = self.getChannelObject('State')
            print "self.chanAttState : ", self.chanAttState
            self.chanAttState.connectSignal('update', self.attStateChanged)
            #self.chanAttFactor = self.getChannelObject('appliedTransmission')
            
            self.chanAttFactor = self.getChannelObject('Status')
            self.chanAttFactor.connectSignal('update', self.attFactorChanged)
            
            self.chanAttToggle = self.getChannelObject('State')
            self.chanAttToggle.connectSignal('update', self.attToggleChanged)
            
            self.getAtteConfig()
            
        logging.getLogger().debug("AttenuatorsPX2: self.labels, self.bits, self.attno, %s, %s, %s" %( self.labels, self.bits, self.attno))
        
    def getAtteConfig(self):
        pass

    def getAtteConfig_OLD(self):
        logging.getLogger().debug("HOS Attenuator: passe dans getAtteConfig")
        self.attno = len( self['atte'] )

        for att_i in range( self.attno ):
           obj = self['atte'][att_i]
           self.labels.append( obj.label )
           self.bits.append( obj.bits )
        self.NumToLabel = dict([(int(l.split()[0]), l) for l in self.labels])
        
    def getAttState(self):
        logging.getLogger().debug("HOS Attenuator: passe dans getAttState")
        logging.getLogger().debug("Attenuator state read from the device %s",self.Attenuatordevice.State().name)
        try:
            #print "HEYO", self.Attenuatordevice.StatefiltersCombination
            print self.Attenuatordevice.Status()
            value= AttenuatorsPX2.stateAttenuator[self.Attenuatordevice.State().name]
        except:
            logging.getLogger("HWR").error('%s: received value on channel is not a integer value', str(self.name()))
            value=None
        return value

    def getAttFactor(self):
        logging.getLogger().debug("HOS Attenuator: passe dans getAttFactor")
        print 'self.Attenuatordevice.Status()', self.Attenuatordevice.Status() 
        try:
            #value = float(self.Attenuatordevice.appliedTransmission)
            status = self.Attenuatordevice.Status()
            status = status[:status.index(':')]
            print 'status', status
            value = status #self.Attenuatordevice.Status() #1. #float(self.Attenuatordevice.computedTransmission)
        except:
            logging.getLogger("HWR").error('%s: received value on channel is not a float value', str(self.name()))
            value=None
        return value

    def connected(self):
        self.setIsReady(True)
 
    def disconnected(self):
        self.setIsReady(False)

    def attStateChanged(self, channelValue):
        logging.getLogger("HWR").debug("%s: AttenuatorsPX2.attStateChanged: %s", self.name(), channelValue)
        self.emit('attStateChanged', (AttenuatorsPX2.stateAttenuator[str(channelValue)], ))

    def attFactorChanged(self, channelValue):
        print 'attFactorChanged', channelValue
        print 'self.Attenuatordevice.Status()', self.Attenuatordevice.Status()
        try:
            status = self.Attenuatordevice.Status()
            status = status[:status.index(':')]
            print 'status', status
            value = status
            #value = float(channelValue)
        except:
            logging.getLogger("HWR").error('%s: received value on channel is not a float value', str(self.name()))
        else:
            logging.getLogger("HWR").info('%s: AttenuatorsPX2, received value on channel', str(self.name()))
            self.emit('attFactorChanged', (value, )) 
    
    def attToggleChanged(self, channelValue):
#        print "Dans attToggleChanged  channelValue = %s" %channelValue
        logging.getLogger().debug("HOS Attenuator: passe dans attToggleChanged")
        try:
            value = int(channelValue)
        except:
            logging.getLogger("HWR").error('%s: received value on channel is not a float value', str(self.name()))
        else:
            self.emit('toggleFilter', (value, )) 
            
    def setTransmission(self, value) :
        logging.getLogger("HWR").debug("%s: AttenuatorsPX2.setTransmission: %s", self.name(), value)
        print value
        self.Attenuatordevice.write_attribute(self.NumToLabel[value], True) #.computedAttenuation = 1.0/(value/100.0)
        #try:
            #self.Attenuatordevice.write_attribute(value, True) #.computedAttenuation = 1.0/(value/100.0)
        #except:
            #logging.getLogger("HWR").error('%s: received value on channel is not valid', str(self.name()))
            #value=None
        return value
        
    def toggle(self, value) :
        print "Toggle value = %s" %value
        logging.getLogger().debug("HOS Attenuator: passe dans toggle")
        self.Attenuatordevice.write_attribute(value, True)
        
#        old_value = self.Attenuatordevice.filtersCombination       
#        try:
#            self.Attenuatordevice.filtersCombination = old_value "sys/database/dbds1")+ (2**(value-1))
#        except:
#            logging.getLogger("HWR").error('%s: the filter doesn\'t exist', str(self.name()))
#            value=None
        return value
                          
            
    def errorDeviceInstance(self,device) :
        #db = SimpleDevice("sys/database/dbds1")
        db = DeviceProxy("sys/database/dbds1")
        logging.getLogger().error("Check Instance of Device server %s" % db.DbGetDeviceInfo(device)[1][3])
        self.sDisconnected()
コード例 #60
0
    def init(self):
        AbstractDetector.init(self)

        lima_device = self.get_property("lima_device")
        pilatus_device = self.get_property("pilatus_device")

        if None in (lima_device, pilatus_device):
            return

        try:
            for channel_name in (
                    "latency_time",
                    "acq_status",
                    "acq_trigger_mode",
                    "saving_mode",
                    "acq_nb_frames",
                    "acq_expo_time",
                    "saving_directory",
                    "saving_prefix",
                    "saving_suffix",
                    "saving_next_number",
                    "saving_index_format",
                    "saving_format",
                    "saving_overwrite_policy",
                    "saving_header_delimiter",
                    "last_image_saved",
                    "image_roi",
            ):
                self.add_channel(
                    {
                        "type": "tango",
                        "name": channel_name,
                        "tangoname": lima_device
                    },
                    channel_name,
                )

            for channel_name in ("fill_mode", "threshold"):
                self.add_channel(
                    {
                        "type": "tango",
                        "name": channel_name,
                        "tangoname": pilatus_device,
                    },
                    channel_name,
                )

            pilatus_tg_device = DeviceProxy(pilatus_device)

            if hasattr(pilatus_tg_device, "working_energy"):
                self.add_channel(
                    {
                        "type": "tango",
                        "name": "working_energy",
                        "tangoname": pilatus_device,
                    },
                    "working_energy",
                )
            self.add_channel(
                {
                    "type": "tango",
                    "name": "energy_threshold",
                    "tangoname": pilatus_device,
                },
                "energy_threshold",
            )

            self.add_command(
                {
                    "type": "tango",
                    "name": "prepare_acq",
                    "tangoname": lima_device
                },
                "prepareAcq",
            )
            self.add_command(
                {
                    "type": "tango",
                    "name": "start_acq",
                    "tangoname": lima_device
                },
                "startAcq",
            )
            self.add_command(
                {
                    "type": "tango",
                    "name": "stop_acq",
                    "tangoname": lima_device
                },
                "stopAcq",
            )
            self.add_command(
                {
                    "type": "tango",
                    "name": "reset",
                    "tangoname": lima_device
                }, "reset")
            self.add_command(
                {
                    "type": "tango",
                    "name": "set_image_header",
                    "tangoname": lima_device
                },
                "SetImageHeader",
            )

            self.get_channel_object("image_roi").connect_signal(
                "update", self.roi_mode_changed)

            self.get_command_object("prepare_acq").setDeviceTimeout(10000)

        except ConnectionError:
            self.update_state(HardwareObjectState.FAULT)
            logging.getLogger("HWR").error("Could not connect to detector %s" %
                                           lima_device)