Пример #1
0
class IntegerParameterWidget(NumericParameterWidget):
    """Widget class for Integer parameter."""
    def __init__(self, parameter, parent=None):
        """Constructor

        .. versionadded:: 2.2

        :param parameter: A IntegerParameter object.
        :type parameter: IntegerParameter

        """
        super(IntegerParameterWidget, self).__init__(parameter, parent)

        self._input = QSpinBox()
        self._input.setValue(self._parameter.value)
        self._input.setMinimum(self._parameter.minimum_allowed_value)
        self._input.setMaximum(self._parameter.maximum_allowed_value)
        tool_tip = 'Choose a number between %d and %d' % (
            self._parameter.minimum_allowed_value,
            self._parameter.maximum_allowed_value)
        self._input.setToolTip(tool_tip)

        self._input.setSizePolicy(self._spin_box_size_policy)

        self._inner_input_layout.addWidget(self._input)
        self._inner_input_layout.addWidget(self._unit_widget)
class IntegerParameterWidget(NumericParameterWidget):
    """Widget class for Integer parameter."""
    def __init__(self, parameter, parent=None):
        """Constructor

        .. versionadded:: 2.2

        :param parameter: A IntegerParameter object.
        :type parameter: IntegerParameter

        """
        super(IntegerParameterWidget, self).__init__(parameter, parent)

        self._input = QSpinBox()
        self._input.setValue(self._parameter.value)
        self._input.setMinimum(self._parameter.minimum_allowed_value)
        self._input.setMaximum(self._parameter.maximum_allowed_value)
        tool_tip = 'Choose a number between %d and %d' % (
            self._parameter.minimum_allowed_value,
            self._parameter.maximum_allowed_value)
        self._input.setToolTip(tool_tip)

        self._input.setSizePolicy(self._spin_box_size_policy)

        self.inner_input_layout.addWidget(self._input)
        self.inner_input_layout.addWidget(self._unit_widget)
Пример #3
0
class FloatColumnConfigurationWidget(QWidget, columnproviders.AbstractColumnConfigurationWidget):
    def __init__(self, parent, hex_widget, column):
        QWidget.__init__(self, parent)
        columnproviders.AbstractColumnConfigurationWidget.__init__(self)
        self.hexWidget = hex_widget
        self.column = column

        self.cmbBinaryFormat = QComboBox(self)
        self.cmbBinaryFormat.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred)

        for fmt in (valuecodecs.FloatCodec.FormatFloat, valuecodecs.FloatCodec.FormatDouble):
            self.cmbBinaryFormat.addItem(valuecodecs.FloatCodec.formatName(fmt), fmt)
            if column is not None and column.valuecodec.binaryFormat == fmt:
                self.cmbBinaryFormat.setCurrentIndex(self.cmbBinaryFormat.count() - 1)

        self.spnPrecision = QSpinBox(self)
        self.spnPrecision.setMinimum(0)
        self.spnPrecision.setMaximum(12)
        if column is not None:
            self.spnPrecision.setValue(column.formatter.precision)
        else:
            self.spnPrecision.setValue(6)

        self.spnColumnsOnRow = QSpinBox(self)
        self.spnColumnsOnRow.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred)
        self.spnColumnsOnRow.setMinimum(1)
        self.spnColumnsOnRow.setMaximum(32)
        if column is not None:
            self.spnColumnsOnRow.setValue(column.columnsOnRow)
        else:
            self.spnColumnsOnRow.setValue(4)

        self.setLayout(QFormLayout())
        self.layout().setContentsMargins(0, 0, 0, 0)
        self.layout().addRow(utils.tr('Binary format:'), self.cmbBinaryFormat)
        self.layout().addRow(utils.tr('Digits after point:'), self.spnPrecision)
        self.layout().addRow(utils.tr('Columns on row:'), self.spnColumnsOnRow)

    @property
    def _valueCodec(self):
        c = valuecodecs.FloatCodec()
        c.binaryFormat = self.cmbBinaryFormat.itemData(self.cmbBinaryFormat.currentIndex())
        return c

    @property
    def _formatter(self):
        f = formatters.FloatFormatter()
        f.precision = self.spnPrecision.value()
        return f

    def createColumnModel(self, hex_widget):
        return FloatColumnModel(hex_widget.document, self._valueCodec, self._formatter, self.spnColumnsOnRow.value())

    def saveToColumn(self, column):
        column.valuecodec = self._valueCodec
        column.formatter = self._formatter
        column.columnsOnRow = self.spnColumnsOnRow.value()
        column.reset()
Пример #4
0
class PointParameterWidget(GenericParameterWidget):
    """Widget class for Integer parameter."""
    def __init__(self, parameter, parent=None):
        """Constructor

        .. versionadded:: 2.2

        :param parameter: A IntegerParameter object.
        :type parameter: IntegerParameter

        """
        # Size policy
        self._spin_box_size_policy = QSizePolicy(
            QSizePolicy.Fixed, QSizePolicy.Fixed)

        super(PointParameterWidget, self).__init__(parameter, parent)

        self._input_x = QSpinBox()
        self._input_x.setValue(self._parameter.value[0])
        tool_tip = 'X'
        self._input_x.setToolTip(tool_tip)
        self._input_x.setSizePolicy(self._spin_box_size_policy)

        self._input_y = QSpinBox()
        self._input_y.setValue(self._parameter.value[1])
        tool_tip = 'Y'
        self._input_y.setToolTip(tool_tip)
        self._input_y.setSizePolicy(self._spin_box_size_policy)

        self._inner_input_layout.addWidget(self._input_x)
        self._inner_input_layout.addWidget(self._input_y)

    def get_parameter(self):
        """Obtain boolean parameter object from the current widget state.

        :returns: A BooleanParameter from the current state of widget

        """
        self._parameter.value = (self._input_x.value(), self._input_y.value())
        return self._parameter
Пример #5
0
class CharColumnConfigurationWidget(QWidget, columnproviders.AbstractColumnConfigurationWidget):
    def __init__(self, parent, hex_widget, column):
        QWidget.__init__(self, parent)
        columnproviders.AbstractColumnConfigurationWidget.__init__(self)
        self.hexWidget = hex_widget
        self.columnModel = column

        self.setLayout(QFormLayout())
        self.layout().setContentsMargins(0, 0, 0, 0)

        self.cmbEncoding = QComboBox(self)
        self.cmbEncoding.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred)
        self.layout().addRow(utils.tr('Encoding:'), self.cmbEncoding)
        for encoding in sorted(encodings.encodings.keys()):
            self.cmbEncoding.addItem(encoding)
            if column is not None and column.codec.name.lower() == encoding.lower():
                self.cmbEncoding.setCurrentIndex(self.cmbEncoding.count() - 1)
        if column is None:
            self.cmbEncoding.setCurrentIndex(self.cmbEncoding.findText('Windows-1251'))

        self.spnBytesOnRow = QSpinBox(self)
        self.spnBytesOnRow.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred)
        self.spnBytesOnRow.setMinimum(1)
        self.spnBytesOnRow.setMaximum(32)
        self.layout().addRow(utils.tr('Bytes on row:'), self.spnBytesOnRow)
        if column is not None:
            self.spnBytesOnRow.setValue(column.bytesOnRow)
        else:
            self.spnBytesOnRow.setValue(16)

    def createColumnModel(self, hex_widget):
        model = CharColumnModel(self.hexWidget.document, encodings.getCodec(self.cmbEncoding.currentText()),
                                self.hexWidget.font(), self.spnBytesOnRow.value())
        return model

    def saveToColumn(self, column):
        column.codec = encodings.getCodec(self.cmbEncoding.currentText())
        column._bytesOnRow = self.spnBytesOnRow.value()
        column.reset()
Пример #6
0
class IntervalWidget(QWidget):
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)

        layout = QHBoxLayout(self)
        layout.setContentsMargins(0,0,0,0)

        self.spinbox = QSpinBox(self)
        self.combo = QComboBox(self)

        sp = self.spinbox.sizePolicy()
        sp.setHorizontalStretch(1)
        self.spinbox.setSizePolicy(sp)

        self.spinbox.setRange(0, (1 << 31) - 1)
        self.spinbox.setSingleStep(1)

        self.combo.addItem('Seconds')
        self.combo.addItem('Milliseconds')

        layout.addWidget(self.spinbox)
        layout.addWidget(self.combo)

    def set_interval(self, interval):
        if ('%.03f' % interval).endswith('.000'):
            self.spinbox.setValue(int(interval))
            self.combo.setCurrentIndex(0)
        else:
            self.spinbox.setValue(round(interval * 1000.0))
            self.combo.setCurrentIndex(1)

    def get_interval(self):
        if self.combo.currentIndex() == 0:
            return self.spinbox.value()
        else:
            return self.spinbox.value() / 1000.0
