Example #1
0
 def initStyle(self,show=False):
     print 'In AlarmFormula.initStyle(%s)' %(self.obj or self.formula)
     try:
         self.org_formula = self.formula
         self.setChildrenCollapsible(False)
         self.setOrientation(Qt.Qt.Vertical)
         ###################################################################
         upperPanel = Qt.QFrame() #self
         upperPanel.setLayout(Qt.QGridLayout())
         self.insertWidget(0,upperPanel)
         self.editcb = Qt.QCheckBox('Edit')
         self.undobt = Qt.QPushButton()
         self.savebt = Qt.QPushButton()
         l = Qt.QLabel('Formula:')
         l.setFont(get_bold_font())
         self.tf = fandango.qt.QDropTextEdit() #Qt.QTextBrowser()
         self.tf.setMinimumHeight(100)
         if self.obj is not None:
             self.tf.setClickHook(self.onEdit)#@todo setClickHook stop working for unknown reasons !?!?!
             self.tf.setReadOnly(True)
             self.tf.setEnabled(False)
             self.connect(self.editcb,Qt.SIGNAL('toggled(bool)'),self.onEdit)
             upperPanel.layout().addWidget(self.editcb,0,4,1,1)
             self.undobt.setIcon(getThemeIcon('edit-undo'))
             self.undobt.setToolTip('Undo changes in formula')
             self.undobt.setEnabled(True)
             self.connect(self.undobt,Qt.SIGNAL('pressed()'),self.undoEdit)
             upperPanel.layout().addWidget(self.undobt,0,5,1,1)
             self.savebt.setIcon(getThemeIcon('media-floppy'))
             self.savebt.setToolTip('Save Alarm Formula')
             self.savebt.setEnabled(False)
             upperPanel.layout().addWidget(self.savebt,0,6,1,1)
             self.connect(self.savebt,Qt.SIGNAL('pressed()'),self.onSave)
         upperPanel.layout().addWidget(l,0,0,1,1)
         upperPanel.layout().addWidget(self.tf,1,0,1,7)
         ###################################################################
         lowerPanel,row = Qt.QFrame(),0 #self,2
         lowerPanel.setLayout(Qt.QGridLayout())
         self.insertWidget(1,lowerPanel)
         l = Qt.QLabel('Result:')
         l.setFont(get_bold_font())
         lowerPanel.layout().addWidget(l,row,0,1,1)
         self.tb = Qt.QTextEdit()
         #tb.setPlainText('Formula:\n\t%s\n\nOutput:\n\t%s'%(test.source,result))
         self.tb.setMinimumHeight(50)
         self.tb.setReadOnly(True)
         self.redobt = Qt.QPushButton()
         self.redobt.setIcon(getThemeIcon('view-refresh'))
         self.redobt.setToolTip('Update result')
         self.connect(self.redobt,Qt.SIGNAL('pressed()'),self.updateResult)
         lowerPanel.layout().addWidget(self.redobt,row,6,1,1)
         lowerPanel.layout().addWidget(self.tb,row+1,0,1,7)
         ###################################################################
         #Refresh from formula:
         if self.formula: self.updateFormula(self.formula)
         if show: self.show()
         print 'AlarmFormula.initStyle(%s) finished.'%self.formula
     except:
         print traceback.format_exc()
         print 'Unable to show AlarmFormula(%s)'%self.formula
 def __init__(self, parent=None, multirow=True):
     Qt.QFrame.__init__(self, parent)
     self.setToolTip(self.__help__)
     self.setLayout(Qt.QGridLayout())
     self.api = None
     self.reader = None
     self.schema = Qt.QLabel('SCHEMA:')
     self.attribute = Qt.QLabel('at/tri/bu/te')
     self.start = Qt.QPushButton('Start')
     self.stop = Qt.QPushButton('Stop')
     self.export = Qt.QPushButton('Export')
     self.archiver = fqt.MenuContexted(Qt.QLabel)('archiver(ID)')
     multirow = 3 if multirow else 0
     self.setTable(multirow)
     length = 6
     self.layout().addWidget(self.schema, 0, 0, 1, 1)
     self.layout().addWidget(self.attribute, 0, 1, 1, int(length / 2))
     self.layout().addWidget(self.table, 1, 0, multirow or 1, length)
     self.layout().addWidget(self.archiver, multirow + 2, 0, 1, 2)
     self.layout().addWidget(self.export, multirow + 2, length - 3, 1, 1)
     self.layout().addWidget(self.start, multirow + 2, length - 2, 1, 1)
     self.layout().addWidget(self.stop, multirow + 2, length - 1, 1, 1)
     self.setFrameStyle(self.Panel)
     self.checkDropSupport()
     self.setDropEventCallback(self.setModel)
     self.setModes()
     self.connect(self.start, Qt.SIGNAL('pressed()'), self.applyModes)
     self.connect(self.stop, Qt.SIGNAL('pressed()'), self.resetModes)
     self.connect(self.export,
                  Qt.SIGNAL('pressed()'),
                  lambda s=self: show_history(s.getModel(), {'hdb': 'hdb'}.
                                              get(s.getSchema(), '*'),
                                              parent=s))
     self.connect(self, Qt.SIGNAL('archive'), self.startArchiving)
     self.connect(self, Qt.SIGNAL('update'), self.setModes)
    def setup(self, parent, logger, trend):
        self.trend = trend or logger.trend
        self.logger = logger
        self.setWindowTitle("Reload Archiving")
        lwidget, lcheck = Qt.QVBoxLayout(), Qt.QHBoxLayout()
        self.setLayout(lwidget)

        self._reloadbutton = Qt.QPushButton('Reload Archiving')
        self.layout().addWidget(self._reloadbutton)
        self._reloadbutton.connect(self._reloadbutton, Qt.SIGNAL('clicked()'),
                                   self.logger.resetBuffers)
        self._decimatecombo = Qt.QComboBox()
        self._decimatecombo.addItems([t[0] for t in DECIMATION_MODES])
        self._decimatecombo.setCurrentIndex(0)
        self._nonescheck = Qt.QCheckBox('Remove Nones')
        self._nonescheck.setChecked(True)
        self._nonescheck.connect(self._nonescheck, Qt.SIGNAL('toggled(bool)'),
                                 self.toggle_nones)
        self._windowedit = Qt.QLineEdit()
        self._windowedit.setText('0')

        dl = Qt.QGridLayout()
        dl.addWidget(Qt.QLabel('Decimation method:'), 0, 0, 1, 2)
        dl.addWidget(self._decimatecombo, 0, 3, 1, 2)
        dl.addWidget(Qt.QLabel('Fixed Period (0=AUTO)'), 1, 0, 1, 1)
        dl.addWidget(self._windowedit, 1, 1, 1, 1)
        dl.addWidget(self._nonescheck, 1, 2, 1, 2)
        self.layout().addLayout(dl)
