コード例 #1
0
ファイル: dbview.py プロジェクト: SergioLaime/txscada
 def contextMenuEvent(self, event):
     '''
     Cuando se hace click derecho sobre la fila.
     Establecer las acciones disponibles: Reparación y Notificación.
     '''
     row_num = self.rowAt(event.pos().y())
     self.selectRow( row_num )
     self._current_row = row_num
     
     query = PyQSqlQuery(self.model().query())
     query.seek(row_num)
     self.current_ev_id = query.ev_id
     
     
     # Eviar que se cuelgue ante una edicion
     # TODO: Fijarse en esto. Falta desahbilitar bien cuando no hay eventos.
     self.reset()
     if not self.current_ev_id: 
         self.actionAtender.setEnabled(False)
         self.actionReparar.setEnabled(False)
     
     if not self.model().index(row_num, self.model().index_ts_a ).data().toDate():
         self.actionAtender.setEnabled(True)
         self.actionReparar.setEnabled(False)
     elif not self.model().index(row_num, self.model().index_ts_r ).data().toDate():
         self.actionAtender.setEnabled(False)
         self.actionReparar.setEnabled(True)
     else:
         self.actionAtender.setEnabled(False)
         self.actionReparar.setEnabled(False)
     
     if self.menu.actions():
         self.menu.exec_(self.mapToGlobal(event.pos()))
コード例 #2
0
ファイル: dbview.py プロジェクト: SergioLaime/txscada
    def on_actionAddUC_triggered(self):
        '''
        Añadir una UC mediante un archivo SMF del configurador de Ricardo.|
        '''
        #self.model().insertRecord(-1, QSqlRecord())
        smfs = QFileDialog.getOpenFileNames(None, 'Seleccione lo(s) archivo(s) SMF',
                                                '', u'Archivo de configuración de semaforización (*.smf *.SMF)')
        ok, error = 0, 0
        if smfs:
            for smf in smfs:
                smf = str(smf) # QString -> str
                try:
                    smf_data = parse_smf(smf)
                    if not smf_data:
                        QMessageBox.warning(None, "No se pudo abrir %s" % smf, "Error: No se pudede abrir %s" % smf)
                        continue
                    nombre = os.path.splitext(os.path.split(smf)[1])[0]
                    query = PyQSqlQuery('''INSERT INTO UC (co_id, id_UC, zona, can_movi, nombre_uc, hab) VALUES
                                                          (%d, %d, %d, %d, '%s', %d)  ''' %
                                                            (smf_data['id_CO'], smf_data['id_UC'], smf_data['Zona'],
                                                             smf_data['CanMovi'], nombre, 1) #Iniciamos el concentrador en 1
                                                            )
                    if query.lastError().isValid():
                        QMessageBox.warning(None, "No se pudo abrir %s" % smf, "Error en inserción en la DB de %s" % nombre)
                        log.err(str(query.lastError().databaseText()))
                    else:
                        uc_id = query.lastInsertId().toInt()[0]
                        log.msg("id UC insertado %d." % uc_id)
                        # String -> Entero
#                        log.msg((smf_data['timovH'], smf_data['timovL']))
#                        timov_bytes = map(lambda i: int(i, 16), (smf_data['timovH'], smf_data['timovL']))
#                        
#                        [smf_data['timovH'], smf_data['timovL']]
                        #timov = timov_h << 8 + timov_l
                        timov = bitfield([smf_data['timovH'], smf_data['timovL']])
                        for n_mov in range(smf_data['CanMovi']):
                            query.exec_('''INSERT INTO Semaforo (uc_id, ti_mov, n_mov) 
                                                            VALUES  ( %d, %d, %d)''' %
                                                            (uc_id, timov[n_mov], n_mov)
                                            )
                            log.msg(str((uc_id, timov[n_mov], n_mov)))
                            if query.lastError().isValid():
                                log.err("Insertando semaforo ocurrio: %s" % str(query.lastError().databaseText()))
                            else:
                                sem_id = query.lastInsertId().toInt()[0]
                                log.msg("Insertado Semaforo: %d" % sem_id)
                        
                    ok += 1
                    
                except IOError:
                    QMessageBox.warning(None, "No se pudo abrir %s" % smf, "Error: No se pudede abrir %s" % smf)
                    error += 1
                
            self.refresh_table()
                    
        log.msg('SMF cargados %d, erroneos: %d' % (ok, error))
