class WebBrowseBrick(Core.BaseBrick): properties = {"url": Property("string", "URL", "", "urlChanged")} connections = { "login": Connection("Login object", [Signal("loggedIn", "loggedIn")], [], "connectionToLogin") } signals = [] slots = [Slot("setURL")] def __init__(self, *args, **kargs): Core.BaseBrick.__init__(self, *args, **kargs) def init(self): self.webViewer = QWebView() self.urlBlank = "about:blank" mainLayout = Qt.QHBoxLayout(self.brick_widget) mainLayout.addWidget(self.webViewer) self.brick_widget.setLayout(mainLayout) self.brick_widget.setStyleSheet("border:1px solid;") self.brick_widget.setSizePolicy(Qt.QSizePolicy.Expanding, Qt.QSizePolicy.Expanding) def urlChanged(self, url): self.urlConfig = url def setUrl(self, url): #TODO:DEBUG print "got url %s" % url self.urlConfig = url # When connected to Login, then block the brick def connectionToLogin(self, pPeer): if pPeer is not None: self.brick_widget.setEnabled(False) self.webViewer.load(QUrl(self.urlBlank)) # Logged In : True or False def loggedIn(self, pValue): self.brick_widget.setEnabled(pValue) if pValue: self.webViewer.load(QUrl(self.urlConfig)) else: self.webViewer.load(QUrl(self.urlBlank))
class BsxVideoBrick(Core.BaseBrick): properties = {} connections = { "samplechanger": Connection("Sample Changer object", [], [], "sample_changer_connected") } def __init__(self, *args, **kargs): Core.BaseBrick.__init__(self, *args, **kargs) def init(self): self._sampleChanger = None mainLayout = Qt.QHBoxLayout(self.brick_widget) self.videoWidget = BsxVideoWidget(self.brick_widget) mainLayout.addWidget(self.videoWidget) self.brick_widget.setLayout(mainLayout) def exceptionCallback(self, exception): pass #logger.info("EXCEPTION:%r", exception) def sample_changer_connected(self, sc): if sc is not None: logger.info("Sample changer VIDEO connected") self._sampleChanger = sc self.videoWidget.setAutoRefreshRate(50) #TODO: Make a callback setting #self.videoWidget.setCallbacks(new_image=self._sampleChanger.getImageJPG, # get_liquid_pos=) # override videoWidget calls self.videoWidget.getNewImage = self._sampleChanger.getImageJPG self.videoWidget.getCurrentLiquidPosition = self._sampleChanger.getCurrentLiquidPosition self.videoWidget.getCurrentBeamLocation = self._sampleChanger.getBeamLocation self.videoWidget.setBeamLocation = self._sampleChanger.setBeamLocation self.videoWidget.exceptionCallback = self.exceptionCallback self.videoWidget.setAutoRefresh(True) else: logger.info("Sample changer VIDEO NOT connected") self.videoWidget.setAutoRefresh(False)
class MotorAlignmentBrick( Core.BaseBrick ): properties = {"caption": Property( "string", "Caption", "", "captionChanged" ), "toolTip": Property( "string", "Tool tip", "", "toolTipChanged" ), "expertModeOnly": Property( "boolean", "Expert mode only", "", "expertModeOnlyChanged", False )} connections = {"motoralignment": Connection( "MotorAlignment object", [Signal( "motorPositionChanged", "motorPositionChanged" )], [Slot( "moveMotor" ), Slot( "getMotorPosition" ), Slot( "getMotorsList" )], "connectedToMotorAlignment" )} signals = [Signal( "executeTestCollect" )] slots = [] def motorPositionChanged( self, pValue ): if self.__motorAlignmentDialog is not None: self.__motorAlignmentDialog.setMotorPosition( pValue ) def expert_mode( self, expert ): self.__expertMode = expert flag = ( not self.__expertModeOnly or self.__expertMode ) self.motorAlignmentPushButton.setEnabled( flag ) if not flag and self.__motorAlignmentDialog is not None: self.__motorAlignmentDialog.close() def __init__( self, *args, **kargs ): Core.BaseBrick.__init__( self, *args, **kargs ) def init( self ): self.__toolTip = "" self.__motorAlignmentDialog = None self.__expertModeOnly = False self.__expertMode = False self.brick_widget.setLayout( Qt.QVBoxLayout() ) self.motorAlignmentPushButton = Qt.QPushButton( self.brick_widget ) Qt.QObject.connect( self.motorAlignmentPushButton, Qt.SIGNAL( "clicked()" ), self.motorAlignmentPushButtonClicked ) self.brick_widget.layout().addWidget( self.motorAlignmentPushButton ) def delete( self ): pass def connectedToMotorAlignment( self, pValue ): pass def captionChanged( self, pValue ): self.motorAlignmentPushButton.setText( pValue ) def toolTipChanged( self, pValue ): self.motorAlignmentPushButton.setToolTip( pValue ) def expertModeOnlyChanged( self, pValue ): self.__expertModeOnly = pValue self.expert_mode( self.__expertMode ) def motorAlignmentPushButtonClicked( self ): if self.__motorAlignmentDialog is not None and self.__motorAlignmentDialog.isVisible(): self.__motorAlignmentDialog.activateWindow() self.__motorAlignmentDialog.raise_() else: motorsList = self.getObject( "motoralignment" ).getMotorsList() if motorsList is None: Qt.QMessageBox.information( self.brick_widget, "Info", "There are no motors specified!" ) else: logger.debug( 'MotorAlignmentBrick: got motor list %s', motorsList ) self.__motorAlignmentDialog = MotorAlignmentDialog( self, motorsList ) self.__motorAlignmentDialog.show()
class ReprocessBrick( Core.BaseBrick ): properties = {} connections = {"reprocess": Connection( "Reprocess object", [Signal( "reprocessDirectoryChanged", "reprocessDirectoryChanged" ), Signal( "reprocessPrefixChanged", "reprocessPrefixChanged" ), Signal( "reprocessRunNumberChanged", "reprocessRunNumberChanged" ), Signal( "reprocessFrameFirstChanged", "reprocessFrameFirstChanged" ), Signal( "reprocessFrameLastChanged", "reprocessFrameLastChanged" ), Signal( "reprocessConcentrationChanged", "reprocessConcentrationChanged" ), Signal( "reprocessCommentsChanged", "reprocessCommentsChanged" ), Signal( "reprocessCodeChanged", "reprocessCodeChanged" ), Signal( "reprocessMaskFileChanged", "reprocessMaskFileChanged" ), Signal( "reprocessDetectorDistanceChanged", "reprocessDetectorDistanceChanged" ), Signal( "reprocessWaveLengthChanged", "reprocessWaveLengthChanged" ), Signal( "reprocessPixelSizeXChanged", "reprocessPixelSizeXChanged" ), Signal( "reprocessPixelSizeYChanged", "reprocessPixelSizeYChanged" ), Signal( "reprocessBeamCenterXChanged", "reprocessBeamCenterXChanged" ), Signal( "reprocessBeamCenterYChanged", "reprocessBeamCenterYChanged" ), Signal( "reprocessNormalisationChanged", "reprocessNormalisationChanged" ), Signal( "reprocessBeamStopDiodeChanged", "reprocessBeamStopDiodeChanged" ), Signal( "reprocessMachineCurrentChanged", "reprocessMachineCurrentChanged" ), Signal( "reprocessKeepOriginalChanged", "reprocessKeepOriginalChanged" ), Signal( "reprocessStatusChanged", "reprocessStatusChanged" )], [Slot( "reprocess" )], "connectionStatusChanged" )} signals = [Signal( "displayResetChanged" ), Signal( "displayItemChanged" )] slots = [] def reprocessDirectoryChanged( self, pValue ): self.directoryLineEdit.setText( pValue ) def reprocessPrefixChanged( self, pValue ): for i in range( 0, self.prefixComboBox.count() ): if pValue == self.prefixComboBox.itemText( i ): self.prefixComboBox.setCurrentIndex( i ) break self.populateRunNumberListWidget() self.populateFrameComboBox() self.__validParameters[1] = self.prefixComboBox.currentIndex() > 0 def reprocessRunNumberChanged( self, pValue ): pass def reprocessFrameFirstChanged( self, pValue ): pass def reprocessFrameLastChanged( self, pValue ): pass def reprocessConcentrationChanged( self, pValue ): if pValue != "": self.concentrationDoubleSpinBox.setValue( float( pValue ) ) def reprocessCommentsChanged( self, pValue ): self.commentsLineEdit.setText( pValue ) def reprocessCodeChanged( self, pValue ): self.codeLineEdit.setText( pValue ) def reprocessMaskFileChanged( self, pValue ): self.maskLineEdit.setText( pValue ) def reprocessDetectorDistanceChanged( self, pValue ): if pValue != "": self.detectorDistanceDoubleSpinBox.setValue( float( pValue ) ) def reprocessWaveLengthChanged( self, pValue ): if pValue != "": self.waveLengthDoubleSpinBox.setValue( float( pValue ) ) def reprocessPixelSizeXChanged( self, pValue ): if pValue != "": self.pixelSizeXDoubleSpinBox.setValue( float( pValue ) ) def reprocessPixelSizeYChanged( self, pValue ): if pValue != "": self.pixelSizeYDoubleSpinBox.setValue( float( pValue ) ) def reprocessBeamCenterXChanged( self, pValue ): self.beamCenterXSpinBox.setValue( int( pValue ) ) def reprocessBeamCenterYChanged( self, pValue ): if pValue != "": self.beamCenterYSpinBox.setValue( int( pValue ) ) def reprocessNormalisationChanged( self, pValue ): if pValue != "": self.normalisationDoubleSpinBox.setValue( float( pValue ) ) def reprocessBeamStopDiodeChanged( self, pValue ): if pValue != "": self.beamStopDiodeDoubleSpinBox.setValue( float( pValue ) ) def reprocessMachineCurrentChanged( self, pValue ): if pValue != "": self.machineCurrentDoubleSpinBox.setValue( float( pValue ) ) def reprocessKeepOriginalChanged( self, pValue ): self.keepOriginalCheckBox.setChecked( pValue == "1" ) def reprocessStatusChanged( self, pValue ): #TODO: Understand if self.__isReprocessing: messageList = pValue.split( ",", 3 ) if messageList[0] == "0": # reprocess done self.SPECBusyTimer.stop() self.__isReprocessing = False self.setButtonState( 0 ) logger.info( messageList[1] ) if self.notifyCheckBox.isChecked(): Qt.QMessageBox.information( self.brick_widget, "Info", "\n %s \n" % messageList[1] ) elif messageList[0] == "1": # reprocess info self.SPECBusyTimer.start( 25000 ) logger.info( messageList[1] ) elif messageList[0] == "2": # reprocess info with item to be displayed self.SPECBusyTimer.start( 25000 ) logger.info( messageList[1] ) self.emit( "displayItemChanged", messageList[2] ) elif messageList[0] == "3": # reprocess warning logger.warning( messageList[1] ) elif messageList[0] == "4": # reprocess error self.SPECBusyTimer.stop() self.__isReprocessing = False self.setButtonState( 0 ) logger.error( messageList[1] ) def connectionStatusChanged( self, pPeer ): pass def __init__( self, *args, **kargs ): Core.BaseBrick.__init__( self, *args, **kargs ) def init( self ): self.__expertMode = False self.__isReprocessing = False self.__validParameters = [False, False, False, False, False] self.brick_widget.setLayout( Qt.QVBoxLayout() ) self.hBoxLayout2 = Qt.QHBoxLayout() self.directoryLabel = Qt.QLabel( "Directory", self.brick_widget ) self.directoryLabel.setFixedWidth( 130 ) self.hBoxLayout2.addWidget( self.directoryLabel ) self.directoryLineEdit = Qt.QLineEdit( self.brick_widget ) self.directoryLineEdit.setMaxLength( 100 ) Qt.QObject.connect( self.directoryLineEdit, Qt.SIGNAL( "textChanged(const QString &)" ), self.directoryLineEditChanged ) self.hBoxLayout2.addWidget( self.directoryLineEdit ) self.directoryPushButton = Qt.QPushButton( "...", self.brick_widget ) self.directoryPushButton.setFixedWidth( 25 ) Qt.QObject.connect( self.directoryPushButton, Qt.SIGNAL( "clicked()" ), self.directoryPushButtonClicked ) self.hBoxLayout2.addWidget( self.directoryPushButton ) self.brick_widget.layout().addLayout( self.hBoxLayout2 ) self.hBoxLayout3 = Qt.QHBoxLayout() self.directoryLabel = Qt.QLabel( "Prefix", self.brick_widget ) self.directoryLabel.setFixedWidth( 130 ) self.hBoxLayout3.addWidget( self.directoryLabel ) self.prefixComboBox = Qt.QComboBox( self.brick_widget ) Qt.QObject.connect( self.prefixComboBox, Qt.SIGNAL( "currentIndexChanged(int)" ), self.prefixComboBoxChanged ) self.hBoxLayout3.addWidget( self.prefixComboBox ) self.brick_widget.layout().addLayout( self.hBoxLayout3 ) self.hBoxLayout4 = Qt.QHBoxLayout() self.runNumberLabel = Qt.QLabel( "Run #", self.brick_widget ) self.runNumberLabel.setFixedWidth( 130 ) self.hBoxLayout4.addWidget( self.runNumberLabel ) self.runNumberListWidget = Qt.QListWidget( self.brick_widget ) self.runNumberListWidget.setSelectionMode( QtGui.QAbstractItemView.ExtendedSelection ) Qt.QObject.connect( self.runNumberListWidget, Qt.SIGNAL( "itemSelectionChanged()" ), self.runNumberListWidgetChanged ) self.hBoxLayout4.addWidget( self.runNumberListWidget ) self.brick_widget.layout().addLayout( self.hBoxLayout4 ) self.hBoxLayout5 = Qt.QHBoxLayout() self.frameLabel = Qt.QLabel( "Frame (first, last)", self.brick_widget ) self.frameLabel.setFixedWidth( 130 ) self.hBoxLayout5.addWidget( self.frameLabel ) self.frameFirstComboBox = Qt.QComboBox( self.brick_widget ) Qt.QObject.connect( self.frameFirstComboBox, Qt.SIGNAL( "currentIndexChanged(int)" ), self.frameFirstComboBoxChanged ) self.hBoxLayout5.addWidget( self.frameFirstComboBox ) self.frameLastComboBox = Qt.QComboBox( self.brick_widget ) Qt.QObject.connect( self.frameLastComboBox, Qt.SIGNAL( "currentIndexChanged(int)" ), self.frameLastComboBoxChanged ) self.hBoxLayout5.addWidget( self.frameLastComboBox ) self.brick_widget.layout().addLayout( self.hBoxLayout5 ) self.hBoxLayout6 = Qt.QHBoxLayout() self.concentrationCheckBox = Qt.QCheckBox( "Concentration", self.brick_widget ) self.concentrationCheckBox.setFixedWidth( 130 ) Qt.QObject.connect( self.concentrationCheckBox, Qt.SIGNAL( "toggled(bool)" ), self.concentrationCheckBoxToggled ) self.hBoxLayout6.addWidget( self.concentrationCheckBox ) self.concentrationDoubleSpinBox = Qt.QDoubleSpinBox( self.brick_widget ) self.concentrationDoubleSpinBox.setSuffix( " mg/ml" ) self.concentrationDoubleSpinBox.setDecimals( 2 ) self.concentrationDoubleSpinBox.setRange( 0, 100 ) self.hBoxLayout6.addWidget( self.concentrationDoubleSpinBox ) self.brick_widget.layout().addLayout( self.hBoxLayout6 ) self.hBoxLayout7 = Qt.QHBoxLayout() self.commentsCheckBox = Qt.QCheckBox( "Comments", self.brick_widget ) self.commentsCheckBox.setFixedWidth( 130 ) Qt.QObject.connect( self.commentsCheckBox, Qt.SIGNAL( "toggled(bool)" ), self.commentsCheckBoxToggled ) self.hBoxLayout7.addWidget( self.commentsCheckBox ) self.commentsLineEdit = Qt.QLineEdit( self.brick_widget ) self.commentsLineEdit.setMaxLength( 100 ) self.commentsLineEdit.setValidator( Qt.QRegExpValidator( Qt.QRegExp( "[a-zA-Z0-9\\%/()=+*^:.\-_ ]*" ), self.commentsLineEdit ) ) self.hBoxLayout7.addWidget( self.commentsLineEdit ) self.brick_widget.layout().addLayout( self.hBoxLayout7 ) self.hBoxLayout8 = Qt.QHBoxLayout() self.codeCheckBox = Qt.QCheckBox( "Code", self.brick_widget ) self.codeCheckBox.setFixedWidth( 130 ) Qt.QObject.connect( self.codeCheckBox, Qt.SIGNAL( "toggled(bool)" ), self.codeCheckBoxToggled ) self.hBoxLayout8.addWidget( self.codeCheckBox ) self.codeLineEdit = Qt.QLineEdit( self.brick_widget ) self.codeLineEdit.setMaxLength( 30 ) self.codeLineEdit.setValidator( Qt.QRegExpValidator( Qt.QRegExp( "^[a-zA-Z][a-zA-Z0-9_]*" ), self.codeLineEdit ) ) self.hBoxLayout8.addWidget( self.codeLineEdit ) self.brick_widget.layout().addLayout( self.hBoxLayout8 ) self.hBoxLayout9 = Qt.QHBoxLayout() self.maskCheckBox = Qt.QCheckBox( "Mask", self.brick_widget ) self.maskCheckBox.setFixedWidth( 130 ) Qt.QObject.connect( self.maskCheckBox, Qt.SIGNAL( "toggled(bool)" ), self.maskCheckBoxToggled ) self.hBoxLayout9.addWidget( self.maskCheckBox ) self.maskLineEdit = Qt.QLineEdit( self.brick_widget ) self.maskLineEdit.setMaxLength( 100 ) Qt.QObject.connect( self.maskLineEdit, Qt.SIGNAL( "textChanged(const QString &)" ), self.maskLineEditChanged ) self.hBoxLayout9.addWidget( self.maskLineEdit ) self.maskDirectoryPushButton = Qt.QPushButton( "...", self.brick_widget ) self.maskDirectoryPushButton.setFixedWidth( 25 ) Qt.QObject.connect( self.maskDirectoryPushButton, Qt.SIGNAL( "clicked()" ), self.maskDirectoryPushButtonClicked ) self.hBoxLayout9.addWidget( self.maskDirectoryPushButton ) self.maskDisplayPushButton = Qt.QPushButton( "Display", self.brick_widget ) self.maskDisplayPushButton.setFixedWidth( 55 ) Qt.QObject.connect( self.maskDisplayPushButton, Qt.SIGNAL( "clicked()" ), self.maskDisplayPushButtonClicked ) self.hBoxLayout9.addWidget( self.maskDisplayPushButton ) self.brick_widget.layout().addLayout( self.hBoxLayout9 ) self.hBoxLayout10 = Qt.QHBoxLayout() self.detectorDistanceCheckBox = Qt.QCheckBox( "Detector distance", self.brick_widget ) self.detectorDistanceCheckBox.setFixedWidth( 130 ) Qt.QObject.connect( self.detectorDistanceCheckBox, Qt.SIGNAL( "toggled(bool)" ), self.detectorDistanceCheckBoxToggled ) self.hBoxLayout10.addWidget( self.detectorDistanceCheckBox ) self.detectorDistanceDoubleSpinBox = Qt.QDoubleSpinBox( self.brick_widget ) self.detectorDistanceDoubleSpinBox.setSuffix( " m" ) self.detectorDistanceDoubleSpinBox.setDecimals( 3 ) self.detectorDistanceDoubleSpinBox.setRange( 0.1, 10 ) self.hBoxLayout10.addWidget( self.detectorDistanceDoubleSpinBox ) self.brick_widget.layout().addLayout( self.hBoxLayout10 ) self.hBoxLayout11 = Qt.QHBoxLayout() self.waveLengthCheckBox = Qt.QCheckBox( "Wave length", self.brick_widget ) self.waveLengthCheckBox.setFixedWidth( 130 ) Qt.QObject.connect( self.waveLengthCheckBox, Qt.SIGNAL( "toggled(bool)" ), self.waveLengthCheckBoxToggled ) self.hBoxLayout11.addWidget( self.waveLengthCheckBox ) self.waveLengthDoubleSpinBox = Qt.QDoubleSpinBox( self.brick_widget ) self.waveLengthDoubleSpinBox.setSuffix( " nm" ) self.waveLengthDoubleSpinBox.setDecimals( 4 ) self.waveLengthDoubleSpinBox.setRange( 0.01, 1 ) self.hBoxLayout11.addWidget( self.waveLengthDoubleSpinBox ) self.brick_widget.layout().addLayout( self.hBoxLayout11 ) self.hBoxLayout12 = Qt.QHBoxLayout() self.pixelSizeCheckBox = Qt.QCheckBox( "Pixel size (x, y)", self.brick_widget ) self.pixelSizeCheckBox.setFixedWidth( 130 ) Qt.QObject.connect( self.pixelSizeCheckBox, Qt.SIGNAL( "toggled(bool)" ), self.pixelSizeCheckBoxToggled ) self.hBoxLayout12.addWidget( self.pixelSizeCheckBox ) self.pixelSizeXDoubleSpinBox = Qt.QDoubleSpinBox( self.brick_widget ) self.pixelSizeXDoubleSpinBox.setSuffix( " um" ) self.pixelSizeXDoubleSpinBox.setDecimals( 1 ) self.pixelSizeXDoubleSpinBox.setRange( 10, 500 ) self.hBoxLayout12.addWidget( self.pixelSizeXDoubleSpinBox ) self.pixelSizeYDoubleSpinBox = Qt.QDoubleSpinBox( self.brick_widget ) self.pixelSizeYDoubleSpinBox.setSuffix( " um" ) self.pixelSizeYDoubleSpinBox.setDecimals( 1 ) self.pixelSizeYDoubleSpinBox.setRange( 10, 500 ) self.hBoxLayout12.addWidget( self.pixelSizeYDoubleSpinBox ) self.brick_widget.layout().addLayout( self.hBoxLayout12 ) self.hBoxLayout13 = Qt.QHBoxLayout() self.beamCenterCheckBox = Qt.QCheckBox( "Beam center (x, y)", self.brick_widget ) self.beamCenterCheckBox.setFixedWidth( 130 ) Qt.QObject.connect( self.beamCenterCheckBox, Qt.SIGNAL( "toggled(bool)" ), self.beamCenterCheckBoxToggled ) self.hBoxLayout13.addWidget( self.beamCenterCheckBox ) self.beamCenterXSpinBox = Qt.QSpinBox( self.brick_widget ) self.beamCenterXSpinBox.setSuffix( " px" ) self.beamCenterXSpinBox.setRange( 1, 9999 ) self.hBoxLayout13.addWidget( self.beamCenterXSpinBox ) self.beamCenterYSpinBox = Qt.QSpinBox( self.brick_widget ) self.beamCenterYSpinBox.setSuffix( " px" ) self.beamCenterYSpinBox.setRange( 1, 9999 ) self.hBoxLayout13.addWidget( self.beamCenterYSpinBox ) self.brick_widget.layout().addLayout( self.hBoxLayout13 ) self.hBoxLayout14 = Qt.QHBoxLayout() self.normalisationCheckBox = Qt.QCheckBox( "Normalisation", self.brick_widget ) self.normalisationCheckBox.setFixedWidth( 130 ) Qt.QObject.connect( self.normalisationCheckBox, Qt.SIGNAL( "toggled(bool)" ), self.normalisationCheckBoxToggled ) self.hBoxLayout14.addWidget( self.normalisationCheckBox ) self.normalisationDoubleSpinBox = Qt.QDoubleSpinBox( self.brick_widget ) self.normalisationDoubleSpinBox.setDecimals( 7 ) self.normalisationDoubleSpinBox.setRange( 0.0001, 10000 ) self.hBoxLayout14.addWidget( self.normalisationDoubleSpinBox ) self.brick_widget.layout().addLayout( self.hBoxLayout14 ) self.hBoxLayout15 = Qt.QHBoxLayout() self.beamStopDiodeCheckBox = Qt.QCheckBox( "Beam stop diode", self.brick_widget ) self.beamStopDiodeCheckBox.setFixedWidth( 130 ) Qt.QObject.connect( self.beamStopDiodeCheckBox, Qt.SIGNAL( "toggled(bool)" ), self.beamStopDiodeCheckBoxToggled ) self.hBoxLayout15.addWidget( self.beamStopDiodeCheckBox ) self.beamStopDiodeDoubleSpinBox = Qt.QDoubleSpinBox( self.brick_widget ) self.beamStopDiodeDoubleSpinBox.setDecimals( 12 ) self.beamStopDiodeDoubleSpinBox.setRange( -1, 1 ) self.hBoxLayout15.addWidget( self.beamStopDiodeDoubleSpinBox ) self.brick_widget.layout().addLayout( self.hBoxLayout15 ) self.hBoxLayout16 = Qt.QHBoxLayout() self.machineCurrentCheckBox = Qt.QCheckBox( "Machine current", self.brick_widget ) self.machineCurrentCheckBox.setFixedWidth( 130 ) Qt.QObject.connect( self.machineCurrentCheckBox, Qt.SIGNAL( "toggled(bool)" ), self.machineCurrentCheckBoxToggled ) self.hBoxLayout16.addWidget( self.machineCurrentCheckBox ) self.machineCurrentDoubleSpinBox = Qt.QDoubleSpinBox( self.brick_widget ) self.machineCurrentDoubleSpinBox.setDecimals( 2 ) self.machineCurrentDoubleSpinBox.setRange( 0, 350 ) self.hBoxLayout16.addWidget( self.machineCurrentDoubleSpinBox ) self.brick_widget.layout().addLayout( self.hBoxLayout16 ) self.hBoxLayout17 = Qt.QHBoxLayout() self.keepOriginalCheckBox = Qt.QCheckBox( "Keep original files", self.brick_widget ) self.keepOriginalCheckBox.setChecked( True ) self.hBoxLayout17.addWidget( self.keepOriginalCheckBox ) self.brick_widget.layout().addLayout( self.hBoxLayout17 ) self.hBoxLayout18 = Qt.QHBoxLayout() self.notifyCheckBox = Qt.QCheckBox( "Notify when done", self.brick_widget ) self.notifyCheckBox.setChecked( True ) self.hBoxLayout18.addWidget( self.notifyCheckBox ) self.brick_widget.layout().addLayout( self.hBoxLayout18 ) self.vBoxLayout0 = Qt.QVBoxLayout() self.vBoxLayout0.addSpacing( 15 ) self.brick_widget.layout().addLayout( self.vBoxLayout0 ) self.hBoxLayout18 = Qt.QHBoxLayout() self.reprocessPushButton = Qt.QPushButton( "Reprocess", self.brick_widget ) self.reprocessPushButton.setToolTip( "Start reprocess with the specified parameters" ) self.hBoxLayout18.addWidget( self.reprocessPushButton ) Qt.QObject.connect( self.reprocessPushButton, Qt.SIGNAL( "clicked()" ), self.reprocessPushButtonClicked ) self.brick_widget.layout().addLayout( self.hBoxLayout18 ) self.hBoxLayout19 = Qt.QHBoxLayout() self.abortPushButton = Qt.QPushButton( "Abort", self.brick_widget ) self.abortPushButton.setToolTip( "Abort ongoing data reprocessing" ) self.hBoxLayout19.addWidget( self.abortPushButton ) Qt.QObject.connect( self.abortPushButton, Qt.SIGNAL( "clicked()" ), self.abortPushButtonClicked ) self.brick_widget.layout().addLayout( self.hBoxLayout19 ) self.directoryLineEditChanged( None ) self.concentrationCheckBoxToggled( False ) self.commentsCheckBoxToggled( False ) self.codeCheckBoxToggled( False ) self.maskCheckBoxToggled( False ) self.detectorDistanceCheckBoxToggled( False ) self.waveLengthCheckBoxToggled( False ) self.pixelSizeCheckBoxToggled( False ) self.beamCenterCheckBoxToggled( False ) self.normalisationCheckBoxToggled( False ) self.beamStopDiodeCheckBoxToggled( False ) self.machineCurrentCheckBoxToggled( False ) self.SPECBusyTimer = Qt.QTimer( self.brick_widget ) Qt.QObject.connect( self.SPECBusyTimer, Qt.SIGNAL( "timeout()" ), self.SPECBusyTimerTimeOut ) self.setButtonState( 0 ) def delete( self ): pass #TODO: replace # def detectorComboBoxChanged(self, pValue): # if not self.__isReprocessing: # self.populatePrefixComboBox() # self.populateRunNumberListWidget() # self.populateFrameComboBox() #TODO: replace # def operationComboBoxChanged(self, pValue): # if not self.__isReprocessing: # self.concentrationCheckBox.setEnabled(pValue in (1, 3)) # self.concentrationDoubleSpinBox.setEnabled(pValue in (1, 3) and self.concentrationCheckBox.isChecked()) # self.commentsCheckBox.setEnabled(pValue in (1, 3)) # self.commentsLineEdit.setEnabled(pValue in (1, 3) and self.commentsCheckBox.isChecked()) # self.codeCheckBox.setEnabled(pValue in (1, 3)) # self.codeLineEdit.setEnabled(pValue in (1, 3) and self.codeCheckBox.isChecked()) # self.maskCheckBox.setEnabled(pValue in (1, 3)) # self.maskLineEdit.setEnabled(pValue in (1, 3) and self.maskCheckBox.isChecked()) # self.maskDirectoryPushButton.setEnabled(pValue in (1, 3) and self.maskCheckBox.isChecked()) # self.maskDisplayPushButton.setEnabled(pValue in (1, 3) and self.maskCheckBox.isChecked()) # self.detectorDistanceCheckBox.setEnabled(pValue in (1, 3)) # self.detectorDistanceDoubleSpinBox.setEnabled(pValue in (1, 3) and self.detectorDistanceCheckBox.isChecked()) # self.waveLengthCheckBox.setEnabled(pValue in (1, 3)) # self.waveLengthDoubleSpinBox.setEnabled(pValue in (1, 3) and self.waveLengthCheckBox.isChecked()) # self.pixelSizeCheckBox.setEnabled(pValue in (1, 3)) # self.pixelSizeXDoubleSpinBox.setEnabled(pValue in (1, 3) and self.pixelSizeCheckBox.isChecked()) # self.pixelSizeYDoubleSpinBox.setEnabled(pValue in (1, 3) and self.pixelSizeCheckBox.isChecked()) # self.beamCenterCheckBox.setEnabled(pValue in (1, 3)) # self.beamCenterXSpinBox.setEnabled(pValue in (1, 3) and self.beamCenterCheckBox.isChecked()) # self.beamCenterYSpinBox.setEnabled(pValue in (1, 3) and self.beamCenterCheckBox.isChecked()) # self.normalisationCheckBox.setEnabled(pValue in (0, 3)) # self.normalisationDoubleSpinBox.setEnabled(pValue in (0, 3) and self.normalisationCheckBox.isChecked()) # self.beamStopDiodeCheckBox.setEnabled(pValue in (0, 3)) # self.beamStopDiodeDoubleSpinBox.setEnabled(pValue in (0, 3) and self.beamStopDiodeCheckBox.isChecked()) # self.machineCurrentCheckBox.setEnabled(pValue in (1, 3)) # self.machineCurrentDoubleSpinBox.setEnabled(pValue in (1, 3) and self.machineCurrentCheckBox.isChecked()) def directoryLineEditChanged( self, pValue ): if not self.__isReprocessing: self.__validParameters[0] = pValue is not None and os.path.exists( pValue ) and not os.path.isfile( pValue ) if self.__validParameters[0]: if str( pValue ).find( " " ) == -1: self.directoryLineEdit.palette().setColor( QtGui.QPalette.Base, QtGui.QColor( 255, 255, 255 ) ) else: self.directoryLineEdit.palette().setColor( QtGui.QPalette.Base, QtGui.QColor( 255, 255, 0 ) ) else: self.directoryLineEdit.palette().setColor( QtGui.QPalette.Base, QtGui.QColor( 255, 0, 0 ) ) self.populatePrefixComboBox() self.populateRunNumberListWidget() self.populateFrameComboBox() self.reprocessPushButton.setEnabled( False not in self.__validParameters ) def directoryPushButtonClicked( self ): directory = QtGui.QFileDialog.getExistingDirectory( self.brick_widget, "Choose a directory", self.directoryLineEdit.text() ) if directory != "": self.directoryLineEdit.setText( directory ) def prefixComboBoxChanged( self, pValue ): if not self.__isReprocessing: self.__validParameters[1] = pValue > 0 self.populateRunNumberListWidget() self.populateFrameComboBox() self.reprocessPushButton.setEnabled( False not in self.__validParameters ) def runNumberListWidgetChanged( self ): if not self.__isReprocessing: selectedItemsCount = len( self.runNumberListWidget.selectedItems() ) self.populateFrameComboBox() self.__validParameters[2] = ( selectedItemsCount > 0 ) self.__validParameters[3] = ( selectedItemsCount > 1 ) self.frameFirstComboBox.setEnabled( selectedItemsCount < 2 ) self.frameLastComboBox.setEnabled( selectedItemsCount < 2 ) self.reprocessPushButton.setEnabled( False not in self.__validParameters ) def frameFirstComboBoxChanged( self, pValue ): if not self.__isReprocessing: self.__validParameters[3] = ( pValue > 0 and self.frameLastComboBox.currentIndex() > 0 and int( self.frameFirstComboBox.currentText() ) <= int( self.frameLastComboBox.currentText() ) ) self.reprocessPushButton.setEnabled( False not in self.__validParameters ) def frameLastComboBoxChanged( self, pValue ): if not self.__isReprocessing: self.__validParameters[3] = ( self.frameFirstComboBox.currentIndex() > 0 and pValue > 0 and int( self.frameFirstComboBox.currentText() ) <= int( self.frameLastComboBox.currentText() ) ) self.reprocessPushButton.setEnabled( False not in self.__validParameters ) def concentrationCheckBoxToggled( self, pValue ): if not self.__isReprocessing: self.concentrationDoubleSpinBox.setEnabled( pValue ) def commentsCheckBoxToggled( self, pValue ): if not self.__isReprocessing: self.commentsLineEdit.setEnabled( pValue ) def codeCheckBoxToggled( self, pValue ): if not self.__isReprocessing: self.codeLineEdit.setEnabled( pValue ) def maskCheckBoxToggled( self, pValue ): if not self.__isReprocessing: self.maskLineEdit.setEnabled( pValue ) self.maskDirectoryPushButton.setEnabled( pValue ) self.maskDisplayPushButton.setEnabled( pValue ) def detectorDistanceCheckBoxToggled( self, pValue ): if not self.__isReprocessing: self.detectorDistanceDoubleSpinBox.setEnabled( pValue ) def waveLengthCheckBoxToggled( self, pValue ): if not self.__isReprocessing: self.waveLengthDoubleSpinBox.setEnabled( pValue ) def pixelSizeCheckBoxToggled( self, pValue ): if not self.__isReprocessing: self.pixelSizeXDoubleSpinBox.setEnabled( pValue ) self.pixelSizeYDoubleSpinBox.setEnabled( pValue ) def beamCenterCheckBoxToggled( self, pValue ): if not self.__isReprocessing: self.beamCenterXSpinBox.setEnabled( pValue ) self.beamCenterYSpinBox.setEnabled( pValue ) def normalisationCheckBoxToggled( self, pValue ): if not self.__isReprocessing: self.normalisationDoubleSpinBox.setEnabled( pValue ) def beamStopDiodeCheckBoxToggled( self, pValue ): if not self.__isReprocessing: self.beamStopDiodeDoubleSpinBox.setEnabled( pValue ) def machineCurrentCheckBoxToggled( self, pValue ): if not self.__isReprocessing: self.machineCurrentDoubleSpinBox.setEnabled( pValue ) def maskLineEditChanged( self, pValue ): if not self.__isReprocessing: if pValue is not None: pValue = str( pValue ) if os.path.isfile( pValue ): i = pValue.rfind( "." ) if i != -1 and pValue[i - 4:i] == "_msk" and pValue[i + 1:] == "edf" and pValue.find( " " ) == -1: flag = 0 else: flag = 1 else: flag = 2 else: flag = 2 if flag == 0: self.__validParameters[4] = True self.maskLineEdit.palette().setColor( QtGui.QPalette.Base, QtGui.QColor( 255, 255, 255 ) ) elif flag == 1: self.__validParameters[4] = True self.maskLineEdit.palette().setColor( QtGui.QPalette.Base, QtGui.QColor( 255, 255, 0 ) ) else: self.__validParameters[4] = False self.maskLineEdit.palette().setColor( QtGui.QPalette.Base, QtGui.QColor( 255, 0, 0 ) ) self.maskDisplayPushButton.setEnabled( self.__validParameters[4] and self.maskCheckBox.isChecked() ) self.reprocessPushButton.setEnabled( False not in self.__validParameters ) def maskDirectoryPushButtonClicked( self ): qFileDialog = QtGui.QFileDialog( self.brick_widget, "Choose a mask file", self.maskLineEdit.text() ) qFileDialog.setAcceptMode( QtGui.QFileDialog.AcceptOpen ) qFileDialog.setFilters( ["ESRF Data Format (*.edf)"] ) if qFileDialog.exec_(): self.maskLineEdit.setText( str( qFileDialog.selectedFiles()[0] ) ) def maskDisplayPushButtonClicked( self ): self.emit( "displayItemChanged", str( self.maskLineEdit.text() ) ) def reprocessPushButtonClicked( self ): if Qt.QMessageBox.question( self.brick_widget, "Warning", "Are you sure that you want to reprocess data collection '" + str( self.prefixComboBox.currentText() ) + "'?", Qt.QMessageBox.Yes, Qt.QMessageBox.No, Qt.QMessageBox.NoButton ) == Qt.QMessageBox.Yes: self.setButtonState( 1 ) self.SPECBusyTimer.start( 20000 ) logger.info( "Start reprocessing..." ) self.emit( "displayResetChanged" ) self.__isReprocessing = True runNumber = "" for item in self.runNumberListWidget.selectedItems(): if runNumber == "": runNumber = str( item.text() ) else: runNumber += "," + str( item.text() ) if len( self.runNumberListWidget.selectedItems() ) == 1: frameFirst = str( self.frameFirstComboBox.currentText() ) frameLast = str( self.frameLastComboBox.currentText() ) else: frameFirst = None frameLast = None if self.concentrationCheckBox.isEnabled() and self.concentrationCheckBox.isChecked(): concentration = self.concentrationDoubleSpinBox.value() else: concentration = None if self.commentsCheckBox.isEnabled() and self.commentsCheckBox.isChecked(): comments = self.commentsLineEdit.text() else: comments = None if self.codeCheckBox.isEnabled() and self.codeCheckBox.isChecked(): code = self.codeLineEdit.text() else: code = None if self.maskCheckBox.isEnabled() and self.maskCheckBox.isChecked(): mask = self.maskLineEdit.text() else: mask = None if self.detectorDistanceCheckBox.isEnabled() and self.detectorDistanceCheckBox.isChecked(): detectorDistance = self.detectorDistanceDoubleSpinBox.value() else: detectorDistance = None if self.waveLengthCheckBox.isEnabled() and self.waveLengthCheckBox.isChecked(): waveLength = self.waveLengthDoubleSpinBox.value() else: waveLength = None if self.pixelSizeCheckBox.isEnabled() and self.pixelSizeCheckBox.isChecked(): pixelSizeX = self.pixelSizeXDoubleSpinBox.value() pixelSizeY = self.pixelSizeYDoubleSpinBox.value() else: pixelSizeX = None pixelSizeY = None if self.beamCenterCheckBox.isEnabled() and self.beamCenterCheckBox.isChecked(): beamCenterX = self.beamCenterXSpinBox.value() beamCenterY = self.beamCenterYSpinBox.value() else: beamCenterX = None beamCenterY = None if self.normalisationCheckBox.isEnabled() and self.normalisationCheckBox.isChecked(): normalisation = self.normalisationDoubleSpinBox.value() else: normalisation = None if self.beamStopDiodeCheckBox.isEnabled() and self.beamStopDiodeCheckBox.isChecked(): beamStopDiode = self.beamStopDiodeDoubleSpinBox.value() else: beamStopDiode = None if self.machineCurrentCheckBox.isEnabled() and self.machineCurrentCheckBox.isChecked(): machineCurrent = self.machineCurrentDoubleSpinBox.value() else: machineCurrent = None if self.keepOriginalCheckBox.isChecked(): keepOriginal = "1" else: keepOriginal = "0" self.getObject( "reprocess" ).reprocess( self.directoryLineEdit.text(), self.prefixComboBox.currentText(), runNumber, frameFirst, frameLast, concentration, comments, code, mask, detectorDistance, waveLength, pixelSizeX, pixelSizeY, beamCenterX, beamCenterY, normalisation, beamStopDiode, machineCurrent, keepOriginal, "20", "1" ) def abortPushButtonClicked( self ): self.SPECBusyTimer.stop() self.__isReprocessing = False self.setButtonState( 0 ) logger.info( "Aborting data reprocess!" ) self.getObject( "reprocess" ).reprocessAbort() def setButtonState( self, pOption ): if pOption == 0: # normal self.keepOriginalCheckBox.setEnabled( True ) self.notifyCheckBox.setEnabled( True ) self.reprocessPushButton.setEnabled( True ) self.abortPushButton.setEnabled( False ) elif pOption == 1: # reprocessing self.keepOriginalCheckBox.setEnabled( False ) self.notifyCheckBox.setEnabled( False ) self.reprocessPushButton.setEnabled( False ) self.abortPushButton.setEnabled( True ) elif pOption == 2: # invalid parameters self.keepOriginalCheckBox.setEnabled( True ) self.notifyCheckBox.setEnabled( True ) self.reprocessPushButton.setEnabled( False ) self.abortPushButton.setEnabled( False ) if self.abortPushButton.isEnabled(): self.abortPushButton.palette().setColor( QtGui.QPalette.Button, QtGui.QColor( 255, 0, 0 ) ) else: self.abortPushButton.palette().setColor( QtGui.QPalette.Button, QtGui.QColor( 235, 235, 235 ) ) def SPECBusyTimerTimeOut( self ): self.SPECBusyTimer.stop() self.__isReprocessing = False self.setButtonState( 0 ) logger.warning( "The frame (or 1D curve) was not reprocessed or didn't appear on time!" ) def populatePrefixComboBox( self ): if os.path.exists( self.directoryLineEdit.text() + "/raw/" ): directory = self.directoryLineEdit.text() + "/raw/" else: directory = self.directoryLineEdit.text() + "/" items = [] if os.path.isdir( directory ): try: for filename in os.listdir( directory ): #TODO: Why is this check needed ? SO 14/3 12 if os.path.isfile( directory + filename ): prefix, run, frame, extra, extension = self.getFilenameDetails( filename ) if frame != "": if self.detectorComboBox.currentIndex() == 0 and extension == "edf" or self.detectorComboBox.currentIndex() == 1 and extension == "gfrm": try: items.index( prefix ) except ValueError: items.append( prefix ) except Exception, e: logger.error( "Full Exception: " + str( e ) ) items.sort() items.insert( 0, "Select" ) currentText = self.prefixComboBox.currentText() self.prefixComboBox.clear() self.prefixComboBox.addItems( items ) try: self.prefixComboBox.setCurrentIndex( items.index( currentText ) ) except ValueError: self.prefixComboBox.setCurrentIndex( 0 )
class BsxFrameBrick(Core.BaseBrick): properties = {} connections = {"display": Connection("Display object", [Signal("displayResetChanged", "displayResetChanged"), Signal("displayItemChanged", "displayItemChanged"), Signal("transmissionChanged", "transmissionChanged"), Signal("grayOut", "grayOut")], []), "login": Connection("Login object", [Signal("loggedIn", "loggedIn")], [], "connectionToLogin")} signals = [] slots = [] def __init__(self, *args, **kargs): Core.BaseBrick.__init__(self, *args, **kargs) def init(self): Qt.QVBoxLayout(self.brick_widget) self.frameDisplay = QubDataImageDisplay(self.brick_widget, noAction = True, forcePopupSubWindow = True) # layout #TODO: Next line will always have an error in Eclipse, even if it is correct. self.frameDisplay.setSizePolicy(Qt.QSizePolicy.MinimumExpanding, Qt.QSizePolicy.MinimumExpanding) self.brick_widget.layout().addWidget(self.frameDisplay) # No foreground color change - all other left in action_enum = [QubDataImageDisplay.QUICK_SCROLL, QubDataImageDisplay.SUB_DATA_VIEW, QubDataImageDisplay.PRINT_PREVIEW, QubDataImageDisplay.SAVE_IMAGE, QubDataImageDisplay.STAT_ACTION, QubDataImageDisplay.HEADER_INFO, QubDataImageDisplay.ZOOM, QubDataImageDisplay.COLORMAP, QubDataImageDisplay.HORIZONTAL_SELECTION, QubDataImageDisplay.VERTICAL_SELECTION, QubDataImageDisplay.LINE_SELECTION, QubDataImageDisplay.POSITION_AND_VALUE] self.frameDisplay.addStdAction(action_enum, zoomValList = None) # Add the monkey dialog box for masks openDialog = QubOpenDialogAction(parent = self.frameDisplay, name = 'mask', iconName = 'mask', group = 'Mask') dialog = QubMaskToolsDialog(None) dialog.setGraphicsView(self.frameDisplay.getDrawingView()) openDialog.setDialog(dialog) openDialog._dialog = dialog self.frameDisplay.addDataAction(openDialog, dialog) # Reference the openDialog to make sure the Garbage Collector does not remove it (_openD could be _dummy) self.frameDisplay._openD = openDialog # When connected to Login, then block the brick def connectionToLogin(self, pPeer): if pPeer is not None: self.brick_widget.setEnabled(False) # Logged In : True or False def loggedIn(self, pValue): self.brick_widget.setEnabled(pValue) def displayItemChanged(self, files_string): #TODO: DEBUG print ">> file_string %r " % files_string filesList = files_string.split(",") for f in filesList: if f.endswith('.edf'): self.frameDisplay.setDataSource(f) def displayResetChanged(self): pass def transmissionChanged(self, _): pass def grayOut(self, _): pass
class BsxAttenuatorsBrick( Core.BaseBrick ): properties = {"maskFormat": Property( "string", "Mask format", "", "maskFormatChanged" ), "suffix": Property( "string", "Suffix", "", "suffixChanged" ), "maximumHistory": Property( "integer", "Maximum history", "", "maximumHistoryChanged" ), "minimumValue": Property( "float", "Minimum value", "", "minimumValueChanged" ), "maximumValue": Property( "float", "Maximum value", "", "maximumValueChanged" ), "orientation": Property( "combo", "Orientation", description = "Layout of widgets", onchange_cb = "orientationChanged", default = "Portrait", choices = ["Portrait", "Landscape"] )} connections = {"attenuators": Connection( "Attenuators object", [Signal( "attenuatorsStateChanged", "attenuatorsStateChanged" ), Signal( "attenuatorsFactorChanged", "attenuatorsFactorChanged" )], [], "connectionStatusChanged" ), "display": Connection( "Display object", [Signal( "displayResetChanged", "displayResetChanged" ), Signal( "displayItemChanged", "displayItemChanged" ), Signal( "transmissionChanged", "transmissionChanged" ), Signal( "grayOut", "grayOut" )], [] ), "login": Connection( "Login object", [Signal( "loggedIn", "loggedIn" )], [], "connectionToLogin" )} signals = [] slots = [] def __init__( self, *args, **kargs ): Core.BaseBrick.__init__( self, *args, **kargs ) self.bsxAttenuator = None def init( self ): self.__filtersDialog = None self.__maskFormat = "" self.__suffix = "" self.__minimumValue = 0 self.__maximumValue = 100 self.loginDone = False self.hBoxLayout = Qt.QHBoxLayout() self.transmissionLabel = Qt.QLabel( "Transmission (current, new)", self.brick_widget ) self.hBoxLayout.addWidget( self.transmissionLabel ) self.currentTransmissionLineEdit = Qt.QLineEdit( self.brick_widget ) self.currentTransmissionLineEdit.setEnabled( True ) self.currentTransmissionLineEdit.setSizePolicy( Qt.QSizePolicy.Expanding, Qt.QSizePolicy.Expanding ) self.currentTransmissionLineEdit.setToolTip( "Current transmission" ) self.hBoxLayout.addWidget( self.currentTransmissionLineEdit ) self.newTransmissionComboBox = Qt.QComboBox( self.brick_widget ) self.newTransmissionComboBox.setEditable( True ) self.newTransmissionComboBox.lineEdit().setMaxLength( 10 ) self.newTransmissionComboBox.setSizePolicy( Qt.QSizePolicy.Expanding, Qt.QSizePolicy.Expanding ) self.newTransmissionComboBox.setToolTip( "New transmission" ) Qt.QObject.connect( self.newTransmissionComboBox, Qt.SIGNAL( "editTextChanged(const QString &)" ), self.newTransmissionComboBoxChanged ) Qt.QObject.connect( self.newTransmissionComboBox.lineEdit(), Qt.SIGNAL( "returnPressed()" ), self.newTransmissionComboBoxReturnPressed ) self.hBoxLayout.addWidget( self.newTransmissionComboBox ) self.filtersPushButton = Qt.QPushButton( "Filters", self.brick_widget ) self.filtersPushButton.setToolTip( "Enable/disable transmission filters" ) Qt.QObject.connect( self.filtersPushButton, Qt.SIGNAL( "clicked()" ), self.filtersPushButtonClicked ) self.newTransmissionComboBoxChanged( None ) # When connected to Login, then block the brick def connectionToLogin( self, pPeer ): if pPeer is not None: # Check if we were already connected first if not self.loginDone: self.brick_widget.setEnabled( False ) # Logged In : True or False def loggedIn( self, pValue ): self.loginDone = pValue self.brick_widget.setEnabled( pValue ) def maskFormatChanged( self, pValue ): self.__maskFormat = pValue self.attenuatorsFactorChanged( self.currentTransmissionLineEdit.text() ) def suffixChanged( self, pValue ): self.__suffix = pValue #self.attenuatorsFactorChanged(self.currentTransmissionLineEdit.text()) def maximumHistoryChanged( self, pValue ): self.newTransmissionComboBox.setMaxCount( pValue ) def minimumValueChanged( self, pValue ): self.__minimumValue = pValue self.newTransmissionComboBox.lineEdit().setValidator( Qt.QDoubleValidator( self.__minimumValue, self.__maximumValue, 10, self.newTransmissionComboBox.lineEdit() ) ) def maximumValueChanged( self, pValue ): self.__maximumValue = pValue self.newTransmissionComboBox.lineEdit().setValidator( Qt.QDoubleValidator( self.__minimumValue, self.__maximumValue, 10, self.newTransmissionComboBox.lineEdit() ) ) def orientationChanged( self, pValue ): if self.brick_widget.layout() is not None: self.hBoxLayout.setParent( None ) self.brick_widget.layout().removeWidget( self.filtersPushButton ) sip.transferback( self.brick_widget.layout() ) if pValue == "Landscape": self.brick_widget.setLayout( Qt.QHBoxLayout() ) self.filtersPushButton.setSizePolicy( Qt.QSizePolicy.Fixed, Qt.QSizePolicy.Expanding ) else: self.brick_widget.setLayout( Qt.QVBoxLayout() ) self.filtersPushButton.setSizePolicy( Qt.QSizePolicy.Expanding, Qt.QSizePolicy.Expanding ) self.brick_widget.layout().addLayout( self.hBoxLayout ) self.brick_widget.layout().addWidget( self.filtersPushButton ) def attenuatorsStateChanged( self, pValue ): if self.__filtersDialog is not None: self.__filtersDialog.filtersChanged( pValue ) # Need to take the new value for Transmission if self.bsxAttenuator is not None: currentTransmission = self.bsxAttenuator.getAttenuatorsFactor() if currentTransmission == "": self.currentTransmissionLineEdit.setText( self.__suffix ) else: if self.__maskFormat == "": self.currentTransmissionLineEdit.setText( str( float( currentTransmission ) ) + self.__suffix ) else: self.currentTransmissionLineEdit.setText( self.__maskFormat % float( currentTransmission ) + self.__suffix ) def attenuatorsFactorChanged( self, pValue ): if pValue == "": self.currentTransmissionLineEdit.setText( self.__suffix ) else: if self.__maskFormat == "": self.currentTransmissionLineEdit.setText( str( float( pValue ) ) + self.__suffix ) else: self.currentTransmissionLineEdit.setText( self.__maskFormat % float( pValue ) + self.__suffix ) # connect to Display def displayResetChanged( self ): pass def displayItemChanged( self, _ ): pass def grayOut( self, grayout ): if grayout is not None: if grayout: self.newTransmissionComboBox.setEditable( False ) self.filtersPushButton.setEnabled( False ) self.currentTransmissionLineEdit.setEnabled( False ) else: self.newTransmissionComboBox.setEditable( True ) # Put back Signal otherwise it is lost (maybe a bug) - SO 19/9 2012 Qt.QObject.connect( self.newTransmissionComboBox.lineEdit(), Qt.SIGNAL( "returnPressed()" ), self.newTransmissionComboBoxReturnPressed ) self.filtersPushButton.setEnabled( True ) self.currentTransmissionLineEdit.setEnabled( True ) def transmissionChanged( self, pValue ): self.getObject( "attenuators" ).setTransmission( float( pValue ) ) def connectionStatusChanged( self, pPeer ): if pPeer is not None: self.bsxAttenuator = pPeer currentTransmission = self.bsxAttenuator.getAttenuatorsFactor() if currentTransmission == "": self.currentTransmissionLineEdit.setText( self.__suffix ) else: if self.__maskFormat == "": self.currentTransmissionLineEdit.setText( str( float( currentTransmission ) ) + self.__suffix ) else: self.currentTransmissionLineEdit.setText( self.__maskFormat % float( currentTransmission ) + self.__suffix ) def newTransmissionComboBoxChanged( self, pValue ): if pValue is None or pValue == "": self.newTransmissionComboBox.lineEdit().palette().setColor( QtGui.QPalette.Base, QtGui.QColor( 255, 255, 0 ) ) else: if self.newTransmissionComboBox.lineEdit().hasAcceptableInput(): self.newTransmissionComboBox.lineEdit().palette().setColor( QtGui.QPalette.Base, QtGui.QColor( 255, 255, 255 ) ) else: self.newTransmissionComboBox.lineEdit().palette().setColor( QtGui.QPalette.Base, QtGui.QColor( 255, 0, 0 ) ) self.newTransmissionComboBox.lineEdit().update() def newTransmissionComboBoxReturnPressed( self ): if self.newTransmissionComboBox.lineEdit().hasAcceptableInput(): if self.newTransmissionComboBox.currentText() != "": logger.info( "Setting transmission to " + self.newTransmissionComboBox.currentText() + " %..." ) self.bsxAttenuator.setTransmission( float( self.newTransmissionComboBox.currentText() ) ) self.newTransmissionComboBox.clearEditText() def toggleFilter( self, pFilter, pChecked, pValue ): if pChecked: logger.info( "Enabling filter '" + pFilter + "'..." ) else: logger.info( "Disabling filter '" + pFilter + "'..." ) self.bsxAttenuator.toggleFilter( pValue ) def filtersPushButtonClicked( self ): if self.__filtersDialog is not None and self.__filtersDialog.isVisible(): self.__filtersDialog.activateWindow() self.__filtersDialog.raise_() else: attenuatorsList = self.bsxAttenuator.getAttenuatorsList() if attenuatorsList is None: Qt.QMessageBox.information( self.brick_widget, "Info", "There are no attenuators specified!" ) else: self.__filtersDialog = FiltersDialog( self, attenuatorsList ) self.__filtersDialog.filtersChanged( self.bsxAttenuator.getAttenuatorsState() ) self.__filtersDialog.show()
class BsxSCBrick( Core.BaseBrick ): properties = {} connections = {"samplechanger": Connection( "Sample Changer object", [Signal( 'seuTemperatureChanged', 'seu_temperature_changed' ), Signal( 'storageTemperatureChanged', 'storage_temperature_changed' ), Signal( 'stateChanged', 'state_changed' ), ], [], "sample_changer_connected" ), "login": Connection( "Login object", [Signal( "loggedIn", "loggedIn" )], [], "connectionToLogin" )} def __init__( self, *args, **kargs ): Core.BaseBrick.__init__( self, *args, **kargs ) def init( self ): self._sampleChanger = None mainLayout = Qt.QHBoxLayout( self.brick_widget ) self.SCWidget = BsxSCWidget( self.brick_widget ) mainLayout.addWidget( self.SCWidget ) self.brick_widget.setLayout( mainLayout ) # self.SCWidget.setState( "Disconnected" ) # When connected to Login, then block the brick def connectionToLogin( self, pPeer ): if pPeer is not None: self.brick_widget.setEnabled( False ) # Logged In : True or False def loggedIn( self, pValue ): self.brick_widget.setEnabled( pValue ) def sample_changer_connected( self, sc ): if sc is not None: logger.info( "Sample Changer connected" ) self._sampleChanger = sc geometry = [ self._sampleChanger.getPlateInfo( i ) for i in range( 1, 3 ) ] #TODO: DEBUG print ">>>> geometry in sample_changer %r" % geometry self.SCWidget.setPlateGeometry( geometry ) # redefine calls in SCWidget self.SCWidget.startSyringeForward = self.startSyringeForward self.SCWidget.startSyringeBackward = self.startSyringeBackward self.SCWidget.stopSyringe = self._sampleChanger.stopSyringe self.SCWidget.setLiquidPositionFixed = self._sampleChanger.setLiquidPositionFixed self.SCWidget.fill = self._sampleChanger.fill self.SCWidget.dry = self._sampleChanger.dry self.SCWidget.flow = self._sampleChanger.flowAll self.SCWidget.recuperate = self._sampleChanger.recuperate self.SCWidget.clean = self._sampleChanger.clean self.SCWidget.abort = self._sampleChanger.abort self.SCWidget.mix = self._sampleChanger.mix self.SCWidget.transfer = self._sampleChanger.transfer self.SCWidget.restart = self._sampleChanger.restart self.SCWidget.setStorageTemperature = self._sampleChanger.setStorageTemperature self.SCWidget.setSEUTemperature = self._sampleChanger.setSEUTemperature self.SCWidget.setState( "READY", "Connected" ) else: logger.info( "Sample Changer NOT connected " ) self.SCWidget.setState( "DISCONNECTED", "SC GUI not running?" ) return def storage_temperature_changed( self, temperature ): self.SCWidget.setCurrentStorageTemperature( temperature ) def seu_temperature_changed( self, temperature ): self.SCWidget.setCurrentSEUTemperature( temperature ) def state_changed( self, state, status ): if self._sampleChanger is None: return try: cmdException = self._sampleChanger.getCommandException() except: print "Could not read sample changer CommandException state: %s, status: %s" % ( state, status ) print "[State changed] error", sys.exc_info()[0] print "Exception in user code:" traceback.print_exc( file = sys.stdout ) cmdException = "" self.SCWidget.setState( state, status, cmdException ) def startSyringeForward( self ): self._sampleChanger.moveSyringeForward( 5 ) def startSyringeBackward( self ): self._sampleChanger.moveSyringeBackward( 5 )
class CURBrick(Core.BaseBrick): connections = { "display": Connection("Display object", [ Signal("displayResetChanged", "displayResetChanged"), Signal("displayItemChanged", "displayItemChanged"), Signal("transmissionChanged", "transmissionChanged"), Signal("grayOut", "grayOut") ], []), "login": Connection("Login object", [Signal("loggedIn", "loggedIn")], [], "connectionToLogin") } signals = [] slots = [] def __init__(self, *args, **kargs): Core.BaseBrick.__init__(self, *args, **kargs) self.collectBrickObject = None self.collectBrickObject = None def init(self): self.__copyLine = [] self.__history = [] # To map samples with rows each time we create a sample we give a unique number # the position of a sample in the map should correspond with the row of the sample in the table # throught the operations self.sampleIDs = [] self.sampleIDCount = 0 self.CBblock = 0 # during swapping callbacks on table rows will be deactivated self.filename = "" self.bufferNames = [] self.copiedSample = None # Setting configuration for columns in the samples table Widget self.column_headers = self.getColumns() self.PARAMLABEL_WIDTH = 130 self.PARAMETERS_WIDTH = 220 # # Style Sheet # self.brick_widget.setStyleSheet("*[table=\"true\"] {font-size: 11px} \ *[valid=\"true\"] {background-color: white}\ *[valid=\"false\"] {background-color: #f99}\ *[sampletype=\"Buffer\"] {background-color: #eec}\ *[sampletype=\"Sample\"] {background-color: #cce}") upfile = os.path.join(os.path.dirname(__file__), "images/up.jpg") downfile = os.path.join(os.path.dirname(__file__), "images/down.jpg") delfile = os.path.join(os.path.dirname(__file__), "images/delete.jpg") uppix = Qt.QPixmap(upfile).scaled(14, 14) downpix = Qt.QPixmap(downfile).scaled(15, 15) delpix = Qt.QPixmap(delfile).scaled(10, 10) self.upIcon = Qt.QIcon(uppix) self.downIcon = Qt.QIcon(downpix) self.deleteIcon = Qt.QIcon(delpix) self.brick_widget.setLayout(Qt.QVBoxLayout()) mainLayout = self.brick_widget.layout() self.robotCheckBox = Qt.QCheckBox("Collect using SC", self.brick_widget) # Note: We use stateChange instead of toggle to avoid infinite loop between CollectBrick and CURBrick Qt.QObject.connect(self.robotCheckBox, Qt.SIGNAL("stateChanged(int)"), self.__robotCheckBoxToggled) mainLayout.addWidget(self.robotCheckBox) self.groupBox = Qt.QGroupBox("Parameters", self.brick_widget) self.groupBox.setSizePolicy(Qt.QSizePolicy.Expanding, Qt.QSizePolicy.Expanding) # All parameters are grayed out until collect using robot (AKA CUR) checkbox is selected self.groupBox.setDisabled(True) self.VerticalParametersLayout = Qt.QVBoxLayout(self.groupBox) mainLayout.addWidget(self.groupBox) # File row layout self.hBoxLayout0 = self.getFirstButtonsRowLayout() self.VerticalParametersLayout.addLayout(self.hBoxLayout0) # Calibration Type or User defined self.optimizationLabel = Qt.QLabel("Type", self.brick_widget) self.optimizationComboBox = Qt.QComboBox(self.brick_widget) self.optimizationComboBox.addItems( ["User defined", "BSA Calibration", "Water Calibration"]) Qt.QObject.connect(self.optimizationComboBox, Qt.SIGNAL("currentIndexChanged(QString)"), self.loadCalibrationTemplate) # Sample Type self.sampleTypeLabel = Qt.QLabel("Sample type", self.brick_widget) self.sampleTypeComboBox = Qt.QComboBox(self.brick_widget) self.sampleTypeComboBox.addItems(["Green", "Yellow", "Red"]) # put all four together self.VerticalParametersLayout.addLayout( self.getHorizontalLabelValueLayoutFactory([ self.optimizationLabel, self.optimizationComboBox, self.sampleTypeLabel, self.sampleTypeComboBox ])) # Storage Temperature self.storageTemperatureLabel = Qt.QLabel("Storage temperature", self.brick_widget) self.storageTemperatureDoubleSpinBox = Qt.QDoubleSpinBox( self.brick_widget) self.storageTemperatureDoubleSpinBox.setSuffix(" C") self.storageTemperatureDoubleSpinBox.setDecimals(2) self.storageTemperatureDoubleSpinBox.setRange(4, 40) self.storageTemperatureDoubleSpinBox.setValue(4) # Ex. Flow Time self.extraFlowTimeLabel = Qt.QLabel("Extra flow time", self.brick_widget) self.extraFlowTimeSpinBox = Qt.QSpinBox(self.brick_widget) self.extraFlowTimeSpinBox.setSuffix(" s") self.extraFlowTimeSpinBox.setRange(0, 900) self.VerticalParametersLayout.addLayout( self.getHorizontalLabelValueLayoutFactory([ self.storageTemperatureLabel, self.storageTemperatureDoubleSpinBox, self.extraFlowTimeLabel, self.extraFlowTimeSpinBox, ])) # Optimization self.optimizationLabel = Qt.QLabel("Optimization", self.brick_widget) self.optimizationComboBox = Qt.QComboBox(self.brick_widget) self.optimizationComboBox.addItems([ "None", "Sample SEU temperature", "Sample code and SEU temperature" ]) # Buffer mode self.bufferModeLabel = Qt.QLabel("Buffer mode", self.brick_widget) self.bufferModeComboBox = Qt.QComboBox(self.brick_widget) self.bufferModeComboBox.addItems( ["First and After", "Before", "After", "None"]) self.VerticalParametersLayout.addLayout( self.getHorizontalLabelValueLayoutFactory([ self.optimizationLabel, self.optimizationComboBox, self.bufferModeLabel, self.bufferModeComboBox ])) # Initial cleaning self.initialCleaningLabel = Qt.QLabel("Initial Cleaning", self.brick_widget) self.initialCleaningCheckBox = Qt.QCheckBox(self.brick_widget) self.initialCleaningCheckBox.setChecked(1) self.VerticalParametersLayout.addLayout( self.getHorizontalLabelValueLayoutFactory( [self.initialCleaningLabel, self.initialCleaningCheckBox])) # History # self.historyLabel = Qt.QLabel( "History", self.brick_widget ) # self.historyLabel.setFixedWidth( self.PARAMLABEL_WIDTH ) # self.historyText = Qt.QTextEdit( self.brick_widget ) # self.historyText.setReadOnly( True ) # self.historyText.setFixedWidth( 600 ) # self.historyText.setFixedHeight( 80 ) # self.clearHistoryPushButton = Qt.QPushButton( "Clear", self.brick_widget ) # self.clearHistoryPushButton.setFixedWidth( 50 ) # Qt.QObject.connect( self.clearHistoryPushButton, Qt.SIGNAL( "clicked()" ), self.clearHistoryPushButtonClicked ) # self.historyLabel.setAlignment( QtCore.Qt.AlignTop ) # self.VerticalParametersLayout.addLayout( self.getHorizontalLayoutFactory( [self.historyLabel, self.historyText, self.clearHistoryPushButton] ) ) # Sample Table self.tableWidget = Qt.QTableWidget(0, len(self.column_headers), self.brick_widget) self.tableWidget.setHorizontalHeaderLabels(self.column_headers) #Set entire table to 11px (see Style Sheet above) self.tableWidget.setProperty("table", "true") self.tableWidget.setFixedHeight(420) self.tableWidget.resizeColumnsToContents() self.tableWidget.setColumnWidth(self.SAMPLETYPE_COLUMN, 70) self.tableWidget.setColumnWidth(self.PLATE_COLUMN, 45) self.tableWidget.setColumnWidth(self.ROW_COLUMN, 45) self.tableWidget.setColumnWidth(self.WELL_COLUMN, 45) self.tableWidget.setColumnWidth(self.COMMENTS_COLUMN, 80) self.tableWidget.setColumnWidth(self.MACROMOLECULE_COLUMN, 110) self.tableWidget.setColumnWidth(self.CODE_COLUMN, 80) self.tableWidget.setColumnWidth(self.VOLUME_COLUMN, 60) self.tableWidget.setSelectionBehavior(Qt.QAbstractItemView.SelectRows) self.tableWidget.setSelectionMode(Qt.QAbstractItemView.SingleSelection) self.VerticalParametersLayout.addLayout( self.getHorizontalLayoutFactory([self.tableWidget])) # Buttons at the end self.addPushButton = Qt.QPushButton("Add Sample", self.brick_widget) Qt.QObject.connect(self.addPushButton, Qt.SIGNAL("clicked()"), self.addPushButtonClicked) self.copyPushButton = Qt.QPushButton("Copy Sample", self.brick_widget) Qt.QObject.connect(self.copyPushButton, Qt.SIGNAL("clicked()"), self.copyPushButtonClicked) self.copyPushButton.setEnabled(0) self.pastePushButton = Qt.QPushButton("Paste Sample", self.brick_widget) Qt.QObject.connect(self.pastePushButton, Qt.SIGNAL("clicked()"), self.pastePushButtonClicked) self.pastePushButton.setEnabled(0) self.clearPushButton = Qt.QPushButton("Clear Configuration", self.brick_widget) Qt.QObject.connect(self.clearPushButton, Qt.SIGNAL("clicked()"), self.clearConfigurationPushButtonClicked) self.VerticalParametersLayout.addLayout( self.getGridLayoutFactory([ self.addPushButton, self.copyPushButton, self.pastePushButton, Qt.QLabel(""), Qt.QLabel(""), Qt.QLabel(""), self.clearPushButton ])) def getFirstButtonsRowLayout(self): self.fileLabel = Qt.QLabel("File", self.brick_widget) self.fileLabel.setFixedWidth(self.PARAMLABEL_WIDTH) self.fileLineEdit = Qt.QLineEdit(self.brick_widget) self.fileLineEdit.setMaxLength(100) self.fileLineEdit.setFixedWidth(400) self.fileLineEdit.setEnabled(False) self.loadPushButton = Qt.QPushButton("Load new", self.brick_widget) self.loadPushButton.setFixedWidth(70) Qt.QObject.connect(self.loadPushButton, Qt.SIGNAL("clicked()"), self.loadPushButtonClicked) self.savePushButton = Qt.QPushButton("Save", self.brick_widget) self.savePushButton.setFixedWidth(70) Qt.QObject.connect(self.savePushButton, Qt.SIGNAL("clicked()"), self.savePushButtonClicked) self.saveAsPushButton = Qt.QPushButton("Save as", self.brick_widget) self.saveAsPushButton.setFixedWidth(70) Qt.QObject.connect(self.saveAsPushButton, Qt.SIGNAL("clicked()"), self.saveAsPushButtonClicked) return self.getHorizontalLayoutFactory([ self.fileLabel, self.fileLineEdit, self.loadPushButton, self.savePushButton, self.saveAsPushButton ]) # self.fillspace = Qt.QLabel( "" ) # self.hBoxLayout16.addWidget( self.fillspace ) def getHorizontalLabelValueLayoutFactory(self, widgets): # only works with 2 or 4 if len(widgets) == 2: widgets[0].setFixedWidth(self.PARAMLABEL_WIDTH) widgets[1].setFixedWidth(self.PARAMETERS_WIDTH) return self.getHorizontalLayoutFactory([widgets[0], widgets[1]]) if len(widgets) == 4: widgets[0].setFixedWidth(self.PARAMLABEL_WIDTH) widgets[1].setFixedWidth(self.PARAMETERS_WIDTH) widgets[2].setFixedWidth(self.PARAMLABEL_WIDTH) widgets[3].setFixedWidth(self.PARAMETERS_WIDTH) # we add a QLabel to make sure we have two rows not too close together return self.getHorizontalLayoutFactory([ widgets[0], widgets[1], Qt.QLabel(" " * 10), widgets[2], widgets[3] ]) return self.getHorizontalLayoutFactory([]) def getGridLayoutFactory(self, widgets): gridBoxLayout = QtGui.QGridLayout() count = 0 for widget in widgets: gridBoxLayout.addWidget(widget, 0, count) count = count + 1 return gridBoxLayout def getHorizontalLayoutFactory(self, widgets): hBoxLayout = Qt.QHBoxLayout() hBoxLayout.setAlignment(QtCore.Qt.AlignLeft) for widget in widgets: hBoxLayout.addWidget(widget) return hBoxLayout def getColumns(self): self.UP_COLUMN = 0 self.DOWN_COLUMN = 1 self.ENABLE_COLUMN = 2 self.SAMPLETYPE_COLUMN = 3 self.PLATE_COLUMN = 4 self.ROW_COLUMN = 5 self.WELL_COLUMN = 6 self.CONCENTRATION_COLUMN = 7 self.COMMENTS_COLUMN = 8 self.MACROMOLECULE_COLUMN = 9 self.CODE_COLUMN = 10 self.VISCOSITY_COLUMN = 11 self.BUFFERNAME_COLUMN = 12 self.TRANSMISSION_COLUMN = 13 self.VOLUME_COLUMN = 14 self.TEMPERATURE_COLUMN = 15 self.FLOW_COLUMN = 16 self.RECUPERATE_COLUMN = 17 self.WAITTIME_COLUMN = 18 self.DELETE_COLUMN = 19 return [ "", "", "Use", "Type", "Plate", "Row", "Well", \ "Concentration", "Comments", "Macromol.", "Code", "Viscosity", "Buffername", \ "Transmission", "Volume", "SEU Temp", "Flow", "Recup", \ "Wait", "Del"] # When connected to Login, then block the brick def connectionToLogin(self, pPeer): if pPeer is not None: self.brick_widget.setEnabled(False) # Logged In : True or False def loggedIn(self, pValue): self.brick_widget.setEnabled(pValue) # add automatically the robot from CollectBrick robotFileName = self.collectBrickObject.getRobotFileName() self.fileLineEdit.setText(robotFileName) if not os.path.exists(robotFileName): if robotFileName != "": Qt.QMessageBox.critical( self.brick_widget, "Error", "Robot file %r does not exist anymore. I will start with an empty one" % robotFileName, Qt.QMessageBox.Ok) self.fileLineEdit.setText("") self.collectBrickObject.setRobotFileName("") if os.path.exists(robotFileName): filename = str(robotFileName) self.loadFile(filename) # Connect to display def grayOut(self, grayout): if grayout is not None: if grayout: self.brick_widget.setEnabled(False) else: self.brick_widget.setEnabled(True) def displayResetChanged(self): pass def displayItemChanged(self, __): pass def transmissionChanged(self, __): pass #TODO: Staffan's note: take it away # def clearHistory( self ): # self.historyText.clear() #TODO: Staffan's note: take it away # def addHistory( self, pLevel, pMessage ): # strLevel = ['INFO', 'WARNING', 'ERROR'] # message = "<i>[%s] %s:</i> <b>%s</b>" % ( time.strftime( "%Y/%m/%d %H:%M:%S" ), strLevel[ pLevel] , pMessage ) # # self.historyText.append( message ) def getCollectRobotPars(self, isAll=0): params = CollectPars() sampleList = SampleList() bufferList = SampleList() params.sampleType = self.sampleTypeComboBox.currentText() params.storageTemperature = self.storageTemperatureDoubleSpinBox.value( ) params.extraFlowTime = self.extraFlowTimeSpinBox.value() params.optimization = self.optimizationComboBox.currentIndex() params.optimizationText = self.optimizationComboBox.currentText() params.initialCleaning = self.initialCleaningCheckBox.isChecked() params.bufferMode = self.bufferModeComboBox.currentIndex() #================================================= # myBuffer mode #================================================= params.bufferFirst = False params.bufferBefore = False params.bufferAfter = False if params.bufferMode == 0: params.bufferFirst = True params.bufferAfter = True elif params.bufferMode == 1: params.bufferBefore = True elif params.bufferMode == 2: params.bufferAfter = True #================================================= # optimization mode #================================================= params.optimSEUtemp = False params.optimCodeAndSEU = False if params.optimization == 1: params.optimSEUtemp = True elif params.optimization == 2: params.optimCodeAndSEU = True # add alll samples into bufferList and sampleList for i in range(0, self.tableWidget.rowCount()): sample = self.getSampleRow(i) if isAll or sample.enable: if sample.isBuffer(): bufferList.append(sample) else: sampleList.append(sample) #================================================= # assign myBuffer to sample # TODO: allow to assign more than one myBuffer. isAll with same name #================================================= for sample in sampleList: sample.buffer = [] if len( bufferList ) == 1: # if there is one and only one myBuffer defined dont look at name. assign sample.buffer.append(bufferList[0]) else: for myBuffer in bufferList: if myBuffer.buffername == sample.buffername: sample.buffer.append(myBuffer) # Optimize data collection procedure (if requested) if params.optimSEUtemp: sampleList.sortSEUtemp() elif params.optimCodeAndSEU: sampleList.sortCodeAndSEU() params.sampleList = sampleList params.bufferList = bufferList return params def loadPushButtonClicked(self): dirname = "" self.filename = str(self.fileLineEdit.text()) if self.filename != "": dirname = os.path.split(self.filename)[0] else: try: dirname = os.path.split( self.collectBrickObject.collectpars.directory) except Exception, e: print "Ignored Exception 6: " + str(e) traceback.print_exc() filename = Qt.QFileDialog.getOpenFileName(self.brick_widget, "Choose a new file to load", dirname, "XML File (*.xml)") if not filename: return self.fileLineEdit.setText(filename) filename = str(filename) self.loadFile(filename)
class BsxGraphBrick(BaseBrick): properties = { "title": Property("string", "Title", "", "titleChanged", "untitled"), "lineWidth": Property("integer", "Line width", "", "lineWidthChanged", 1), "enableGrid": Property("boolean", "Enable grid", "", "enableGridChanged", False), "enableZoom": Property("boolean", "Enable zoom", "", "enableZoomChanged", False), "showPrintButton": Property("boolean", "Show print button", "", "showPrintButtonChanged", True), "showScaleButton": Property("boolean", "Show scale button", "", "showScaleButtonChanged", True), "showGridButton": Property("boolean", "Show grid button", "", "showGridButtonChanged", True), "yAxisLabel": Property("string", "Y axis label", "", "yAxisLabelChanged", ""), "y2AxisLabel": Property("string", "Y2 axis label", "", "y2AxisLabelChanged", ""), "xAxisLabel": Property("string", "X axis label", "", "xAxisLabelChanged", ""), "titleFontSize": Property("combo", "Title font size", "", "titleFontSizeChanged", "14", [ "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24" ]), "axisFontSize": Property("combo", "Axis font size", "", "axisFontSizeChanged", "8", ["6", "7", "8", "9", "10", "11", "12"]), "defaultScale": Property("combo", "Default scale", "", "defaultScaleChanged", "linear", ["linear", "logarithmic"]), "timeOnXAxis": Property("boolean", "Time on X axis", "", "timeOnXAxisChanged", False), "timeElapsedTime": Property("boolean", "Elapsed time", "", "timeElapsedTimeChanged", True), "windowSize": Property("integer", "Window size", "", "windowSizeChanged", "3600") } connections = { "y_curves": Connection("Y-mapped curves provider", [ Signal('new_curves_data', 'new_curves_data'), Signal('erase_curve', 'erase_curve') ], [], 'y_curves_provider_connected'), 'y_scan': Connection( 'Y scan provider', [Signal('new_scan', 'new_scan'), Signal('new_point', 'new_value')], [], 'y_scan_provider_connected') } def __init__(self, *args, **kargs): BaseBrick.__init__(self, *args, **kargs) def init(self): self.__axis_provider = dict() self.__curves_by_provider = dict() self.graphLayout = Qt.QVBoxLayout() self.graphSubLayout = Qt.QHBoxLayout() self.qtBlissGraph = QtBlissGraph() self.graphLayout.addWidget(self.qtBlissGraph) self.printPushButton = Qt.QPushButton("Print") self.graphSubLayout.addWidget(self.printPushButton) Qt.QObject.connect(self.printPushButton, Qt.SIGNAL("clicked()"), self.printPushButtonClicked) self.current_scale = "linear" self.scalePushButton = Qt.QPushButton("Scale") self.scaleMenu = Qt.QMenu(self.scalePushButton) self.scaleActionGroup = Qt.QActionGroup(self.scaleMenu) self.scaleMenuLinear = Qt.QAction("Linear", self.scaleActionGroup) self.scaleMenuLinear.setCheckable(True) self.scaleMenu.addAction(self.scaleMenuLinear) self.scaleMenuLogarithmic = Qt.QAction("Logarithmic", self.scaleActionGroup) self.scaleMenuLogarithmic.setCheckable(True) self.scaleMenu.addAction(self.scaleMenuLogarithmic) Qt.QObject.connect(self.scaleActionGroup, Qt.SIGNAL("triggered(QAction*)"), self.scaleActionGroupTriggered) self.scalePushButton.setMenu(self.scaleMenu) self.graphSubLayout.addWidget(self.scalePushButton) self.gridPushButton = Qt.QPushButton("Grid") self.gridMenu = Qt.QMenu(self.gridPushButton) self.gridActionGroup = Qt.QActionGroup(self.gridMenu) self.gridMenuEnable = Qt.QAction("Enable", self.gridActionGroup) self.gridMenuEnable.setCheckable(True) self.gridMenu.addAction(self.gridMenuEnable) self.gridMenuDisable = Qt.QAction("Disable", self.gridActionGroup) self.gridMenuDisable.setCheckable(True) self.gridMenuDisable.setChecked(True) self.gridMenu.addAction(self.gridMenuDisable) Qt.QObject.connect(self.gridActionGroup, Qt.SIGNAL("triggered(QAction*)"), self.gridActionGroupTriggered) self.gridPushButton.setMenu(self.gridMenu) self.graphSubLayout.addWidget(self.gridPushButton) self.resetPushButton = Qt.QPushButton("Reset") self.graphSubLayout.addWidget(self.resetPushButton) Qt.QObject.connect(self.resetPushButton, Qt.SIGNAL("clicked()"), self.resetPushButtonClicked) self.graphLayout.addLayout(self.graphSubLayout) self.brick_widget.setLayout(self.graphLayout) self.curveData = {} self.timeAxisX = False self.timeAxisElapsedTime = True self.windowSize = None def addCurve(self, pCurve): curveName = pCurve["name"] maptoy2 = pCurve.get("maptoy2", False) if not curveName in self.curveData: self.curveData[curveName] = CurveData(curveName, maptoy2=maptoy2) self.qtBlissGraph.newCurve(curveName, x=self.curveData[curveName].x, y=self.curveData[curveName].y, maptoy2=maptoy2) def addPoint(self, pCurveName, x=None, y=None, pTimeOut=False, replot=True): if y is None: return else: y = float(y) curveData = self.curveData[pCurveName] if self.timeAxisX: if self.timeAxisElapsedTime: if curveData.t0 is None: # 't0' is the starting time (first point added) curveData.t0 = time.time() curveData.t = curveData.t0 t = 0 else: # 't' is the time elapsed between the new point and the previous one t = time.time() - curveData.t curveData.t += t else: t = int(time.strftime("%S")) + int( time.strftime("%H")) * 3600 + int(time.strftime("%M")) * 60 curveData.t = t if self.windowSize > 0: x = 0 n0 = len(curveData.x) curveData.x = filter( None, [x + self.windowSize > 0 and x - t for x in curveData.x]) n = len(curveData.x) if n0 > n: curveData.y = curveData.y[n0 - n:] else: if self.timeAxisElapsedTime: x = curveData.t - curveData.t0 else: x = curveData.t elif x is not None: x = float(x) else: if pTimeOut: return if len(curveData.x) > 0: x = curveData.x[-1] + 1 else: x = 0 curveData.x.append(x) curveData.y.append(y) if self.windowSize: if not self.timeAxisX and len(curveData.y) == self.windowSize: del curveData.y[0] del curveData.x[0] if replot: self.qtBlissGraph.newCurve(pCurveName, curveData.x, curveData.y, maptoy2=curveData.maptoy2) self.qtBlissGraph.replot() def removeCurve(self, pCurveName): try: del self.curveData[pCurveName] except KeyError: pass else: self.qtBlissGraph.newCurve(pCurveName, [], []) def new_y_axis_value(self, *args, **kwargs): self.new_value(*args, **kwargs) def new_y2_axis_value(self, *args, **kwargs): kwargs['maptoy2'] = True self.new_value(*args, **kwargs) def new_curves_data(self, *args, **kwargs): self.new_value(*args, **kwargs) def y2_curves_data(self, *args, **kwargs): kwargs['maptoy2'] = True self.new_value(*args, **kwargs) def new_value(self, value, sender=None, maptoy2=False, signal=None, replot=True): if type(value) == types.DictType: #dict in the form {curvename: [[values for x],[values for y]]} # call ourselves one time per value pair for curve, points in value.iteritems(): self.erase_curve(curve) for (x, y) in zip(points[0], points[1]): self.new_value((x, y, curve), sender=sender, maptoy2=maptoy2, replot=False) curveData = self.curveData[curve] #TODO: taking away the two next lines does a lot for speed - Need to know if hidden and see if we can unhide it self.qtBlissGraph.newCurve(curve, curveData.x, curveData.y, maptoy2=maptoy2) self.qtBlissGraph.replot() return # if value is not a dict, proceed as usual # it's either a tuple or a discrete value if type(value) == types.TupleType and len(value) == 3: curveName = value[2] else: curveName = sender.username() if sender not in self.__curves_by_provider.keys(): self.__curves_by_provider[sender] = [curveName] else: if curveName not in self.__curves_by_provider[sender]: self.__curves_by_provider[sender].append(curveName) if value is None: self.removeCurve(curveName) else: if not curveName in self.curveData: self.addCurve({"name": curveName, 'maptoy2': maptoy2}) if type(value) == types.TupleType: if len(value) >= 2: self.addPoint(curveName, x=value[0], y=value[1], replot=replot) else: self.addPoint(curveName, y=value, replot=replot) def erase_curve(self, curve_name, sender=None): """If the curve_name is None or empty, erase all curves (created by objects sending data packs)""" #logging.debug('%s: erase_curve called with curve_name=%s and sender=%s', self, curve_name, sender) #logging.debug('curves by sender: %r', self.__curves_by_provider) if curve_name is None: if sender is not None: for curve in self.__curves_by_provider.get(sender, []): #logging.debug(' removing curve %s', curve) self.removeCurve(curve) else: self.removeCurve(curve_name) def new_scan(self, parameters, sender=None): self.erase_curve(None, sender) ylabel = parameters.get('ylabel', "") xlabel = parameters.get('xlabel', "") title = parameters.get('title', '') self.qtBlissGraph.setTitle(title) self.qtBlissGraph.xlabel(xlabel) if self.__axis_provider.get(sender, 'y') == 'y': self.qtBlissGraph.ylabel(ylabel) else: self.qtBlissGraph.setAxisTitle(qwt.QwtPlot.yRight, ylabel) def y_curves_provider_connected(self, provider): pass def y_scan_provider_connected(self, provider): self.__axis_provider[provider] = 'y' def titleChanged(self, pValue): self.qtBlissGraph.setTitle(pValue) def lineWidthChanged(self, pValue): self.qtBlissGraph.setactivelinewidth(pValue) self.qtBlissGraph.linewidth = pValue self.qtBlissGraph.replot() def enableGridChanged(self, pValue): if pValue: self.gridMenuEnable.setChecked(True) self.qtBlissGraph.showGrid() else: self.gridMenuDisable.setChecked(True) self.qtBlissGraph.hideGrid() self.qtBlissGraph.replot() def enableZoomChanged(self, pValue): self.qtBlissGraph.enableZoom(pValue) def showPrintButtonChanged(self, pValue): if self.printPushButton is not None: self.printPushButton.setVisible(pValue) def showScaleButtonChanged(self, pValue): if self.scalePushButton is not None: self.scalePushButton.setVisible(pValue) def showGridButtonChanged(self, pValue): if self.gridPushButton is not None: self.gridPushButton.setVisible(pValue) def xAxisLabelChanged(self, pValue): self.qtBlissGraph.xlabel(pValue) def yAxisLabelChanged(self, pValue): self.qtBlissGraph.ylabel(pValue) def y2AxisLabelChanged(self, pValue): self.qtBlissGraph.setAxisTitle(qwt.QwtPlot.yRight, pValue) def titleFontSizeChanged(self, pValue): title = self.qtBlissGraph.title() font = title.font() font.setPointSize(int(pValue)) title.setFont(font) self.qtBlissGraph.setTitle(title) def axisFontSizeChanged(self, pValue): titleX = self.qtBlissGraph.axisTitle(qwt.QwtPlot.xBottom) titleY = self.qtBlissGraph.axisTitle(qwt.QwtPlot.yLeft) titleY2 = self.qtBlissGraph.axisTitle(qwt.QwtPlot.yRight) fontX = titleX.font() fontY = titleY.font() fontY2 = titleY2.font() size = int(pValue) fontX.setPointSize(size) fontY.setPointSize(size) fontY2.setPointSize(size) titleX.setFont(fontX) titleY.setFont(fontY) titleY2.setFont(fontY2) self.qtBlissGraph.setAxisFont(qwt.QwtPlot.xBottom, fontX) self.qtBlissGraph.setAxisFont(qwt.QwtPlot.yLeft, fontY) self.qtBlissGraph.setAxisFont(qwt.QwtPlot.yRight, fontY2) self.qtBlissGraph.setAxisTitle(qwt.QwtPlot.xBottom, titleX) self.qtBlissGraph.setAxisTitle(qwt.QwtPlot.yLeft, titleY) self.qtBlissGraph.setAxisTitle(qwt.QwtPlot.yRight, titleY2) def timeOnXAxisChanged(self, pValue): self.timeAxisX = pValue for curveData in self.curveData.itervalues(): curveData.clear() self.qtBlissGraph.newCurve(str(curveData.objectName()), x=[], y=[], maptoy2=curveData.maptoy2) self.setXAxisScale() def setXAxisScale(self): if self.timeAxisX: self.qtBlissGraph.setx1timescale(True) if self.windowSize is not None: if self.windowSize <= 0: self.qtBlissGraph.xAutoScale = True #self.graphWidget.setAxisAutoScale(qwt.QwtPlot.xBottom) else: self.qtBlissGraph.setX1AxisLimits(0 - int(self.windowSize), 0) #self.graphWidget.setAxisScale(qwt.QwtPlot.xBottom, 0 - self.windowSize, 0) else: self.qtBlissGraph.setx1timescale(False) self.qtBlissGraph.xAutoScale = True #self.graphWidget.setAxisAutoScale(qwt.QwtPlot.xBottom) self.qtBlissGraph.replot() def timeElapsedTimeChanged(self, pValue): self.timeAxisElapsedTime = pValue def windowSizeChanged(self, pValue): self.windowSize = pValue self.setXAxisScale() def printPushButtonClicked(self): self.qtBlissGraph.printps() def scaleActionGroupTriggered(self, scale_action): if scale_action == self.scaleMenuLinear: if self.current_scale != "linear": self.current_scale = "linear" self.qtBlissGraph.toggleLogY() else: if self.current_scale == "linear": self.current_scale = "logarithmic" self.qtBlissGraph.toggleLogY() def defaultScaleChanged(self, scale): if scale == "linear": self.scaleMenuLinear.setChecked(True) self.scaleActionGroupTriggered(self.scaleMenuLinear) else: #logarithmic self.scaleMenuLogarithmic.setChecked(True) self.scaleActionGroupTriggered(self.scaleMenuLogarithmic) def gridActionGroupTriggered(self, pValue): self.setProperty("enableGrid", pValue == self.gridMenuEnable) def resetPushButtonClicked(self): curve_names = self.curveData.keys() for name in curve_names: self.erase_curve(name) self.qtBlissGraph.replot()
class BrowseBrick(Core.BaseBrick): properties = { "enableType": Property("boolean", "Enable type", "", "enableTypeChanged", True) } connections = { "browse": Connection("Browse object", [], [], "connectionStatusChanged"), "image_proxy": Connection("image proxy", [], [Slot('load_files')]), "login": Connection("Login object", [Signal("loggedIn", "loggedIn")], [], "connectionToLogin") } signals = [ Signal("displayResetChanged"), Signal("displayItemChanged"), Signal("transmissionChanged"), Signal("grayOut", "grayOut") ] slots = [] def __init__(self, *args, **kargs): Core.BaseBrick.__init__(self, *args, **kargs) def init(self): self.__expertMode = False self.__formats = [["All", ""], ["Raw EDF (*.edf)", "edf"], ["Normalised EDF (*.edf)", "edf"], ["Bruker (*.gfrm)", "gfrm"], ["ADSC (*.img)", "img"], ["Mar CCD (*.mccd)", "mccd"], ["SPEC (*.dat)", "dat"]] self.brick_widget.setLayout(Qt.QVBoxLayout()) self.brick_widget.layout().setAlignment(QtCore.Qt.AlignTop) self.brick_widget.setSizePolicy(Qt.QSizePolicy.Expanding, Qt.QSizePolicy.Expanding) self.hBoxLayout0 = Qt.QHBoxLayout() self.typeLabel = Qt.QLabel("Type", self.brick_widget) self.typeLabel.setFixedWidth(130) self.hBoxLayout0.addWidget(self.typeLabel) self.typeComboBox = Qt.QComboBox(self.brick_widget) self.typeComboBox.addItems(["Normal", "HDF"]) Qt.QObject.connect(self.typeComboBox, Qt.SIGNAL("currentIndexChanged(int)"), self.typeComboBoxChanged) self.hBoxLayout0.addWidget(self.typeComboBox) self.brick_widget.layout().addLayout(self.hBoxLayout0) self.hBoxLayout1 = Qt.QHBoxLayout() self.locationLabel = Qt.QLabel(self.brick_widget) self.locationLabel.setFixedWidth(130) self.hBoxLayout1.addWidget(self.locationLabel) self.locationLineEdit = Qt.QLineEdit(self.brick_widget) self.locationLineEdit.setMaxLength(100) Qt.QObject.connect(self.locationLineEdit, Qt.SIGNAL("textChanged(const QString &)"), self.locationLineEditChanged) self.hBoxLayout1.addWidget(self.locationLineEdit) self.locationPushButton = Qt.QPushButton("...", self.brick_widget) self.locationPushButton.setFixedWidth(25) Qt.QObject.connect(self.locationPushButton, Qt.SIGNAL("clicked()"), self.locationPushButtonClicked) self.hBoxLayout1.addWidget(self.locationPushButton) self.brick_widget.layout().addLayout(self.hBoxLayout1) self.hBoxLayout2 = Qt.QHBoxLayout() self.formatLabel = Qt.QLabel("Format", self.brick_widget) self.formatLabel.setFixedWidth(130) self.hBoxLayout2.addWidget(self.formatLabel) self.formatComboBox = Qt.QComboBox(self.brick_widget) Qt.QObject.connect(self.formatComboBox, Qt.SIGNAL("currentIndexChanged(int)"), self.formatComboBoxChanged) self.hBoxLayout2.addWidget(self.formatComboBox) self.brick_widget.layout().addLayout(self.hBoxLayout2) self.hBoxLayout3 = Qt.QHBoxLayout() self.prefixLabel = Qt.QLabel("Prefix", self.brick_widget) self.prefixLabel.setFixedWidth(130) self.hBoxLayout3.addWidget(self.prefixLabel) self.prefixComboBox = Qt.QComboBox(self.brick_widget) Qt.QObject.connect(self.prefixComboBox, Qt.SIGNAL("currentIndexChanged(int)"), self.prefixComboBoxChanged) self.hBoxLayout3.addWidget(self.prefixComboBox) self.brick_widget.layout().addLayout(self.hBoxLayout3) self.hBoxLayout4 = Qt.QHBoxLayout() self.runNumberLabel = Qt.QLabel("Run #", self.brick_widget) self.runNumberLabel.setFixedWidth(130) self.hBoxLayout4.addWidget(self.runNumberLabel) self.runNumberComboBox = Qt.QComboBox(self.brick_widget) Qt.QObject.connect(self.runNumberComboBox, Qt.SIGNAL("currentIndexChanged(int)"), self.runNumberComboBoxChanged) self.hBoxLayout4.addWidget(self.runNumberComboBox) self.brick_widget.layout().addLayout(self.hBoxLayout4) self.hBoxLayout5 = Qt.QHBoxLayout() self.extraLabel = Qt.QLabel("Extra", self.brick_widget) self.extraLabel.setFixedWidth(130) self.hBoxLayout5.addWidget(self.extraLabel) self.extraComboBox = Qt.QComboBox(self.brick_widget) Qt.QObject.connect(self.extraComboBox, Qt.SIGNAL("currentIndexChanged(int)"), self.extraComboBoxChanged) self.hBoxLayout5.addWidget(self.extraComboBox) self.brick_widget.layout().addLayout(self.hBoxLayout5) self.hBoxLayout6 = Qt.QHBoxLayout() self.itemsLabel = Qt.QLabel("Items (0)", self.brick_widget) self.itemsLabel.setFixedWidth(130) self.hBoxLayout6.addWidget(self.itemsLabel) self.itemsListWidget = Qt.QListWidget(self.brick_widget) Qt.QObject.connect(self.itemsListWidget, Qt.SIGNAL("itemSelectionChanged()"), self.itemsListWidgetChanged) self.hBoxLayout6.addWidget(self.itemsListWidget) self.brick_widget.layout().addLayout(self.hBoxLayout6) self.vBoxLayout0 = Qt.QVBoxLayout() self.vBoxLayout0.addSpacing(20) self.brick_widget.layout().addLayout(self.vBoxLayout0) self.hBoxLayout7 = Qt.QHBoxLayout() self.refreshPushButton = Qt.QPushButton("Refresh", self.brick_widget) self.refreshPushButton.setToolTip( "Refresh item list with the specified parameters") self.hBoxLayout7.addWidget(self.refreshPushButton) Qt.QObject.connect(self.refreshPushButton, Qt.SIGNAL("clicked()"), self.refreshPushButtonClicked) self.brick_widget.layout().addLayout(self.hBoxLayout7) self.typeComboBoxChanged(self.typeComboBox.currentIndex()) self.locationLineEditChanged(None) # When connected to Login, then block the brick def connectionToLogin(self, pPeer): if pPeer is not None: self.brick_widget.setEnabled(False) # Logged In : True or False def loggedIn(self, pValue): self.brick_widget.setEnabled(pValue) def connectionStatusChanged(self, pPeer): pass def delete(self): pass def enableTypeChanged(self, pValue): self.typeComboBox.setVisible(pValue) self.typeLabel.setVisible(pValue) self.typeComboBox.setCurrentIndex(0) def typeComboBoxChanged(self, pValue): self.formatComboBox.clear() if pValue == 0: self.locationLabel.setText("Directory") for description, self.__ignore in self.__formats: self.formatComboBox.addItem(description) else: self.locationLabel.setText("File") self.formatComboBox.addItems([ "Raw EDF (frame)", "Normalised EDF (frame)", "SPEC (curve)" ]) self.locationChanged(self.locationLineEdit.text(), pValue) def locationLineEditChanged(self, pValue): self.locationChanged(pValue, self.typeComboBox.currentIndex()) def locationChanged(self, pValue, pType): if pType == 0: # directory if pValue is not None and os.path.exists( pValue) and not os.path.isfile(pValue): if str(pValue).find(" ") == -1: self.locationLineEdit.palette().setColor( QtGui.QPalette.Base, QtGui.QColor(255, 255, 255)) else: self.locationLineEdit.palette().setColor( QtGui.QPalette.Base, QtGui.QColor(255, 255, 0)) else: self.locationLineEdit.palette().setColor( QtGui.QPalette.Base, QtGui.QColor(255, 0, 0)) else: # HDF file if pValue is not None and os.path.exists( pValue) and os.path.isfile(pValue): self.locationLineEdit.palette().setColor( QtGui.QPalette.Base, QtGui.QColor(255, 255, 255)) else: self.locationLineEdit.palette().setColor( QtGui.QPalette.Base, QtGui.QColor(255, 0, 0)) self.locationLineEdit.update() self.populatePrefixComboBox() self.populateRunNumberComboBox() self.populateExtraComboBox() self.populateItemsListWidget() def locationPushButtonClicked(self): if self.typeComboBox.currentIndex() == 0: qFileDialog = QtGui.QFileDialog(self.brick_widget, "Choose a directory", self.locationLineEdit.text()) qFileDialog.setFileMode(QtGui.QFileDialog.DirectoryOnly) else: qFileDialog = QtGui.QFileDialog(self.brick_widget, "Choose a HDF file", self.locationLineEdit.text()) qFileDialog.setAcceptMode(QtGui.QFileDialog.AcceptOpen) qFileDialog.setFilters(["Hierarchical Data Format (*.h5; *.hdf5)"]) if qFileDialog.exec_(): self.locationLineEdit.setText(str(qFileDialog.selectedFiles()[0])) def formatComboBoxChanged(self, pValue): if pValue is not None: if self.typeComboBox.currentIndex() == 0: directory = ("", "raw", "2d", "raw", "raw", "raw", "1d")[self.formatComboBox.currentIndex()] if directory != "": directoryList = str( self.locationLineEdit.text()).split("/") for i in range(len(directoryList) - 1, -1, -1): if directoryList[i] != "": if directoryList[i] in ("raw", "1d", "2d"): directoryList[i] = directory else: directoryList.insert(i + 1, directory) break directory = "" for i in range(0, len(directoryList)): if directoryList[i] != "": directory += "/" + directoryList[i] if os.path.exists(directory): self.locationLineEdit.setText(directory) if self.formatComboBox.currentIndex() == 6: self.itemsListWidget.setSelectionMode( QtGui.QAbstractItemView.ExtendedSelection) else: self.itemsListWidget.setSelectionMode( QtGui.QAbstractItemView.SingleSelection) else: pass # implement HDF self.populatePrefixComboBox() self.populateRunNumberComboBox() self.populateExtraComboBox() self.populateItemsListWidget() def prefixComboBoxChanged(self, pValue): if pValue is not None: self.populateRunNumberComboBox() self.populateExtraComboBox() self.populateItemsListWidget() def runNumberComboBoxChanged(self, pValue): if pValue is not None: self.populateExtraComboBox() self.populateItemsListWidget() def extraComboBoxChanged(self, pValue): if pValue is not None: self.populateItemsListWidget() def itemsListWidgetChanged(self): if str(self.locationLineEdit.text()).endswith("/"): directory0 = self.locationLineEdit.text() else: directory0 = self.locationLineEdit.text() + "/" items = "" for item in self.itemsListWidget.selectedItems(): if items == "": items = str(directory0 + item.text()) else: items += "," + str(directory0 + item.text()) if item.text().split(".")[-1] != "dat": directoryList = str(self.locationLineEdit.text()).split("/") for i in range(len(directoryList) - 1, -1, -1): if directoryList[i] != "": if directoryList[i] in ("raw"): directoryList[i] = "1d" else: directoryList.insert(i + 1, "1d") break directory1 = "" for i in range(0, len(directoryList)): if directoryList[i] != "": directory1 += "/" + directoryList[i] filename = str(directory1 + "/" + item.text().split(".")[0] + ".dat") if os.path.exists(filename): items += "," + filename self.emit("displayItemChanged", items) self.getObject('image_proxy').load_files(items.split(',')) def refreshPushButtonClicked(self): self.populateItemsListWidget() def populatePrefixComboBox(self): items = [] if self.typeComboBox.currentIndex() == 0: comboFormat = self.__formats[self.formatComboBox.currentIndex()][1] if os.path.isdir(self.locationLineEdit.text()): try: for filename in os.listdir(self.locationLineEdit.text()): if os.path.isfile(self.locationLineEdit.text() + "/" + filename): prefix, self.__runIgnored, self.__frameIgnored, self.__extraIgnored, extension = self.getFilenameDetails( filename) flag = False if self.formatComboBox.currentIndex() == 0: for i in range(1, len(self.__formats)): if extension == self.__formats[i][1]: flag = True break else: flag = (extension == comboFormat) if flag: try: items.index(prefix) except ValueError: items.append(prefix) except Exception, e: logger.error("Full Exception: " + str(e)) else:
class BsxShutterBrick(Core.BaseBrick): description = 'Simple class to display and control a shutter' properties = { "icons": PropertyGroup( "Icons", "Select icons for different elements", "set_icons", { "opened": Property("image", "Opened"), "closed": Property("image", "Closed") }), 'shutter_name': Property( 'string', #type 'Shutter name', #label 'The name of the shutter', #description 'shutterNameStateChanged', #onchange_cb '') #default value , 'show_state': Property( 'boolean', #type 'Show state', #label '', #description 'showStateChanged', #onchange_cb True) #default value , 'show_button': Property( 'boolean', #type 'Show button', #label 'Allow the user to manipulate the shutter\'s state', #description 'showButtonChanged', #onchange_cb True) #default value , 'orientation': Property( 'combo', #type 'Orientation', #label description='Layout of widgets', onchange_cb='orientationChanged', default='Portrait', choices=['Portrait', 'Landscape']) } connections = { "shutter": Connection("Shutter object", [Signal("stateChanged", "shutter_state_changed")], [Slot("open"), Slot("close")], "connectionStatusChanged"), "display": Connection("Display object", [ Signal("displayResetChanged", "displayResetChanged"), Signal("displayItemChanged", "displayItemChanged"), Signal("transmissionChanged", "transmissionChanged"), Signal("grayOut", "grayOut") ], []), "login": Connection("Login object", [Signal("loggedIn", "loggedIn")], [], "connectionToLogin") } # TACO Shutterstate # shutterState = {"unknown": Qt.QColor(0x64, 0x64, 0x64), # "closed": Qt.QColor(0xff, 0x0, 0xff), # "opened": Qt.QColor(0x0, 0xff, 0x0), # "moving": Qt.QColor(0x66, 0x33, 0x0), # "automatic": Qt.QColor(0x0, 0x99, 0x0), # "fault": Qt.QColor(0x99, 0x0, 0x0), # "disabled": Qt.QColor(0xec, 0x3c, 0xdd), # "error": Qt.QColor(0xff, 0x0, 0x0)} # TANGO Shutterstate shutterState = { "on": Qt.QColor(0x0, 0xff, 0x0), "off": Qt.QColor(0xec, 0x3c, 0xdd), "closed": Qt.QColor(0xff, 0x0, 0xff), "opened": Qt.QColor(0x0, 0xff, 0x0), "insert": Qt.QColor(0x66, 0x33, 0x0), "extract": Qt.QColor(0x66, 0x33, 0x0), "moving": Qt.QColor(0xff, 0xa5, 0x0), "standby": Qt.QColor(0x66, 0x33, 0x0), "fault": Qt.QColor(0xff, 0x0, 0x0), "init": Qt.QColor(0x66, 0x33, 0x0), "running": Qt.QColor(0x66, 0x33, 0x0), "alarm": Qt.QColor(0x99, 0x0, 0x0), "disabled": Qt.QColor(0xec, 0x3c, 0xdd), "unknown": Qt.QColor(0x64, 0x64, 0x64), "error": Qt.QColor(0xff, 0x0, 0x0) } def __init__(self, *args, **kwargs): Core.BaseBrick.__init__(self, *args, **kwargs) def init(self): self.shutterName = None self.state = None self.loginDone = False self.shutter_state = Qt.QLabel("Unknown", self.brick_widget) self.shutter_state.setAutoFillBackground(True) self.shutter_state.palette().setColor(QtGui.QPalette.Background, self.shutterState["unknown"]) self.shutter_state.setAlignment(Qt.Qt.AlignCenter) self.shutter_state.setToolTip("Current shutter state") self.shutter_cmd = Qt.QPushButton("Unknown", self.brick_widget) self.shutter_cmd.setToolTip("Unknown shutter state") Qt.QObject.connect(self.shutter_cmd, Qt.SIGNAL("clicked()"), self.shutter_cmd_clicked) # When connected to Login, then block the brick def connectionToLogin(self, pPeer): if pPeer is not None: # Check if we were already connected first if not self.loginDone: self.brick_widget.setEnabled(False) # Logged In : True or False def loggedIn(self, pValue): self.loginDone = pValue self.brick_widget.setEnabled(pValue) # Connect to display def grayOut(self, grayout): if grayout is not None: if grayout: self.brick_widget.setEnabled(False) else: self.brick_widget.setEnabled(True) def displayResetChanged(self): pass def displayItemChanged(self, __): pass def transmissionChanged(self, __): pass def set_icons(self, icons): pass def shutterNameStateChanged(self, pValue): self.shutterName = pValue self.shutter_state.setToolTip("Current '%s' shutter state" % self.shutterName) state = self.state # force redisplay of state so the shutter name is displayed. if state is None: state = 'unknown' self.shutter_state_changed(state) def showStateChanged(self, pValue): if self.shutter_state is not None: self.shutter_state.setVisible(pValue) def showButtonChanged(self, pValue): if self.shutter_cmd is not None: self.shutter_cmd.setVisible(pValue) def orientationChanged(self, pValue): if self.brick_widget.layout() is not None: self.brick_widget.layout().removeWidget(self.shutter_state) self.brick_widget.layout().removeWidget(self.shutter_cmd) sip.transferback(self.brick_widget.layout()) if pValue == "Landscape": self.brick_widget.setLayout(Qt.QHBoxLayout()) else: self.brick_widget.setLayout(Qt.QVBoxLayout()) self.brick_widget.layout().addWidget(self.shutter_state) self.brick_widget.layout().addWidget(self.shutter_cmd) def shutter_state_changed(self, state): self.state = state if state in ("opened", "automatic"): self.shutter_cmd.setText("Close") self.shutter_cmd.setEnabled(True) if self.shutterName is None: self.shutter_cmd.setToolTip("Close shutter") else: self.shutter_cmd.setToolTip("Close '%s' shutter" % self.shutterName) elif state == "unknown": self.shutter_cmd.setText("Unknown") self.shutter_cmd.setEnabled(True) if self.shutterName is None: self.shutter_cmd.setToolTip("Unknown shutter state") else: self.shutter_cmd.setToolTip("Unknown '%s' shutter state" % self.shutterName) else: self.shutter_cmd.setText("Open") self.shutter_cmd.setEnabled(True) if self.shutterName is None: self.shutter_cmd.setToolTip("Open shutter") else: self.shutter_cmd.setToolTip("Open '%s' shutter" % self.shutterName) palette = self.shutter_state.palette() palette.setColor(QtGui.QPalette.Background, self.shutterState[state]) self.shutter_state.setPalette(palette) if self.shutterName is not None: state = '%s: %s' % (self.shutterName, state) self.shutter_state.setText(state) def connectionStatusChanged(self, pPeer): self.brick_widget.setEnabled(pPeer is not None) if pPeer is not None: pPeer.connect("ready", self.enable) def enable(self, arg): self.brick_widget.setEnabled(arg) def shutter_cmd_clicked(self): if self.shutter_cmd.text() == "Open": if self.shutterName is None: logger.info("Opening shutter...") else: logger.info("Opening '%s' shutter..." % self.shutterName) self.getObject('shutter').open() else: if self.shutterName is None: logger.info("Closing shutter...") else: logger.info("Closing '%s' shutter..." % self.shutterName) self.getObject('shutter').close()
class CommandBrick(Core.BaseBrick): # ============================================= # PROPERTIES/CONNECTIONS DEFINITION # ============================================= properties = { "caption": Property("string", "Caption", "", "captionChanged"), "parameter": Property("string", "Parameter", "", "parameterChanged"), "toolTip": Property("string", "Tool tip", "", "toolTipChanged"), "expertModeOnly": Property("boolean", "Expert mode only", "", "expertModeOnlyChanged", False), "warningPopup": Property("boolean", "WarningPopup", "", "warningChanged", False) } connections = { "command": Connection("Command object", [Signal("commandStatusChanged", "commandStatusChanged")], [Slot("executeCommand")], "connectionStatusChanged") } signals = [] slots = [] def __init__(self, *args, **kargs): Core.BaseBrick.__init__(self, *args, **kargs) def init(self): self.__parameter = "" self.__toolTip = "" self.__expertModeOnly = False self.__expertMode = False self.__warning = False self.__caption = "" self.brick_widget.setLayout(Qt.QVBoxLayout()) self.commandPushButton = Qt.QPushButton(self.brick_widget) Qt.QObject.connect(self.commandPushButton, Qt.SIGNAL("clicked()"), self.commandPushButtonClicked) self.brick_widget.layout().addWidget(self.commandPushButton) def captionChanged(self, pValue): self.__caption = pValue self.commandPushButton.setText(pValue) def parameterChanged(self, pValue): self.__parameter = pValue def toolTipChanged(self, pValue): self.__toolTip = pValue self.commandPushButton.setToolTip(self.__toolTip) def expertModeOnlyChanged(self, pValue): self.__expertModeOnly = pValue self.expert_mode(self.__expertMode) def warningChanged(self, pValue): self.__warning = pValue def commandPushButtonClicked(self): if self.__warning: answer = Qt.QMessageBox.warning( self.brick_widget, "Warning", "You clicked on " + self.__caption + ".\nDo you really want to execute this command ?", Qt.QMessageBox.Ok, (Qt.QMessageBox.Cancel | Qt.QMessageBox.Default)) if answer == Qt.QMessageBox.Cancel: return self.getObject("command").executeCommand(self.__parameter) def commandStatusChanged(self, pValue): messageList = pValue.split(",", 2) if len(messageList) == 2: if messageList[0] == "0": # command info logger.info(messageList[1]) elif messageList[0] == "1": # command warning logger.warning(messageList[1]) elif messageList[0] == "2": # command error logger.error(messageList[1]) def expert_mode(self, expert): self.__expertMode = expert self.commandPushButton.setEnabled(not self.__expertModeOnly or self.__expertMode) def connectionStatusChanged(self, peer): self.calibration_object = peer if self.calibration_object is None: self.brick_widget.setEnabled(False) else: self.brick_widget.setEnabled(True)
class VacPumpBrick(Core.BaseBrick): properties = {} connections = { "pumping": Connection("Pumping object", [], [ Slot("exftclose"), Slot("exscclose"), Slot("vacftclose"), Slot("vacscclose"), Slot("vacftopen"), Slot("vacscopen"), Slot("rv5open"), Slot("rv6open"), Slot("getValveThreshold"), Slot("getPumpThreshold"), Slot("getUSThreshold"), Slot("getFTTimeout"), Slot("getSCTimeout"), Slot("getFTVacuum"), Slot("getSCVacuum"), Slot("getUSVacuum") ], "connectionToPumping") } signals = [] slots = [] def __init__(self, *args, **kargs): Core.BaseBrick.__init__(self, *args, **kargs) self.pumpingObject = None self.valveThreshold = None self.pumpThreshold = None self.usThreshold = None self.ftTimeout = None self.scTimeout = None self.ftvacuum = 0.0 self.scvacuum = 0.0 self.usvacuum = 0.0 def init(self): self.brick_widget.setLayout(Qt.QVBoxLayout()) self.commandPushButton = Qt.QPushButton(self.brick_widget) Qt.QObject.connect(self.commandPushButton, Qt.SIGNAL("clicked()"), self.commandPushButtonClicked) self.brick_widget.layout().addWidget(self.commandPushButton) # Only in expert mode self.commandPushButton.setEnabled(False) self.commandPushButton.setToolTip( "Make Vacuum in Flight Tube and/or Sample Changer safely") self.commandPushButton.setText("Smart Vacuum") def getTimeToRefresh(self): return 0.1 def waitForFtVacuum(self): # Now wait for vacuum in FT first time_to_wait = self.ftTimeout timeToRefresh = self.getTimeToRefresh() increaseForCountOneSec = int(1 / timeToRefresh) countForPrint = 0 logger.info( "Waiting for flight tube vacuum to be OK. %d seconds left..." % time_to_wait) while time_to_wait > 0: countForPrint = countForPrint + 1 if countForPrint == increaseForCountOneSec * 10: logger.info( "Waiting for flight tube vacuum to be OK. %d seconds left..." % time_to_wait) countForPrint = 0 QtGui.qApp.processEvents() time.sleep(min(timeToRefresh, time_to_wait)) self.ftvacuum = float(self.pumpingObject.getFTVacuum()) if (self.ftvacuum < self.valveThreshold): return True time_to_wait = time_to_wait - timeToRefresh return False def waitForScVacuum(self): # Now wait for vacuum in SC first time_to_wait = self.scTimeout timeToRefresh = self.getTimeToRefresh() increaseForCountOneSec = int(1 / timeToRefresh) countForPrint = 0 logger.info( "Waiting for sample changer vacuum to be OK. %d seconds left..." % time_to_wait) while time_to_wait > 0: countForPrint = countForPrint + 1 if countForPrint == increaseForCountOneSec * 10: logger.info( "Waiting for sample changer vacuum to be OK. %d seconds left..." % time_to_wait) countForPrint = 0 QtGui.qApp.processEvents() time.sleep(min(timeToRefresh, time_to_wait)) self.scvacuum = float(self.pumpingObject.getSCVacuum()) if (self.scvacuum < self.valveThreshold): return True time_to_wait = time_to_wait - timeToRefresh return False def commandPushButtonClicked(self): answer = Qt.QMessageBox.warning( self.brick_widget, "Warning", "You clicked on Pump Vacuum\nDo you really want to execute this command ?", Qt.QMessageBox.Ok, (Qt.QMessageBox.Cancel | Qt.QMessageBox.Default)) if answer == Qt.QMessageBox.Cancel: return if self.pumpingObject is None: logger.error("Is not connected with the CO Server. I stop") return # Logic starts here self.ftvacuum = float(self.pumpingObject.getFTVacuum()) self.scvacuum = float(self.pumpingObject.getSCVacuum()) self.usvacuum = float(self.pumpingObject.getUSVacuum()) if (self.ftvacuum < 0 or self.scvacuum < 0 or self.usvacuum < 0): logging.error("Can not read vacuum gauges. I stop") return if (self.usvacuum > self.usThreshold): logger.error( "Upstream vacuum below threshold. Please contact expert") answer = Qt.QMessageBox.warning( self.brick_widget, "Warning", "Error in upstream vacuum\nDo you want to continue anyway ?", Qt.QMessageBox.Ok, (Qt.QMessageBox.Cancel | Qt.QMessageBox.Default)) if answer == Qt.QMessageBox.Cancel: return if ((self.scvacuum < self.valveThreshold) and (self.ftvacuum < self.valveThreshold)): # SC and FT vacuum OK #TODO: DEBUG print "sc vacuum %r " % self.scvacuum print "ft vacuum %r " % self.ftvacuum print "valve Threshold %r " % self.valveThreshold logger.info("Vacuum already OK in Sample Changer") logger.info("Vacuum already OK in Flight Tube") self.pumpingObject.rv5open() self.pumpingObject.rv6open() elif ((self.scvacuum < self.valveThreshold) and (self.ftvacuum < self.pumpThreshold)): # SC OK and FT good but not air logger.info("Vacuum already OK in Sample Changer") self.pumpingObject.rv5open() self.pumpingObject.exftclose() Qt.QMessageBox.information( self.brick_widget, "Info", "Please go into the Hutch and start pump and ONLY when done click OK" ) self.pumpingObject.vacftopen() # wait for vacuum if self.waitForFtVacuum(): logger.info("Vacuum achieved in Flight Tube") self.pumpingObject.rv6open() self.pumpingObject.vacftclose() Qt.QMessageBox.information( self.brick_widget, "Info", "Please go into the Hutch and stop the pump") else: logger.warning( "Timeout, could not achieve vacuum in Flight Tube") self.pumpingObject.vacftclose() elif ((self.scvacuum < self.valveThreshold)): # SC OK and in FT is air - FT vacuum value from Logic - If we came here, FT is air logger.info("Vacuum already OK in Sample Changer") self.pumpingObject.rv5open() self.pumpingObject.exftclose() self.pumpingObject.vacftopen() Qt.QMessageBox.information( self.brick_widget, "Info", "Please go into the Hutch and start pump and ONLY when done click OK" ) # Now wait for vacuum if self.waitForFtVacuum(): logger.info("Vacuum achieved in Flight Tube") self.pumpingObject.rv6open() self.pumpingObject.vacftclose() Qt.QMessageBox.information( self.brick_widget, "Info", "Please go into the Hutch and stop the pump") else: logger.warning( "Timeout, could not achieve vacuum in Flight Tube") self.pumpingObject.vacftclose() elif ((self.ftvacuum < self.valveThreshold) and (self.scvacuum < self.pumpThreshold)): # FT OK and SC good but not air logger.info("Vacuum already OK in Flight Tube") self.pumpingObject.exscclose() Qt.QMessageBox.information( self.brick_widget, "Info", "Please go into the Hutch and start pump and ONLY when done click OK" ) self.pumpingObject.vacscopen() # Now wait for vacuum if self.waitForScVacuum(): logger.info("Vacuum achieved in Sample Changer") self.pumpingObject.vacscclose() self.pumpingObject.rv5open() logger.info("Check Flight Tube Vacuum again") self.ftvacuum = float(self.pumpingObject.getFTVacuum()) if (self.ftvacuum >= self.valveThreshold): self.pumpingObject.vacftopen() # Now wait for vacuum if self.waitForFtVacuum(): logger.info("Vacuum achieved in Flight Tube") self.pumpingObject.vacftclose() self.pumpingObject.rv6open() Qt.QMessageBox.information( self.brick_widget, "Info", "Please go into the Hutch and stop the pump") else: logger.warning( "Timeout, could not achieve vacuum in Flight Tube") self.pumpingObject.vacftclose() else: logger.info("Vacuum still OK in Flight Tube") self.pumpingObject.rv6open() Qt.QMessageBox.information( self.brick_widget, "Info", "Please go into the Hutch and stop the pump") else: logger.warning( "Timeout, could not achieve vacuum in Sample Changer") self.pumpingObject.vacscclose() elif ((self.ftvacuum < self.valveThreshold)): # FT OK and in SC is air - SC vacuum value from Logic - If we came here, SC in air logger.info("Vacuum already OK in Flight Tube") self.pumpingObject.exscclose() self.pumpingObject.vacscopen() Qt.QMessageBox.information( self.brick_widget, "Info", "Please go into the Hutch and start pump and ONLY when done click OK" ) # Now wait for vacuum if self.waitForScVacuum(): logger.info("Vacuum achieved in Sample Changer") self.pumpingObject.vacscclose() self.pumpingObject.rv5open() logger.info("Check Flight Tube Vacuum again") self.ftvacuum = float(self.pumpingObject.getFTVacuum()) if (self.ftvacuum >= self.valveThreshold): self.pumpingObject.vacftopen() # Now wait for vacuum if self.waitForFtVacuum(): logger.info("Vacuum achieved in Flight Tube") self.pumpingObject.vacftclose() self.pumpingObject.rv6open() Qt.QMessageBox.information( self.brick_widget, "Info", "Please go into the Hutch and stop the pump") else: logger.warning( "Timeout, could not achieve vacuum in Flight Tube") self.pumpingObject.vacftclose() else: logger.info("Vacuum still OK in Flight Tube") self.pumpingObject.rv6open() Qt.QMessageBox.information( self.brick_widget, "Info", "Please go into the Hutch and stop the pump") else: logger.warning( "Timeout, could not achieve vacuum in Sample Changer") self.pumpingObject.vacscclose() elif ((self.ftvacuum < self.pumpThreshold) and (self.scvacuum < self.pumpThreshold)): #TODO: DEBUG print "sc vacuum %r " % self.scvacuum print "ft vacuum %r " % self.ftvacuum print "pump Threshold %r " % self.pumpThreshold # FT and SC both good and not air self.pumpingObject.exftclose() self.pumpingObject.exscclose() Qt.QMessageBox.information( self.brick_widget, "Info", "Please go into the Hutch and start pump and ONLY when done click OK" ) self.pumpingObject.vacscopen() self.pumpingObject.vacftopen() # Now wait for vacuum in SC first if self.waitForScVacuum(): logger.info("Vacuum achieved in Sample Changer") # Now deal with FT # wait for vacuum if self.waitForFtVacuum(): logger.info("Vacuum achieved in Flight Tube") self.pumpingObject.rv6open() self.pumpingObject.rv5open() self.pumpingObject.vacscclose() self.pumpingObject.vacftclose() Qt.QMessageBox.information( self.brick_widget, "Info", "Please go into the Hutch and stop the pump") else: logger.warning( "Timeout, could not achieve vacuum in Flight Tube") self.pumpingObject.vacscclose() self.pumpingObject.vacftclose() else: logger.warning( "Timeout, could not achieve vacuum in Sample Changer") self.pumpingObject.vacsclose() self.pumpingObject.vacftclose() # we do not try to do anything else elif ((self.ftvacuum < self.pumpThreshold)): # FT good and in SC is air - SC vacuum value from Logic - If we came here, SC in air self.pumpingObject.exftclose() self.pumpingObject.exscclose() self.pumpingObject.vacscopen() Qt.QMessageBox.information( self.brick_widget, "Info", "Please go into the Hutch and start pump and ONLY when done click OK" ) self.pumpingObject.vacftopen() # Now wait for vacuum in SC first if self.waitForScVacuum(): logger.info("Vacuum achieved in Sample Changer") # Now deal with FT # Now wait for vacuum if self.waitForFtVacuum(): logger.info("Vacuum achieved in Flight Tube") self.pumpingObject.rv6open() self.pumpingObject.rv5open() self.pumpingObject.vacscclose() self.pumpingObject.vacftclose() Qt.QMessageBox.information( self.brick_widget, "Info", "Please go into the Hutch and stop the pump") else: logger.warning( "Timeout, could not achieve vacuum in Flight Tube") self.pumpingObject.vacscclose() self.pumpingObject.vacftclose() else: logger.warning( "Timeout, could not achieve vacuum in Sample Changer") self.pumpingObject.vacscclose() self.pumpingObject.vacftclose() elif ((self.scvacuum < self.pumpThreshold)): # SC good and in FT is air - FT vacuum value from Logic - If we came here, FT in air self.pumpingObject.exftclose() self.pumpingObject.exscclose() self.pumpingObject.vacftopen() Qt.QMessageBox.information( self.brick_widget, "Info", "Please go into the Hutch and start pump and ONLY when done click OK" ) self.pumpingObject.vacscopen() # Now wait for vacuum in SC first if self.waitForScVacuum(): logger.info("Vacuum achieved in Sample Changer") # Now deal with FT # Now wait for vacuum if self.waitForFtVacuum(): logger.info("Vacuum achieved in Flight Tube") self.pumpingObject.rv6open() self.pumpingObject.rv5open() self.pumpingObject.vacscclose() self.pumpingObject.vacftclose() Qt.QMessageBox.information( self.brick_widget, "Info", "Please go into the Hutch and stop the pump") else: logger.warning( "Timeout, could not achieve vacuum in Flight Tube") self.pumpingObject.vacscclose() self.pumpingObject.vacftclose() else: logger.warning( "Timeout, could not achieve vacuum in Sample Changer") self.pumpingObject.exftclose() self.pumpingObject.vacftclose() else: # SC and FT is air - FT and SC vacuum value from Logic - If we came here, FT and SC in air self.pumpingObject.exftclose() self.pumpingObject.exscclose() self.pumpingObject.vacftopen() self.pumpingObject.vacscopen() Qt.QMessageBox.information( self.brick_widget, "Info", "Please go into the Hutch and start pump and ONLY when done click OK" ) # Now wait for vacuum in SC first if self.waitForScVacuum(): logger.info("Vacuum achieved in Sample Changer") # Now deal with FT # Now wait for vacuum if self.waitForFtVacuum(): logger.info("Vacuum achieved in Flight Tube") self.pumpingObject.rv6open() self.pumpingObject.rv5open() self.pumpingObject.vacscclose() self.pumpingObject.vacftclose() Qt.QMessageBox.information( self.brick_widget, "Info", "Please go into the Hutch and stop the pump") else: logger.warning( "Timeout, could not achieve vacuum in Flight Tube") self.pumpingObject.vacscclose() self.pumpingObject.vacftclose() else: logger.warning( "Timeout, could not achieve vacuum in Sample Changer") self.pumpingObject.exftclose() self.pumpingObject.vacftclose() def expert_mode(self, expert): self.__expertMode = expert self.commandPushButton.setEnabled(self.__expertMode) def connectionToPumping(self, peer): if peer is not None: self.pumpingObject = peer # let us read in the static object if not already done if self.valveThreshold is None: self.valveThreshold = float( self.pumpingObject.getValveThreshold()) if self.pumpThreshold is None: self.pumpThreshold = float( self.pumpingObject.getPumpThreshold()) if self.usThreshold is None: self.usThreshold = float(self.pumpingObject.getUSThreshold()) if self.ftTimeout is None: self.ftTimeout = int(self.pumpingObject.getFTTimeout()) if self.scTimeout is None: self.scTimeout = int(self.pumpingObject.getSCTimeout())
class BsxRobotBrick(Core.BaseBrick): properties = {} connections = { "samplechanger": Connection("Sample Changer object", [ Signal('seuTemperatureChanged', 'seu_temperature_changed'), Signal('storageTemperatureChanged', 'storage_temperature_changed'), Signal('stateChanged', 'state_changed') ], [], "sample_changer_connected") } def sample_changer_connected(self, sc): if sc is not None: self._sampleChanger = sc self.__updateTimer.start(50) else: self.__updateTimer.stop() def __init__(self, *args, **kargs): Core.BaseBrick.__init__(self, *args, **kargs) def init(self): self.__sampleChangerFrame = None self.__robotMoveState = 0 self.__scanCurveX = {} self.__scanCurveY = {} self._isDrawing = False self.selectedBeamLocation = None self._sampleChanger = None self.count = 0 self.robotLayout = Qt.QVBoxLayout(self.brick_widget) self.robotSampleChangerFrameLabel = RobotSampleChangerFrameLabel( self, self.brick_widget) self.robotSampleChangerFrameLabel.setSizePolicy( Qt.QSizePolicy.Expanding, Qt.QSizePolicy.Expanding) self.robotSampleChangerFrameLabel.setScaledContents(True) self.robotSampleChangerFramePainter = Qt.QPainter() self.robotSampleChangerFramePixmap = QtGui.QPixmap() self.robotLayout.addWidget(self.robotSampleChangerFrameLabel) self.robotHBoxLayout1 = Qt.QHBoxLayout() self.robotSampleStateLabel = Qt.QLabel("State", self.brick_widget) self.robotHBoxLayout1.addWidget(self.robotSampleStateLabel) self.robotSampleChangerStateLineEdit = Qt.QLineEdit(self.brick_widget) self.robotSampleChangerStateLineEdit.setDisabled(True) self.robotHBoxLayout1.addWidget(self.robotSampleChangerStateLineEdit) self.robotSampleChangerStatusLineEdit = Qt.QLineEdit(self.brick_widget) self.robotSampleChangerStatusLineEdit.setDisabled(True) self.robotHBoxLayout1.addWidget(self.robotSampleChangerStatusLineEdit) self.robotLayout.addLayout(self.robotHBoxLayout1) self.robotHBoxLayout2 = Qt.QHBoxLayout() self.robotStorageTemperatureLabel = Qt.QLabel( "Temperature (SEU, storage)", self.brick_widget) self.robotHBoxLayout2.addWidget(self.robotStorageTemperatureLabel) self.robotSEUTemperatureLineEdit = Qt.QLineEdit(self.brick_widget) self.robotSEUTemperatureLineEdit.setDisabled(True) self.robotHBoxLayout2.addWidget(self.robotSEUTemperatureLineEdit) self.robotSEUTemperaturePushButton = Qt.QPushButton( "Set", self.brick_widget) Qt.QObject.connect(self.robotSEUTemperaturePushButton, Qt.SIGNAL("clicked()"), self.robotSEUTemperaturePushButtonClicked) self.robotHBoxLayout2.addWidget(self.robotSEUTemperaturePushButton) self.robotStorageTemperatureLineEdit = Qt.QLineEdit(self.brick_widget) self.robotStorageTemperatureLineEdit.setDisabled(True) self.robotHBoxLayout2.addWidget(self.robotStorageTemperatureLineEdit) self.robotStorageTemperaturePushButton = Qt.QPushButton( "Set", self.brick_widget) Qt.QObject.connect(self.robotStorageTemperaturePushButton, Qt.SIGNAL("clicked()"), self.robotStorageTemperaturePushButtonClicked) self.robotHBoxLayout2.addWidget(self.robotStorageTemperaturePushButton) self.robotLayout.addLayout(self.robotHBoxLayout2) self.robotHBoxLayout3 = Qt.QHBoxLayout() self.robotMoveBackwardPushButton = Qt.QPushButton( "|<<", self.brick_widget) Qt.QObject.connect(self.robotMoveBackwardPushButton, Qt.SIGNAL("pressed()"), self.robotMoveBackwardPushButtonPressed) Qt.QObject.connect(self.robotMoveBackwardPushButton, Qt.SIGNAL("released()"), self.robotMoveBackwardPushButtonReleased) self.robotHBoxLayout3.addWidget(self.robotMoveBackwardPushButton) self.robotStopPushButton = Qt.QPushButton("||", self.brick_widget) Qt.QObject.connect(self.robotStopPushButton, Qt.SIGNAL("clicked()"), self.robotStopPushButtonClicked) self.robotHBoxLayout3.addWidget(self.robotStopPushButton) #self.robotMovePushButton = Qt.QPushButton(">", self.brick_widget) #Qt.QObject.connect(self.robotMovePushButton, Qt.SIGNAL("clicked()"), self.robotMovePushButtonClicked) #self.robotHBoxLayout3.addWidget(self.robotMovePushButton) self.robotMoveForwardPushButton = Qt.QPushButton( ">>|", self.brick_widget) Qt.QObject.connect(self.robotMoveForwardPushButton, Qt.SIGNAL("pressed()"), self.robotMoveForwardPushButtonPressed) Qt.QObject.connect(self.robotMoveForwardPushButton, Qt.SIGNAL("released()"), self.robotMoveForwardPushButtonReleased) self.robotHBoxLayout3.addWidget(self.robotMoveForwardPushButton) self.robotFlowPushButton = Qt.QPushButton("Flow", self.brick_widget) Qt.QObject.connect(self.robotFlowPushButton, Qt.SIGNAL("clicked()"), self.robotFlowPushButtonClicked) self.robotHBoxLayout3.addWidget(self.robotFlowPushButton) self.robotRecuperatePushButton = Qt.QPushButton( "Recuperate", self.brick_widget) Qt.QObject.connect(self.robotRecuperatePushButton, Qt.SIGNAL("clicked()"), self.robotRecuperatePushButtonClicked) self.robotHBoxLayout3.addWidget(self.robotRecuperatePushButton) self.robotLayout.addLayout(self.robotHBoxLayout3) self.robotHBoxLayout4 = Qt.QHBoxLayout() self.robotRestartPushButton = Qt.QPushButton("Restart", self.brick_widget) self.robotRestartMenu = Qt.QMenu(self.robotRestartPushButton) self.robotRestartWithHomingAction = Qt.QAction("With homing", self.robotRestartMenu) self.robotRestartMenu.addAction(self.robotRestartWithHomingAction) self.robotRestartWithoutHomingAction = Qt.QAction( "Without homing", self.robotRestartMenu) self.robotRestartMenu.addAction(self.robotRestartWithoutHomingAction) Qt.QObject.connect(self.robotRestartWithHomingAction, Qt.SIGNAL("triggered(bool)"), self.robotRestartWithHomingActionTriggered) Qt.QObject.connect(self.robotRestartWithoutHomingAction, Qt.SIGNAL("triggered(bool)"), self.robotRestartWithoutHomingActionTriggered) self.robotRestartPushButton.setMenu(self.robotRestartMenu) self.robotHBoxLayout4.addWidget(self.robotRestartPushButton) self.robotAbortPushButton = Qt.QPushButton("Abort", self.brick_widget) Qt.QObject.connect(self.robotAbortPushButton, Qt.SIGNAL("clicked()"), self.robotAbortPushButtonClicked) self.robotHBoxLayout4.addWidget(self.robotAbortPushButton) self.robotCleanPushButton = Qt.QPushButton("Clean", self.brick_widget) Qt.QObject.connect(self.robotCleanPushButton, Qt.SIGNAL("clicked()"), self.robotCleanPushButtonClicked) self.robotHBoxLayout4.addWidget(self.robotCleanPushButton) self.robotFillPushButton = Qt.QPushButton("Fill", self.brick_widget) Qt.QObject.connect(self.robotFillPushButton, Qt.SIGNAL("clicked()"), self.robotFillPushButtonClicked) self.robotHBoxLayout4.addWidget(self.robotFillPushButton) self.robotDryPushButton = Qt.QPushButton("Dry", self.brick_widget) Qt.QObject.connect(self.robotDryPushButton, Qt.SIGNAL("clicked()"), self.robotDryPushButtonClicked) self.robotHBoxLayout4.addWidget(self.robotDryPushButton) self.robotFixLiquidPositionPushButton = Qt.QPushButton( "Fix liquid position", self.brick_widget) Qt.QObject.connect(self.robotFixLiquidPositionPushButton, Qt.SIGNAL("clicked()"), self.robotFixLiquidPositionPushButtonClicked) self.robotHBoxLayout4.addWidget(self.robotFixLiquidPositionPushButton) self.robotSnapshotPushButton = Qt.QPushButton("Snapshot", self.brick_widget) Qt.QObject.connect(self.robotSnapshotPushButton, Qt.SIGNAL("clicked()"), self.robotSnapshotPushButtonClicked) self.robotHBoxLayout4.addWidget(self.robotSnapshotPushButton) self.robotLayout.addLayout(self.robotHBoxLayout4) self.__sampleChangerDisplayFlag = False self.__sampleChangerDisplayMessage = "" self.__updateTimer = QtCore.QTimer(self.brick_widget) QtCore.QObject.connect(self.__updateTimer, QtCore.SIGNAL('timeout()'), self.updateSampleChanger) def updateSampleChanger(self): self._sampleChangerFrame = self._sampleChanger.getImageJPG() self.refreshSampleChangerFrame() def robotStorageTemperaturePushButtonClicked(self): def cancelPushButtonClicked(): dialog.reject() def okPushButtonClicked(): dialog.accept() dialog = Qt.QDialog(self.brick_widget) dialog.setWindowTitle("Storage temperature") dialog.setModal(True) vBoxLayout = Qt.QVBoxLayout() dialog.setLayout(vBoxLayout) vBoxLayout.addWidget( Qt.QLabel("Please, insert new storage temperature:")) temperatureDoubleSpinBox = Qt.QDoubleSpinBox(dialog) temperatureDoubleSpinBox.setSuffix(" C") temperatureDoubleSpinBox.setDecimals(2) temperatureDoubleSpinBox.setRange(4, 40) try: temperatureDoubleSpinBox.setValue( float( self.robotStorageTemperatureLineEdit.text().split(" ")[0])) except ValueError: temperatureDoubleSpinBox.setValue(20) vBoxLayout.addWidget(temperatureDoubleSpinBox) buttonHBoxLayout = Qt.QHBoxLayout(dialog) cancelPushButton = Qt.QPushButton("Cancel", dialog) Qt.QObject.connect(cancelPushButton, Qt.SIGNAL("clicked()"), cancelPushButtonClicked) buttonHBoxLayout.addWidget(cancelPushButton) okPushButton = Qt.QPushButton("Ok", dialog) Qt.QObject.connect(okPushButton, Qt.SIGNAL("clicked()"), okPushButtonClicked) buttonHBoxLayout.addWidget(okPushButton) vBoxLayout.addLayout(buttonHBoxLayout) if dialog.exec_(): logger.info("Setting storage temperature to '" + str(temperatureDoubleSpinBox.value()) + "'...") self.__sampleChangerDisplayFlag = True self.__sampleChangerDisplayMessage = "Error when trying to set storage temperature!" self._sampleChanger.setStorageTemperature( temperatureDoubleSpinBox.value()) def robotSEUTemperaturePushButtonClicked(self): def cancelPushButtonClicked(): dialog.reject() def okPushButtonClicked(): dialog.accept() dialog = Qt.QDialog(self.brick_widget) dialog.setWindowTitle("SEU temperature") dialog.setModal(True) vBoxLayout = Qt.QVBoxLayout() dialog.setLayout(vBoxLayout) vBoxLayout.addWidget(Qt.QLabel("Please, insert new SEU temperature:")) temperatureDoubleSpinBox = Qt.QDoubleSpinBox(dialog) temperatureDoubleSpinBox.setSuffix(" C") temperatureDoubleSpinBox.setDecimals(2) temperatureDoubleSpinBox.setRange(4, 60) try: temperatureDoubleSpinBox.setValue( float(self.robotSEUTemperatureLineEdit.text().split(" ")[0])) except ValueError: temperatureDoubleSpinBox.setValue(20) vBoxLayout.addWidget(temperatureDoubleSpinBox) buttonHBoxLayout = Qt.QHBoxLayout(dialog) cancelPushButton = Qt.QPushButton("Cancel", dialog) Qt.QObject.connect(cancelPushButton, Qt.SIGNAL("clicked()"), cancelPushButtonClicked) buttonHBoxLayout.addWidget(cancelPushButton) okPushButton = Qt.QPushButton("Ok", dialog) Qt.QObject.connect(okPushButton, Qt.SIGNAL("clicked()"), okPushButtonClicked) buttonHBoxLayout.addWidget(okPushButton) vBoxLayout.addLayout(buttonHBoxLayout) if dialog.exec_(): logger.info("Setting SEU temperature to '" + str(temperatureDoubleSpinBox.value()) + "'...") self.__sampleChangerDisplayFlag = True self.__sampleChangerDisplayMessage = "Error when trying to set SEU temperature!" self._sampleChanger.setSEUTemperature( temperatureDoubleSpinBox.value()) def robotFillPushButtonClicked(self): geometry = [self._sampleChanger.getPlateInfo(i) for i in range(1, 3)] #TODO: DEBUG print ">>>> geometry from Robot %r" % geometry logger.info('geometry: %s', geometry) print ">>>> END DEBUG" logger.debug('geometry: %s', geometry) dialog = WellPickerDialog(geometry, title='Fill', display_volume=True, parent=self.brick_widget) ret = dialog.exec_() if ret: selected_well = dialog.get_selected_well() logger.info('filling from [plate, row, column,volume] = %s', selected_well) #TODO: DEBUG: print ">>> selected_well %r" % selected_well print ">>> 1, 2, 3, 4 " print selected_well[1] print selected_well[2] print selected_well[3] print selected_well[4] print type(selected_well[3]) print type(selected_well[4]) self._sampleChanger.fill(selected_well) def robotDryPushButtonClicked(self): dryTime, buttonOk = Qt.QInputDialog.getInteger( self.brick_widget, "Dry", "\nPlease, insert time of drying (seconds):", 15, 1, 60, 2) if buttonOk: logger.info("Drying robot...") self.__sampleChangerDisplayFlag = True self.__sampleChangerDisplayMessage = "Error when trying to dry robot!" self._sampleChanger.dry(dryTime) def robotFixLiquidPositionPushButtonClicked(self): logger.info("Fixing liquid position...") self.__sampleChangerDisplayFlag = True self.__sampleChangerDisplayMessage = "Error when trying to fix liquid position!" self._sampleChanger.setLiquidPositionFixed(True) def robotMoveBackwardPushButtonPressed(self): logger.info("Moving syringe backward...") self.__robotMoveState = 1 self.__sampleChangerDisplayFlag = True self.__sampleChangerDisplayMessage = "Error when trying to move syringe backward!" self._sampleChanger.moveSyringeBackward(5) def robotMoveBackwardPushButtonReleased(self): self.__robotMoveState = 0 self.robotStopPushButtonClicked() def robotStopPushButtonClicked(self): logger.info("Stopping syringe...") self.__sampleChangerDisplayFlag = True self.__sampleChangerDisplayMessage = "Error when trying to stop syringe!" self._sampleChanger.stopSyringe() def robotMovePushButtonClicked(self): logger.info("Moving syringe forward...") self.__sampleChangerDisplayFlag = True self.__sampleChangerDisplayMessage = "Error when trying to move syringe forward!" self._sampleChanger.moveSyringeForward(5) def robotMoveForwardPushButtonPressed(self): self.__robotMoveState = 2 self.robotMovePushButtonClicked() def robotMoveForwardPushButtonReleased(self): self.__robotMoveState = 0 self.robotStopPushButtonClicked() def robotFlowPushButtonClicked(self): def cancelPushButtonClicked(): dialog.reject() def okPushButtonClicked(): dialog.accept() dialog = Qt.QDialog(self.brick_widget) dialog.setWindowTitle("Flow") dialog.setModal(True) vBoxLayout = Qt.QVBoxLayout() dialog.setLayout(vBoxLayout) timeHBoxLayout = Qt.QHBoxLayout(dialog) timeHBoxLayout.addWidget(Qt.QLabel("Time", dialog)) timeSpinBox = Qt.QSpinBox(dialog) timeSpinBox.setSuffix(" s") timeSpinBox.setRange(1, 1000) timeSpinBox.setValue(10) timeHBoxLayout.addWidget(timeSpinBox) vBoxLayout.addLayout(timeHBoxLayout) buttonHBoxLayout = Qt.QHBoxLayout(dialog) cancelPushButton = Qt.QPushButton("Cancel", dialog) Qt.QObject.connect(cancelPushButton, Qt.SIGNAL("clicked()"), cancelPushButtonClicked) buttonHBoxLayout.addWidget(cancelPushButton) okPushButton = Qt.QPushButton("Ok", dialog) Qt.QObject.connect(okPushButton, Qt.SIGNAL("clicked()"), okPushButtonClicked) buttonHBoxLayout.addWidget(okPushButton) vBoxLayout.addLayout(buttonHBoxLayout) if dialog.exec_(): logger.info("Flowing '" + str(timeSpinBox.value()) + "' second(s)...") self.__sampleChangerDisplayFlag = True self.__sampleChangerDisplayMessage = "Error when trying to flow!" self._sampleChanger.flowAll(timeSpinBox.value()) def robotRecuperatePushButtonClicked(self): geometry = [self._sampleChanger.getPlateInfo(i) for i in range(1, 3)] #TODO: DEBUG print ">>>> geometry from Robot %r" % geometry logger.debug('geometry: %s', geometry) dialog = WellPickerDialog(geometry, title='Recuperate', parent=self.brick_widget) ret = dialog.exec_() if ret: selected_well = dialog.get_selected_well() logger.info('recuperating from [plate, row, column] = %s', selected_well) #TODO: DEBUG: print ">>> selected_well %r" % selected_well print ">>> 1, 2, 3, 4 " print selected_well[1] print selected_well[2] print selected_well[3] print selected_well[4] print type(selected_well[3]) print type(selected_well[4]) self._sampleChanger.recuperate(int(selected_well[1]), int(selected_well[2]), int(selected_well[3])) def robotRestartWithHomingActionTriggered(self): logger.info("Restarting (with homing) the robot...") self.__sampleChangerDisplayFlag = True self.__sampleChangerDisplayMessage = "Error when trying to restart (with homing) the robot!" self._sampleChanger.restart(True) def robotRestartWithoutHomingActionTriggered(self): logger.info("Restarting (without homing) the robot...") self.__sampleChangerDisplayFlag = True self.__sampleChangerDisplayMessage = "Error when trying to restart (without homing) the robot!" self._sampleChanger.restart(False) def robotAbortPushButtonClicked(self): logger.info("Aborting the robot...") self.__sampleChangerDisplayFlag = False self._sampleChanger.abort() def robotCleanPushButtonClicked(self): logger.info("Cleaning the robot...") self.__sampleChangerDisplayFlag = True self.__sampleChangerDisplayMessage = "Error when trying to clean the robot!" self._sampleChanger.clean() def robotSnapshotPushButtonClicked(self): filterList = [ "Portable Network Graphics (*.png)", "Windows Bitmap (*.bmp)", "Joint Photographics Experts Group (*.jpg)" ] qFileDialog = QtGui.QFileDialog(self.brick_widget, "Save image", ".") qFileDialog.setAcceptMode(QtGui.QFileDialog.AcceptSave) qFileDialog.setFilters(filterList) if qFileDialog.exec_(): if qFileDialog.selectedNameFilter() == filterList[0]: formatGraphics = "PNG" elif qFileDialog.selectedNameFilter() == filterList[1]: formatGraphics = "BMP" else: formatGraphics = "JPG" fileName = str(qFileDialog.selectedFiles()[0]) if not fileName.upper().endswith("." + formatGraphics): fileName += "." + formatGraphics if QtGui.QPixmap.grabWidget( self.robotSampleChangerFrameLabel).save( fileName, formatGraphics): Qt.QMessageBox.information( self.brick_widget, "Info", "Image was successfully saved in file '" + fileName + "'!") else: Qt.QMessageBox.critical( self.brick_widget, "Error", "Error when trying to save image to file '" + fileName + "'!") def state_changed(self, state, status): self.robotSampleChangerStateLineEdit.setText(state) self.robotSampleChangerStatusLineEdit.setText(status) self.robotStorageTemperaturePushButton.setEnabled(state == "STANDBY") self.robotSEUTemperaturePushButton.setEnabled(state == "STANDBY") self.robotFillPushButton.setEnabled(state == "STANDBY") self.robotDryPushButton.setEnabled(state == "STANDBY" and status == "Cleaned") self.robotMoveBackwardPushButton.setEnabled( state == "STANDBY" or self.__robotMoveState == 1) self.robotStopPushButton.setEnabled(state == "MOVING") #self.robotMovePushButton.setEnabled(state == "STANDBY") self.robotMoveForwardPushButton.setEnabled( state == "STANDBY" or self.__robotMoveState == 2) self.robotFlowPushButton.setEnabled(state == "STANDBY" and status == "Loaded") self.robotRecuperatePushButton.setEnabled(state == "STANDBY" and status == "Loaded") self.robotRestartPushButton.setEnabled(state not in ("MOVING", "RUNNING", "INIT", "Not connected")) self.robotAbortPushButton.setEnabled(state in ("ALARM", "STANDBY", "MOVING", "RUNNING")) self.robotCleanPushButton.setEnabled(state == "STANDBY") currentLiquidPositionList = self._sampleChanger.getCurrentLiquidPosition( ) self.robotFixLiquidPositionPushButton.setEnabled( state == "STANDBY" and currentLiquidPositionList is not None and len(currentLiquidPositionList) > 0) if state == "STANDBY": if self.__sampleChangerDisplayFlag: if self.__sampleChangerDisplayMessage != "": message = self.__sampleChangerDisplayMessage self.__sampleChangerDisplayMessage = "" if self._sampleChanger.getCommandException( ) is not None and self._sampleChanger.getCommandException( ) != "": Qt.QMessageBox.critical(self.brick_widget, "Error", message) self.__sampleChangerDisplayFlag = False else: self.__sampleChangerDisplayFlag = True def storage_temperature_changed(self, temperature): #logger.debug('storage temp: %r', temperature) self.robotStorageTemperatureLineEdit.setText("%02.2f C" % float(temperature)) def seu_temperature_changed(self, temperature): #logger.debug('seu temp: %r', temperature) self.robotSEUTemperatureLineEdit.setText("%02.2f C" % float(temperature)) def refreshSampleChangerFrame(self): self.robotSampleChangerFramePixmap = QtGui.QPixmap() self.robotSampleChangerFramePixmap.loadFromData( self._sampleChangerFrame, "JPG") self.robotSampleChangerFramePainter.begin( self.robotSampleChangerFramePixmap) try: self.robotSampleChangerFramePainter.setPen(QtCore.Qt.green) self.robotSampleChangerFramePainter.drawText( 5, 15, "%d/%02d/%02d" % (time.localtime()[0], time.localtime()[1], time.localtime()[2])) self.robotSampleChangerFramePainter.drawText( 5, 30, "%02d:%02d:%02d" % (time.localtime()[3], time.localtime()[4], time.localtime()[5])) currentLiquidPositionList = self._sampleChanger.getCurrentLiquidPosition( ) if currentLiquidPositionList is not None: for currentLiquidPosition in currentLiquidPositionList: self.robotSampleChangerFramePainter.drawLine( currentLiquidPosition, 0, currentLiquidPosition, self.robotSampleChangerFrameLabel.height()) if self._isDrawing: self.robotSampleChangerFramePainter.setPen(QtCore.Qt.red) self.robotSampleChangerFramePainter.drawRect( self.selectedBeamLocation[0], self.selectedBeamLocation[1], self.selectedBeamLocation[2] - self.selectedBeamLocation[0], self.selectedBeamLocation[3] - self.selectedBeamLocation[1]) else: beamLocation = self._sampleChanger.getBeamLocation() if beamLocation is not None: # values are now separated by the UNIT SEPARATOR ascii character # Many thanks to the complete moron who thought that was a good idea, and who didn't tell us it changed # -- TB beamLocationList = beamLocation.split(chr(ascii.US)) self.selectedBeamLocation = [ int(beamLocationList[1]), int(beamLocationList[2]), int(beamLocationList[3]), int(beamLocationList[4]) ] self.robotSampleChangerFramePainter.setPen( QtCore.Qt.red) self.robotSampleChangerFramePainter.drawRect( self.selectedBeamLocation[0], self.selectedBeamLocation[1], self.selectedBeamLocation[2] - self.selectedBeamLocation[0], self.selectedBeamLocation[3] - self.selectedBeamLocation[1]) finally: self.robotSampleChangerFramePainter.end() self.robotSampleChangerFrameLabel.setPixmap( self.robotSampleChangerFramePixmap)
class EnergyWaveLengthBrick(Core.BaseBrick): properties = {} connections = { "energy": Connection("Energy object", [Signal("energyChanged", "energyChanged")], [ Slot("setEnergy"), Slot("getEnergy"), Slot("pilatusReady"), Slot("pilatusReset"), Slot("setPilatusFill"), Slot("energyAdjustPilatus") ], "connectedToEnergy"), "login": Connection("Login object", [Signal("loggedIn", "loggedIn")], [], "connectionToLogin"), "display": Connection("Display object", [ Signal("displayResetChanged", "displayResetChanged"), Signal("displayItemChanged", "displayItemChanged"), Signal("transmissionChanged", "transmissionChanged"), Signal("grayOut", "grayOut") ], []), } signals = [] slots = [] def __init__(self, *args, **kargs): Core.BaseBrick.__init__(self, *args, **kargs) # to keep track in case a dialog boxes is open self.__energyDialogOpen = False self.__energyDialog = None self.__waveLengthDialogOpen = False self.__waveLengthDialog = None self.loginDone = False def init(self): # The keV to Angstrom calc self.hcOverE = 12.3984 self.vboxLayout = Qt.QVBoxLayout() self.hBox1Layout = Qt.QHBoxLayout() self.brick_widget.setLayout(self.vboxLayout) self.energyLabel = Qt.QLabel("Energy [keV] ", self.brick_widget) self.hBox1Layout.addWidget(self.energyLabel) self.energyLineEdit = Qt.QLineEdit(self.brick_widget) self.energyLineEdit.setEnabled(False) self.energyLineEdit.setSizePolicy(Qt.QSizePolicy.Expanding, Qt.QSizePolicy.Expanding) self.energyLineEdit.setToolTip("Current Energy") self.hBox1Layout.addWidget(self.energyLineEdit) self.newEnergyPushButton = Qt.QPushButton("New Energy", self.brick_widget) Qt.QObject.connect(self.newEnergyPushButton, Qt.SIGNAL("clicked()"), self.newEnergyPushButtonClicked) self.hBox1Layout.addWidget(self.newEnergyPushButton) self.brick_widget.layout().addLayout(self.hBox1Layout) self.hBox2Layout = Qt.QHBoxLayout() self.wavelengthLabel = Qt.QLabel("Wavelength [A] ", self.brick_widget) self.hBox2Layout.addWidget(self.wavelengthLabel) self.waveLengthLineEdit = Qt.QLineEdit(self.brick_widget) self.waveLengthLineEdit.setEnabled(False) self.waveLengthLineEdit.setSizePolicy(Qt.QSizePolicy.Expanding, Qt.QSizePolicy.Expanding) self.waveLengthLineEdit.setToolTip("Current Wavelength") self.hBox2Layout.addWidget(self.waveLengthLineEdit) self.newWaveLengthPushButton = Qt.QPushButton("New Wavelength", self.brick_widget) Qt.QObject.connect(self.newWaveLengthPushButton, Qt.SIGNAL("clicked()"), self.newWaveLengthPushButtonClicked) self.hBox2Layout.addWidget(self.newWaveLengthPushButton) self.brick_widget.layout().addLayout(self.hBox2Layout) # When connected to Login, then block the brick def connectionToLogin(self, pPeer): if pPeer is not None: # Check if we were already connected first if not self.loginDone: self.brick_widget.setEnabled(False) # Connect to display def grayOut(self, grayout): if grayout is not None: if grayout: self.newEnergyPushButton.setEnabled(False) self.newWaveLengthPushButton.setEnabled(False) else: self.newEnergyPushButton.setEnabled(True) self.newWaveLengthPushButton.setEnabled(True) def displayItemChanged(self, _): pass def displayResetChanged(self): pass def transmissionChanged(self, _): pass # Logged In : True or False def loggedIn(self, pValue): self.loginDone = pValue self.brick_widget.setEnabled(pValue) def newEnergyPushButtonClicked(self): # Check if pilatus is ready if not self.energyControlObject.pilatusReady(): Qt.QMessageBox.critical(self.brick_widget, "Error", "Pilatus detector is busy.. Try later", Qt.QMessageBox.Ok) return if self.__energyDialogOpen: self.__energyDialog.activateWindow() self.__energyDialog.raise_() else: self.__energyDialog = EnterEnergy(self) self.__energyDialog.show() def energyDialogOpen(self): self.__energyDialogOpen = True def energyDialogClose(self): self.__energyDialogOpen = False def newWaveLengthPushButtonClicked(self): # Check if pilatus is ready if not self.energyControlObject.pilatusReady(): Qt.QMessageBox.critical(self.brick_widget, "Error", "Pilatus detector is busy.. Try later", Qt.QMessageBox.Ok) return if self.__waveLengthDialogOpen: self.__waveLengthDialog.activateWindow() self.__waveLengthDialog.raise_() else: self.__waveLengthDialog = EnterWaveLength(self) self.__waveLengthDialog.show() def waveLengthDialogOpen(self): self.__waveLengthDialogOpen = True def waveLengthDialogClose(self): self.__waveLengthDialogOpen = False def setEnergy(self, energyStr): if self.energyControlObject is not None: # Put 30 second timeout, since Pilatus can be long self.energyControlObject.setEnergy(energyStr, timeout=30) # make sure you set gapfill as well self.energyControlObject.setPilatusFill() else: logging.error("Could not set Energy to " + energyStr) def getEnergy(self): if self.energyControlObject is not None: return self.energyControlObject.getEnergy() else: logging.error("Could not get Energy") def energyChanged(self, pValue): if pValue is not None: self.__energy = float(pValue) energyStr = "%.4f" % self.__energy self.energyLineEdit.setText(energyStr + " keV") # and calculate wavelength wavelength = self.hcOverE / self.__energy wavelengthStr = "%.4f" % wavelength self.waveLengthLineEdit.setText(wavelengthStr + " Angstrom") def connectedToEnergy(self, pPeer): if pPeer is not None: self.energyControlObject = pPeer # read energy when getting contact with CO Object self.__energy = float(self.energyControlObject.getEnergy()) energyStr = "%.4f" % self.__energy self.energyLineEdit.setText(energyStr + " keV") # and calculate wavelength wavelength = self.hcOverE / self.__energy wavelengthStr = "%.4f" % wavelength self.waveLengthLineEdit.setText(wavelengthStr + " Angstrom")