Example #4
0
    def onNew(self):
        w = Qt.QDialog(self.Form)
        w.setWindowTitle('Add New PyAlarm Device')
        w.setLayout(Qt.QGridLayout())
        server, device = Qt.QLineEdit(w), Qt.QLineEdit(w)
        server.setText('TEST')
        device.setText('test/pyalarm/1')
        w.layout().addWidget(Qt.QLabel('Server Instance'), 0, 0, 1, 1)
        w.layout().addWidget(server, 0, 1, 1, 1)
        w.layout().addWidget(Qt.QLabel('Device Name'), 1, 0, 1, 1)
        w.layout().addWidget(device, 1, 1, 1, 1)
        doit = Qt.QPushButton('Apply')
        w.layout().addWidget(doit, 2, 0, 2, 2)

        def create(s=server, d=device, p=w):
            try:
                s, d = str(s.text()), str(d.text())
                if '/' not in s: s = 'PyAlarm/%s' % s
                import fandango.tango as ft
                ft.add_new_device(s, 'PyAlarm', d)
                print('%s - %s: created!' % (s, d))
            except:
                traceback.print_exc()
            self.api.load()
            p.close()

        QtCore.QObject.connect(doit, QtCore.SIGNAL("clicked()"), create)
        w.exec_()
        self.setDevCombo()