コード例 #3
0
ファイル: dbview.py プロジェクト: SergioLaime/txscada
 def on_actionRemoveUC_triggered(self):
     log.msg('Quitar UC fina %d' % self._current_row)
     resp = QMessageBox.question(self, self.trUtf8('Eliminar la UC?'),
                          self.trUtf8("Seguro que desea eliminar la UC?"),
                          QMessageBox.Yes | QMessageBox.No | QMessageBox.Cancel,
                          QMessageBox.Cancel)
     if resp == QMessageBox.Yes:
         uc_id = self.model().data(self.model().index(self._current_row,self.model().fieldIndex('id'))).toInt()[0]
         log.msg('Quitando UC de la DB id = %d' % uc_id)
         query = PyQSqlQuery()
         
         transaction = qApp.instance().db_con.transaction()
         log.msg('Inicio de la tranasccion? %s' % transaction)
         try:
             query_esquinas_uc = QSqlQuery('SELECT id FROM Esquina WHERE uc_id = %d'% uc_id)
             while query_esquinas_uc.next():
                 esquina_id = query_esquinas_uc.value(0).toInt()[0]
                 log.msg('Se van a borrar la Esquina_Calles')
                 query.exec_('DELETE FROM Esquina_Calles WHERE esquina_id = %d'% esquina_id)         
                 log.msg('El id de la esquina a borrar es = %d'%esquina_id)         
                 query.exec_('DELETE FROM Esquina WHERE Esquina.id = %d' % esquina_id)
                 log.msg("%s" % query.lastError().databaseText() or "OK")
             log.msg('Se van a borrar los semaforos')
             query.exec_('DELETE FROM Semaforo WHERE uc_id = %d'% uc_id)                             
             self.model().removeRow( self._current_row )
         
             if not query.lastError().type() == QSqlError.NoError:
                 if transaction:
                     qApp.instance().db_con.rollback()
                 log.err('Error en la DB: %s' % query.lastError().databaseText())
             else:
                 if transaction:
                     commit = qApp.instance().db_con.commit()
                     log.msg('Commit exitoso %s' % commit)
         except Exception, e:
             log.err(str(e))
             if transaction:
                 qApp.instance().db_con.rollback()
コード例 #4
0
ファイル: dbview.py プロジェクト: SergioLaime/txscada
 def on_actionAtender_triggered(self):
     if not self.current_ev_id:
         return
     
     r = QMessageBox.question(self, "Desea atender este evento?",
                          "Desea atender este evento?",
                          QMessageBox.Yes | QMessageBox.No | QMessageBox.Cancel)
     if r == QMessageBox.Yes:
         
         query = PyQSqlQuery()
         query.prepare("UPDATE EV SET EV.ts_a = ?, EV.atendido = 'o' WHERE id = %d" % self.current_ev_id )
         query.bindValue(0, QVariant(QDateTime.currentDateTime()))
         query.exec_()
         query.exec_('''SELECT co_id, id_UC from UC INNER JOIN EV 
                     ON EV.uc_id = UC.id WHERE EV.id = %d''' % self.current_ev_id )
         qApp.instance().emit(SIGNAL('event_attended(int, int)'), query.co_id, query.id_UC)
         log.msg('Atencion %s' % (query.lastError().databaseText() or "OK"))
         # Actualizar
         self.refresh_table()
