Ejemplo n.º 1
0
class Mysocket(QtCore.QThread):
    '''
    classdocs
    '''
    def __init__(self, parent = None):
        QtCore.QThread.__init__(self)
        self.qtobj=QObject()
        self.mysql=ConMysql()
        self.mysql.setting('localhost', 'root', '443622796', 3306, 'utf8')
        self.mysql.open()
        self.mysql.start()
        
        self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        #self.s.bind(('192.168.1.107', 8899))
        self.s.bind(('192.168.0.199', 8899))
        #self.s.bind((socket.gethostbyname(socket.gethostname()), 8899))
        self.s.listen(5)
        
    def run(self):
        sprint.sprint('程序开始运行,等待连接...')
        while True:
            
            #print "current has %d threads" % (threading.activeCount())
            #for item in threading.enumerate():
            #    print item
            
            self.sock, self.addr =self.s.accept()   
            
            self.t =tcplink(self.sock,self.addr,self.mysql)
            
            self.t.start()
            self.qtobj.emit(SIGNAL("NewData"), self.t)
Ejemplo n.º 2
0
class Mysocket(QtCore.QThread):
    '''
    classdocs
    '''
    def __init__(self, parent=None):
        QtCore.QThread.__init__(self)
        self.qtobj = QObject()
        self.mysql = ConMysql()
        self.mysql.setting('localhost', 'root', '443622796', 3306, 'utf8')
        self.mysql.open()
        self.mysql.start()

        self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        #self.s.bind(('192.168.1.107', 8899))
        self.s.bind(('192.168.0.199', 8899))
        #self.s.bind((socket.gethostbyname(socket.gethostname()), 8899))
        self.s.listen(5)

    def run(self):
        sprint.sprint('程序开始运行,等待连接...')
        while True:

            #print "current has %d threads" % (threading.activeCount())
            #for item in threading.enumerate():
            #    print item

            self.sock, self.addr = self.s.accept()

            self.t = tcplink(self.sock, self.addr, self.mysql)

            self.t.start()
            self.qtobj.emit(SIGNAL("NewData"), self.t)
Ejemplo n.º 3
0
 def itemCollapsedOrExpanded(self, item):
     if item.isExpanded():
         item.expanded()
     else:  # collapsed
         item.collapsed()
     self.setVisibleRowCount()
     QObject.emit(self, SIGNAL("contentChanged(void)"))
Ejemplo n.º 4
0
    def _connect(self):
        try:
            if not self._connected:
                if not self._attempts < self.kMaxAttempts:
                    if not self._resetTimer.isActive():
                        Log.progress(Settings.getMeta("name") + ": Max connection attempts reached - waiting " + str(self.kResetTimer) + " seconds before retrying" )
                        self._resetTimer.start(self.kResetTimer*1000)  # 1 minute parameterise
                    return
                if self._attempts > 0 and (time.time() - pow(2,self._attempts +1)) < self._attemped:
                        return
                Log.debug("Trying to connect")
                self._attemped = time.time()
                result = self.mqttc.connect(str(self._host), int(self._port),int( self._keepAlive), 1)
                self._connected = result == mqtt.MQTT_ERR_SUCCESS # paho
#                self._connected = result == mqtt.MOSQ_ERR_SUCCESS # mosquitto
                if not self._connected:
                    self._attempts += 1
                    Log.progress(mqtt.connack_string(connResult))
                    QObject.emit(self, SIGNAL('mqttConnectionError'), self, mqtt.connack_string(connResult))
 
        except Exception as e:
            msg = 'MQTT: ' + str(e)

            QObject.emit(self, SIGNAL('mqttConnectionError'), self, msg)
            #Log.progress(msg)
            Log.debug(msg)
            #exc_type, exc_value, exc_traceback = sys.exc_info()
            #Log.debug(repr(traceback.format_exception(exc_type, exc_value,
             #                                         exc_traceback)))
            self._attempts += 1
            self._connected = False
Ejemplo n.º 5
0
    def runBtnSwitch(self):
        self.treeWidget.blockSignals(
            True
        )  #prevents time and other values from updating. Stops time re-add during successive runs.
        if self.runBtn.text() == "Run":
            self.resetTestStats()
            self.runBtn.setText("Stop")
            self.getTestsToRun()
            self.treeWidget.blockSignals(
                False
            )  #prevents time and other values from updating. Stops time re-add during successive runs.

            if not self.TestRunner.isRunning():
                self.TestRunner.start()
            QObject.emit(self.qt_object, SIGNAL("start"))

        elif self.runBtn.text() == "Stop":
            self.TestRunner.stop_test_run()
            self.stopTests = True
            self.testingStarted = False
            self.runBtn.setText("Kill")

        elif self.runBtn.text() == "Kill":
            self.TestRunner.terminate()
            self.TestRunner.wait()
            self.endTestRun()