Пример #7
0
class VolumeEditorWidget(QWidget):
    def __init__( self, volumeeditor, parent=None ):
        super(VolumeEditorWidget, self).__init__(parent=parent)
        self._ve = volumeeditor

        self.setFocusPolicy(Qt.StrongFocus)

        # setup quadview
        self.quadview = QuadView(self)
        self.quadview.addWidget(0, self._ve.imageViews[2])
        self.quadview.addWidget(1, self._ve.imageViews[0])
        self.quadview.addWidget(2, self._ve.imageViews[1])

        #3d overview
        #self.overview = OverviewScene(self, self._ve._shape[1:4])
        #self.quadview.addWidget(3, self.overview)
        self.quadview.addWidget(3, QWidget(self))
        #FIXME: resurrect        
        #self.overview.changedSlice.connect(self.changeSlice)
        #self._ve.changedSlice.connect(self.overview.ChangeSlice)

        # layout
        viewingLayout = QVBoxLayout()
        viewingLayout.setContentsMargins(10,2,0,2)
        viewingLayout.setSpacing(0)
        viewingLayout.addWidget(self.quadview)
        self.quadview.setContentsMargins(0,0,10,0)

        # Label below views
        labelLayout = QHBoxLayout()
        labelLayout.setMargin(0)
        labelLayout.setSpacing(5)
        labelLayout.setContentsMargins(0,0,0,0)
        self.posLabel = QLabel()
        self.pixelValuesLabel = QLabel()
        labelLayout.addWidget(self.posLabel)
        labelLayout.addWidget(self.pixelValuesLabel)
        labelLayout.addStretch()
        viewingLayout.addLayout(labelLayout)

        # Right side toolbox
        self._toolBox = QWidget()
        self._toolBox.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum)
        self._toolBoxLayout = QVBoxLayout()
        self._toolBoxLayout.setMargin(5)
        self._toolBox.setLayout(self._toolBoxLayout)
        self._toolBoxLayout.addStretch()

        # Toggle slice intersection marks
        self.indicateSliceIntersectionButton = QToolButton()
        self.indicateSliceIntersectionButton.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum)
        self.indicateSliceIntersectionButton.setText("Indicate Current Position")
        self.indicateSliceIntersectionButton.setCheckable(True)
        self.indicateSliceIntersectionButton.setChecked(True)        
        self._toolBoxLayout.addWidget(self.indicateSliceIntersectionButton)

        # Channel Selector QComboBox in right side tool box
        self._channelSpin = QSpinBox()
        self._channelSpin.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum)
        self._channelSpin.setEnabled(True)
        channelLayout = QHBoxLayout()
        channelLayout.addWidget(self._channelSpin)
        self._channelSpinLabel = QLabel("Channel:")
        self._toolBoxLayout.addWidget(self._channelSpinLabel)
        self._toolBoxLayout.addLayout(channelLayout)

        #time selector
        self._timeSpin = QSpinBox()
        self._timeSpin.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum)
        self._timeSpin.setEnabled(True)
        timeLayout = QHBoxLayout()
        timeLayout.addWidget(self._timeSpin)
        self._timeSpinLabel = QLabel("Time:")
        self._toolBoxLayout.addWidget(self._timeSpinLabel)
        self._toolBoxLayout.addLayout(timeLayout)
        
        self._toolBoxLayout.setAlignment(Qt.AlignTop)

        self._channelSpin.setRange(0,self._ve._shape[-1] - 1)
        self._timeSpin.setRange(0,self._ve._shape[0] - 1)
        def setChannel(c):
            print "set channel = %d, posModel has channel = %d" % (c, self._ve.posModel.channel)
            if c == self._ve.posModel.channel:
                return
            self._ve.posModel.channel = c
        self._channelSpin.valueChanged.connect(setChannel)
        def getChannel(newC):
            self._channelSpin.setValue(newC)
        self._ve.posModel.channelChanged.connect(getChannel)
        def setTime(t):
            print "set channel = %d, posModel has time = %d" % (t, self._ve.posModel.time)
            if t == self._ve.posModel.time:
                return
            self._ve.posModel.time = t
        self._timeSpin.valueChanged.connect(setTime)
        def getTime(newT):
            self._timeSpin.setValue(newT)
        self._ve.posModel.timeChanged.connect(getTime)

        # setup the layout for display
        self.splitter = QSplitter()
        self.splitter.setContentsMargins(0,0,0,0)
        tempWidget = QWidget()
        tempWidget.setLayout(viewingLayout)
        self.splitter.addWidget(tempWidget)
        self.splitter.addWidget(self._toolBox)
        splitterLayout = QVBoxLayout()
        splitterLayout.setMargin(0)
        splitterLayout.setSpacing(0)
        splitterLayout.addWidget(self.splitter)
        self.setLayout(splitterLayout)

        # drawing
        axisLabels = ["X:", "Y:", "Z:"]
        for i, v in enumerate(self._ve.imageViews):
            v.hud = SliceSelectorHud()
            #connect interpreter
            v.hud.sliceSelector.valueChanged.connect(partial(self._ve.navInterpret.changeSliceAbsolute, axis=i))
            #hud
            v.hud.bgColor = self._ve.navCtrl.axisColors[i] #FIXME
            v.hud.label = axisLabels[i]
            v.hud.minimum = 0
            v.hud.maximum = self._ve.posModel.volumeExtent(i)

        def toggleSliceIntersection(state):
            self._ve.navCtrl.indicateSliceIntersection = state
        self.indicateSliceIntersectionButton.toggled.connect(toggleSliceIntersection)

        #Enabling this makes cursor movement too slow...
        #self._ve.posModel.cursorPositionChanged.connect(self._updateInfoLabels)

        # shortcuts
        self._initShortcuts()

        
        self.updateGeometry()
        self.update()
        self.quadview.update()

    def _shortcutHelper(self, keySequence, group, description, parent, function, context = None, enabled = None):
        shortcut = QShortcut(QKeySequence(keySequence), parent, member=function, ambiguousMember=function)
        if context != None:
            shortcut.setContext(context)
        if enabled != None:
            shortcut.setEnabled(True)
        return shortcut, group, description

    def _initShortcuts(self):
        self.shortcuts = []
        self.shortcuts.append(self._shortcutHelper("Ctrl+Z", "Labeling", "History undo", self, self._ve.historyUndo, Qt.ApplicationShortcut, True))
        self.shortcuts.append(self._shortcutHelper("Ctrl+Shift+Z", "Labeling", "History redo", self, self._ve.historyRedo, Qt.ApplicationShortcut, True))
        self.shortcuts.append(self._shortcutHelper("Ctrl+Y", "Labeling", "History redo", self, self._ve.historyRedo, Qt.ApplicationShortcut, True))
        self.shortcuts.append(self._shortcutHelper("l", "Labeling", "Go to next label (cyclic, forward)", self, self._ve.nextLabel))
        self.shortcuts.append(self._shortcutHelper("k", "Labeling", "Go to previous label (cyclic, backwards)", self, self._ve.prevLabel))
        
        def fullscreenView(axis):
            m = not self.quadview.maximized
            print "maximize axis=%d = %r" % (axis, m)
            self.quadview.setMaximized(m, axis)
        
        maximizeShortcuts = ['x', 'y', 'z']
        maximizeViews     = [1,   2,     0]
        for i, v in enumerate(self._ve.imageViews):
            self.shortcuts.append(self._shortcutHelper(maximizeShortcuts[i], "Navigation", \
                                  "Enlarge slice view %s to full size" % maximizeShortcuts[i], \
                                  self, partial(fullscreenView, maximizeViews[i]), Qt.WidgetShortcut))
            
            #self.shortcuts.append(self._shortcutHelper("n", "Labeling", "Increase brush size", v,self._ve._drawManager.brushSmaller, Qt.WidgetShortcut))
            #self.shortcuts.append(self._shortcutHelper("m", "Labeling", "Decrease brush size", v, self._ve._drawManager.brushBigger, Qt.WidgetShortcut))
            self.shortcuts.append(self._shortcutHelper("+", "Navigation", "Zoom in", v,  v.zoomIn, Qt.WidgetShortcut))
            self.shortcuts.append(self._shortcutHelper("-", "Navigation", "Zoom out", v, v.zoomOut, Qt.WidgetShortcut))
            
            self.shortcuts.append(self._shortcutHelper("q", "Navigation", "Switch to next channel",     v, self._ve.nextChannel,     Qt.WidgetShortcut))
            self.shortcuts.append(self._shortcutHelper("a", "Navigation", "Switch to previous channel", v, self._ve.previousChannel, Qt.WidgetShortcut))
            
            def sliceDelta(axis, delta):
                newPos = copy.copy(self._ve.posModel.slicingPos)
                newPos[axis] += delta
                self._ve.posModel.slicingPos = newPos
            self.shortcuts.append(self._shortcutHelper("p", "Navigation", "Slice up",   v, partial(sliceDelta, i, 1),  Qt.WidgetShortcut))
            self.shortcuts.append(self._shortcutHelper("o", "Navigation", "Slice down", v, partial(sliceDelta, i, -1), Qt.WidgetShortcut))
            
            self.shortcuts.append(self._shortcutHelper("Ctrl+Up",   "Navigation", "Slice up",   v, partial(sliceDelta, i, 1),  Qt.WidgetShortcut))
            self.shortcuts.append(self._shortcutHelper("Ctrl+Down", "Navigation", "Slice down", v, partial(sliceDelta, i, -1), Qt.WidgetShortcut))
            
            self.shortcuts.append(self._shortcutHelper("Ctrl+Shift+Up",   "Navigation", "10 slices up",   v, partial(sliceDelta, i, 10),  Qt.WidgetShortcut))
            self.shortcuts.append(self._shortcutHelper("Ctrl+Shift+Down", "Navigation", "10 slices down", v, partial(sliceDelta, i, -10), Qt.WidgetShortcut))

    def _updateInfoLabels(self, pos):
        if any((pos[i] < 0 or pos[i] >= self._ve.posModel.shape[i] for i in xrange(3))):
            self._ve.posLabel.setText("")
            return
        self.posLabel.setText("<b>x:</b> %03i  <b>y:</b> %03i  <b>z:</b> %03i" % (pos[0], pos[1], pos[2]))
