def __init__(self, views=None):

        if views is None:
            print('load views from database ...')
            views = ft.get_class_devices('PanicViewDS')
            views.append(ft.get_tango_host())

        print('ViewChooser(%s)' % views)
        self.view = ''
        self.views = fd.dicts.SortedDict()
        for v in views:
            if ':' in v:
                self.views[v] = v
            else:
                desc = ft.get_device(v).Description.split('\n')[0]
                self.views[desc] = v

        Qt.QDialog.__init__(self, None)
        #self.setModal(True)
        self.setWindowTitle('PANIC View Chooser')
        self.setLayout(Qt.QVBoxLayout())
        self.layout().addWidget(Qt.QLabel('Choose an AlarmView'))
        self.chooser = Qt.QComboBox()
        self.chooser.addItems(self.views.keys())
        self.layout().addWidget(self.chooser)
        self.button = Qt.QPushButton('Done')
        self.layout().addWidget(self.button)
        self.button.connect(self.button, Qt.SIGNAL('pressed()'), self.done)
        self.button.connect(self.button, Qt.SIGNAL('pressed()'), self.close)
    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)
    def showRawValues(self):

        try:
            self._dl = fn.qt.QDialogWidget(buttons=True)
            qc = Qt.QComboBox()
            qc.addItems(sorted(self.last_args.keys()))
            self._dl.setWidget(qc)
            #dates = []
            #try:
            #self.warning('-------------------')
            #dates.append(self.trend.axisScaleDiv(self.trend.xBottom).lowerBound())
            #dates.append(self.trend.axisScaleDiv(self.trend.xBottom).upperBound())
            #self.warning(dates)
            #except: self.warning(traceback.format_exc())
            self._dl.setAccept(lambda q=qc: show_history(
                parseTrendModel(str(q.currentText()))[1]))  #,dates=dates))
            self._dl.show()
        except:
            self.warning(traceback.format_exc())
    def __init__(self, trend, parent=None, layout=Qt.QVBoxLayout):
        print('DatesWidget(%s)' % trend)
        #parent = parent or trend.legend()
        Qt.QWidget.__init__(self, parent or trend)
        #trend.showLegend(True)
        self._trend = trend
        if not hasattr(trend, '_datesWidget'):
            trend._datesWidget = self

        self.setLayout(layout())
        self.DEFAULT_START = 'YYYY/MM/DD hh:mm:ss'
        self.setTitle("Show Archiving since ...")
        self.xLabelStart = Qt.QLabel('Start')
        self.xEditStart = Qt.QLineEdit(self.DEFAULT_START)
        self.xEditStart.setToolTip("""
            Start date, it can be: 
            <empty>              #apply -range to current date
            YYYY/MM/DD hh:mm:ss  #absolute
            -1d/h/m/s            #relative to current date
            """)
        self.xLabelRange = Qt.QLabel("Range")
        self.xRangeCB = Qt.QComboBox()
        self.xRangeCB.setEditable(True)
        self.xRangeCB.addItems(["", "1 m", "1 h", "1 d", "1 w", "30 d", "1 y"])
        self.xRangeCB.setToolTip("""
            Any range like:
            <empty> show data from Start 'til now
            1m : X minutes
            1h : X hours
            1d : X days
            1w : X weeks
            1y : X years
            """)
        self.xRangeCB.setCurrentIndex(1)
        self.xApply = Qt.QPushButton("Refresh")
        self.layout().addWidget(
            QWidgetWithLayout(self, child=[self.xLabelStart, self.xEditStart]))
        self.layout().addWidget(
            QWidgetWithLayout(self, child=[self.xLabelRange, self.xRangeCB]))
        self.layout().addWidget(QWidgetWithLayout(self, child=[self.xApply]))
        trend.connect(self.xApply, Qt.SIGNAL("clicked()"), self.refreshAction)

        if hasattr(self._trend, 'getArchivedTrendLogger'):
            self.logger = self._trend.getArchivedTrendLogger()
            self.xInfo = Qt.QPushButton("Expert")
            self.layout().addWidget(QWidgetWithLayout(self,
                                                      child=[self.xInfo]))
            trend.connect(self.xInfo, Qt.SIGNAL("clicked()"),
                          self.logger.show_dialog)

        #if parent is trend.legend():

        #trend.legend().setLayout(Qt.QVBoxLayout())
        #trend.legend().layout().setAlignment(Qt.Qt.AlignBottom)
        #self.setMinimumWidth(150)
        #self.setMinimumHeight(15*4)
        #trend.legend().layout().addWidget(self)
        #trend.legend().setMinimumWidth(150)
        #trend.setMinimumHeight(250)
        #try:
        #trend.legend().children()[0].setMinimumWidth(150)
        #trend.legend().children()[0].children()[0].setMinimumWidth(150)
        #except:
        #ms = Qt.QMessageBox.warning(trend,"Error!",traceback.format_exc())

        return
예제 #5
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)
 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