Example #5
0
 def initStyle(self):
     print 'In AttributesPreview.initStyle()'
     try:
         self.setLayout(Qt.QGridLayout())
         self.redobt = Qt.QPushButton()
         self.redobt.setIcon(getThemeIcon('view-refresh'))
         self.redobt.setToolTip('Update result')
         self.taurusForm=TaurusForm()
         self.taurusForm.setWithButtons(False)
         self.taurusForm.setWindowTitle('Preview')
         self.layout().addWidget(self.redobt,0,6,1,1)
         self.layout().addWidget(Qt.QLabel('Values of attributes used in the Alarm formula:'),0,0,1,1)
         self.layout().addWidget(self.taurusForm,1,0,1,7)
         self.connect(self.redobt,Qt.SIGNAL('pressed()'),self.updateAttributes)
     except:
         print traceback.format_exc()
    def setupUi(self, USE_SCROLL=False, SHOW_OPTIONS=False, USE_TREND=False):
        self.setWindowTitle('Tango Finder : Search Attributes and Archiving')
        self.setLayout(Qt.QVBoxLayout())
        self.setMinimumWidth(950)  #550)
        #self.setMinimumHeight(700)

        self.layout().setAlignment(Qt.Qt.AlignTop)
        self.browser = Qt.QFrame()
        self.browser.setLayout(Qt.QVBoxLayout())

        self.chooser = Qt.QTabWidget()
        self.chooser.setTabPosition(
            self.chooser.West if SHOW_OPTIONS else self.chooser.North)
        #self.combo = Qt.QComboBox() # Combo used for domains, currently disabled

        self.searchbar = Qt.QFrame()
        self.searchbar.setLayout(Qt.QGridLayout())

        #self.label = Qt.QLabel('Type a part of device name and a part of attribute name, use "*" or " " as wildcards:')
        #self.layout().addWidget(self.label)

        self.ServerFilter = Qt.QLineEdit()
        self.ServerFilter.setMaximumWidth(250)
        self.DeviceFilter = fandango.qt.Dropable(Qt.QLineEdit)()
        self.DeviceFilter.setSupportedMimeTypes(
            fandango.qt.TAURUS_DEV_MIME_TYPE)
        self.AttributeFilter = fandango.qt.Dropable(Qt.QLineEdit)()
        self.AttributeFilter.setSupportedMimeTypes(
            [fandango.qt.TAURUS_ATTR_MIME_TYPE, fandango.qt.TEXT_MIME_TYPE])
        self.update = Qt.QPushButton('Update')
        self.archivecheck = Qt.QCheckBox("Show archived attributes only")
        self.archivecheck.setChecked(True)

        self.searchbar.layout().addWidget(
            Qt.QLabel(
                'Enter Device and Attribute filters using wildcards '
                '(e.g. li/ct/plc[0-9]+ / ^stat*$ & !status ) and push Update'),
            0, 0, 3, 13)

        [
            self.searchbar.layout().addWidget(o, x, y, h, w)
            for o, x, y, h, w in (
                (Qt.QLabel("Device or Alias:"), 4, 0, 1, 1),
                (self.DeviceFilter, 4, 1, 1, 4),
                (Qt.QLabel("Attribute:"), 4, 5, 1, 1),
                (self.AttributeFilter, 4, 6, 1, 4),
                (self.update, 4, 10, 1, 1),
                (self.archivecheck, 4, 11, 1, 2),
            )
        ]

        if SHOW_OPTIONS:
            self.options = Qt.QWidget()  #self.searchbar
            self.options.setLayout(Qt.QGridLayout())
            separator = lambda x: Qt.QLabel(' ' * x)
            row = 1
            [
                self.options.layout().addWidget(o, x, y, h, w)
                for o, x, y, h, w in (
                    #separator(120),Qt.QLabel("Options: "),separator(5),
                    (Qt.QLabel("Server: "), row, 0, 1, 1),
                    (self.ServerFilter, row, 1, 1, 4),
                    (Qt.QLabel(''), row, 2, 1, 11))
            ]
            #self.panel = generate_table(load_all_thermocouples('SR14')[-1])
            self.optiontab = Qt.QTabWidget()
            self.optiontab.addTab(self.searchbar, 'Filters')
            self.optiontab.addTab(self.options, 'Options')
            self.optiontab.setMaximumHeight(100)
            self.optiontab.setTabPosition(self.optiontab.North)
            self.browser.layout().addWidget(self.optiontab)

        else:
            self.browser.layout().addWidget(self.searchbar)

        self.toppan = Qt.QWidget(self)
        self.toppan.setLayout(Qt.QVBoxLayout())

        if USE_SCROLL:
            print '*' * 30 + ' USE_SCROLL=True ' + '*' * 30
            ## TO USE SCROLL, HEADER HAS BEEN SET AS A SEPARATE WIDGET
            #self.header = QGridTable(self.toppan)
            #self.header.setHorizontalHeaderLabels(self.LABELS)
            #self.header.setColumnWidth(0,350)
            self.headers = []
            self.header = Qt.QWidget(self.toppan)
            self.header.setLayout(Qt.QHBoxLayout())
            for l, s in zip(self.LABELS, self.SIZES):
                ql = Qt.QLabel(l)
                self.headers.append(ql)
                #if s is not None:
                #ql.setFixedWidth(s)
                #else:
                #ql.setSizePolicy(Qt.QSizePolicy.MinimumExpanding,Qt.QSizePolicy.Fixed)
                self.header.layout().addWidget(ql)

            self.toppan.layout().addWidget(self.header)

            self._scroll = MyScrollArea(self.toppan)  #Qt.QScrollArea(self)
            self._background = AttributesPanel(
                self._scroll
            )  #At least a panel should be kept (never deleted) in background to not crash the worker!
            self.panel = None
            self._scroll.setChildrenPanel(self.panel)
            self._scroll.setWidget(self.panel)
            self._scroll.setMaximumHeight(700)
            self.toppan.layout().addWidget(self._scroll)
            self.attrpanel = self._background
        else:
            self.panel = AttributesPanel(self.toppan)
            self.toppan.layout().addWidget(self.panel)
            self.attrpanel = self.panel

        self.toppan.layout().addWidget(
            Qt.QLabel(
                'Drag any attribute from the first column into the trend or any taurus widget you want:'
            ))

        self.browser.layout().addWidget(self.toppan)
        self.chooser.addTab(self.browser, 'Search ...')

        if USE_TREND:
            self.split = Qt.QSplitter(Qt.Qt.Vertical)
            self.split.setHandleWidth(25)
            self.split.addWidget(self.chooser)

            from taurus.qt.qtgui.plot import TaurusTrend
            from PyTangoArchiving.widget.trend import ArchivingTrend, ArchivingTrendWidget
            self.trend = ArchivingTrendWidget()  #TaurusArchivingTrend()
            self.trend.setUseArchiving(True)
            self.trend.showLegend(True)
            self.attrpanel.trend = self.trend

            if TaurusModelChooser is not None:
                self.treemodel = TaurusModelChooser(parent=self.chooser)
                self.chooser.addTab(self.treemodel, 'Tree')
                self.treemodel.updateModels.connect(self.trend.addModels)
                #self.treemodel.connect(self.treemodel,Qt.SIGNAL('updateModels'),self.trend.addModels)
            else:
                tracer('TaurusModelChooser not available!')

            self.split.addWidget(self.trend)
            self.layout().addWidget(self.split)
        else:
            self.layout().addWidget(self.chooser)
        type(self)._persistent_ = self
    def generateTable(self, values):

        #thermocouples = thermocouples if thermocouples is not None else self.thermocouples
        self.setRowCount(len(values))
        self.setColumnCount(5)
        #self.vheaders = []
        self.offset = 0
        self.widgetbuffer = []

        for i, tc in enumerate(sorted(values)):
            #print 'setTableRow(%s,%s)'%(i,tc)
            model, device, attribute, alias, archived, ok = tc
            model, device, attribute, alias = map(
                str.upper, (model, device, attribute, alias))

            #self.vheaders.append(model)
            def ITEM(m, model='', size=0):
                q = fandango.qt.Draggable(Qt.QLabel)(m)
                if size is not 0:
                    q.setMinimumWidth(size)  #(.7*950/5.)
                q._model = model
                q._archived = archived
                q.setDragEventCallback(lambda s=q: s._model)
                return q

            ###################################################################
            qf = Qt.QFrame()
            qf.setLayout(Qt.QGridLayout())
            qf.setMinimumWidth(self.SIZES[0])
            qf.setSizePolicy(Qt.QSizePolicy.Expanding, Qt.QSizePolicy.Fixed)
            #Order changed, it is not clear if it has to be done before or after adding TaurusValue selfect
            self.setCellWidget(i + self.offset, 0, qf)

            #print('Adding item: %s, %s, %s, %s, %s' % (model,device,attribute,alias,archived))
            if ok:
                tv = TaurusValue()  #TaurusValueLabel()
                qf.layout().addWidget(tv, 0, 0)
                tv.setParent(qf)
            else:
                self.setItem(i + self.offset, 0, ITEM(model, model))

            devlabel = ITEM(device, model, self.SIZES[1])
            self.setItem(i + self.offset, 1, devlabel)
            self.setItem(i + self.offset, 2,
                         ITEM(attribute, model, self.SIZES[2]))
            self.setItem(i + self.offset, 3, ITEM(alias, model, self.SIZES[3]))

            from PyTangoArchiving.widget.panel import showArchivingModes, show_history
            if archived:
                active = self.reader.is_attribute_archived(model, active=True)
                txt = '/'.join(a.upper() if a in active else a
                               for a in archived)
            else:
                txt = '...'
            q = Qt.QPushButton(txt)
            q.setFixedWidth(self.SIZES[-2])
            q.setToolTip("""%s<br><br><pre>
              'HDB' : Archived and updated, push to export values
              'hdb' : Archiving stopped, push to export values
              '...' : Not archived
              </pre>""" % txt)
            self.connect(q,
                         Qt.SIGNAL("pressed ()"),
                         lambda a=self.reader.get_attribute_alias(
                             model), o=q: setattr(q, 'w', show_history(a))
                         )  #showArchivingModes(a,parent=self)))
            self.setItem(i + self.offset, 4, q)

            qc = Qt.QCheckBox()
            qc.setFixedWidth(self.SIZES[-1])
            self.setItem(i + self.offset, 5, qc, 1, 1, Qt.Qt.AlignCenter,
                         model)

            if ok:
                #print('Setting Model %s'%model)
                #ADDING WIDGETS IN BACKGROUND DIDN'T WORKED, I JUST CAN SET MODELS FROM THE WORKER
                try:
                    if self.worker:
                        self.worker.put([(lambda w=tv, m=model: w.setModel(m))
                                         ])
                        #print 'worker,put,%s'%str(model)
                    else:
                        tv.setModel(model)
                except:
                    print traceback.format_exc()
                self.models.append(tv)

            #self.widgetbuffer.extend([qf,self.itemAt(i+self.offset,1),self.itemAt(i+self.offset,2),self.itemAt(i+self.offset,3),self.itemAt(i+self.offset,4)])
            fandango.threads.Event().wait(.02)

        if len(values):

            def setup(o=self):
                [o.setRowHeight(i, 20) for i in range(o.rowCount())]
                #o.setColumnWidth(0,350)
                o.update()
                o.repaint()
                #print o.rowCount()
                o.show()

            setup(self)

        if self.worker:
            print('%s.next()' % (self.worker))
            self.worker.next()

        #threading.Event().wait(10.)
        tracer('Out of generateTable()')
    def show_history(self, attribute):
        TABS = []
        print 'getting archiving readers ...'
        from PyTangoArchiving import Reader
        hdb = Reader(db='hdb', schema='hdb')
        tdb = Reader(db='tdb', schema='tdb')
        tformat = '%Y-%m-%d %H:%M:%S'
        str2epoch = lambda s: time.mktime(time.strptime(s, tformat))
        epoch2str = lambda f: time.strftime(tformat, time.localtime(f))
        attribute = attribute.lower()

        if attribute in hdb.get_attributes(
        ) or attribute in tdb.get_attributes():
            print '%s is being archived' % attribute
            di = Qt.QDialog()
            wi = di  #QtGui.QWidget(di)
            wi.setLayout(Qt.QGridLayout())
            begin = Qt.QLineEdit()
            begin.setText(epoch2str(time.time() - 3600))
            end = Qt.QLineEdit()
            end.setText(epoch2str(time.time()))
            wi.setWindowTitle('Show Archiving')
            wi.layout().addWidget(
                Qt.QLabel('Enter Begin and End dates in %s format' % tformat),
                0, 0, 1, 2)
            wi.layout().addWidget(Qt.QLabel('Begin:'), 1, 0, 1, 1)
            wi.layout().addWidget(Qt.QLabel('End:'), 2, 0, 1, 1)
            wi.layout().addWidget(begin, 1, 1, 1, 1)
            wi.layout().addWidget(end, 2, 1, 1, 1)
            buttons = Qt.QDialogButtonBox(Qt.QDialogButtonBox.Ok
                                          | Qt.QDialogButtonBox.Cancel)
            wi.connect(buttons, Qt.SIGNAL('accepted()'), wi.accept)
            wi.connect(buttons, Qt.SIGNAL('rejected()'), wi.reject)
            wi.layout().addWidget(buttons, 3, 0, 1, 2)

            def check_values():
                di.exec_()
                if di.result():
                    print 'checking result ...'
                    start, stop = str(begin.text()), str(end.text())
                    if not all(
                            re.match(
                                '[0-9]+-[0-9]+-[0-9]+ [0-9]+:[0-9]+:[0-9]+',
                                str(s).strip()) for s in (start, stop)):
                        print 'dates are wrong ...'
                        Qt.QMessageBox.warning(
                            None, 'Show archiving',
                            'Dates seem not in %s format' % (tformat),
                            Qt.QMessageBox.Ok)
                        return check_values()
                    else:
                        print 'getting values ...'
                        reader = tdb if str2epoch(start) > (
                            time.time() - 5 * 24 * 3600.
                        ) and attribute in tdb.get_attributes() else hdb
                        print 'using %s reader' % reader.schema
                        values = reader.get_attribute_values(
                            attribute, str2epoch(start), str2epoch(stop))
                        if not len(
                                values
                        ) and reader is tdb and attribute in hdb.get_attributes(
                        ):
                            print 'tdb failed, retrying with hdb'
                            values = hdb.get_attribute_values(
                                attribute, str2epoch(start), str2epoch(stop))
                        print 'drawing table from %d values' % len(values)
                        tab = Qt.QTableWidget()
                        tab.setWindowTitle('%s: %s to %s' %
                                           (attribute, start, stop))
                        tab.setRowCount(len(values))
                        tab.setColumnCount(2)
                        tab.setHorizontalHeaderLabels(['TIME', 'VALUE'])
                        for i, tup in enumerate(values):
                            date, value = tup
                            tab.setItem(i, 0,
                                        Qt.QTableWidgetItem(epoch2str(date)))
                            tab.setItem(i, 1, Qt.QTableWidgetItem(str(value)))
                        tab.show()
                        tab.resizeColumnsToContents()
                        tab.horizontalHeader().setStretchLastSection(True)
                        TABS.append(tab)
                        tab.connect(tab,
                                    Qt.SIGNAL('close()'),
                                    lambda o=tab: TABS.remove(o))
                        print 'show_history done ...'
                        return tab
                else:
                    print 'dialog closed'
                    return None

            print 'asking for dates ...'
            return check_values()
        else:
            Qt.QMessageBox.warning(
                None, 'Show archiving',
                'Attribute %s is not being archived' % attribute,
                Qt.QMessageBox.Ok)