Пример #8
0
class PiezoSpeaker(PluginBase):
    qtcb_beep_finished = pyqtSignal()
    qtcb_morse_finished = pyqtSignal()

    def __init__(self, *args):
        PluginBase.__init__(self, BrickletPiezoSpeaker, *args)

        self.ps = self.device

        self.qtcb_beep_finished.connect(self.cb_beep)
        self.ps.register_callback(self.ps.CALLBACK_BEEP_FINISHED,
                                  self.qtcb_beep_finished.emit)
        self.qtcb_morse_finished.connect(self.cb_morse)
        self.ps.register_callback(self.ps.CALLBACK_MORSE_CODE_FINISHED,
                                  self.qtcb_morse_finished.emit)

        self.has_stoppable_beep = self.firmware_version >= (2, 0, 2)

        self.frequency_label = QLabel('Frequency (585 - 7100 Hz): ')
        self.frequency_box = QSpinBox()
        self.frequency_box.setMinimum(585)
        self.frequency_box.setMaximum(7100)
        self.frequency_box.setValue(1000)
        self.frequency_layout = QHBoxLayout()
        self.frequency_layout.addWidget(self.frequency_label)
        self.frequency_layout.addWidget(self.frequency_box)
        self.frequency_layout.addStretch()

        self.beep_box = QSpinBox()
        self.beep_box.setMinimum(0)
        self.beep_box.setMaximum(2147483647)
        self.beep_box.setValue(1000)
        self.beep_box.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred)
        self.beep_label = QLabel('Duration [ms]: ')
        self.beep_button = QPushButton('Send Beep')
        self.beep_layout = QHBoxLayout()
        self.beep_layout.addWidget(self.beep_label)
        self.beep_layout.addWidget(self.beep_box)
        self.beep_layout.addWidget(self.beep_button)

        self.morse_edit = QLineEdit()
        self.morse_edit.setText('- .. -. -.- . .-. ..-. --- .-. --. .')
        self.morse_edit.setMaxLength(60)
        self.morse_label = QLabel('Morse Code: ')
        self.morse_button = QPushButton('Send Morse Code')
        self.morse_layout = QHBoxLayout()
        self.morse_layout.addWidget(self.morse_label)
        self.morse_layout.addWidget(self.morse_edit)
        self.morse_layout.addWidget(self.morse_button)

        self.calibrate_button = QPushButton('Calibrate')
        self.scale_button = QPushButton('Play Scale')
        self.scale_layout = QHBoxLayout()
        self.scale_layout.addWidget(self.scale_button)
        self.scale_layout.addWidget(self.calibrate_button)
        self.scale_layout.addStretch()

        self.scale_timer = QTimer()
        self.scale_timer.setInterval(25)
        self.scale_time = 585

        self.status_label = QLabel('Status: Idle')

        self.beep_button.clicked.connect(self.beep_clicked)
        self.morse_button.clicked.connect(self.morse_clicked)
        self.scale_button.clicked.connect(self.scale_clicked)
        self.scale_timer.timeout.connect(self.scale_timeout)
        self.calibrate_button.clicked.connect(self.calibrate_clicked)

        layout = QVBoxLayout(self)
        layout.addLayout(self.frequency_layout)
        layout.addLayout(self.beep_layout)
        layout.addLayout(self.morse_layout)
        layout.addLayout(self.scale_layout)
        layout.addWidget(self.status_label)
        layout.addStretch()

    def start(self):
        pass

    def stop(self):
        pass

    def destroy(self):
        pass

    def get_url_part(self):
        return 'piezo_speaker'

    @staticmethod
    def has_device_identifier(device_identifier):
        return device_identifier == BrickletPiezoSpeaker.DEVICE_IDENTIFIER

    def cb_beep(self):
        self.beep_button.setDisabled(False)
        self.morse_button.setDisabled(False)
        self.scale_button.setDisabled(False)
        self.status_label.setText('Status: Idle')

    def cb_morse(self):
        self.beep_button.setDisabled(False)
        self.morse_button.setDisabled(False)
        self.scale_button.setDisabled(False)
        self.status_label.setText('Status: Idle')

    def calibrate_clicked(self):
        self.status_label.setText('Status: Calibrating...')
        self.status_label.repaint()
        QApplication.processEvents()
        self.ps.calibrate()
        self.status_label.setText('Status: New calibration stored in EEPROM')

    def scale_timeout(self):
        try:
            self.status_label.setText(str(self.scale_time) + 'Hz')
            self.ps.beep(40, self.scale_time)
        except ip_connection.Error:
            return

        self.scale_time += 50
        if self.scale_time > 7100:
            self.scale_time = 585
            self.scale_timer.stop()

    def scale_clicked(self):
        self.scale_time = 585
        self.scale_timeout()
        self.scale_timer.start()
        self.beep_button.setDisabled(True)
        self.morse_button.setDisabled(True)
        self.scale_button.setDisabled(True)

    def beep_clicked(self):
        freq = self.frequency_box.value()
        duration = self.beep_box.value()

        try:
            self.ps.beep(duration, freq)
        except ip_connection.Error:
            return

        if duration > 0 or not self.has_stoppable_beep:
            self.beep_button.setDisabled(True)
            self.morse_button.setDisabled(True)
            self.scale_button.setDisabled(True)
            self.status_label.setText('Status: Beeping...')

    def morse_clicked(self):
        freq = self.frequency_box.value()
        morse = self.morse_edit.text()
        try:
            self.ps.morse_code(morse, freq)
        except ip_connection.Error:
            return

        self.beep_button.setDisabled(True)
        self.morse_button.setDisabled(True)
        self.scale_button.setDisabled(True)
        self.status_label.setText('Status: Beeping...')
Пример #9
0
class XTimeDeltaEdit(QFrame):
    def __init__(self, parent=None):
        super(XTimeDeltaEdit, self).__init__(parent)
        
        # define custom properties
        self.setStyleSheet(COMBO_STYLE)
        
        self._numberSpinner = QSpinBox(self)
        self._numberSpinner.setRange(0, 100000)
        self._numberSpinner.setFrame(False)
        self._numberSpinner.setButtonSymbols(QSpinBox.NoButtons)
        self._numberSpinner.setSizePolicy(QSizePolicy.Expanding,
                                          QSizePolicy.Expanding)
        
        self._unitCombo = QComboBox(self)
        self._unitCombo.setEditable(True)
        self._unitCombo.setInsertPolicy(QComboBox.NoInsert)
        self._unitCombo.setFrame(False)
        self._unitCombo.addItems(['year(s)',
                                  'month(s)',
                                  'week(s)',
                                  'day(s)',
                                  'hour(s)',
                                  'minute(s)',
                                  'second(s)'])
        
        self._unitCombo.setCurrentIndex(3)
        self._unitCombo.setSizePolicy(QSizePolicy.Expanding,
                                      QSizePolicy.Expanding)
        
        self._directionCombo = QComboBox(self)
        self._directionCombo.addItems(['ago', 'from now'])
        self._directionCombo.setEditable(True)
        self._directionCombo.setInsertPolicy(QComboBox.NoInsert)
        self._directionCombo.setFrame(False)
        self._directionCombo.setSizePolicy(QSizePolicy.Expanding,
                                           QSizePolicy.Expanding)
        
        # setup ui
        self.setFrameShape(QFrame.StyledPanel)
        self.setFrameShadow(QFrame.Sunken)
        self.setBackgroundRole(QPalette.Base)
        self.setAutoFillBackground(True)
        
        layout = QHBoxLayout()
        layout.setContentsMargins(2, 2, 2, 2)
        layout.setSpacing(0)
        layout.addWidget(self._numberSpinner)
        layout.addWidget(self._unitCombo)
        layout.addWidget(self._directionCombo)
        self.setLayout(layout)
        
    def delta(self):
        """
        Returns a delta based on this widget's information.
        
        :return     <datetime.timedelta>
        """
        number      = self._numberSpinner.value()
        unit        = self._unitCombo.currentText()
        direction   = self._directionCombo.currentText()
        
        # use past tense
        if direction == 'ago':
            number = -number
        
        if unit == 'year(s)':
            return datetime.timedelta(number * 365)
        elif unit == 'month(s)':
            return datetime.timedelta(number * 30)
        elif unit == 'week(s)':
            return datetime.timedelta(number * 7)
        elif unit == 'day(s)':
            return datetime.timedelta(number)
        elif unit == 'hour(s)':
            return datetime.timedelta(0, number * 3600)
        elif unit == 'minute(s)':
            return datetime.timedelta(0, number * 60)
        else:
            return datetime.timedelta(0, number)
    
    def setDelta(self, delta):
        """
        Sets the time delta for this widget to the inputed delta.
        
        :param      delta | <datetime.timedelta>
        """
        days = int(delta.days)
        secs = int(delta.total_seconds())
        
        direction = 'from now'
        if secs < 0:
            direction = 'ago'
        
        if days and days % 365 == 0:
            number = days / 365
            unit = 'year(s)'
        elif days and days % 30 == 0:
            number = days / 30
            unit = 'month(s)'
        elif days and days % 7 == 0:
            number = days / 7
            unit = 'week(s)'
        elif days:
            number = days
            unit = 'day(s)'
        elif secs % 3600 == 0:
            number = secs / 3600
            unit = 'hour(s)'
        elif secs % 60 == 0:
            number = secs / 60
            unit = 'minute(s)'
        else:
            number = secs
            unit = 'second(s)'
        
        self._numberSpinner.setValue(abs(int(number)))
        self._unitCombo.setCurrentIndex(self._unitCombo.findText(unit))
        index = self._directionCombo.findText(direction)
        self._directionCombo.setCurrentIndex(index)