コード例 #5
0
ファイル: print_dlg.py プロジェクト: SergioLaime/txscada
    def accept(self):
        ''' Generar la query en función del los parámetros '''
        where = ''
        # Filro por UC
        if self.comboBox_UC.isEnabled():
            where = 'EV.uc_id = %d' % self.comboBox_UC.get_col_value(1)
            
        # Filtro por tipo
        if self.comboBox_tipo.isEnabled():
            data = self.comboBox_tipo.itemData(self.comboBox_tipo.currentIndex())
            data = data.toInt()[0]
            if where:
                where = '%s AND EV.tipo = %s' % (where, data) 
            else:
                where = 'EV.tipo = %s' % (data, )
            
        fecha_desde = self.dateTimeEdit_desde.dateTime()
        fecha_hasta = self.dateTimeEdit_hasta.dateTime()
        where = where and '%s AND' % where
        
        query = PyQSqlQuery("""
            SELECT * FROM ((EV INNER JOIN UC ON EV.uc_id = UC.id)
            INNER JOIN CO ON UC.co_id = CO.id_CO) LEFT JOIN EV_Descripcion ON EV.tipo = EV_Descripcion.tipo 
                    AND EV.codigo = EV_Descripcion.codigo WHERE %s ts_bit >= '%s' AND ts_bit < '%s'
                    ORDER BY EV.ts_bit DESC, EV.ts_bit_ms DESC
                    """ %
                      (where, 
                       fecha_desde.toString(MYSQL_DATE_FORMAT_FOR_QSTRING), 
                       fecha_hasta.toString(MYSQL_DATE_FORMAT_FOR_QSTRING),
                       
                       )
            )
        
        query.exec_()
        
        if query.lastError().type() != QSqlError.NoError:
            log.msg('Error en la DB?: %s' %query.lastError().databaseText())
            QMessageBox.critical(self, "Error",
                                 '<p>Se ha producido un error «%s».</p>' % query.lastError().databaseText())
            return
        
        if not query.size():
            QMessageBox.information(self, "Sin resultados",
                                 '<p>La consulta no ha producido resultados.</p>')
            return
        d = Deferred()
        d.addCallback(render_template, template = self.template, 
                      query = query, 
                      fecha_desde = fecha_desde, 
                      fecha_hasta = fecha_hasta)
        d.addErrback(mostar_excepcion)
        d.callback(None)
        
#        try:
#            time1 = time()
#            f = open(self.template, 'r')
#            template = Template(f.read())
#            f.close()
#            time2 = time()
#            log.msg("Lectura de template:\t%f" % (time2 - time1))
#            salida_template = template.render(eventos = query,
#                                              fecha_desde = fecha_desde.toPyDateTime(),
#                                              fecha_hasta = fecha_hasta.toPyDateTime(),)
#            time3 = time()
#            log.msg("Renderizacion del template:\t%f" % (time3 - time2))
#            nombre_salida = mktemp('.pdf', 'reporte-')
#            salida_archivo = open(nombre_salida, 'w')
#            pdf = pisa.pisaDocument(salida_template.encode("UTF-8"), salida_archivo)
#            time4 = time()
#            log.msg("Generacion del documento:\t%f"%( time4 - time3))
#            if not pdf:
#                raise Exception('No se pudo generar el pdf')
#            salida_archivo.close()
#        except Exception, e:
#            import traceback
#            log.msg(traceback.format_exc())
#            QMessageBox.critical(self, u"Error",
#                                 u'<p>Se ha producido un error al generar el reporte «%s».</p>' % e)
#            log.err('Error %s' % e)
#            #raise
#        else:
#            log.msg('Trying to open report')
#            if sys.platform.count('linux'):
#                cmd = commands.getoutput('which xdg-open')
#                if cmd:
#                    os.spawnl(os.P_NOWAIT, cmd, cmd, nombre_salida)
#                else:
#                    log.err('No puedo abrir el archivo %s' % nombre_salida)
#            elif sys.platform.count('win32'):
#                cmd = os.path.join(os.environ['WINDIR'], 'system32', 'cmd.exe')
#                os.spawnl(os.P_NOWAIT, cmd, cmd, 'start', '/c', nombre_salida)
#                
        QDialog.accept(self)