Example #9
0
    def show_new_dialog(klass, attribute, schema='*', parent=None, dates=[]):
        try:
            if not Qt.QApplication.instance(): Qt.QApplication([])
        except:
            pass
        print 'in Vacca.widgets.show_history(%s)'

        print 'getting archiving readers ...'
        from PyTangoArchiving import Reader
        rd = Reader(schema.lower())
        hdb = Reader('hdb')
        tdb = Reader('tdb')
        attribute = str(attribute).lower()

        try:
            dates = dates or klass.get_default_dates()
            if not all(map(fandango.isString, dates)):
                dates = map(epoch2str, dates)
        except:
            traceback.print_exc()
            dates = epoch2str(), epoch2str()

        schemas = rd.is_attribute_archived(attribute, preferent=False)
        if schemas:
            print '%s is being archived' % attribute
            di = Qt.QDialog(parent)
            wi = di  #QtGui.QWidget(di)
            wi.setLayout(Qt.QGridLayout())
            begin = Qt.QLineEdit()
            begin.setText(dates[0])
            end = Qt.QLineEdit()
            end.setText(dates[1])
            tfilter = Qt.QLineEdit()
            vfilter = Qt.QCheckBox()
            wi.setWindowTitle('Show %s Archiving' % attribute)
            wil = wi.layout()
            wi.layout().addWidget(Qt.QLabel(attribute), 0, 0, 1, 2)
            wi.layout().addWidget(Qt.QLabel('Preferred Schema'), 1, 0, 1, 1)
            qschema = Qt.QComboBox()
            qschema.insertItems(0, ['*'] + list(schemas))
            wil.addWidget(qschema, 1, 1, 1, 1)
            #qb = Qt.QPushButton("Save as preferred schema")
            #wil.addWidget(qb,wil.rowCount(),0,1,2)
            #qi.connect(qb,Qt.SIGNAL('pushed()'),save_schema)
            wil.addWidget(
                Qt.QLabel('Enter Begin and End dates in %s format' % tformat),
                2, 0, 1, 2)
            wil.addWidget(Qt.QLabel('Begin:'), 3, 0, 1, 1)
            wil.addWidget(begin, 3, 1, 1, 1)
            wil.addWidget(Qt.QLabel('End:'), 4, 0, 1, 1)
            wil.addWidget(end, 4, 1, 1, 1)
            wil.addWidget(Qt.QLabel('Time Filter:'), 5, 0, 1, 1)
            wil.addWidget(tfilter, 5, 1, 1, 1)
            wil.addWidget(Qt.QLabel('Value Filter:'), 6, 0, 1, 1)
            wil.addWidget(vfilter, 6, 1, 1, 1)
            buttons = Qt.QDialogButtonBox(wi)
            buttons.addButton(Qt.QPushButton("Export"),
                              Qt.QDialogButtonBox.AcceptRole)

            bt = Qt.QPushButton("Apply")
            buttons.addButton(bt, Qt.QDialogButtonBox.ApplyRole)

            def set_schema(r=rd, a=attribute, qs=qschema):
                print 'setting schema ...'
                schema = str(qs.currentText()).strip()
                r.set_preferred_schema(a, schema)

            buttons.connect(bt, Qt.SIGNAL('clicked()'), set_schema)

            buttons.addButton(Qt.QPushButton("Close"),
                              Qt.QDialogButtonBox.RejectRole)

            #  Qt.QDialogButtonBox.Apply\
            #    |Qt.QDialogButtonBox.Open|Qt.QDialogButtonBox.Close)
            wi.connect(buttons, Qt.SIGNAL('accepted()'), wi.accept)
            wi.connect(buttons, Qt.SIGNAL('rejected()'), wi.reject)
            wi.layout().addWidget(buttons, 7, 0, 1, 2)

            def check_values():
                di.exec_()
                print 'checking schema ...'
                schema = str(qschema.currentText()).strip()
                if schema != '*':
                    rd.set_preferred_schema(attribute, schema)
                if di.result():
                    print 'checking result ...'
                    try:
                        start, stop = str(begin.text()), str(end.text())
                        try:
                            tf = int(str(tfilter.text()))
                        except:
                            tf = 0
                        vf = vfilter.isChecked()
                        if not all(
                                re.match(
                                    '[0-9]+-[0-9]+-[0-9]+ [0-9]+:[0-9]+:[0-9]+',
                                    str(s).strip()) for s in (start, stop)):
                            print 'dates are wrong ...'
                            Qt.QMessageBox.warning(
                                None, 'Show archiving',
                                'Dates seem not in %s format' % (tformat),
                                Qt.QMessageBox.Ok)
                            return check_values()
                        else:
                            print 'getting values ...'
                            print 'using %s reader' % rd.schema
                            values = rd.get_attribute_values(
                                attribute, str2epoch(start), str2epoch(stop))
                            if not len(
                                    values
                            ) and schema == '*' and hdb.is_attribute_archived(
                                    attribute, active=True):
                                print 'tdb failed, retrying with hdb'
                                values = hdb.get_attribute_values(
                                    attribute, str2epoch(start),
                                    str2epoch(stop))
                            if vf:
                                values = fandango.arrays.decimate_array(values)
                            if tf:
                                print 'Filtering %d values (1/%dT)' % (
                                    len(values), tf)
                                values = fandango.arrays.filter_array(
                                    values, window=tf)  #,begin=start,end=stop)

                            twi = klass.setup_table(attribute, start, stop,
                                                    values)
                            klass.set_default_dates(str2epoch(start),
                                                    str2epoch(stop))

                            button = Qt.QPushButton('Save to file')
                            button2 = Qt.QPushButton('Send to email')

                            def save_to_file(var=attribute,
                                             data=values,
                                             parent=twi,
                                             edit=True):
                                try:
                                    options = {
                                        'sep': '\\t',
                                        'arrsep': '\\ ',
                                        'linesep': '\\n'
                                    }
                                    import codecs
                                    dd = QOptionDialog(model=options,
                                                       title='CSV Options')
                                    dd.exec_()
                                    for k, v in options.items():
                                        options[k] = codecs.escape_decode(
                                            str(v))[0]
                                    print options

                                    filename = Qt.QFileDialog.getSaveFileName(
                                        parent, 'File to save',
                                        '/data/' + PyTangoArchiving.files.
                                        get_data_filename(
                                            var, data, 'csv', 'human'),
                                        'CSV files (*.csv)')

                                    PyTangoArchiving.files.save_data_file(
                                        var,
                                        data,
                                        filename,
                                        format='csv',
                                        **options)
                                    if edit:
                                        try:
                                            os.system('gedit %s &' % filename)
                                        except:
                                            pass
                                    return filename
                                except Exception, e:
                                    Qt.QMessageBox.warning(
                                        None, "Warning",
                                        "Unable to save %s\n:%s" %
                                        (filename, e))

                            def send_by_email(var=attribute,
                                              data=values,
                                              parent=twi):
                                #subject,text,receivers,sender='',attachments=None,trace=False):
                                try:
                                    receivers, ok = Qt.QInputDialog.getText(
                                        None, 'Send by email', 'to:')
                                    if ok:
                                        filename = str(
                                            save_to_file(var,
                                                         data,
                                                         parent,
                                                         edit=False))
                                        fandango.linos.sendmail(
                                            filename,
                                            attribute,
                                            receivers=str(receivers),
                                            attachments=[filename])
                                except Exception, e:
                                    Qt.QMessageBox.warning(
                                        None, "Warning",
                                        "Unable to send %s\n:%s" %
                                        (filename, e))

                            #button.setTextAlignment(Qt.Qt.AlignCenter)
                            twi.connect(button, Qt.SIGNAL("pressed ()"),
                                        save_to_file)
                            twi.layout().addWidget(button)
                            twi.connect(button2, Qt.SIGNAL("pressed ()"),
                                        send_by_email)
                            twi.layout().addWidget(button2)
                            twi.show()

                            TABS.append(twi)
                            twi.connect(twi,
                                        Qt.SIGNAL('close()'),
                                        lambda o=twi: TABS.remove(o))
                            print 'show_history done ...'
                            return twi
                    except Exception, e:
                        print traceback.format_exc()
                        Qt.QMessageBox.warning(
                            None, "Warning",
                            "Unable to retrieve the values (%s), sorry" % e)