Пример #10
0
class XTimeDeltaEdit(QFrame):
    def __init__(self, parent=None):
        super(XTimeDeltaEdit, self).__init__(parent)

        # define custom properties
        self.setStyleSheet(COMBO_STYLE)

        self._numberSpinner = QSpinBox(self)
        self._numberSpinner.setRange(0, 100000)
        self._numberSpinner.setFrame(False)
        self._numberSpinner.setButtonSymbols(QSpinBox.NoButtons)
        self._numberSpinner.setSizePolicy(QSizePolicy.Expanding,
                                          QSizePolicy.Expanding)

        self._unitCombo = QComboBox(self)
        self._unitCombo.setEditable(True)
        self._unitCombo.setInsertPolicy(QComboBox.NoInsert)
        self._unitCombo.setFrame(False)
        self._unitCombo.addItems([
            'year(s)', 'month(s)', 'week(s)', 'day(s)', 'hour(s)', 'minute(s)',
            'second(s)'
        ])

        self._unitCombo.setCurrentIndex(3)
        self._unitCombo.setSizePolicy(QSizePolicy.Expanding,
                                      QSizePolicy.Expanding)

        self._directionCombo = QComboBox(self)
        self._directionCombo.addItems(['ago', 'from now'])
        self._directionCombo.setEditable(True)
        self._directionCombo.setInsertPolicy(QComboBox.NoInsert)
        self._directionCombo.setFrame(False)
        self._directionCombo.setSizePolicy(QSizePolicy.Expanding,
                                           QSizePolicy.Expanding)

        # setup ui
        self.setFrameShape(QFrame.StyledPanel)
        self.setFrameShadow(QFrame.Sunken)
        self.setBackgroundRole(QPalette.Base)
        self.setAutoFillBackground(True)

        layout = QHBoxLayout()
        layout.setContentsMargins(2, 2, 2, 2)
        layout.setSpacing(0)
        layout.addWidget(self._numberSpinner)
        layout.addWidget(self._unitCombo)
        layout.addWidget(self._directionCombo)
        self.setLayout(layout)

    def delta(self):
        """
        Returns a delta based on this widget's information.
        
        :return     <datetime.timedelta>
        """
        number = self._numberSpinner.value()
        unit = self._unitCombo.currentText()
        direction = self._directionCombo.currentText()

        # use past tense
        if direction == 'ago':
            number = -number

        if unit == 'year(s)':
            return datetime.timedelta(number * 365)
        elif unit == 'month(s)':
            return datetime.timedelta(number * 30)
        elif unit == 'week(s)':
            return datetime.timedelta(number * 7)
        elif unit == 'day(s)':
            return datetime.timedelta(number)
        elif unit == 'hour(s)':
            return datetime.timedelta(0, number * 3600)
        elif unit == 'minute(s)':
            return datetime.timedelta(0, number * 60)
        else:
            return datetime.timedelta(0, number)

    def setDelta(self, delta):
        """
        Sets the time delta for this widget to the inputed delta.
        
        :param      delta | <datetime.timedelta>
        """
        days = int(delta.days)
        secs = int(delta.total_seconds())

        direction = 'from now'
        if secs < 0:
            direction = 'ago'

        if days and days % 365 == 0:
            number = days / 365
            unit = 'year(s)'
        elif days and days % 30 == 0:
            number = days / 30
            unit = 'month(s)'
        elif days and days % 7 == 0:
            number = days / 7
            unit = 'week(s)'
        elif days:
            number = days
            unit = 'day(s)'
        elif secs % 3600 == 0:
            number = secs / 3600
            unit = 'hour(s)'
        elif secs % 60 == 0:
            number = secs / 60
            unit = 'minute(s)'
        else:
            number = secs
            unit = 'second(s)'

        self._numberSpinner.setValue(abs(int(number)))
        self._unitCombo.setCurrentIndex(self._unitCombo.findText(unit))
        index = self._directionCombo.findText(direction)
        self._directionCombo.setCurrentIndex(index)
Пример #11
0
class PiezoSpeaker(PluginBase):
    qtcb_beep_finished = pyqtSignal()
    qtcb_morse_finished = pyqtSignal()

    def __init__(self, *args):
        PluginBase.__init__(self, BrickletPiezoSpeaker, *args)

        self.ps = self.device

        self.qtcb_beep_finished.connect(self.cb_beep)
        self.ps.register_callback(self.ps.CALLBACK_BEEP_FINISHED,
                                  self.qtcb_beep_finished.emit)
        self.qtcb_morse_finished.connect(self.cb_morse)
        self.ps.register_callback(self.ps.CALLBACK_MORSE_CODE_FINISHED,
                                  self.qtcb_morse_finished.emit)

        self.has_stoppable_beep = self.firmware_version >= (2, 0, 2)

        self.frequency_label = QLabel('Frequency (585Hz-7100Hz): ')
        self.frequency_box = QSpinBox()
        self.frequency_box.setMinimum(585)
        self.frequency_box.setMaximum(7100)
        self.frequency_box.setValue(1000)
        self.frequency_layout = QHBoxLayout()
        self.frequency_layout.addWidget(self.frequency_label)
        self.frequency_layout.addWidget(self.frequency_box)
        self.frequency_layout.addStretch()

        self.beep_box = QSpinBox()
        self.beep_box.setMinimum(0)
        self.beep_box.setMaximum(2147483647)
        self.beep_box.setValue(1000)
        self.beep_box.setSizePolicy(QSizePolicy.Expanding,
                                    QSizePolicy.Preferred)
        self.beep_label = QLabel('Duration (ms): ')
        self.beep_button = QPushButton('Send Beep')
        self.beep_layout = QHBoxLayout()
        self.beep_layout.addWidget(self.beep_label)
        self.beep_layout.addWidget(self.beep_box)
        self.beep_layout.addWidget(self.beep_button)

        self.morse_edit = QLineEdit()
        self.morse_edit.setText('- .. -. -.- . .-. ..-. --- .-. --. .')
        self.morse_edit.setMaxLength(60)
        self.morse_label = QLabel('Morse Code: ')
        self.morse_button = QPushButton('Send Morse Code')
        self.morse_layout = QHBoxLayout()
        self.morse_layout.addWidget(self.morse_label)
        self.morse_layout.addWidget(self.morse_edit)
        self.morse_layout.addWidget(self.morse_button)

        self.calibrate_button = QPushButton('Calibrate')
        self.scale_button = QPushButton('Play Scale')
        self.scale_layout = QHBoxLayout()
        self.scale_layout.addWidget(self.scale_button)
        self.scale_layout.addWidget(self.calibrate_button)
        self.scale_layout.addStretch()

        self.calibrate_layout = QHBoxLayout()
        self.calibrate_layout.addStretch()

        self.scale_timer = QTimer()
        self.scale_timer.setInterval(25)
        self.scale_time = 585

        self.status_label = QLabel('')

        self.beep_button.clicked.connect(self.beep_clicked)
        self.morse_button.clicked.connect(self.morse_clicked)
        self.scale_button.clicked.connect(self.scale_clicked)
        self.scale_timer.timeout.connect(self.scale_timeout)
        self.calibrate_button.clicked.connect(self.calibrate_clicked)

        layout = QVBoxLayout(self)
        layout.addLayout(self.frequency_layout)
        layout.addLayout(self.beep_layout)
        layout.addLayout(self.morse_layout)
        layout.addLayout(self.scale_layout)
        layout.addWidget(self.status_label)
        #        layout.addLayout(self.calibrate_layout)
        layout.addStretch()

    def start(self):
        pass

    def stop(self):
        pass

    def destroy(self):
        pass

    def get_url_part(self):
        return 'piezo_speaker'

    @staticmethod
    def has_device_identifier(device_identifier):
        return device_identifier == BrickletPiezoSpeaker.DEVICE_IDENTIFIER

    def cb_beep(self):
        self.beep_button.setDisabled(False)
        self.morse_button.setDisabled(False)
        self.scale_button.setDisabled(False)
        self.status_label.setText('')

    def cb_morse(self):
        self.beep_button.setDisabled(False)
        self.morse_button.setDisabled(False)
        self.scale_button.setDisabled(False)
        self.status_label.setText('')

    def calibrate_clicked(self):
        self.status_label.setText('Calibrating')
        self.status_label.repaint()
        QApplication.processEvents()
        self.ps.calibrate()
        self.status_label.setText('New calibration stored in EEPROM')

    def scale_timeout(self):
        try:
            self.status_label.setText(str(self.scale_time) + 'Hz')
            self.ps.beep(40, self.scale_time)
        except ip_connection.Error:
            return

        self.scale_time += 50
        if self.scale_time > 7100:
            self.scale_time = 585
            self.scale_timer.stop()

    def scale_clicked(self):
        self.scale_time = 585
        self.scale_timeout()
        self.scale_timer.start()
        self.beep_button.setDisabled(True)
        self.morse_button.setDisabled(True)
        self.scale_button.setDisabled(True)

    def beep_clicked(self):
        freq = self.frequency_box.value()
        duration = self.beep_box.value()

        try:
            self.ps.beep(duration, freq)
        except ip_connection.Error:
            return

        if duration > 0 or not self.has_stoppable_beep:
            self.beep_button.setDisabled(True)
            self.morse_button.setDisabled(True)
            self.scale_button.setDisabled(True)
            self.status_label.setText('Beeping...')

    def morse_clicked(self):
        freq = self.frequency_box.value()
        morse = self.morse_edit.text()
        try:
            self.ps.morse_code(morse, freq)
        except ip_connection.Error:
            return

        self.beep_button.setDisabled(True)
        self.morse_button.setDisabled(True)
        self.scale_button.setDisabled(True)
        self.status_label.setText('Beeping...')