Ejemplo n.º 6
0
    def resultPointValueListMethod(resultValueList, dataBaseProcedureData_0,
                                   point3d_0, procEntityListType_0, parent):
        if len(resultValueList) > 0:
            lat = None
            lon = None
            if define._units == QGis.Meters:
                point3d = QgisHelper.CrsTransformPoint(
                    float(resultValueList[1]), float(resultValueList[2]),
                    define._xyCrs, define._latLonCrs)

                lat = Degrees(point3d.get_Y(), None, None,
                              DegreesType.Latitude)
                lon = Degrees(point3d.get_X(), None, None,
                              DegreesType.Longitude)
            else:
                lat = Degrees(float(resultValueList[2]), None, None,
                              DegreesType.Latitude)
                lon = Degrees(float(resultValueList[1]), None, None,
                              DegreesType.Longitude)
            str0 = lon.method_1("dddmmss.ssssH")
            textString = lat.method_1("ddmmss.ssssH")
            procEntityBases = DlgAixmSelectPosition.smethod_1(
                dataBaseProcedureData_0, procEntityListType_0, point3d_0,
                textString, str0)
            dlgAixmSelectPosition = DlgAixmSelectPosition()
            naN = None
            degree = None
            result, naN, degree = Geo.smethod_2(point3d_0.get_X(),
                                                point3d_0.get_Y())
            if (result):
                dataBaseProcedureData_0.method_60(procEntityBases,
                                                  procEntityListType_0,
                                                  naN.ToString(),
                                                  degree.ToString())
            dlgAixmSelectPosition.lstItems.Sorted = True
            for procEntityBase in procEntityBases:
                dlgAixmSelectPosition.lstItems.Add(procEntityBase)
            if (procEntityListType_0 != ProcEntityListType.CentersEx
                    and procEntityListType_0 != ProcEntityListType.FixesEx):
                dlgAixmSelectPosition.btnNewPCP.setEnabled(False)
                dlgAixmSelectPosition.btnNewPCP.setVisible(False)
            resultDlg = dlgAixmSelectPosition.exec_()
            procEntityBase_0 = None
            if (resultDlg != 1):
                if dlgAixmSelectPosition.newTypeSelected == NewDbEntryType.DPN:
                    flag, procEntityBase_0 = DlgAixmNewDPN.smethod_0(
                        dataBaseProcedureData_0, naN, degree)
                elif dlgAixmSelectPosition.newTypeSelected == NewDbEntryType.PCP:
                    flag, procEntityBase_0 = DlgAixmNewPCP.smethod_0(
                        dataBaseProcedureData_0, naN, degree)
                else:
                    flag = False
            else:
                procEntityBase_0 = dlgAixmSelectPosition.lstItems.SelectedItem
                flag = True
            QObject.emit(parent,
                         SIGNAL("DlgAixmSelectPosition_Smethod_0_Event"), flag,
                         procEntityBase_0)
            return
Ejemplo n.º 7
0
 def doAction(self, text="", methodObj=None):
     #        print "doAction pre"
     if not methodObj:
         return
     try:
         methodObj()
     except Exception, e:
         QObject.emit(self, SIGNAL("exception(QString, PyQt_PyObject)"), text, e)
Ejemplo n.º 8
0
 def _connectError(self, client, msg):
     Log.debug(msg)
     QObject.emit(self, SIGNAL('mqttOnCompletion'), self, False, msg)
     if not self._callbackonerr is None:
         self._callbackonerr(self, False, msg)
     elif not self._callback is None:
         self._callback(self, False, msg)
     self.kill()
Ejemplo n.º 9
0
 def _connectError(self,client, msg):
     Log.debug(msg)
     QObject.emit(self, SIGNAL('mqttOnCompletion'), self, False, msg)
     if not self._callbackonerr is None:
         self._callbackonerr(self,False,msg)
     elif not self._callback is None:
         self._callback(self,False,msg)
     self.kill()
Ejemplo n.º 10
0
 def setNoise(self, aNoise):
     '''
     Must be between 0 and 1 included
     '''
     if  0 <=  aNoise <= 1:
         self._noise = aNoise
     else:
         raise ConnectionError("Noise must be between 0 and 1")
     QObject.emit(emitter(self), SIGNAL('noiseChanged'), self._noise)
Ejemplo n.º 11
0
 def append_data(self, mlist):
     """ Append data from a tuple in the model """
     try:
         if len(mlist[0])==3:
             self.items = self.items + mlist
             QObject.emit(self, \
                 SIGNAL("dataChanged(const QModelIndex&, const QModelIndex &)"), self.createIndex(0,0), self.createIndex(0,len(self.items))) # pylint: disable=C0301
     except StandardError:
         pass
Ejemplo n.º 12
0
 def append_data(self, mlist):
     """ Append data from a tuple in the model """
     try:
         if len(mlist[0]) == 3:
             self.items = self.items + mlist
             QObject.emit(self, \
                 SIGNAL("dataChanged(const QModelIndex&, const QModelIndex &)"), self.createIndex(0,0), self.createIndex(0,len(self.items))) # pylint: disable=C0301
     except StandardError:
         pass
Ejemplo n.º 13
0
 def onMessage(self, client, obj, msg):
     self._messages += 1
     if self._messages > 1:
         return # ignore subsequent
     self._timer.stop()
     client.disconnect()
     QObject.emit(self, SIGNAL('mqttOnCompletion'), self, True, msg.payload)
     if not self._callback is None:
         self._callback(self,True,msg)
Ejemplo n.º 14
0
   def __init__(self):
       "Initialize the HomeoUniselector instance"
 
       '''sets the defaults for the uniselector weights. 
       Can be (and usually is) overridden by subclasses'''
       
       self._lowerBound = 0
       self._upperBound = 1
       self._beeps = False
       QObject.emit(emitter(self), SIGNAL('uniselSoundChanged'), self._beeps)
Ejemplo n.º 15
0
 def onMessage(self, client, obj, msg):
     self._messages += 1
     if self._messages > 1:
         return  # ignore subsequent
     self._timer.stop()
     client.disconnect()
     QObject.emit(self, SIGNAL('mqttOnCompletion'), self, True, msg.payload)
     if not self._callback is None:
         self._callback(self, True, msg)
     self.kill()
Ejemplo n.º 16
0
 def dispatch_next_fuzz_item(self):
     if self.keep_fuzzing:
         fuzz_item = self.get_next_fuzz_item()
         if fuzz_item:
             QObject.emit(self.fuzz_callback, SIGNAL('fuzzItemAvailable(int, QByteArray, QUrl)'), fuzz_item[0], fuzz_item[1], fuzz_item[2])
         else:
             self.processed_urls = {}
             QObject.emit(self.fuzz_callback, SIGNAL('fuzzRunFinished()'))
     else:
         self.processed_urls = {}
Ejemplo n.º 17
0
    def dispatch_next_render_item(self):
###->        print('****7')
        if self.keep_spidering:
###->            print('****8')
            render_item = self.get_next_render_item()
            if render_item:
                self.renderer_available = False
                QObject.emit(self.spider_callback, SIGNAL('spiderItemAvailable(int, QString, QUrl, int)'), render_item[0], render_item[1], render_item[2], render_item[3])
            else:
                self.renderer_available = True
Ejemplo n.º 18
0
    def setAbsoluteWeight(self, aPositiveValue):
        'Utility function that changes the weight of a connection without changing its sign (i.e. the switch)'
        if aPositiveValue == 0:
            self._switch = 1
            self._weight = 0
        else:
            if 0 < aPositiveValue <= 1:
                self._weight= aPositiveValue