Example #10
0
    def setModel(self,
                 model=None,
                 rows=0,
                 cols=0,
                 side=0,
                 fontsize=0,
                 **kwargs):
        print('QAlarmPanel.setModel(%s)' % model)
        import panic, math

        if isinstance(model, AlarmView):
            self.view = model
            self.api = self.view.api
        else:  #if fd.isString(model):
            self.api = panic.AlarmAPI(model, extended=True)
            self.view = AlarmView(api=self.api, verbose=False)

        self.tags = self.view.sort(sortkey=('priority', 'tag'), keep=False)
        self.alarms = self.view.alarms
        self.old_devs = set()
        self.actives = []
        self.panels = []
        self.setCurrentAlarm(None)

        self.fontsize = fontsize

        if rows and not cols:
            self.rows = int(rows)
            self.cols = int(math.ceil((1 + len(self.tags)) / self.rows))
        elif cols and not rows:
            self.rows = int(math.ceil((1 + len(self.tags)) / cols))
            self.cols = int(cols)
        else:
            self.cols = int(cols or math.ceil(math.sqrt(1 + len(self.tags))))
            self.rows = int(
                rows or ((self.cols - 1) if self.cols *
                         (self.cols - 1) >= 1 + len(self.tags) else self.cols))

        self.setLayout(Qt.QGridLayout())
        self.labels = []
        for i in range(self.rows):
            self.labels.append([])
            for j in range(self.cols):
                self.labels[i].append(QAlarmPanelLabel(self))
                self.layout().addWidget(self.labels[i][j], i, j, 1, 1)
        self.logo = self.labels[-1][-1]
        self.logo.setClickHook(self.showGUI)

        self._title = 'PANIC Alarm Panel (%s)' % str(model
                                                     or fd.get_tango_host())
        self.setWindowTitle(self._title)
        url = os.path.dirname(panic.__file__) + '/gui/icon/panic-6-big.png'
        px = Qt.QPixmap(url)
        self.setWindowIcon(Qt.QIcon(px))
        #self.labels[self.rows-1][self.cols-1].resize(50,50)

        print('QAlarmPanel(%s): %d alarms , %d cols, %d rows: %s' %
              (model, len(self.tags), self.cols, self.rows,
               fd.log.shortstr(self.tags)) + '\n' + '#' * 80)

        self.refreshTimer = Qt.QTimer()
        Qt.QObject.connect(self.refreshTimer, Qt.SIGNAL("timeout()"),
                           self.updateAlarms)

        self.refreshTimer.start(self.REFRESH_TIME)
        side = side or (min((self.rows, self.cols)) == 1 and 50) or 50  #70#120
        if all((cols, rows, side)):
            width, height = side * cols, side * rows
            self.logo.setPixmap(px.scaled(side, side))
        else:
            width, height = min((800, side * self.cols)), min(
                (800, side * self.rows))
            self.logo.setPixmap(px.scaled(side, side))  #70,70))
            #px.scaled(height/self.rows,height/self.rows))
        #if (width/self.rows)>=50:
        self.resize(width, height)
        self.show()
 def setupUi(self,USE_SCROLL=False,SHOW_OPTIONS=True,USE_TREND=False):
     self.setWindowTitle('Tango Finder : Search Attributes and Archiving')
     self.setLayout(Qt.QVBoxLayout())
     self.setMinimumWidth(950)#550)
     #self.setMinimumHeight(700)
     self.layout().setAlignment(Qt.Qt.AlignTop)
     self.chooser = Qt.QFrame()
     self.chooser.setLayout(Qt.QHBoxLayout())
     self.combo = Qt.QComboBox() #(self)
     #self.chooser.layout().addWidget(Qt.QLabel('Choose a domain to see temperatures status:'))
     #self.chooser.layout().addWidget(self.combo)
     #self.layout().addWidget(self.chooser)
     if True:
         self.searchbar = Qt.QFrame()
         self.searchbar.setLayout(Qt.QGridLayout()) 
         self.label = Qt.QLabel('Type a part of device name and a part of attribute name, use "*" or " " as wildcards:')
         #self.search = Qt.QLineEdit()
         self.ServerFilter = Qt.QLineEdit()
         self.ServerFilter.setMaximumWidth(250)
         self.DeviceFilter = fandango.qt.Dropable(Qt.QLineEdit)()
         self.DeviceFilter.setSupportedMimeTypes(fandango.qt.TAURUS_DEV_MIME_TYPE)
         self.AttributeFilter = fandango.qt.Dropable(Qt.QLineEdit)()
         self.AttributeFilter.setSupportedMimeTypes([fandango.qt.TAURUS_ATTR_MIME_TYPE,fandango.qt.TEXT_MIME_TYPE])
         self.update = Qt.QPushButton('Update')
         self.archivecheck = Qt.QCheckBox("Show archived attributes only")
         self.archivecheck.setChecked(False)
         self.layout().addWidget(self.label)
         [self.searchbar.layout().addWidget(o,x,y,h,w) for o,x,y,h,w in (
             (Qt.QLabel("Device or Alias:"),0,0,1,1),(self.DeviceFilter,0,1,1,4),
             (Qt.QLabel("Attribute:"),0,5,1,1),(self.AttributeFilter,0,6,1,4),
             (self.update,0,10,1,1),(self.archivecheck,0,11,1,2),
             )]
         self.searchbar.layout().addWidget(Qt.QLabel('Enter Device and Attribute filters using wildcards (e.g. li/ct/plc[0-9]+ / ^stat*$ & !status ) and push Update'),1,0,4,13)
         if SHOW_OPTIONS:
             self.options = Qt.QWidget() #self.searchbar
             self.options.setLayout(Qt.QGridLayout())
             separator = lambda x:Qt.QLabel(' '*x)
             row = 1
             [self.options.layout().addWidget(o,x,y,h,w) for o,x,y,h,w in (
                 #separator(120),Qt.QLabel("Options: "),separator(5),
                 (Qt.QLabel("Server: "),row,0,1,1),(self.ServerFilter,row,1,1,4),(Qt.QLabel(''),row,2,1,11)
                 )]
             #self.panel = generate_table(load_all_thermocouples('SR14')[-1])
             self.optiontab = Qt.QTabWidget()
             self.optiontab.addTab(self.searchbar,'Filters')
             self.optiontab.addTab(self.options,'Options')
             self.optiontab.setMaximumHeight(100)
             self.optiontab.setTabPosition(self.optiontab.North)
             self.layout().addWidget(self.optiontab)
         else: self.layout().addWidget(self.searchbar)
         
     self.toppan = Qt.QWidget(self)
     self.toppan.setLayout(Qt.QVBoxLayout())
     if True:
         self.header = QGridTable(self.toppan)
         self.header.setHorizontalHeaderLabels('Label/Value Device Attribute Alias Archiving'.split())
         self.header.setColumnWidth(0,350)
         self.toppan.layout().addWidget(self.header)
     
     if USE_SCROLL:
         print '*'*30 + ' USE_SCROLL=True '+'*'*30
         self._scroll = MyScrollArea(self.toppan)#Qt.QScrollArea(self)
         self._background = AttributesPanel(self._scroll) #At least a panel should be kept (never deleted) in background to not crash the worker!
         self.panel = None
         self._scroll.setChildrenPanel(self.panel)
         self._scroll.setWidget(self.panel)
         self._scroll.setMaximumHeight(700)
         self.toppan.layout().addWidget(self._scroll)
     else:
         self.panel = AttributesPanel(self.toppan)
         self.toppan.layout().addWidget(self.panel)
         
     self.toppan.layout().addWidget(Qt.QLabel('Drag any attribute from the first column into the trend or any taurus widget you want:'))
     
     if USE_TREND:
         self.split = Qt.QSplitter(Qt.Qt.Vertical)
         self.split.setHandleWidth(10)
         self.split.addWidget(self.toppan)
         
         from taurus.qt.qtgui.plot import TaurusTrend
         from PyTangoArchiving.widget.trend import ArchivingTrend,ArchivingTrendWidget
         self.trend = ArchivingTrendWidget() #TaurusArchivingTrend()
         self.trend.setUseArchiving(True)
         self.trend.showLegend(True)
         self.split.addWidget(self.trend)
         self.layout().addWidget(self.split)
     else:
         self.layout().addWidget(self.toppan)
     type(self)._persistent_ = self