class IndustrialDualAnalogInV2(COMCUPluginBase):
    def __init__(self, *args):
        COMCUPluginBase.__init__(self, BrickletIndustrialDualAnalogInV2, *args)

        self.analog_in = self.device

        self.cbe_voltage0 = CallbackEmulator(functools.partial(self.analog_in.get_voltage, 0),
                                             functools.partial(self.cb_voltage, 0),
                                             self.increase_error_count)

        self.cbe_voltage1 = CallbackEmulator(functools.partial(self.analog_in.get_voltage, 1),
                                             functools.partial(self.cb_voltage, 1),
                                             self.increase_error_count)

        self.calibration = None

        self.sample_rate_label = QLabel('Sample Rate:')
        self.sample_rate_combo = QComboBox()
        self.sample_rate_combo.addItem('976 Hz')
        self.sample_rate_combo.addItem('488 Hz')
        self.sample_rate_combo.addItem('244 Hz')
        self.sample_rate_combo.addItem('122 Hz')
        self.sample_rate_combo.addItem('61 Hz')
        self.sample_rate_combo.addItem('4 Hz')
        self.sample_rate_combo.addItem('2 Hz')
        self.sample_rate_combo.addItem('1 Hz')

        self.current_voltage = [None, None] # float, V
        self.calibration_button = QPushButton('Calibration...')

        self.sample_rate_combo.currentIndexChanged.connect(self.sample_rate_combo_index_changed)
        self.calibration_button.clicked.connect(self.calibration_button_clicked)

        plots = [('Channel 0', Qt.red, lambda: self.current_voltage[0], format_voltage),
                 ('Channel 1', Qt.blue, lambda: self.current_voltage[1], format_voltage)]
        self.plot_widget = PlotWidget('Voltage [V]', plots)

        # Define lines
        line = QFrame()
        line.setFrameShape(QFrame.HLine)
        line.setFrameShadow(QFrame.Sunken)

        line1 = QFrame()
        line1.setFrameShape(QFrame.HLine)
        line1.setFrameShadow(QFrame.Sunken)

        line2 = QFrame()
        line2.setFrameShape(QFrame.HLine)
        line2.setFrameShadow(QFrame.Sunken)

        # Define channel LED status config widgets
        self.led_config_ch0_label = QLabel('Channel 0')
        self.led_config_ch1_label = QLabel('Channel 1')
        self.led_config_label = QLabel('LED Config:')
        self.led_status_config_label = QLabel('LED Status Config:')
        self.led_status_config_ch0_min_label = QLabel('Min:')
        self.led_status_config_ch0_max_label = QLabel('Max:')
        self.led_status_config_ch1_min_label = QLabel('Min:')
        self.led_status_config_ch1_max_label = QLabel('Max:')

        self.led_config_ch0_combo = QComboBox()
        self.led_config_ch0_combo.addItem('Off')
        self.led_config_ch0_combo.addItem('On')
        self.led_config_ch0_combo.addItem('Show Heartbeat')
        self.led_config_ch0_combo.addItem('Show Channel Status')
        self.led_config_ch0_combo.currentIndexChanged.connect(self.led_config_ch0_combo_changed)

        self.led_config_ch1_combo = QComboBox()
        self.led_config_ch1_combo.addItem('Off')
        self.led_config_ch1_combo.addItem('On')
        self.led_config_ch1_combo.addItem('Show Heartbeat')
        self.led_config_ch1_combo.addItem('Show Channel Status')
        self.led_config_ch1_combo.currentIndexChanged.connect(self.led_config_ch1_combo_changed)

        self.led_status_config_ch0_combo = QComboBox()
        self.led_status_config_ch0_combo.addItem('Threshold')
        self.led_status_config_ch0_combo.addItem('Intensity')
        self.led_status_config_ch0_combo.currentIndexChanged.connect(self.led_status_config_ch0_combo_changed)

        self.led_status_config_ch1_combo = QComboBox()
        self.led_status_config_ch1_combo.addItem('Threshold')
        self.led_status_config_ch1_combo.addItem('Intensity')
        self.led_status_config_ch1_combo.currentIndexChanged.connect(self.led_status_config_ch1_combo_changed)

        self.led_status_config_ch0_min_sbox = QSpinBox()
        self.led_status_config_ch0_min_sbox.setMinimum(-35000)
        self.led_status_config_ch0_min_sbox.setMaximum(35000)
        self.led_status_config_ch0_min_sbox.setValue(0)
        self.led_status_config_ch0_min_sbox.setSingleStep(1)
        self.led_status_config_ch0_min_sbox.setSuffix(' mV')
        self.led_status_config_ch0_min_sbox.valueChanged.connect(self.led_status_config_ch0_min_sbox_changed)

        self.led_status_config_ch0_max_sbox = QSpinBox()
        self.led_status_config_ch0_max_sbox.setMinimum(-35000)
        self.led_status_config_ch0_max_sbox.setMaximum(35000)
        self.led_status_config_ch0_max_sbox.setValue(0)
        self.led_status_config_ch0_max_sbox.setSingleStep(1)
        self.led_status_config_ch0_max_sbox.setSuffix(' mV')
        self.led_status_config_ch0_max_sbox.valueChanged.connect(self.led_status_config_ch0_max_sbox_changed)

        self.led_status_config_ch1_min_sbox = QSpinBox()
        self.led_status_config_ch1_min_sbox.setMinimum(-35000)
        self.led_status_config_ch1_min_sbox.setMaximum(35000)
        self.led_status_config_ch1_min_sbox.setValue(0)
        self.led_status_config_ch1_min_sbox.setSingleStep(1)
        self.led_status_config_ch1_min_sbox.setSuffix(' mV')
        self.led_status_config_ch1_min_sbox.valueChanged.connect(self.led_status_config_ch1_min_sbox_changed)

        self.led_status_config_ch1_max_sbox = QSpinBox()
        self.led_status_config_ch1_max_sbox.setMinimum(-35000)
        self.led_status_config_ch1_max_sbox.setMaximum(35000)
        self.led_status_config_ch1_max_sbox.setValue(0)
        self.led_status_config_ch1_max_sbox.setSingleStep(1)
        self.led_status_config_ch1_max_sbox.setSuffix(' mV')
        self.led_status_config_ch1_max_sbox.valueChanged.connect(self.led_status_config_ch1_max_sbox_changed)

        # Define size policies
        h_sp = QSizePolicy()
        h_sp.setHorizontalPolicy(QSizePolicy.Expanding)

        # Set size policies
        self.sample_rate_combo.setSizePolicy(h_sp)
        self.led_config_ch0_combo.setSizePolicy(h_sp)
        self.led_config_ch1_combo.setSizePolicy(h_sp)
        self.led_status_config_ch0_combo.setSizePolicy(h_sp)
        self.led_status_config_ch1_combo.setSizePolicy(h_sp)
        self.led_status_config_ch0_min_sbox.setSizePolicy(h_sp)
        self.led_status_config_ch0_max_sbox.setSizePolicy(h_sp)
        self.led_status_config_ch1_min_sbox.setSizePolicy(h_sp)
        self.led_status_config_ch1_max_sbox.setSizePolicy(h_sp)

        # Define layouts
        hlayout = QHBoxLayout()
        vlayout = QVBoxLayout()
        glayout = QGridLayout()
        layout = QVBoxLayout(self)
        hlayout_ch0_min_max = QHBoxLayout()
        hlayout_ch1_min_max = QHBoxLayout()

        # Populate layouts
        vlayout.addWidget(self.calibration_button)
        hlayout.addWidget(self.sample_rate_label)
        hlayout.addWidget(self.sample_rate_combo)
        vlayout.addLayout(hlayout)
        vlayout.addWidget(line1)

        hlayout_ch0_min_max.addWidget(self.led_status_config_ch0_min_label)
        hlayout_ch0_min_max.addWidget(self.led_status_config_ch0_min_sbox)
        hlayout_ch0_min_max.addWidget(self.led_status_config_ch0_max_label)
        hlayout_ch0_min_max.addWidget(self.led_status_config_ch0_max_sbox)

        hlayout_ch1_min_max.addWidget(self.led_status_config_ch1_min_label)
        hlayout_ch1_min_max.addWidget(self.led_status_config_ch1_min_sbox)
        hlayout_ch1_min_max.addWidget(self.led_status_config_ch1_max_label)
        hlayout_ch1_min_max.addWidget(self.led_status_config_ch1_max_sbox)

        glayout.addWidget(self.led_config_ch0_label, 0, 1, 1, 1) # R, C, RS, CS
        glayout.addWidget(self.led_config_ch1_label, 0, 2, 1, 1)

        glayout.addWidget(line2, 1, 0, 1, 3)

        glayout.addWidget(self.led_config_label, 2, 0, 1, 1)
        glayout.addWidget(self.led_config_ch0_combo, 2, 1, 1, 1)
        glayout.addWidget(self.led_config_ch1_combo, 2, 2, 1, 1)

        glayout.addWidget(self.led_status_config_label, 3, 0, 1, 1)
        glayout.addWidget(self.led_status_config_ch0_combo, 3, 1, 1, 1)
        glayout.addWidget(self.led_status_config_ch1_combo, 3, 2, 1, 1)

        glayout.addLayout(hlayout_ch0_min_max, 4, 1, 1, 1)
        glayout.addLayout(hlayout_ch1_min_max, 4, 2, 1, 1)

        layout.addWidget(self.plot_widget)
        layout.addWidget(line)
        layout.addLayout(vlayout)
        layout.addLayout(glayout)

        self.ui_group_ch_status_ch0 = [self.led_status_config_ch0_combo,
                                       self.led_status_config_ch0_min_sbox,
                                       self.led_status_config_ch0_max_sbox]

        self.ui_group_ch_status_ch1 = [self.led_status_config_ch1_combo,
                                       self.led_status_config_ch1_min_sbox,
                                       self.led_status_config_ch1_max_sbox]

    def start(self):
        async_call(self.analog_in.get_voltage, 0, lambda x: self.cb_voltage(0, x), self.increase_error_count)
        async_call(self.analog_in.get_voltage, 1, lambda x: self.cb_voltage(1, x), self.increase_error_count)
        async_call(self.analog_in.get_sample_rate, None, self.get_sample_rate_async, self.increase_error_count)
        async_call(self.analog_in.get_channel_led_config,
                   CH_0,
                   lambda config: self.get_channel_led_config_async(CH_0, config),
                   self.increase_error_count)
        async_call(self.analog_in.get_channel_led_status_config,
                   CH_0,
                   lambda config: self.get_channel_led_status_config_async(CH_0, config),
                   self.increase_error_count)
        async_call(self.analog_in.get_channel_led_config,
                   CH_1,
                   lambda config: self.get_channel_led_config_async(CH_1, config),
                   self.increase_error_count)
        async_call(self.analog_in.get_channel_led_status_config,
                   CH_1,
                   lambda config: self.get_channel_led_status_config_async(CH_1, config),
                   self.increase_error_count)

        self.cbe_voltage0.set_period(100)
        self.cbe_voltage1.set_period(100)

        self.plot_widget.stop = False

    def stop(self):
        self.cbe_voltage0.set_period(0)
        self.cbe_voltage1.set_period(0)

        self.plot_widget.stop = True

    def destroy(self):
        if self.calibration != None:
            self.calibration.close()

    @staticmethod
    def has_device_identifier(device_identifier):
        return device_identifier == BrickletIndustrialDualAnalogInV2.DEVICE_IDENTIFIER

    def calibration_button_clicked(self):
        if self.calibration == None:
            self.calibration = Calibration(self)

        self.calibration_button.setEnabled(False)
        self.calibration.show()

    def sample_rate_combo_index_changed(self, index):
        async_call(self.analog_in.set_sample_rate, index, None, self.increase_error_count)

    def led_config_ch0_combo_changed(self, index):
        if index != self.analog_in.CHANNEL_LED_CONFIG_SHOW_CHANNEL_STATUS:
            for e in self.ui_group_ch_status_ch0:
                e.setEnabled(False)
        else:
            for e in self.ui_group_ch_status_ch0:
                e.setEnabled(True)

        self.analog_in.set_channel_led_config(CH_0, index)

    def led_config_ch1_combo_changed(self, index):
        if index != self.analog_in.CHANNEL_LED_CONFIG_SHOW_CHANNEL_STATUS:
            for e in self.ui_group_ch_status_ch1:
                e.setEnabled(False)
        else:
            for e in self.ui_group_ch_status_ch1:
                e.setEnabled(True)

        self.analog_in.set_channel_led_config(CH_1, index)

    def led_status_config_ch0_combo_changed(self, index):
        self.analog_in.set_channel_led_status_config(CH_0,
                                                     self.led_status_config_ch0_min_sbox.value(),
                                                     self.led_status_config_ch0_max_sbox.value(),
                                                     index)

    def led_status_config_ch1_combo_changed(self, index):
        self.analog_in.set_channel_led_status_config(CH_1,
                                                     self.led_status_config_ch1_min_sbox.value(),
                                                     self.led_status_config_ch1_max_sbox.value(),
                                                     index)

    def led_status_config_ch0_min_sbox_changed(self, value):
        QObject.sender(self).blockSignals(True)

        self.analog_in.set_channel_led_status_config(CH_0,
                                                     self.led_status_config_ch0_min_sbox.value(),
                                                     self.led_status_config_ch0_max_sbox.value(),
                                                     self.led_status_config_ch0_combo.currentIndex())

        QObject.sender(self).blockSignals(False)

    def led_status_config_ch0_max_sbox_changed(self, value):
        QObject.sender(self).blockSignals(True)

        self.analog_in.set_channel_led_status_config(CH_0,
                                                     self.led_status_config_ch0_min_sbox.value(),
                                                     self.led_status_config_ch0_max_sbox.value(),
                                                     self.led_status_config_ch0_combo.currentIndex())

        QObject.sender(self).blockSignals(False)

    def led_status_config_ch1_min_sbox_changed(self, value):
        QObject.sender(self).blockSignals(True)


        self.analog_in.set_channel_led_status_config(CH_1,
                                                     self.led_status_config_ch1_min_sbox.value(),
                                                     self.led_status_config_ch1_max_sbox.value(),
                                                     self.led_status_config_ch1_combo.currentIndex())

        QObject.sender(self).blockSignals(False)

    def led_status_config_ch1_max_sbox_changed(self, value):
        QObject.sender(self).blockSignals(True)

        self.analog_in.set_channel_led_status_config(CH_1,
                                                     self.led_status_config_ch1_min_sbox.value(),
                                                     self.led_status_config_ch1_max_sbox.value(),
                                                     self.led_status_config_ch1_combo.currentIndex())

        QObject.sender(self).blockSignals(False)

    def get_voltage_value0(self):
        return self.voltage_value[0]

    def get_voltage_value1(self):
        return self.voltage_value[1]

    def get_sample_rate_async(self, rate):
        self.sample_rate_combo.blockSignals(True)

        self.sample_rate_combo.setCurrentIndex(rate)

        self.sample_rate_combo.blockSignals(False)

    def get_channel_led_config_async(self, channel, config):
        self.led_config_ch0_combo.blockSignals(True)
        self.led_config_ch1_combo.blockSignals(True)

        if channel == CH_0:
            self.led_config_ch0_combo.setCurrentIndex(config)
        elif channel == CH_1:
            self.led_config_ch1_combo.setCurrentIndex(config)

        self.led_config_ch0_combo.blockSignals(False)
        self.led_config_ch1_combo.blockSignals(False)

    def get_channel_led_status_config_async(self, channel, config):
        self.led_status_config_ch0_combo.blockSignals(True)
        self.led_status_config_ch1_combo.blockSignals(True)

        if channel == CH_0:
            self.led_status_config_ch0_combo.setCurrentIndex(config.config)
            self.led_status_config_ch0_max_sbox.setValue(config.max)
            self.led_status_config_ch0_min_sbox.setValue(config.min)
        elif channel == CH_1:
            self.led_status_config_ch1_combo.setCurrentIndex(config.config)
            self.led_status_config_ch1_max_sbox.setValue(config.max)
            self.led_status_config_ch1_min_sbox.setValue(config.min)

        self.led_status_config_ch0_combo.blockSignals(False)
        self.led_status_config_ch1_combo.blockSignals(False)

    def cb_voltage(self, sensor, voltage):
        self.current_voltage[sensor] = voltage / 1000.0