#            QObject.emit(emitter(self), SIGNAL('weightChanged'), self._weight)
        "signal back to unit's potentiometer in case of self-connections"
        if self.incomingUnit == self.outgoingUnit:
            QObject.emit(emitter(self.incomingUnit), SIGNAL('potentiometerChangedLineEdit'), str(round(self._weight, 4)))
Ejemplo n.º 19
0
 def dispatch_next_fuzz_item(self):
     if self.keep_fuzzing:
         fuzz_item = self.get_next_fuzz_item()
         if fuzz_item:
             QObject.emit(
                 self.fuzz_callback,
                 SIGNAL('fuzzItemAvailable(int, QByteArray, QUrl)'),
                 fuzz_item[0], fuzz_item[1], fuzz_item[2])
         else:
             self.processed_urls = {}
             QObject.emit(self.fuzz_callback, SIGNAL('fuzzRunFinished()'))
     else:
         self.processed_urls = {}
Ejemplo n.º 20
0
class GUILogWriter(object):
    """Provides writeable file-like interface to send text to GUI."""
    def __init__(self):
        self.emitter = QObject()
        self.softspace = 0

    def write(self, message):
        self.emitter.emit(SIGNAL("AppendToLog"), message)

    def flush(self):
        pass

    def close(self):
        pass
Ejemplo n.º 21
0
 def dispatch_next_render_item(self):
     ###->        print('****7')
     if self.keep_spidering:
         ###->            print('****8')
         render_item = self.get_next_render_item()
         if render_item:
             self.renderer_available = False
             QObject.emit(
                 self.spider_callback,
                 SIGNAL('spiderItemAvailable(int, QString, QUrl, int)'),
                 render_item[0], render_item[1], render_item[2],
                 render_item[3])
         else:
             self.renderer_available = True
Ejemplo n.º 22
0
class GUILogWriter(object):
    """Provides writeable file-like interface to send text to GUI."""
    
    def __init__(self):
        self.emitter = QObject()
        self.softspace = 0
        
    def write(self, message):
        self.emitter.emit(SIGNAL("AppendToLog"), message)
        
    def flush(self):
        pass
    
    def close(self):
        pass
Ejemplo n.º 23
0
    def runFor(self,ticks):
        '''Start the simulation by setting the units 'in motion' and run it 
           for a certain number of ticks. 
           This involves cycling through the units and asking them to update themselves, 
           then collecting data for each unit.
           First check that there are enough data to start'''

        sleepTime = self.slowingFactor

        if self.isReadyToGo():
            if self.time is None:
                self.time = 0
            "FOR TESTING"
            outputString = ("INITIAL DATA AT TIME: %u and tick: %u \n" % (self.time,  ticks))
            for unit in self.homeoUnits:
                outputString += ('Unit %s with output %.3f and critical deviation %.3f \n' %
                                 (unit.name,
                                 unit.currentOutput,
                                 unit.criticalDeviation))
            "END TESTING"
            
            while self.time < ticks:
                for unit in self.homeoUnits:
                    if self.collectsData:
                        self.dataCollector.atTimeIndexAddDataUnitForAUnit(self.time, unit)
                    unit.time =  self.time
                    # sys.stderr.write("the status of %s in the function is %s and in the ivar is %s \n" % (unit.name, unit.isActive(), unit._status))
#                     print "unit: %s of type %s about to update with value: %.3f" % (unit.name, type(unit), unit.criticalDeviation)
                    if unit.isActive():
                        unit.selfUpdate()
                self.time +=  1
                QObject.emit(emitter(self), SIGNAL('homeostatTimeChanged'), self.time)
                time.sleep(sleepTime / 1000)               # sleep accepts seconds, slowingFactor is in milliseconds
        else:
            sys.stderr.write('Warning: Homeostat is not ready to start')
            
        "FOR TESTING"
        outputString = 'FINAL DATA AT TIME: %u and tick %u \n' % (self.time, ticks)
        for unit in self.homeoUnits:
            outputString += ('Unit %s with output %.3f and deviation %.3f \n' %
                             (unit.name,
                             unit.currentOutput,
                             unit.criticalDeviation))
        "END TESTING"
