def resetModes(self): self.logger().show() try: attr = self.getModel() schema = self.getSchema() print('%s: resetModes(%s)' % (fun.time2str(), attr)) qm = Qt.QMessageBox(Qt.QMessageBox.Warning, 'Confirmation', '%s archiving will be stopped' % attr, Qt.QMessageBox.Ok | Qt.QMessageBox.Cancel) r = qm.exec_() if r == Qt.QMessageBox.Ok: if not self.api: self.api = pta.api(self.getSchema().lower(), logger=self.logger()) self.api.log = self.logger() #self.emit(Qt.SIGNAL('archive'),attr,modes) Qt.QApplication.instance().setOverrideCursor( Qt.QCursor(Qt.Qt.WaitCursor)) thr = threading.Thread(target=self.startArchiving, args=(attr, {})) QLoggerDialog._threads = filter(Thread.is_alive, self.threads()) + [thr] thr.start() else: self.logger().hide() except: traceback.print_exc() print('%s: resetModes(...): running!' % (fun.time2str()))
def __init__(self, parent=None, domains=None, regexp='*pnv-*', USE_SCROLL=True, USE_TREND=False): print('%s: ArchivingBrowser()' % fun.time2str()) Qt.QWidget.__init__(self, parent) self.setupUi(USE_SCROLL=USE_SCROLL, USE_TREND=USE_TREND, SHOW_OPTIONS=False) self.load_all_devices() try: import PyTangoArchiving self.reader = PyTangoArchiving.Reader('*') self.archattrs = sorted(set(self.reader.get_attributes())) self.archdevs = list( set(a.rsplit('/', 1)[0] for a in self.archattrs)) except: traceback.print_exc() self.extras = [] #self.domains = domains if domains else ['MAX','ANY','LI/LT','BO/BT']+['SR%02d'%i for i in range(1,17)]+['FE%02d'%i for i in (1,2,4,9,11,13,22,24,29,34)] #self.combo.addItems((['Choose...']+self.domains) if len(self.domains)>1 else self.domains) self.connectSignals() print('%s: ArchivingBrowser(): done' % fun.time2str())
def startArchiving(self, attr, modes): try: print('%s: startArchiving(%s)' % (fun.time2str(), attr)) #self.api.load_attribute_modes([attr]) if modes: self.api.start_archiving(attr, modes) else: self.api.stop_archiving(attr) news = self.reader.get_attribute_modes(attr, force=True) self.emit(Qt.SIGNAL('update'), news, modes) except: self.logger().error(traceback.format_exc()) print('%s: startArchiving(%s): done!' % (fun.time2str(), attr))
def startArchiving(self,attr,modes): try: print('%s: startArchiving(%s)'%(fun.time2str(),attr)) #self.api.load_attribute_modes([attr]) if modes: self.api.start_archiving(attr,modes) else: self.api.stop_archiving(attr) news = self.reader.get_attribute_modes(attr,force=True) self.emit(Qt.SIGNAL('update'),news,modes) except: self.logger().error(traceback.format_exc()) print('%s: startArchiving(%s): done!'%(fun.time2str(),attr))
def get_next_month(date): if not fun.isString(date): date = time2str(date) year,month,day = map(int,date.split()[0].split('-')) if month<12: return '%04d-%02d-%02d' % (year,month+1,1) else: return '%04d-%02d-%02d' % (year+1,1,1)
def setModes(self, modes={}, expected={}): """ modes is a dictionary like {'MODE_P':[period]} """ print(type(self).__name__, 'setModes', self.getModel(), modes) if pta.utils.modes_to_string(expected) == pta.utils.modes_to_string( modes): self.logger().hide() for i, m in enumerate(('MODE_P', 'MODE_R', 'MODE_A')): for j in range(3): t = self.table.item(i, j) if not t: t = Qt.QTableWidgetItem('') self.table.setItem(i, j, t) if m in modes and j < len(modes[m]): t.setText(str(modes[m][j])) #print((i,j,modes[m][j])) else: t.setText('') if 'archiver' in modes: try: db = self.reader.get_database() attr_id = modes.get('ID') date = db.get_table_updates( db.get_table_name(attr_id)).values()[0] if date < time.time() - 600: date = '<b>%s</b>' % fun.time2str(date) else: date = fun.time2str(date) dev = modes['archiver'] self.archiver.setText('%s(%s,%s)' % (dev, attr_id, date)) self.archiver.setContextCallbacks({ 'Test Device': fun.partial(showTestDevice, device=dev), 'Show Info': fun.partial(showDeviceInfo, device=dev), 'Show Logs': self.logger().show, 'Refresh': fun.partial(self.setModel, model=self.getModel()), }) except: traceback.print_exc() else: self.archiver.setText('...') self.archiver.setContextCallbacks({}) Qt.QApplication.instance().restoreOverrideCursor() return
def applyModes(self): self.logger().show() #Qt.QApplication.instance().setOverrideCursor(Qt.QCursor(Qt.Qt.WaitCursor)) try: attr = self.getModel() v = F.check_attribute(attr, brief=True) if isinstance(v, (type(None), Exception)): Qt.QMessageBox.warning( self, "Warning", "%s is not readable nor archivable" % attr) self.logger().hide() return if fun.isSequence(v) or fun.isString(v): Qt.QMessageBox.warning(self, "Warning", "%s array type is not supported" % attr) self.logger().hide() return modes = self.getModes() or {'MODE_P': [60000]} schema = self.getSchema() print('%s: applyModes(%s)' % (fun.time2str(), modes)) msg = 'Modes to be applied:\n' for m, v in modes.items(): msg += '\t%s.%s: %s\n' % (schema, m, v) qm = Qt.QMessageBox(Qt.QMessageBox.Warning, 'Confirmation', msg, Qt.QMessageBox.Ok | Qt.QMessageBox.Cancel) r = qm.exec_() if r == Qt.QMessageBox.Ok: if not self.api: self.api = pta.api(self.getSchema().lower(), logger=self.logger()) self.api.log = self.logger() #self.emit(Qt.SIGNAL('archive'),attr,modes) Qt.QApplication.instance().setOverrideCursor( Qt.QCursor(Qt.Qt.WaitCursor)) thr = threading.Thread(target=self.startArchiving, args=(attr, modes)) QLoggerDialog._threads = filter(Thread.is_alive, self.threads()) + [thr] thr.start() else: self.logger().hide() except: self.logger().error(traceback.print_exc()) print('%s: applyModes(...): running!' % (fun.time2str()))
def always_executed_hook(self): msg = 'Attributes in cache:\n' for k,v in self.AttrData.items(): msg+='\t%s: %s\n'%(k,fn.time2str(v[0])) print(time.ctime()+"In "+ self.get_name()+ "::always_executed_hook()"+'\n'+msg) status = 'The device is in %s state\n\n'%self.get_state() status += msg self.set_status(status) self.GetCurrentQueries()
def always_executed_hook(self): msg = 'Attributes in cache:\n' for k, v in self.AttrData.items(): msg += '\t%s: %s\n' % (k, fn.time2str(v[0])) print(time.ctime() + "In " + self.get_name() + "::always_executed_hook()" + '\n' + msg) status = 'The device is in %s state\n\n' % self.get_state() status += msg self.set_status(status) self.GetCurrentQueries()
def setModes(self,modes={},expected={}): """ modes is a dictionary like {'MODE_P':[period]} """ print(type(self).__name__,'setModes',self.getModel(),modes) if modes_to_string(expected) == modes_to_string(modes): self.logger().hide() for i,m in enumerate(('MODE_P','MODE_R','MODE_A')): for j in range(3): t = self.table.item(i,j) if not t: t = Qt.QTableWidgetItem('') self.table.setItem(i,j,t) if m in modes and j<len(modes[m]): t.setText(str(modes[m][j])) #print((i,j,modes[m][j])) else: t.setText('') if 'archiver' in modes: try: db = self.reader.get_database() attr_id = modes.get('ID') date = db.get_table_updates(db.get_table_name(attr_id)).values()[0] if date<time.time()-600: date = '<b>%s</b>' % fun.time2str(date) else: date = fun.time2str(date) dev = modes['archiver'] self.archiver.setText('%s(%s,%s)'%(dev,attr_id,date)) self.archiver.setContextCallbacks({ 'Test Device':fun.partial(showTestDevice,device=dev), 'Show Info':fun.partial(showDeviceInfo,device=dev), 'Show Logs':self.logger().show, 'Refresh':fun.partial(self.setModel,model=self.getModel()), }) except: traceback.print_exc() else: self.archiver.setText('...') self.archiver.setContextCallbacks({}) Qt.QApplication.instance().restoreOverrideCursor() return
def resetModes(self): self.logger().show() try: attr = self.getModel() schema = self.getSchema() print('%s: resetModes(%s)'%(fun.time2str(),attr)) qm = Qt.QMessageBox(Qt.QMessageBox.Warning,'Confirmation', '%s archiving will be stopped'%attr, Qt.QMessageBox.Ok|Qt.QMessageBox.Cancel) r = qm.exec_() if r == Qt.QMessageBox.Ok: if not self.api: self.api = pta.api(self.getSchema().lower(),logger=self.logger()) self.api.log = self.logger() #self.emit(Qt.SIGNAL('archive'),attr,modes) Qt.QApplication.instance().setOverrideCursor(Qt.QCursor(Qt.Qt.WaitCursor)) thr = threading.Thread(target=self.startArchiving,args=(attr,{})) QLoggerDialog._threads = filter(Thread.is_alive,self.threads())+[thr] thr.start() else: self.logger().hide() except: traceback.print_exc() print('%s: resetModes(...): running!'%(fun.time2str()))
def applyModes(self): self.logger().show() #Qt.QApplication.instance().setOverrideCursor(Qt.QCursor(Qt.Qt.WaitCursor)) try: attr = self.getModel() v = F.check_attribute(attr,brief=True) if isinstance(v,(type(None),Exception)): Qt.QMessageBox.warning(self,"Warning","%s is not readable nor archivable"%attr) self.logger().hide() return if fun.isSequence(v) or fun.isString(v): Qt.QMessageBox.warning(self,"Warning","%s array type is not supported"%attr) self.logger().hide() return modes = self.getModes() or {'MODE_P':[60000]} schema = self.getSchema() print('%s: applyModes(%s)'%(fun.time2str(),modes)) msg = 'Modes to be applied:\n' for m,v in modes.items(): msg += '\t%s.%s: %s\n'%(schema,m,v) qm = Qt.QMessageBox(Qt.QMessageBox.Warning,'Confirmation',msg,Qt.QMessageBox.Ok|Qt.QMessageBox.Cancel) r = qm.exec_() if r == Qt.QMessageBox.Ok: if not self.api: self.api = pta.api(self.getSchema().lower(),logger=self.logger()) self.api.log = self.logger() #self.emit(Qt.SIGNAL('archive'),attr,modes) Qt.QApplication.instance().setOverrideCursor(Qt.QCursor(Qt.Qt.WaitCursor)) thr = threading.Thread(target=self.startArchiving,args=(attr,modes)) QLoggerDialog._threads = filter(Thread.is_alive,self.threads())+[thr] thr.start() else: self.logger().hide() except: self.logger().error(traceback.print_exc()) print('%s: applyModes(...): running!'%(fun.time2str()))
def trace(self, msg, level=0): if level <= self.loglevel: print '%s ModbusArray(%s): %s' % (fun.time2str(), self.name, msg)
if atformat is PyTango.SpectrumAttr: values = [conv(v[2] or 0.) for v in data] else: values = [map(conv,v[2]) for v in data] if values: print time.ctime()+'In read_dyn_attr(%s): %s[%d]:%s...%s'%(aname,type(values[0]),len(values),values[0],values[-1]) else: print '\tno values' attr.set_value(values,len(values)) elif aname.endswith('_t'): values = [float(v[0] or 0.) for v in data] if values: print time.ctime()+'In read_dyn_attr(%s): %s[%d]:%s...%s'%(aname,type(values[0]),len(values),values[0],values[-1]) else: print '\tno values' attr.set_value(values,len(values)) elif aname.endswith('_d'): values = [fn.time2str(float(v[0] or 0.)) for v in data] if values: print(time.ctime()+'In read_dyn_attr(%s): %s[%d]:%s...%s' %(aname,type(values[0]),len(values), values[0],values[-1])) else: print('\tno values') attr.set_value(values,len(values)) elif aname.endswith('_ld'): lv = [fn.time2str(float(v[0] or 0.)) for v in data[-1:]] if lv: print(time.ctime()+'In read_dyn_attr(%s): %s[%d]:%s...%s' %(aname,type(lv[0]),len(lv),lv[0],lv[-1])) else: print '\tno values' attr.set_value(lv[-1])
def dates2times(argin): """ Parsing dates like 'Y-M-D h:m' or '+/-X(shmdw)' """ return [fn.time2str(fn.str2time(a)) for a in argin]
class PyExtractor(PyTango.Device_4Impl): #--------- Add you global variables here -------------------------- @staticmethod def dates2times(argin): """ Parsing dates like 'Y-M-D h:m' or '+/-X(shmdw)' """ return [fn.time2str(fn.str2time(a)) for a in argin] @staticmethod def bool2float(argin): return float(not fn.isFalse(argin)) @staticmethod def tag2attr(argin): if any(argin.endswith(s) for s in ('_r', '_t', '_w', '_d')): argin = argin[:-2] if '/' not in argin: argin = argin.replace('__', '/') return argin @staticmethod def attr2tag(argin): if '/' in argin: argin = argin.replace('/', '__') return argin def read_dyn_attr(self, attr): #attr.set_value(1.0) aname, values = attr.get_name(), [] attribute = self.tag2attr(aname) print time.ctime() + 'In read_dyn_attr(%s)' % aname try: req, atformat, attype, data = self.AttrData[attribute] except Exception, e: print('Unable to read %s: key = %s ; cache = %s' % (attr, attribute, self.AttrData.keys())) traceback.print_exc() raise e conv = self.bool2float if attype is PyTango.DevBoolean \ else (float if attype is PyTango.DevDouble else str) if aname.endswith('_r'): if atformat is PyTango.SpectrumAttr: values = [conv(v[1] or 0.) for v in data] else: values = [map(conv, v[1]) for v in data] if values: print time.ctime() + 'In read_dyn_attr(%s): %s[%d]:%s...%s' % ( aname, type(values[0]), len(values), values[0], values[-1]) else: print '\tno values' attr.set_value(values, len(values)) elif aname.endswith('_w'): if atformat is PyTango.SpectrumAttr: values = [conv(v[2] or 0.) for v in data] else: values = [map(conv, v[2]) for v in data] if values: print time.ctime() + 'In read_dyn_attr(%s): %s[%d]:%s...%s' % ( aname, type(values[0]), len(values), values[0], values[-1]) else: print '\tno values' attr.set_value(values, len(values)) elif aname.endswith('_t'): values = [float(v[0] or 0.) for v in data] if values: print time.ctime() + 'In read_dyn_attr(%s): %s[%d]:%s...%s' % ( aname, type(values[0]), len(values), values[0], values[-1]) else: print '\tno values' attr.set_value(values, len(values)) elif aname.endswith('_d'): values = [fn.time2str(float(v[0] or 0.)) for v in data] if values: print time.ctime() + 'In read_dyn_attr(%s): %s[%d]:%s...%s' % ( aname, type(values[0]), len(values), values[0], values[-1]) else: print '\tno values' attr.set_value(values, len(values)) else: if atformat == PyTango.SpectrumAttr: if attype == PyTango.DevString: values = [(fn.time2str(d[0]), str(d[1])) for d in data] else: values = [(d[0], conv(d[1])) for d in data] else: if attype is PyTango.DevString: values = [[fn.time2str(d[0])] + map(str, d[1]) for d in data] else: values = [[d[0]] + map(conv, d[1]) for d in data] if values: print time.ctime() + 'In read_dyn_attr(%s): %s[%d]:%s...%s' % ( aname, type(values[0]), len(values), values[0], values[-1]) else: print '\tno values' attr.set_value(values, len(values)) print '\treturned %d values' % len(values)
def read_dyn_attr(self, attr): try: #attr.set_value(1.0) aname, values = attr.get_name(), [] attribute = self.tag2attr(aname) print time.ctime() + 'In read_dyn_attr(%s)' % aname print(self.counter) try: req, atformat, attype, data = self.AttrData[attribute] except Exception, e: print('Unable to read %s: key = %s ; cache = %s' % (attr, attribute, self.AttrData.keys())) traceback.print_exc() raise e conv = self.bool2float if attype is PyTango.DevBoolean \ else (float if attype is PyTango.DevDouble else str) if aname.endswith('_r'): if atformat is PyTango.SpectrumAttr: values = [conv(v[1] or 0.) for v in data] else: values = [map(conv, v[1]) for v in data] if values: print time.ctime( ) + 'In read_dyn_attr(%s): %s[%d]:%s...%s' % ( aname, type( values[0]), len(values), values[0], values[-1]) else: print '\tno values' attr.set_value(values, len(values)) elif aname.endswith('_l'): print('%s: %s' % (aname, data)) if data[-1:]: value = conv(data[-1][1]) date = float(data[-1][0] or 0.) q = ft.AttrQuality.ATTR_VALID else: value = None date = fn.now() q = ft.AttrQuality.ATTR_INVALID print( time.ctime() + 'In read_dyn_attr(%s): (%s,%s,%s)' % (aname, value, date, q)) attr.set_value_date_quality((value or 0.), date, q) elif aname.endswith('_w'): if atformat is PyTango.SpectrumAttr: values = [conv(v[2] or 0.) for v in data] else: values = [map(conv, v[2]) for v in data] if values: print time.ctime( ) + 'In read_dyn_attr(%s): %s[%d]:%s...%s' % ( aname, type( values[0]), len(values), values[0], values[-1]) else: print '\tno values' attr.set_value(values, len(values)) elif aname.endswith('_t'): values = [float(v[0] or 0.) for v in data] if values: print time.ctime( ) + 'In read_dyn_attr(%s): %s[%d]:%s...%s' % ( aname, type( values[0]), len(values), values[0], values[-1]) else: print '\tno values' attr.set_value(values, len(values)) elif aname.endswith('_d'): values = [fn.time2str(float(v[0] or 0.)) for v in data] if values: print time.ctime( ) + 'In read_dyn_attr(%s): %s[%d]:%s...%s' % ( aname, type( values[0]), len(values), values[0], values[-1]) else: print '\tno values' attr.set_value(values, len(values)) elif aname.endswith('_ld'): lv = [fn.time2str(float(v[0] or 0.)) for v in data[-1:]] if lv: print( time.ctime() + 'In read_dyn_attr(%s): %s[%d]:%s...%s' % (aname, type(lv[0]), len(lv), lv[0], lv[-1])) else: print '\tno values' attr.set_value(lv[-1]) else: if atformat == PyTango.SpectrumAttr: if attype == PyTango.DevString: values = [(fn.time2str(d[0]), str(d[1])) for d in data] else: values = [(d[0], conv(d[1])) for d in data] else: if attype is PyTango.DevString: values = [[fn.time2str(d[0])] + map(str, d[1]) for d in data] else: values = [[d[0]] + map(conv, d[1]) for d in data] if values: print time.ctime( ) + 'In read_dyn_attr(%s): %s[%d]:%s...%s' % ( aname, type( values[0]), len(values), values[0], values[-1]) else: print '\tno values' attr.set_value(values, len(values)) print '\treturned %d values' % len(values)
def trace(self, msg, level=0): if level <= self.loglevel: print '%s ModbusMap: %s' % (fun.time2str(), msg)
lambda s, l=10: ('{0:<%d}' % (l or 4)).format(s), #'time' : lambda s,l=25: ('{:^%d}'%l).format(s), 'device': lambda s, l=25: ('{0:^%d}' % (l or 4)).format(s), 'description': lambda s, l=50: ('{0:<}').format(s), 'message': lambda s, l=50: ('{0:<}').format(s), 'severity': lambda s, l=10: ('{0:^%d}' % (l or 4)).format(s), 'priority': lambda s, l=10: ('{0:^%d}' % (l or 4)).format(s), 'get_state': lambda s, l=10: ('{0:^%d}' % (l or 4)).format(s), 'get_time': lambda s, l=20: ('{0:^%d}' % (l or 4)).format(time2str(s, bt=0)), 'active': lambda s, l=20: (('{0:^%d}' % (l or 4)).format('FAILED!' if s is None else ('Not Active' if not s else (s if s in (1, True) else (time2str(s, bt=0)))))), 'formula': lambda s, l=100: ('{0:^%d}' % (l or 4)).format(s), #'tag' : lambda s,l: ('{:^%d}'%l).format(s), }) INFO_REQUESTS = ['SETTINGS', 'STATE', 'VALUES', 'SNAP'] #THIS ARE ALSO THE DIFFERENT ACTION TYPES TO BE CONFIGURED MESSAGE_TYPES = [ 'ALARM',