class Ui_TurnProtectionAndObstacleAssessment(object):
    def setupUi(self, Form):
        Form.setObjectName(_fromUtf8("Form"))
        Form.resize(435, 580)
        self.verticalLayout = QVBoxLayout(Form)
        self.verticalLayout.setObjectName(_fromUtf8("verticalLayout"))

        self.gbGeneral = GroupBox(Form)
        self.gbGeneral.Caption = "General"
        self.verticalLayout.addWidget(self.gbGeneral)

        # self.cmbAerodrome = ComboBoxPanel(self.gbGeneral, True)
        # self.cmbAerodrome.Caption = "Aerodrome"
        # self.cmbAerodrome.LabelWidth = 120
        # self.gbGeneral.Add = self.cmbAerodrome
        #
        # self.cmbRwyDir = ComboBoxPanel(self.gbGeneral, True)
        # self.cmbRwyDir.Caption = "Runway Direction"
        # self.cmbRwyDir.LabelWidth = 120
        # self.cmbRwyDir.Width = 120
        # self.gbGeneral.Add = self.cmbRwyDir

        self.cmbRnavSpecification = ComboBoxPanel(self.gbGeneral)
        self.cmbRnavSpecification.Caption = "Rnav Specification"
        self.cmbRnavSpecification.LabelWidth = 150
        self.gbGeneral.Add = self.cmbRnavSpecification

        self.frameChbThree = Frame(self.gbGeneral, "HL")
        self.gbGeneral.Add = self.frameChbThree

        self.chbUseTwoWpt = CheckBox(self.frameChbThree)
        self.chbUseTwoWpt.Caption = "Use 2 Waypoints"
        self.frameChbThree.Add = self.chbUseTwoWpt

        self.chbInsertSymbol = CheckBox(self.frameChbThree)
        self.chbInsertSymbol.Caption = "Insert Symbol(s)"
        self.frameChbThree.Add = self.chbInsertSymbol

        self.chbCatH = CheckBox(self.frameChbThree)
        self.chbCatH.Caption = "Cat.H"
        self.frameChbThree.Add = self.chbCatH

        self.cmbPhaseOfFlight = ComboBoxPanel(self.gbGeneral)
        self.cmbPhaseOfFlight.Caption = "Phase Of Flight"
        self.cmbPhaseOfFlight.LabelWidth = 150
        self.gbGeneral.Add = self.cmbPhaseOfFlight

        self.pnlArp = PositionPanel(self.gbGeneral)
        self.pnlArp.Caption = "Aerodrome Reference Point(ARP)"
        self.pnlArp.btnCalculater.hide()
        self.pnlArp.hideframe_Altitude()
        self.gbGeneral.Add = self.pnlArp

        self.gbWaypoint1 = GroupBox(self.gbGeneral)
        self.gbWaypoint1.Caption = "Waypoint1"
        self.gbGeneral.Add = self.gbWaypoint1

        self.cmbType1 = ComboBoxPanel(self.gbWaypoint1)
        self.cmbType1.Caption = "Type"
        self.cmbType1.LabelWidth = 150
        self.gbWaypoint1.Add = self.cmbType1

        self.pnlTolerances = RnavTolerancesPanel(self.gbWaypoint1)
        self.pnlTolerances.set_Att(Distance(0.8, DistanceUnits.NM))
        self.pnlTolerances.set_Xtt(Distance(1, DistanceUnits.NM))
        self.pnlTolerances.set_Asw(Distance(2, DistanceUnits.NM))
        self.gbWaypoint1.Add = self.pnlTolerances

        self.pnlWaypoint1 = PositionPanel(self.gbWaypoint1)
        self.pnlWaypoint1.btnCalculater.hide()
        self.pnlWaypoint1.hideframe_Altitude()
        self.gbWaypoint1.Add = self.pnlWaypoint1

        self.gbWaypoint2 = GroupBox(self.gbGeneral)
        self.gbWaypoint2.Caption = "Waypoint2"
        self.gbGeneral.Add = self.gbWaypoint2

        self.cmbType2 = ComboBoxPanel(self.gbWaypoint2)
        self.cmbType2.Caption = "Type"
        self.cmbType2.LabelWidth = 150
        self.gbWaypoint2.Add = self.cmbType2

        self.pnlTolerances2 = RnavTolerancesPanel(self.gbWaypoint2)
        self.pnlTolerances2.set_Att(Distance(0.8, DistanceUnits.NM))
        self.pnlTolerances2.set_Xtt(Distance(1, DistanceUnits.NM))
        self.pnlTolerances2.set_Asw(Distance(2, DistanceUnits.NM))
        self.gbWaypoint2.Add = self.pnlTolerances2

        self.pnlWaypoint2 = PositionPanel(self.gbWaypoint2)
        self.pnlWaypoint2.btnCalculater.hide()
        self.pnlWaypoint2.hideframe_Altitude()
        self.gbWaypoint2.Add = self.pnlWaypoint2

        self.frmRadioBtns = Frame(self.gbGeneral, "HL")
        self.gbGeneral.Add = self.frmRadioBtns

        self.rdnTF = QRadioButton(self.frmRadioBtns)
        self.rdnTF.setObjectName("rdnTF")
        self.rdnTF.setText("TF")
        self.rdnTF.setChecked(True)
        self.frmRadioBtns.Add = self.rdnTF

        self.rdnDF = QRadioButton(self.frmRadioBtns)
        self.rdnDF.setObjectName("rdnDF")
        self.rdnDF.setText("DF")
        self.frmRadioBtns.Add = self.rdnDF

        self.rdnCF = QRadioButton(self.frmRadioBtns)
        self.rdnCF.setObjectName("rdnCF")
        self.rdnCF.setText("CF")
        self.frmRadioBtns.Add = self.rdnCF


        self.chbCircularArcs = CheckBox(self.gbGeneral)
        self.chbCircularArcs.Caption = "Use Circular Arcs Method for Turns <= 30"
        self.gbGeneral.Add = self.chbCircularArcs

        self.gbParameters = GroupBox(Form)
        self.gbParameters.Caption = "Parameters"
        self.verticalLayout.addWidget(self.gbParameters)

        self.cmbSelectionMode = ComboBoxPanel(self.gbParameters)
        self.cmbSelectionMode.Caption = "Selection Mode"
        self.cmbSelectionMode.LabelWidth = 150
        self.gbParameters.Add = self.cmbSelectionMode


        self.pnlInbound = TrackRadialBoxPanel(self.gbParameters)
        self.pnlInbound.Caption = "In-bound Track"
        self.pnlInbound.LabelWidth = 150
        self.gbParameters.Add = self.pnlInbound

        self.pnlOutbound = TrackRadialBoxPanel(self.gbParameters)
        self.pnlOutbound.Caption = "Out-bound Track"
        self.pnlOutbound.LabelWidth = 150
        self.gbParameters.Add = self.pnlOutbound


        # icon = QIcon()
        # icon.addPixmap(QPixmap(_fromUtf8("Resource/coordinate_capture.png")), QIcon.Normal, QIcon.Off)

        self.pnlIas = SpeedBoxPanel(self.gbParameters)
        self.pnlIas.Caption = "IAS"
        self.pnlIas.LabelWidth = 150
        self.pnlIas.Value = Speed(250)
        self.gbParameters.Add = self.pnlIas

        self.pnlTas = SpeedBoxPanel(self.gbParameters)
        self.pnlTas.Caption = "TAS"
        self.pnlTas.Enabled = False
        self.pnlTas.LabelWidth = 150
        self.gbParameters.Add = self.pnlTas

        self.pnlAltitude = AltitudeBoxPanel(self.gbParameters)
        self.pnlAltitude.Caption = "Altitude"
        self.pnlAltitude.LabelWidth = 150
        self.pnlAltitude.Value = Altitude(1000)
        self.gbParameters.Add = self.pnlAltitude

        self.pnlIsa = NumberBoxPanel(self.gbParameters, "0.0")
        self.pnlIsa.CaptionUnits = define._degreeStr + "C"
        self.pnlIsa.Caption = "ISA"
        self.pnlIsa.LabelWidth = 150
        self.pnlIsa.Value = 15
        self.gbParameters.Add = self.pnlIsa

        self.pnlBankAngle = NumberBoxPanel(self.gbParameters, "0.0")
        self.pnlBankAngle.CaptionUnits = define._degreeStr
        self.pnlBankAngle.Caption = "Bank Angle"
        self.pnlBankAngle.LabelWidth = 150
        self.pnlBankAngle.Value = 25
        self.gbParameters.Add = self.pnlBankAngle

        self.pnlBankEstTime = NumberBoxPanel(self.gbParameters, "0.0")
        self.pnlBankEstTime.Caption = "Bank Establishment Time"
        self.pnlBankEstTime.Value = 1
        self.pnlBankEstTime.LabelWidth = 150
        self.pnlBankEstTime.Value = 5
        self.gbParameters.Add = self.pnlBankEstTime

        self.pnlPilotTime = NumberBoxPanel(self.gbParameters, "0.0")
        self.pnlPilotTime.Caption = "Pilot Reaction Time"
        self.pnlPilotTime.Value = 6
        self.pnlPilotTime.LabelWidth = 150
        self.gbParameters.Add = self.pnlPilotTime

        self.pnlWind = WindPanel(self.gbParameters)
        self.pnlWind.LabelWidth = 145
        self.gbParameters.Add = self.pnlWind

        self.pnlPrimaryMoc = AltitudeBoxPanel(self.gbParameters)
        self.pnlPrimaryMoc.Caption = "Primary Moc"
        self.pnlPrimaryMoc.LabelWidth = 150
        self.gbParameters.Add = self.pnlPrimaryMoc

        self.cmbConstructionType = ComboBoxPanel(self.gbParameters)
        self.cmbConstructionType.Caption = "Construction Type"
        self.cmbConstructionType.LabelWidth = 150
        self.gbParameters.Add = self.cmbConstructionType

        self.frameMOCmultipiler = Frame(self.gbParameters, "HL")
        self.gbParameters.Add = self.frameMOCmultipiler

        self.labelMOCmultipiler = QLabel(self.frameMOCmultipiler)
        self.labelMOCmultipiler.setMinimumSize(QSize(145, 0))
        self.labelMOCmultipiler.setMaximumSize(QSize(145, 16777215))
        font = QFont()
        font.setBold(False)
        font.setWeight(50)
        self.labelMOCmultipiler.setFont(font)
        self.labelMOCmultipiler.setObjectName(_fromUtf8("labelMOCmultipiler"))
        self.labelMOCmultipiler.setText("MOCmultipiler")
        self.frameMOCmultipiler.Add = self.labelMOCmultipiler

        self.mocSpinBox = QSpinBox(self.frameMOCmultipiler)
        sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.mocSpinBox.sizePolicy().hasHeightForWidth())
        self.mocSpinBox.setSizePolicy(sizePolicy)
        self.mocSpinBox.setMinimumSize(QSize(70, 0))
        self.mocSpinBox.setMaximumSize(QSize(70, 16777215))
        self.mocSpinBox.setMinimum(1)
        self.mocSpinBox.setObjectName(_fromUtf8("mocSpinBox"))
        self.frameMOCmultipiler.Add = self.mocSpinBox

        spacerItem = QSpacerItem(10,10,QSizePolicy.Expanding, QSizePolicy.Minimum)
        self.frameMOCmultipiler.layoutBoxPanel.addItem(spacerItem)

        self.chbDrawTolerance = CheckBox(self.gbParameters)
        self.chbDrawTolerance.Caption = "Draw Waypoint Tolerance"
        self.gbParameters.Add = self.chbDrawTolerance