Ejemplo n.º 24
0
class Uploader(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
        self.qobj = QObject()
        
        self.avrdude = const.avrdude
        self.avrdude_conf = const.avrconf
        self.mcu = 'atmega328p'
        self.speed = "115200"
        self.protocol = "arduino"
        self.comport = "COM3"
        self.flash_bin = ''
        
        self.__buildUploadCmd()
    
    def __buildUploadCmd(self):
        self.upload_cmd = "%s -C%s -v -p%s -c%s -P%s -b%s -D -Uflash:w:%s:i 2>%s" % (
                           self.avrdude,
                           self.avrdude_conf,
                           self.mcu,
                           self.protocol,
                           self.comport,
                           self.speed,
                           self.flash_bin,
                           const.arduloader_log)
    
    def resetUploadArgs(self, argsdict):
        assert type(argsdict) is dict
        
        self.mcu = argsdict["mcu"]
        self.speed = argsdict["speed"]
        self.protocol = argsdict["protocol"]
        self.comport = argsdict["comport"]
        self.flash_bin = argsdict["flash_bin"]
        
        self.__buildUploadCmd()
        
    def run(self):
        self.upload()
        
    def upload(self):
        ret, text = getstatusoutput(self.upload_cmd)
        self.qobj.emit(SIGNAL(const.finish_sig), ret, text)
        
Ejemplo n.º 25
0
class Thumbnailmaker(QRunnable):
    """
    Worker thread for creating thumbnails
    """
    def __init__(self, filename, width, height, parent=None):
        QRunnable.__init__(self)

        self.dontrun = False

        self.filename = filename
        self._w = width
        self._h = height

        # Need a QObject to emit signals from a QRunnable
        self.obj = QObject()

    def dontRun(self):
        self.dontrun = True

    def run(self):
        """
        Method run by the worker thread, responsible for downscaling
        one image to thumbnail size
        """

        if self.dontrun: # dont run the image resize if the image is not needed
            return

        # Use two way scaling of the image.
        # The result will be calculated faster than a one-way
        # SmoothTransformation but will be as nice.
        thumb = QtGui.QImage(self.filename)\
                .scaled(self._w * 4, self._h * 4,
                        Qt.KeepAspectRatio,
                        Qt.FastTransformation)\
                .scaled(self._w, self._h,
                        Qt.KeepAspectRatio,
                        Qt.SmoothTransformation)

        logging.info("creating thumbnail image for %s is done", self.filename)
        self.obj.emit(SIGNAL("imageDone"), thumb)
Ejemplo n.º 26
0
    def loop(self, timeout=0.1):

        if not self.isConnected():
            if not self._killing:
                self._connect()
            return
        try:
            connResult = self.mqttc.loop(timeout)
            if connResult == mqtt.MQTT_ERR_SUCCESS: # paho
#            if connResult == mqtt.MOSQ_ERR_SUCCESS: # mosquitto
                return
            
            self._connected = False
            self._attempts += 1
            
            Log.warn("MQTT: An error occurred while looping")
            QObject.emit(self, SIGNAL('mqttConnectionError'), self, mqtt.error_string(connResult))
        except ValueError as e:
            if e == 'Invalid timeout.':
                QObject.emit(self, SIGNAL('mqttOnTimeout'), self, "Connection Timeout")
            else:
                Log.debug("Paho Client ValueError" + str(e))
        except Exception as e:
            QObject.emit(self, SIGNAL('mqttConnectionError'), self, str(e))
            Log.debug("MQTT Connect: Unknown exception raised "  + str(e))
Ejemplo n.º 27
0
class FileDialogSignal(QWidget):
    ''' NO DOCUMENTATION '''
    def __init__(self, parent=None, typeName=None, param=None):
        ''' NO DOCUMENTATION '''
        QWidget.__init__(self, parent)
        self.o = QObject()
        self.param = param
        self.type = typeName

    def updateParam(self, param):
        ''' NO DOCUMENTATION '''
        self.param = param

    def updateType(self, typeName):
        ''' NO DOCUMENTATION '''
        self.type = typeName

    def relayButtonSignal(self):
        ''' NO DOCUMENTATION '''
        #print "relayButtonSignal"
        self.o.emit(SIGNAL("buttonPressed(PyQt_PyObject,PyQt_PyObject)"),
                    self.type, self.param)
Ejemplo n.º 28
0
class FileDialogSignal(QWidget):
    ''' NO DOCUMENTATION '''

    def __init__(self, parent=None, typeName=None, param=None):
        ''' NO DOCUMENTATION '''
        QWidget.__init__(self, parent)
        self.o = QObject()
        self.param = param
        self.type = typeName

    def updateParam(self,param):
        ''' NO DOCUMENTATION '''
        self.param = param

    def updateType(self,typeName):
        ''' NO DOCUMENTATION '''
        self.type = typeName

    def relayButtonSignal(self):
        ''' NO DOCUMENTATION '''
        #print "relayButtonSignal"
        self.o.emit(SIGNAL("buttonPressed(PyQt_PyObject,PyQt_PyObject)"),self.type,self.param)
Ejemplo n.º 29
0
class Uploader(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
        self.qobj = QObject()

        self.avrdude = const.avrdude
        self.avrdude_conf = const.avrconf
        self.mcu = 'atmega328p'
        self.speed = "115200"
        self.protocol = "arduino"
        self.comport = "COM3"
        self.flash_bin = ''

        self.__buildUploadCmd()

    def __buildUploadCmd(self):
        self.upload_cmd = "%s -C%s -v -p%s -c%s -P%s -b%s -D -Uflash:w:%s:i 2>%s" % (
            self.avrdude, self.avrdude_conf, self.mcu, self.protocol,
            self.comport, self.speed, self.flash_bin, const.arduloader_log)

    def resetUploadArgs(self, argsdict):
        assert type(argsdict) is dict

        self.mcu = argsdict["mcu"]
        self.speed = argsdict["speed"]
        self.protocol = argsdict["protocol"]
        self.comport = argsdict["comport"]
        self.flash_bin = argsdict["flash_bin"]

        self.__buildUploadCmd()

    def run(self):
        self.upload()

    def upload(self):
        ret, text = getstatusoutput(self.upload_cmd)
        self.qobj.emit(SIGNAL(const.finish_sig), ret, text)
Ejemplo n.º 30
0
 def newWeight(self, aWeight):
     "updates weight and switch on the basis -1 <=  aWeight <= 1"
     
     if aWeight == 0:
         self._switch = 1
         self._weight = 0
     else:
         if -1 <= aWeight <= 1:
             self._weight= abs(aWeight)
             self._switch = np.sign(aWeight)
         else:
             raise(ConnectionError, "A HomeoConnection weight must be between -1 and 1")
     QObject.emit(emitter(self), SIGNAL('weightChanged'), self._weight)
     QObject.emit(emitter(self), SIGNAL('switchChanged'), self._switch)
     
     "Signaling back to the incoming unit's potentiometer and switch in case of a self-connection"
     try:
         if self.incomingUnit == self.outgoingUnit:
             QObject.emit(emitter(self.incomingUnit), SIGNAL('potentiometerChangedLineEdit'), str(round(self._weight, 4)))
             QObject.emit(emitter(self.incomingUnit), SIGNAL('switchChangedLineEdit'), str(int(self._switch)))
     except AttributeError:
         pass
Ejemplo n.º 31
0
class TransFuze():
    """
    Convert input image to a fuze-suitable image
    """
    #Do something useful
    def __init__(self, GUI = None):
        self.size = [int(QSettings().value("imagew",QVariant(defaultsize[0])).toInt()[0]), int(QSettings().value("imageh",QVariant(defaultsize[1])).toInt()[0])]
        self.size = defaultsize
        self.GUI = GUI
        self.tab = GUI.Image
        if self.GUI != None:
            self.qobject = QObject()
            self.qobject.connect(self.qobject, SIGNAL("stop"),GUI.WAIT)
            self.qobject.connect(self.qobject, SIGNAL("working"),GUI.Status)
            self.qobject.connect(self.qobject, SIGNAL("Exception"),GUI.ErrorDiag)
            self.qobject.connect(self.qobject, SIGNAL("itemDone"),GUI.DelItem)
            self.qobject.connect(self.qobject, SIGNAL("finished"),GUI.getReady)

    def convert(self,args, FINALPREFIX =  None):
        """
        This method converts the passed files to jpg viewable in the fuze.
        """
        self.qobject.emit(SIGNAL("stop"),self.tab)
        for argument in args:
            try:
                self.qobject.emit(SIGNAL("working"),"Converting " + argument + "...")
                image = Image.open(argument)
                image.thumbnail(self.size, Image.ANTIALIAS)
                if FINALPREFIX == None:
                    image.save(os.path.splitext(argument)[0] + "_fuze.jpg")
                else:
                    image.save(os.path.join(FINALPREFIX,os.path.splitext(os.path.basename(argument))[0] + "_fuze.jpg"))
                self.qobject.emit(SIGNAL("itemDone"), argument, True)
            except Exception, e:
                print e
                self.qobject.emit(SIGNAL("Exception"),e)
        self.qobject.emit(SIGNAL("finished"),self.tab)
Ejemplo n.º 32
0
    def toggleSwitch(self, aNumber):
        "Change the polarity of the connection to aNumber"
#        self.newWeight(self.weight * -1)
#        QObject.emit(emitter(self), SIGNAL('switchChanged'), self._switch)
        acceptedValues = (-1,1)
        oldWeight = self.weight
        oldSwitch = self.switch     
        try:
            if int(aNumber) in acceptedValues:
                newWeight = abs(oldWeight) * int(aNumber)
                self.newWeight(newWeight)
                self._switch = int(aNumber)
#                sys.stderr.write("Unit %s's new weight is %f: with switch equal to %f. The value passed from the GUI was %f . \nThe old weight was %f and the old switch was %f, and the old unit's switch was %f\n" 
#                                 % (self.name, self.inputConnections[0].weight, self.switch, int(aNumber), oldWeight, oldSwitch, oldUnitSwitch))
            else: 
                raise  ConnectionError
        except ValueError:
            sys.stderr.write("Tried to assign a non-numeric value to the switch of the connection from %s to %s The value was: %s\n" % (self.outgoingUnit.name, self.incomingUnit.name, aNumber))
        finally:
            QObject.emit(emitter(self), SIGNAL('switchChanged'), self._switch)
            QObject.emit(emitter(self), SIGNAL('switchChangedLineEdit'), str(int(self._switch)))
            QObject.emit(emitter(self.incomingUnit), SIGNAL('switchChangedLineEdit'),str(int(self._switch))) 
Ejemplo n.º 33
0
        self.exec_()


class ActionHandler(QObject):
    """Executes an action on a certain device (methodObj)."""

    def doAction(self, text="", methodObj=None):
        #        print "doAction pre"
        if not methodObj:
            return
        try:
            methodObj()
        except Exception, e:
            QObject.emit(self, SIGNAL("exception(QString, PyQt_PyObject)"), text, e)
        finally:
            QObject.emit(self, SIGNAL("actionDone(void)"))

    def emitPwdSignal(self):
        resList = [""]
        QObject.emit(self, SIGNAL("passwordDialog(PyQt_PyObject)"), resList)
        return str(resList[0])


class MyTreeWidgetItem(QTreeWidgetItem):
    """An item (row) in the GUI device tree. Has an associated device and 
    keeps track of the existing and visible children of a node."""

    _dev = None  # one element list (&reference ?)
    _overallChildCount = None
    _visibleChildCount = None
Ejemplo n.º 34
0
 def show(self, f):
     QObject.emit(emitter(self), SIGNAL('test'), f)
Ejemplo n.º 35
0
class PlotConfig(object):
    """
    Plot config represents settings information relating to plot lines.
    All values are available as properties.
    """

    def __init__(self, name, linestyle="-", marker="", color=(0.0, 0.0, 0.0), alpha=0.75, zorder=1, picker=None, visible=True):
        self._name = name
        self._linestyle = linestyle
        self._marker = marker
        self._color = color
        self._alpha = alpha
        self._is_visible = visible
        self._z_order = zorder
        self._picker = picker

        self.signal_handler = QObject()

    def notify(self):
        """Tell all listeners that something has changed. Automatically called by setters."""
        self.signal_handler.emit(SIGNAL('plotConfigChanged(PlotConfig)'), self)

    def get_name(self):
        return self._name

    name = property(get_name, doc="The name of this plot.")

    def hasStyle(self):
        return not self.style == ""

    def get_style(self):
        return (str(self._marker) + str(self._linestyle)).strip()

    style = property(get_style, doc="Returns the combined style of line style and marker style.")

    def setLinestyle(self, linestyle):
        self._linestyle = linestyle
        self.notify()

    def getLinestyle(self):
        return self._linestyle

    linestyle = property(getLinestyle, setLinestyle, doc="Line style")

    def setMarker(self, marker):
        self._marker = marker
        self.notify()

    def getMarker(self):
        return self._marker

    marker = property(getMarker, setMarker, doc="Marker style")

    def setAlpha(self, alpha):
        self._alpha = alpha
        self.notify()

    def getAlpha(self):
        return self._alpha

    alpha = property(getAlpha, setAlpha, doc="Transparency of the line. 1 = Opaque ... 0 transparent.")

    def setColor(self, color):
        self._color = color
        self.notify()

    def getColor(self):
        return self._color

    color = property(getColor, setColor, doc="Color of the line.")


    def set_is_visible(self, is_visible):
        self._is_visible = is_visible
        self.notify()

    def is_visible(self):
        return self._is_visible

    is_visible = property(is_visible, set_is_visible, doc="Hide or show the plotline.")

    def set_z_order(self, z_order):
        self._z_order = z_order
        self.notify()

    def get_z_order(self):
        return self._z_order

    z_order = property(get_z_order, set_z_order, doc="Z drawing order. 10 = top ... 1 = bottom.")

    def setPicker(self, picker):
        self._picker = picker
        self.notify()

    def getPicker(self):
        return self._picker

    picker = property(getPicker, setPicker, doc="Picker radius")
Ejemplo n.º 36
0
class Fuze():
    """
    This class implements a convert() method used to convert video files for the fuze.
    """
    def __init__(self, GUI = None):
        self.pool = multiprocessing.Pool()
        self.GUI = GUI
        self.CWD = os.getcwd()
        self.qobject = QObject()
        if self.GUI:
            self.qobject.connect(self.qobject, SIGNAL("stop"),GUI.WAIT)
            self.qobject.connect(self.qobject, SIGNAL("working"),GUI.Status)
            self.qobject.connect(self.qobject, SIGNAL("Exception"),GUI.ErrorDiag)
            self.qobject.connect(self.qobject, SIGNAL("itemDone"),GUI.DelItem)
            self.qobject.connect(self.qobject, SIGNAL("finished"),GUI.getReady)
        self.LoadSettings()
        self.xterm = None

        if os.name != 'posix' or not self.GUI:
            global xterm
            xterm = None

    def LoadSettings(self):
        """
        Loads video4fuze's settings for this instance
        """
        global mencoderpass1
        global mencoderpass2
        global mencodersinglepass
        global pass2
        self.Settings = QSettings(QSettings.IniFormat, QSettings.UserScope, info.ORGNAME, info.NAME)
        mencoderpass1 = unicode(self.Settings.value("mencoderpass1", QVariant(mencoderpass1)).toString())
        mencoderpass2 = unicode(self.Settings.value("mencoderpass2", QVariant(mencoderpass2)).toString())
        mencodersinglepass = unicode(self.Settings.value("mencodersinglepass",QVariant(mencodersinglepass)).toString())
        pass2 = self.Settings.value("2pass",QVariant(pass2)).toBool()
        print "Current settings:"
        print
        if pass2:
            print "Two-pass conversion;"
            print "Pass 1: ",  mencoderpass1
            print "Pass 2: ",  mencoderpass2
        else:
            print "Single-pass conversion;"
            print "Options used: ",  mencodersinglepass

    def convert(self,args, dest =  None):
        """
        This method converts any video file passed as argument to a file suitable for the sansa fuze.
        """
        vdict['FINALPREFIX'] = dest
        if self.GUI:
            self.qobject.emit(SIGNAL("stop"),self.GUI.Video)
            self.qobject.emit(SIGNAL("working"),"Converting files...")
        os.chdir(vdict['fuzemuxPrefix'])

        argslist = []
        for arg in args:
            if os.path.isfile(arg):
                argslist.append((arg, vdict))
            elif os.path.isdir(arg):
                if not os.path.isdir(arg + '/VIDEO_TS') and not os.path.isdir(arg + '/BDMV/STREAM'):
                    glob_file =  arg + '/*.??*'
                    for file in glob.glob(glob_file):
                        argslist.append((file, vdict))
                else:
                    argslist.append((arg, vdict))
            else:
                print arg,': file not found'
        #print [a[0] for a in argslist]

        for file, error in self.pool.map(_convert_process, argslist):
            if error:
                self.qobject.emit(SIGNAL("Exception"),unicode(error))
                print file, 'could not be converted succesfully'
            if self.GUI:
                self.qobject.emit(SIGNAL("itemDone"),file)
        os.chdir(self.CWD)
        if self.GUI:
            self.qobject.emit(SIGNAL("finished"),self.GUI.Video)
            print "Finished!"
Ejemplo n.º 37
0
 def __emitStatus(self, status):
     QObject.emit(self, SIGNAL('qidianStatus'), status)
Ejemplo n.º 38
0
class QRunner(QRunnable):

    """
    Only QRunnable objects can be used with the QThreadPool
    therefore we need to do the whole song and dance with
    creating QRunnables, connecting signals and other such nonsense.
    """

    def __init__(self, ifname, ofname, cls):

        """
        This class does the work of moving the files to the executable to
        process the pdf pages.

        This class should not be called directly as it is a QRunnable object
        therefore we need a QThreadPool object to start/stop and monitor
        progress.

        The worker is QWorker and will create these instances for us.
        """

        # Init parent object
        QRunnable.__init__(self)

        # create an instance of a QObject so we can emit signals
        self.q_object = QObject()

        # take the inputs
        self.ofname = ofname
        self.ifname = ifname
        self.res = cls.resolution
        self.mode = cls.mode

        # gs exe
        self.gscriptpath = '"' +  os.getcwd() + r'\gs\gs9.02\bin'

    def run(self):

        """
        Tasks to put in separate thread.
        """

        self.process_file()
        self.q_object.emit(SIGNAL("finished()"))


    def process_file(self):

        """
        Converts PDF pages to tif files,

        Uses ghostscript from the command line
        """

        process = QProcess()

        process.start(' '.join([
                           self.gscriptpath + '\gswin32c.exe"',   #gs exe
                           '-q',
                           '-dNOPAUSE',
                           '-dBATCH',
                           # resolution/dpi
                           '-r{0}x{0}'.format(self.res),
                           # container type, see gs docs
                           '-sDEVICE={0}'.format(self.mode),
                           '-sPAPERSIZE=a4',   # page size
                           '-sOutputFile=%s %s' % (str(self.ofname),
                                                   str(self.ifname))]))
                           # don't spawn cmd window

        process.waitForFinished(-1)
Ejemplo n.º 39
0
 def toggleBeeping(self):
     self._beeps = not self._beeps 
     QObject.emit(emitter(self), SIGNAL('unitUniselSoundChanged'), self._beeps)
Ejemplo n.º 40
0
 def acceptDlg(self):
     self.legs.refresh()
     QObject.emit(self, SIGNAL("DlgAixmProcLegs_Smethod_0_Event"),
                  self.legs, self.data)
     self.accept()
Ejemplo n.º 41
0
 def triggerAction(self, checked=False):
     if self.methodObj:
         QObject.emit(self, SIGNAL("triggered(QString, PyQt_PyObject)"), self.text(), self.methodObj)
Ejemplo n.º 42
0
 def __emitVoteOk(self, userName, bookName, recVoteNum, advVoteNum):
     QObject.emit(self, SIGNAL('qidianVoteOk'), userName, bookName, recVoteNum, advVoteNum)
Ejemplo n.º 43
0
 def emitPwdSignal(self):
     resList = [""]
     QObject.emit(self, SIGNAL("passwordDialog(PyQt_PyObject)"), resList)
     return str(resList[0])
Ejemplo n.º 44
0
class nexusDoor(taurus.core.tango.sardana.macroserver.BaseDoor):

    ## constructor
    # \param name door name
    # \param kw dictionary with other arguments
    def __init__(self, name, **kw):
        print "nexusDoor.__init__()", name
        self.call__init__(taurus.core.tango.sardana.macroserver.BaseDoor, name,
                          **kw)

        ## Nexus scan directory
        self.scandir = ""
        ## Nexus file name
        self.filename = ""
        ## serial number
        self.serialno = 0

        ## start position
        self.start = 0
        ## stop position
        self.stop = 100
        ## number of points
        self.np = 100

        ## device aliases
        self.deviceAliases = {}
        ## cut device aliases
        self.cutDeviceAliases = {}
        ## dictionary with names to replace
        self.toReplace = {}
        ## configuration server
        self.cnfServer = None
        ## Nexus writer
        self.nexusWriter = None

        ## writing status
        self.writing = False

        ## signal emitter
        if PYQT:
            self.emitter = QObject()
        else:
            self.emitter = None

        ##  component selection mode
        self.__ccmode = 'SARDANA_MODE'

        env = self.getEnvironment()
        if not env.has_key('NexusWriterDevice'):
            ## Nexus writer device name
            self.device = 'haso228k.desy.de:10000/p09/tdw/r228'
            self.setEnvironment('NexusWriterDevice', self.device)
        else:
            ## Nexus writer device name
            self.device = self.getEnvironment('NexusWriterDevice')

        if not env.has_key('ScanFinished'):
            self.setEnvironment('ScanFinished', 'True')

        env = self.getEnvironment()

        if not env.has_key('ConfigurationServerDevice'):
            ## configuration server device name
            self.cnfdevice = 'haso228k.desy.de:10000/p09/mcs/r228'
            self.setEnvironment('ConfigurationServerDevice', self.cnfdevice)
        else:
            ## configuration server device name
            self.cnfdevice = self.getEnvironment('ConfigurationServerDevice')

    ## provides a device alias
    # \param name device name
    # \return device alias
    def get_alias(self, name):
        # if name does not contain a "/" it's probably an alias
        if name.find("/") == -1:
            return name

        # haso107klx:10000/expchan/hasysis3820ctrl/1
        if name.find(':') >= 0:
            lst = name.split("/")
            name = "/".join(lst[1:])
        return db.get_alias(name)

    ## creates a file name from dataRecord variables
    # \param dataRecord Sardana data record
    def prepareFileName(self, dataRecord):

        if type(dataRecord[1]['data']['scanfile']).__name__ == 'list':
            scanfile = dataRecord[1]['data']['scanfile'][0]
        else:
            scanfile = dataRecord[1]['data']['scanfile']
        self.scandir = dataRecord[1]['data']['scandir']
        self.serialno = dataRecord[1]['data']['serialno']
        self.filename = "%s_%05d.%s" % (scanfile.rpartition('.')[0],
                                        self.serialno, "h5")
#        startTime = dataRecord[1]['data']['starttime']
#        title = dataRecord[1]['data']['title']

## finds scan limits
# \param dataRecord Sardana data record

    def findScanLimits(self, dataRecord):

        # get the scan limits from the title
        cmd = dataRecord[1]['data']['title'].split()
        self.start, self.stop, self.np = 0, 100, 100

        # ascan exp_dmy01 0 1 10 0.2
        if cmd[0] == 'ascan':
            self.start = float(cmd[2])
            self.stop = float(cmd[3])
            self.np = int(cmd[4])

        # a2scan exp_dmy01 0 1 exp_dmy02 2 3 10 0.2
        elif cmd[0] == 'a2scan':
            self.start = float(cmd[2])
            self.stop = float(cmd[3])
            self.np = int(cmd[7])

        # a3scan exp_dmy01 0 1 exp_dmy02 2 3 exp_dmy03 3 4 10 0.2
        elif cmd[0] == 'a3scan':
            self.start = float(cmd[2])
            self.stop = float(cmd[3])
            self.np = int(cmd[10])
        else:
            raise Exception(
                "nexusDoor.findScanLimits",
                "cmd not recognized %s" % (dataRecord[1]['data']['title']))
        return

    ## creates Nexus configuration
    # \param dataRecord Sardana data record
    # \returns Nexus configuration string
    def createNexusConfiguration(self, dataRecord):
        self.deviceAliases = {}
        self.toReplace = {}

        env = self.getEnvironment()
        if env.has_key('SelectionMode'):
            self.__ccmode = self.getEnvironment('SelectionMode')

        for elm in dataRecord[1]['data']['counters']:
            alias = self.get_alias(str(elm))
            self.deviceAliases[alias] = elm
        for elm in dataRecord[1]['data']['column_desc']:
            if "name" in elm.keys():
                alias = self.get_alias(str(elm["name"]))
                self.deviceAliases[alias] = elm["name"]

        self.cutDeviceAliases = {}
        for alias in self.deviceAliases.keys():
            if alias.startswith("sca_exp_mca"):
                self.cutDeviceAliases[alias] = "_".join(alias.split("_")[:3])
                self.toReplace[alias] = "_".join(alias.split("_")[:3])
            else:
                self.cutDeviceAliases[alias] = alias

        dsFound = {}
        cpReq = {}
        self.cnfServer = PyTango.DeviceProxy(self.cnfdevice)
        if not self.cnfServer or not hasattr(self.cnfServer, "State"):
            raise Exception, "Configuration server not accessible"

        if PYQT:
            self.emitter.emit(SIGNAL("updateCServer(QString)"),
                              QString(self.cnfdevice))

            #         self.cnfServer.State() == PyTango.DevState.RUNNING:
            #            self.cnfServer.Init()
        self.cnfServer.Open()

        if self.__ccmode == 'SARDANA_MODE':
            cmps = self.cnfServer.AvailableComponents()
            for cp in cmps:
                dss = self.cnfServer.ComponentDataSources(cp)
                for ds in dss:
                    if ds in self.cutDeviceAliases.values():

                        print ds, "found in ", cp
                        if ds not in dsFound.keys():
                            dsFound[ds] = []
                        dsFound[ds].append(cp)
                        if cp not in cpReq.keys():
                            cpReq[cp] = []
                        cpReq[cp].append(ds)

            for ds in self.cutDeviceAliases.values():
                if ds not in dsFound.keys():
                    print "Warning:", ds, "not found!"

        mandatory = self.cnfServer.MandatoryComponents()
        print "Default Components", mandatory
        print "Sardana Components", cpReq.keys()
        if not mandatory and not cpReq.keys():
            raise Exception, "None of the components selected"
        self.cnfServer.CreateConfiguration(cpReq.keys())
        cnfxml = self.cnfServer.XMLString
        return cnfxml

    ## inits Nexus Writer
    # \param xml Nexus configuration string
    def initNexusWriter(self, xml):

        self.nexusWriter = PyTango.DeviceProxy(self.device)
        if not self.nexusWriter or not hasattr(self.nexusWriter, 'State'):
            raise Exception, "Tango Data Server not accessible"

        if PYQT:
            self.emitter.emit(SIGNAL("updateNWriter(QString)"),
                              QString(self.device))

        self.nexusWriter.Init()
        print " Connected to: ", self.device

        fname = "%s/%s" % (self.scandir, self.filename)
        print "FILE:", fname
        self.nexusWriter.FileName = fname.encode()

        if PYQT:
            self.emitter.emit(SIGNAL("updateFile(QString)"), QString(fname))

        print "opening the H5 file"
        self.nexusWriter.OpenFile()

        amsterdam = timezone('Europe/Amsterdam')
        fmt = '%Y-%m-%dT%H:%M:%S.%f%z'
        starttime = amsterdam.localize(datetime.now())

        theString = '{"data": {'\
            +' "sample_name":"test sample 1",'\
            +' "start_time":"'+  str(starttime.strftime(fmt)) + '"' \
            +'}  }'
        #                +' "start_time":"2012-11-14T14:05:23.2344-0200"' \

        self.nexusWriter.XMLSettings = xml

        self.nexusWriter.JSONRecord = theString
        print "opening the entry"
        self.nexusWriter.OpenEntry()

    ## prepares a new scan and performs the INIT mode writing
    # \param dataRecord Sardana data record
    def prepareNewScan(self, dataRecord):

        self.indexScan = 0
        self.prepareFileName(dataRecord)
        self.findScanLimits(dataRecord)
        if PYQT:
            self.emitter.emit(SIGNAL("updateNP(int,int)"), self.indexScan,
                              self.np + 1)

        try:
            xml = self.createNexusConfiguration(dataRecord)
        except:
            self.writing = False
            print sys.exc_info()[0]
            raise
        try:
            self.initNexusWriter(xml)
        except:
            self.writing = False
            print sys.exc_info()[0]
            #            raise Exception,"Configuration cannot be performed. Abort writing"
            raise

    ## performs the FINAL mode writing and closes the Nexus file
    # \param dataRecord Sardana data record
    def closeScan(self, dataRecord):
        # close the H5 file
        # optional JSON attribute

        amsterdam = timezone('Europe/Amsterdam')
        fmt = '%Y-%m-%dT%H:%M:%S.%f%z'
        endtime = amsterdam.localize(datetime.now())


        theString = '{"data": {'\
            +' "end_time":"'+  str(endtime.strftime(fmt)) + '"' \
            +'}  }'

        self.nexusWriter.JSONRecord = theString
        print "closing the entry"
        self.nexusWriter.CloseEntry()
        print "closing the H5 file"
        self.nexusWriter.CloseFile()

    ## replaces alias but cut aliases according to self.toReplaces
    # \param text with aliases
    # \returns text with cut aliases
    def replaceAliases(self, text):
        res = text
        if self.toReplace:
            for el in self.toReplace.keys():
                res = res.replace(el, self.toReplace[el])
        return res

    ## records Data
    # \param s door s parameter
    # \param t door t parameter
    # \param v door v parameter
    # \returns dataRecord on STEP mode
    def recordDataReceived(self, s, t, v):
        try:
            dataRecord = taurus.core.tango.sardana.macroserver.BaseDoor.recordDataReceived(
                self, s, t, v)
        except:
            self.writing = False
            raise Exception, "Problems in fetching dataRecord"

        if dataRecord == None:
            return
        print ">>> recordDataReceived "
        pp.pprint(dataRecord)

        # new scan

        if "type" in dataRecord[1] and dataRecord[1]['type'] == "data_desc":
            finished = False if self.getEnvironment(
                'ScanFinished').upper() == "FALSE" else True

            if not finished:
                self.closeScan(dataRecord)
            self.setEnvironment('ScanFinished', 'False')
            self.writing = True
            print "Writing NeXus: INIT"
            self.prepareNewScan(dataRecord)
            return dataRecord

        # end of the scan2
        if "type" in dataRecord[1] and dataRecord[1]['type'] == "record_end":
            if self.writing:
                print "Writing NeXus: FINAL"
                self.closeScan(dataRecord)
                env = self.getEnvironment()
                self.setEnvironment('ScanFinished', 'True')

            return dataRecord

        # record step
        if "type" in dataRecord[1] and dataRecord[1]['type'] == "record_data":
            if self.writing:
                jsonString = self.replaceAliases(json.dumps(dataRecord[1]))
                print "Writing NeXus: STEP"
                self.nexusWriter.record(jsonString)

                self.indexScan += 1
                if PYQT:
                    self.emitter.emit(SIGNAL("updateNP(int,int)"),
                                      self.indexScan, self.np + 1)

            return dataRecord

        return dataRecord
Ejemplo n.º 45
0
 def emit( self, record ):
     QObject.emit( self, SIGNAL("log(QString,int)"), "%s: %s" % (record.name, record.getMessage()), 5000 )