Пример #14
0
class SliceSelectorHud(QFrame):
    """
    Heads up display for slice selection.
    
    Compact widget that shows a name, a spinbox
    and its maximum value explicitly. A background color can
    be set.
    """
    
    @property
    def maximum(self): return self._maximum
    @property
    def minimum(self): return self._minimum
    @maximum.setter
    def maximum(self, m):
        self._maximum = m
        self.coordLabel.setText("of %d" % self._maximum)
        self.sliceSelector.setRange(self._minimum, self._maximum)
    @minimum.setter
    def minimum(self, m):
        self._minimum = m
        self.sliceSelector.setRange(self._minimum, self._maximum)
    @property
    def label(self):
        return self._label
    @label.setter
    def label(self, l):
        self._label = l
        self.dimLabel.setText(l)
    
    @property
    def bgColor(self):
        return self._bgColor
    @bgColor.setter
    def bgColor(self, color):
        self._bgColor = color
        palette = self.palette();
        palette.setColor(self.backgroundRole(), color);
        self.setAutoFillBackground(True);
        self.setPalette(palette)
    
    def __init__(self, parent = None):
        super(SliceSelectorHud, self).__init__(parent)

        # init properties
        self._minimum = 0
        self._maximum = 1
        self._label   = ''
        self._bgColor = QColor(255,255,255)

        # configure self
        #
        # a border-radius of >0px to make the Hud appear rounded
        # does not work together with an QGLWidget, the corners just appear black
        # instead of transparent
        #self.setStyleSheet("QFrame {background-color: white; color: black; border-radius: 0px;}")
        
        
        
        self.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)

        self.setLayout(QHBoxLayout())
        self.layout().setContentsMargins(3,1,3,1)

        # dimension label
        self.dimLabel = QLabel(self)
        font = self.dimLabel.font()
        font.setBold(True)
        self.dimLabel.setFont(font)
        self.layout().addWidget(self.dimLabel)

        # coordinate selection
        self.sliceSelector = QSpinBox()
        self.sliceSelector.setButtonSymbols(QAbstractSpinBox.NoButtons)
        self.sliceSelector.setAlignment(Qt.AlignRight)
        self.sliceSelector.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)            
        self.layout().addWidget(self.sliceSelector)

        # coordinate label
        self.coordLabel = QLabel()
        self.layout().addWidget(self.coordLabel)
Пример #15
0
class HexColumnConfigurationWidget(QWidget, columnproviders.AbstractColumnConfigurationWidget):
    def __init__(self, parent, hex_widget, column):
        QWidget.__init__(self, parent)
        columnproviders.AbstractColumnConfigurationWidget.__init__(self)
        self.hexWidget = hex_widget
        self.column = column

        self.setLayout(QFormLayout())
        self.layout().setContentsMargins(0, 0, 0, 0)

        self.cmbBinaryFormat = QComboBox(self)
        self.cmbBinaryFormat.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred)
        self.layout().addRow(utils.tr('Binary format:'), self.cmbBinaryFormat)
        self.cmbBinaryFormat.currentIndexChanged[int].connect(self._onBinaryFormatChanged)

        self.chkSigned = QCheckBox()
        self.layout().addRow(utils.tr('Signed values:'), self.chkSigned)
        if column is not None:
            self.chkSigned.setChecked(column.valuecodec.signed)

        self.cmbEndianess = QComboBox(self)
        self.cmbEndianess.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred)
        self.layout().addRow(utils.tr('Endianess:'), self.cmbEndianess)
        self.cmbEndianess.addItem(utils.tr('Little endian'), valuecodecs.LittleEndian)
        self.cmbEndianess.addItem(utils.tr('Big endian'), valuecodecs.BigEndian)
        if column is not None:
            self.cmbEndianess.setCurrentIndex(self.cmbEndianess.findData(column.valuecodec.endianess))
        else:
            self.cmbEndianess.setCurrentIndex(0)

        icodec = valuecodecs.IntegerCodec
        for fmt in (icodec.Format8Bit, icodec.Format16Bit, icodec.Format32Bit, icodec.Format64Bit):
            self.cmbBinaryFormat.addItem(icodec.formatName(fmt), fmt)
            if column is not None and column.valuecodec.binaryFormat == fmt:
                self.cmbBinaryFormat.setCurrentIndex(self.cmbBinaryFormat.count() - 1)
        if column is None:
            self.cmbBinaryFormat.setCurrentIndex(0)

        self.cmbBase = QComboBox(self)
        self.cmbBase.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred)
        self.layout().addRow(utils.tr('Base:'), self.cmbBase)
        for base in ((utils.tr('Hex'), 16), (utils.tr('Dec'), 10), (utils.tr('Oct'), 8), (utils.tr('Bin'), 2)):
            self.cmbBase.addItem(base[0], base[1])
        if column is not None:
            self.cmbBase.setCurrentIndex(self.cmbBase.findData(column.formatter.base))

        self.spnColumnsOnRow = QSpinBox(self)
        self.spnColumnsOnRow.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred)
        self.spnColumnsOnRow.setMinimum(1)
        self.spnColumnsOnRow.setMaximum(32)
        self.layout().addRow(utils.tr('Columns on row:'), self.spnColumnsOnRow)
        if column is not None:
            self.spnColumnsOnRow.setValue(column.columnsOnRow)
        else:
            self.spnColumnsOnRow.setValue(16)

    def _onBinaryFormatChanged(self, index):
        self.cmbEndianess.setEnabled(self.cmbBinaryFormat.itemData(index) != valuecodecs.IntegerCodec.Format8Bit)

    @property
    def _valueCodec(self):
        valuecodec = valuecodecs.IntegerCodec()
        valuecodec.binaryFormat = self.cmbBinaryFormat.itemData(self.cmbBinaryFormat.currentIndex())
        valuecodec.signed = self.chkSigned.isChecked()
        valuecodec.endianess = self.cmbEndianess.itemData(self.cmbEndianess.currentIndex())
        return valuecodec

    @property
    def _formatter(self):
        valuecodec = self._valueCodec
        formatter = formatters.IntegerFormatter()
        formatter.base = self.cmbBase.itemData(self.cmbBase.currentIndex())
        maximal = formatter.format(valuecodec.maximal)
        minimal = formatter.format(valuecodec.minimal)
        if minimal.startswith('-'):
            minimal = minimal[1:]
        formatter.padding = max(len(maximal), len(minimal))
        return formatter

    def createColumnModel(self, hex_widget):
        return HexColumnModel(hex_widget.document, self._valueCodec, self._formatter, self.spnColumnsOnRow.value())

    def saveToColumn(self, column):
        column.valuecodec = self._valueCodec
        column.formatter = self._formatter
        column.columnsOnRow = self.spnColumnsOnRow.value()
        column.reset()