示例#1
0
def start_q_watcher(app, emu_window, proc_comms_q_to_em, proc_comms_q_from_em):
    # need to spawn a worker thread that watches the proc_comms_q
    # need to seperate queue function from queue thread
    # http://stackoverflow.com/questions/4323678/threading-and-signals-problem
    # -in-pyqt
    q_watcher = QueueWatcher(app, emu_window, proc_comms_q_to_em,
                             proc_comms_q_from_em)
    q_watcher_thread = QThread()
    q_watcher.moveToThread(q_watcher_thread)
    q_watcher_thread.started.connect(q_watcher.check_queue)

    # now that we've set up the thread, let's set up rest of signals/slots
    q_watcher.set_out_enable.connect(emu_window.set_output_enable)
    q_watcher.set_out_disable.connect(emu_window.set_output_disable)
    q_watcher.get_in.connect(emu_window.get_input)
    q_watcher.get_out.connect(emu_window.get_output)

    emu_window.send_output.connect(q_watcher.send_get_out_pin_result)
    emu_window.send_input.connect(q_watcher.send_get_in_pin_result)
    emu_window.interrupt_flagger.connect(q_watcher.handle_interrupt)

    # not sure why this doesn't work by connecting to q_watcher_thread.quit
    def about_to_quit():
        q_watcher_thread.quit()

    app.aboutToQuit.connect(about_to_quit)

    q_watcher_thread.start()
示例#2
0
    def _refresh(self):
        'Refresh the list of Computers'
        self._btnRefresh.setEnabled(False)
        self._btnRefresh.setText('Scanning...')
        self._model.clear()
        
        typ = self.wizard().field('type')
        if typ == len(ComputerTypes):
            # Custom Computer Type
            didx = self.wizard().field('driver')
            drvr = list_drivers().keys()[didx]
            dopt = self.wizard().field('driveropt')
        else:
            # Predefined Computer Type
            drvr = ComputerTypes[typ]['driver']
            dopt = ComputerTypes[typ]['driveropt']
        
        dclass = list_drivers()[drvr]['class']
        doptions = [] if dopt == '' else dopt.split(':')
        
        thread = QThread(self)
        
        #FIXME: ZOMG HAX: Garbage Collector will eat DiscoveryWorker when moveToThread is called
        #NOTE: Qt.QueuedConnection is important...
        self.worker = None
        self.worker = DiscoveryWorker(dclass, doptions)
        self.worker.moveToThread(thread)
        thread.started.connect(self.worker.start, Qt.QueuedConnection)
        self.worker.foundDevice.connect(self._model.addItem, Qt.QueuedConnection)
        self.worker.finished.connect(self._discoverFinished, Qt.QueuedConnection)
        self.worker.finished.connect(self.worker.deleteLater, Qt.QueuedConnection)
        self.worker.finished.connect(thread.deleteLater, Qt.QueuedConnection)

        thread.start()
示例#3
0
 def __init__(self, patches, db, parent=None):
     QThread.__init__(self, parent)
     
     self.logger = logging.getLogger(__name__)
     self.process = None
     self.patches = patches
     self.parentDb = db
示例#4
0
    def __init__(self,
                 instruments,
                 name=None,
                 settings=None,
                 log_output=None,
                 timeout=1000000000):

        self._recording = False
        self._timeout = timeout

        Script.__init__(self,
                        name,
                        settings,
                        instruments,
                        log_output=log_output)
        QThread.__init__(self)

        self.sweeper = self.instruments['zihf2'].daq.sweep(self._timeout)
        self.sweeper.set('sweep/device', self.instruments['zihf2'].device)

        self.data = deque()

        # todo: clean this up! and plot data in gui!
        self._sweep_values = {
            'frequency': [],
            'x': [],
            'y': [],
            'phase': [],
            'r': []
        }.keys()
示例#5
0
    def __init__(self, quitNetclient, name="NetClient"):

        # Call the thread's constructor
        QThread.__init__(self)

        # Initialize the net client. Variables to keep track of glance counts
        self.On = True
        # self.glance = []
        # self.frame = []
        self.oneCount = 0
        self.zeroCount = 0
        self.maxOnes = 0
        self.lowCount = 0
        self.warnCount = 0
        self.dangerCount = 0
        self.resetCount = 0
        # self.duration = []
        # self.listOfDict = []

        # Not sure if this is going to work. This might not even be used...
        self.usage = __doc__
        self.parser = optparse.OptionParser(self.usage)
        self.options, self.args = self.parser.parse_args()

        quitNetclient.connect(self.exitAll, Qt.QueuedConnection)
    def testQThreadReceiversExtern(self):
        #QThread.receivers() - Inherited protected method

        obj = QThread()
        self.assertEqual(obj.receivers(SIGNAL('destroyed()')), 0)
        QObject.connect(obj, SIGNAL("destroyed()"), self.cb)
        self.assertEqual(obj.receivers(SIGNAL("destroyed()")), 1)
示例#7
0
 def __init__(self, inp=None, dur=None, thr_counter=0):
     QThread.__init__(self)
     self.inp = inp
     self.dur = dur
     self.outp = None
     self.abo = None
     self.thr_counter = thr_counter
    def __init__(self):
        QThread.__init__(self)

        Bin.exporter = JupiterExporter()
        BinPacking.bin_packing_progress = self

        self.directory = None
        self.images = []

        self.method = BinPackingThread.METHODS[0]
        self.bin_size = BinPackingThread.SIZES[0]

        self.bin_parameter = {
            "next_fit_shelf": {},
            "first_fit_shelf": {
                "selection_variant": FirstFitShelfBin.BEST_VARIANTS,
                "selection_heuristic": FirstFitShelfBin.SHORT_SIDE_FIT,
            },
            "guillotine": {
                "selection_variant": GuillotineBin.BEST_VARIANTS,
                "selection_heuristic": GuillotineBin.SHORT_SIDE_FIT,
                "split_rule": Rect.RULE_SAS,
            },
            "max_rects": {},
        }
示例#9
0
    def __init__(self):
        QThread.__init__(self)
        self.camera = CameraFixe()

        self.imageCount = 1
        self.nombreDImage = 3
        self.nombreDeForme = 4

        self.localisationIles = LocalisationIle()
        self.localisationRobot = LocalisationRobot()
        self.localisationRepere = LocalisationRepere()
        self.localisationTresor = LocalisationTresor()
        self.afficheurImage = AfficheurImage()

        self.couleurCarreTrouvee = ""
        self.xPositionCarreTrouvee = 0
        self.yPositionCarreTrouvee = 0

        self.couleurTriangleTrouvee = ""
        self.xPositionTriangleTrouvee = 0
        self.yPositionTriangleTrouvee = 0

        self.couleurCercleTrouvee = ""
        self.xPositionCercleTrouvee = 0
        self.yPositionCercleTrouvee = 0

        self.couleurPentagoneTrouvee = ""
        self.xPositionPentagoneTrouvee = 0
        self.yPositionPentagoneTrouvee = 0

        self.xPositionRobotTrouvee = 0
        self.yPositionRobotTrouvee = 0

        self.carreIndex = 0
        self.triangleIndex = 0
        self.cercleIndex = 0
        self.pentagoneIndex = 0

        self.detectionIlesTimeout = 10
        self.ratioMaximum = 0.14

        self.listeFormesThread = []
        self.listeCouleursThread = []
        self.listePositionsThread = []
        self.positionRobotThread = []

        self.conteurDetectionIles = 0
        self.conteurDetectionTresor = 0
        self.conteurDetectionRepere = 0

        self.time = None
        self.timeImage = time.time()
        self.estVerouillee = False

        self.sauvegardePath = "C:\Users\phili_000\Desktop\Design 3\Design3\Code\Projet\photos\\table_iles_robot_MOD.jpg"

        self.photo = None

        self.reset = False
        self.startCycle = False
示例#10
0
 def reset (self):
     self.serial.setDTR (False)
     self.serial.setRTS (False)
     QThread.msleep (250)
     self.serial.setDTR (True)
     self.serial.setRTS (True)
     QThread.msleep (50)
示例#11
0
 def __init__(self):
     QThread.__init__(self)
     self.code = ""
     self.carte = Carte()
     self.planification = Cheminement(self.carte)
     self.voltageRestant = ""
     self.ileCible = -1
     self.positionTresor = []
     self.destination = []
     self.pause = True
     self.reset = False
     self.startCycle = False
     self.demiCercle = 180
     self.tempAttenteRotation = 9
     self.delaiAjustement = 4.5
     self.metreSeconde = 15
     self.metre = 100
     self.actionPrecedente = ""
     self.actionCourrante = ""
     self.nouvelleAction = False
     self.finCycle = False
     self.connected = False
     self.noPathFound = False
     self.aIle = False
     self.diametreIle = 2.125
     self.deltaPosition = 15
     self.deltaAngle = 4
     self.deltaDiametreIle = 0.125
示例#12
0
    def __init__(
        self,
        account,
        call,
        #dbus_handler,
        ):
        """
        account: An account.

        call is one of

          'HomeTimeline': Fetch the home time line
          'Mentions': Fetch user mentions
          'DMs': Fetch direct messages
          'Search:*': Fetch search results where * is the terms to search for
          'RetrieveLists': Retrive lists
          'List:*:*': The first * should be replace with the user and
                      the second with the id
          'Near:*:*': Fetch tweets near (1km) a the specified
                      location.  The first start is the the first
                      geocode and the second * is the second geocode.
        """
        QThread.__init__(self)
        self.account = account
        self.call = call
        #self.dbus_handler = dbus_handler
        socket.setdefaulttimeout(60)
示例#13
0
    def __init__(self, patches, db, parent=None):
        QThread.__init__(self, parent)

        self.logger = logging.getLogger(__name__)
        self.process = None
        self.patches = patches
        self.parentDb = db
示例#14
0
    def __init__(self):
        QThread.__init__(self)
        
        self.running = True
        self.queue = queue.Queue()

        # If we have internet connetction we can receive dat from server
        self.data_from_server = True

        # Offsets period
        self.p_offsets = config['p_offsets']
        # Offsets stack size
        self.n_samples = config['o_buffer']
        # Offsets list
        self.offsets = None

        # Socket
        self.sock_con = None

        # Graph density. Send to pipeline every n-th sample
        self.density = calculateDensity(config['time_axe_range']) # self.calculateDensity(2) 

        # Data server
        if self.data_from_server:
            self.host = config['host']
            # self.host = 'localhost'
            self.port = config['port']
示例#15
0
 def _btnTransferClicked(self):
     'Transfer Dives'
     idx = self._cbxComputer.currentIndex()
     dc = self._cbxComputer.itemData(idx, Qt.UserRole+0)
     
     if self._logbook.session.dirty:
         print "Flushing dirty session"
         self._logbook.rollback()
     
     self._txtLogbook.setEnabled(False)
     self._btnBrowse.setEnabled(False)
     self._cbxComputer.setEnabled(False)
     self._btnAddComputer.setEnabled(False)
     self._btnRemoveComputer.setEnabled(False)
     self._btnTransfer.setEnabled(False)
     self._btnExit.setEnabled(False)
     
     self._txtStatus.clear()
     
     thread = QThread(self)
     
     #FIXME: ZOMG HAX: Garbage Collector will eat TransferWorker when moveToThread is called
     #NOTE: Qt.QueuedConnection is important...
     self.worker = None
     self.worker = TransferWorker(dc)
     thread.started.connect(self.worker.start, Qt.QueuedConnection)
     self.worker.moveToThread(thread)
     self.worker.finished.connect(self._transferFinished, Qt.QueuedConnection)
     self.worker.finished.connect(self.worker.deleteLater, Qt.QueuedConnection)
     self.worker.finished.connect(thread.deleteLater, Qt.QueuedConnection)
     self.worker.progress.connect(self._transferProgress, Qt.QueuedConnection)
     self.worker.started.connect(self._transferStart, Qt.QueuedConnection)
     self.worker.status.connect(self._transferStatus, Qt.QueuedConnection)
     
     thread.start()
示例#16
0
    def __init__(self,
                 scripts,
                 name=None,
                 settings=None,
                 log_output=None,
                 timeout=1000000000):
        self._recording = False
        self._timeout = timeout

        Script.__init__(self,
                        name,
                        settings,
                        scripts=scripts,
                        log_output=log_output)
        QThread.__init__(self)

        self.data = deque()

        # todo: clean this up! and plot data in gui!
        self._sweep_values = {
            'frequency': [],
            'x': [],
            'y': [],
            'phase': [],
            'r': []
        }.keys()
示例#17
0
    def onLogin(self, host, username, passwd, ssl):
        """
        Slot. Triggers a log in request to the server.
        
        :param host: Indicates the hostname of the FTP server
        :param username: Username to log in into the FTP server
        :param passwd: Password to log in into the FTP server
        :param ssl: Indicates whether the FTP needs SSL support
        """

        self.sync = Sync(host, ssl)
        self.syncStarted.connect(self.sync.initQueue)
        self.sync.server.downloadProgress.connect(self.onDownloadProgress)
        self.sync.server.uploadProgress.connect(self.onUploadProgress)
        self.sync.server.fileEvent.connect(self.onFileEvent)
        self.sync.server.badFilenameFound.connect(self.badNameWarning)
        self.sync.server.loginCompleted.connect(self.onLoginCompleted)
        self.sync.server.fileEventCompleted.connect(self.onFileEventCompleted)
        self.sync.server.ioError.connect(self.onIOError)
        # Added by Si
        self.sync.server.textStatus.connect(self.setStatus)

        self.sync.statusChanged.connect(self.setStatus)
        self.loginRequested.connect(self.sync.server.onLogin)

        self.syncThread = QThread()
        self.sync.moveToThread(self.syncThread)
        self.syncThread.start()

        QApplication.instance().lastWindowClosed.connect(self.syncThread.quit)
        self.loginRequested.emit(username, passwd)
    def testQThreadReceiversExtern(self):
        #QThread.receivers() - Inherited protected method

        obj = QThread()
        self.assertEqual(obj.receivers(SIGNAL('destroyed()')), 0)
        QObject.connect(obj, SIGNAL("destroyed()"), self.cb)
        self.assertEqual(obj.receivers(SIGNAL("destroyed()")), 1)
def start_q_watcher(app, emu_window, proc_comms_q_to_em, proc_comms_q_from_em):
    # need to spawn a worker thread that watches the proc_comms_q
    # need to seperate queue function from queue thread
    # http://stackoverflow.com/questions/4323678/threading-and-signals-problem
    # -in-pyqt
    q_watcher = QueueWatcher(
        app, emu_window, proc_comms_q_to_em, proc_comms_q_from_em)
    q_watcher_thread = QThread()
    q_watcher.moveToThread(q_watcher_thread)
    q_watcher_thread.started.connect(q_watcher.check_queue)

    # now that we've set up the thread, let's set up rest of signals/slots
    q_watcher.set_out_enable.connect(emu_window.set_output_enable)
    q_watcher.set_out_disable.connect(emu_window.set_output_disable)
    q_watcher.get_in.connect(emu_window.get_input)
    q_watcher.get_out.connect(emu_window.get_output)

    emu_window.send_output.connect(q_watcher.send_get_out_pin_result)
    emu_window.send_input.connect(q_watcher.send_get_in_pin_result)
    emu_window.interrupt_flagger.connect(q_watcher.handle_interrupt)

    # not sure why this doesn't work by connecting to q_watcher_thread.quit
    def about_to_quit():
        q_watcher_thread.quit()
    app.aboutToQuit.connect(about_to_quit)

    q_watcher_thread.start()
    def __init__(self, instruments, name = None, settings = None, log_output = None):

        self._recording = False

        Script.__init__(self, name, settings, instruments, log_output = log_output)
        QThread.__init__(self)

        self.data = deque()
 def __init__(self):
     QThread.__init__(self)
     self.grblWriter = None
     self.gcode = None
     self.stopFlag = False
     self.pauseFlag = False
     self.currentLine = 0
     self.waitForPause = False
示例#22
0
文件: gui.py 项目: mrf345/chrome-cut
 def __init__(self, todo=None, dur=None, ip=None, vidl=None):
     QThread.__init__(self)
     self.todo = todo
     self.dur = dur
     self.ip = ip
     self.vidl = vidl
     self.outp = None
     self.abo = None
示例#23
0
 def __init__(self, maximum, parent=None):
     QThread.__init__(self, parent)
     self.maximum = maximum
     # this semaphore is used to stop the thread from outside.  As long
     # as the thread is permitted to run, it has yet a single resource
     # available.  If the thread is stopped, this resource is acquired,
     # and the thread breaks its counting loop at the next iteration.
     self._run_semaphore = QSemaphore(1)
示例#24
0
 def __init__(self, user, parent=None):
     QThread.__init__(self, parent)
     self.exiting = False
     self.refreshed = MySignal()
     self.dumpuser = MySignal()
     self.newcourses = CoursesSignal()
     self.removable = CoursesSignal()
     self.user = user
 def __init__(self, maximum, parent=None):
     QThread.__init__(self, parent)
     self.maximum = maximum
     # this semaphore is used to stop the thread from outside.  As long
     # as the thread is permitted to run, it has yet a single resource
     # available.  If the thread is stopped, this resource is acquired,
     # and the thread breaks its counting loop at the next iteration.
     self._run_semaphore = QSemaphore(1)
示例#26
0
 def __init__(self, *params):
     QThread.__init__(self)        
     self.parms = params
     self.ret_code = None
     self.output = StringIO()
     self.procs = []
     self.procs_str = ''
     Logger.getLoggerFor(self.__class__)
示例#27
0
 def __init__(self, network, logLevel=None, **kwargs):
     assert (isinstance(network, Network))
     self._network = network
     self.sim_start = self.sim_end = None
     self.stepsLeft = 0
     self.logger = logging.getLogger('pymote.simulation')
     self.logger.level = logLevel or logging.DEBUG
     QThread.__init__(self)
示例#28
0
    def __init__(self, port):
        QThread.__init__(self)

        self._port = port
        self._serial = None
        self._parser = Parser()
        self._cancel = False
        self._timeout = None
示例#29
0
    def __init__(self):

        QThread.__init__(self)

        self.__service = RunDefService()

        self.__pid = None
        self.__id = None
示例#30
0
 def __init__(self, monitorable, args=(), kwargs=None):
     QThread.__init__(self)
     self._monitorable = monitorable
     self._args = args
     if kwargs is None:
         kwargs = {}
     self._kwargs = kwargs
     self._is_cancelled = False
 def __init__(self):
     QThread.__init__(self)
     self.grblWriter = None
     self.gcode = None
     self.stopFlag = False
     self.pauseFlag = False
     self.currentLine = 0
     self.waitForPause = False
     self.errorStatus = False
示例#32
0
    def __init__(self, script):
        """
        This is a wrapper for scripts that are not QThread, to execute them on a different thread than the gui
        Args:
            script: script to be executed

        """
        self.script = script
        QThread.__init__(self)
示例#33
0
 def __init__(self, network, logLevel=None, **kwargs):
     assert(isinstance(network, Network))
     self._network = network
     self.stepsLeft = 0
     self.logger = logging.getLogger('pymote.simulation')
     self.logger.level = logLevel or logging.DEBUG
     self.logger.debug('Simulation %s created successfully.' %
                       (hex(id(self))))
     QThread.__init__(self)
示例#34
0
 def __init__(self, network, logLevel=None, **kwargs):
     assert (isinstance(network, Network))
     self._network = network
     self.stepsLeft = 0
     self.logger = logging.getLogger('pymote.simulation')
     self.logger.level = logLevel or logging.DEBUG
     self.logger.debug('Simulation %s created successfully.' %
                       (hex(id(self))))
     QThread.__init__(self)
 def __init__(self, instruments, scripts, name = None, settings = None,  log_output = None):
     """
     Example of a script that emits a QT signal for the gui
     Args:
         name (optional): name of script, if empty same as class name
         settings (optional): settings for this script, if empty same as default settings
     """
     Script.__init__(self, name, settings = settings,scripts =scripts, instruments = instruments, log_output = log_output)
     QThread.__init__(self)
示例#36
0
    def Record(self):

        if self.action_Record.isChecked():

            if not self.acquiring:
                self.workerThread = QThread(self)
                self.workerThread.start()

                self.worker = Worker(self)
                self.worker.moveToThread(self.workerThread)

                try:
                    self.start_rec.disconnect()
                except:
                    pass

                while 1:
                    try:
                        self.sock.send('StartAcquisition')
                        self.sock.recv()
                    except:
                        continue
                    break

                while 1:
                    try:
                        self.sock.send('StartRecord')
                        self.sock.recv()
                    except:
                        continue
                    break

                self.vidbuffer = []
                self.start_rec.connect(self.worker.acquire)
                self.recording = True
                self.start_rec.emit('start!')

            else:

                while 1:
                    try:
                        self.sock.send('StartRecord')
                        self.sock.recv()
                    except:
                        continue
                    break

                self.vidbuffer = []
                self.recording = True

            record_icon = self.style().standardIcon(QStyle.SP_DialogNoButton)
            #set the icon for the action
            self.action_Record.setIcon(record_icon)
            self.action_Record.setEnabled(False)

            self.action_Acq.setChecked(False)
            self.action_Acq.setEnabled(True)
 def __init__(self, name, readTimeout=1000, dev = None, parent=None):
   Keithley.__init__(self,dev)
   QThread.__init__(self)
   self.name = name
   self.readTimeout = readTimeout
   self.connectInstrument()
   self.selectCurrent()
   self.zeroCorrect()
   self.sr = SignalReceiver(self)
   self.sr.moveToThread(self)
示例#38
0
 def __init__(self, url):
     QThread.__init__(self)
     self.url = url
     self.new_version = None
     self.frozenapp = esky.Esky(sys.executable, self.url)
     try:
         log.Debug('Checking for new version at {0}'.format(self.url))
         self.new_version = self.frozenapp.find_update()
     except Exception, e:
         log.Error(str(e))
示例#39
0
 def __init__(self, url):
     QThread.__init__(self)
     self.url = url
     self.new_version = None 
     self.frozenapp = esky.Esky(sys.executable, self.url)
     try:
         log.Debug('Checking for new version at {0}'.format(self.url))
         self.new_version = self.frozenapp.find_update()
     except Exception, e:
         log.Error(str(e))
示例#40
0
 def __init__(self, name=None, settings=None, log_output=None):
     """
     Example of a script that emits a QT signal for the gui
     Args:
         name (optional): name of script, if empty same as class name
         settings (optional): settings for this script, if empty same as default settings
     """
     Script.__init__(self, name, settings, log_output=log_output)
     # QtCore.QThread.__init__(self)
     QThread.__init__(self)
示例#41
0
 def __init__(self, app, *args, **kwargs):
     QThread.__init__(self, *args, **kwargs)
     self.app = app
     self.status = STATUS_NONE
     self.last_sync = datetime.now()
     self.timer = QTimer()
     self.timer.timeout.connect(self.sync)
     self.update_timer()
     self.wait_condition = QWaitCondition()
     self.mutex = QMutex()
示例#42
0
    def __init__(self, cmd, img):
        """Initialize executor.

        Args:
            cmd -- command to execute (str)
            img -- path to resulting image (the renderer output) (str)
        """
        super().__init__(QCoreApplication.instance())
        self.thread = QThread()
        self.worker = Worker(cmd, img)
        self.thread.setObjectName("fcd-renderexec")
示例#43
0
 def __init__(self, path=None, db=[], key=None):
     QThread.__init__(self)
     self.path = path
     self.session = db[2]
     self.File = db[3]
     self.Folder = db[4]
     self.key = key
     self.estmf = self.session.query(self.Folder).count()
     self.estm = self.session.query(self.File).count()
     self.abo = None
     self.err = None
示例#44
0
    def __init__(self, netclient, parID_Signal, name="Receiver"):
        # Call the thread's constructor
        QThread.__init__(self)

        # Set the thread's data
        self.name = name

        # Initialize the variables
        self.netFileData = []
        self.recFileData = []
        self.receiverData = {
            "FRAME": '0',
            "GAZE": '0',
            "OneCount": '0',
            "ZeroCount": '0',
            "MaxCount": '0',
            "WarnCount": '0',
            "DangerCount": '0',
            "RstCount": '0',
            "GlanceCount": '0',
            "LowCount": '0'
        }
        self.frameValue = 0
        self.logStream = 0
        self.laneDepart = 0.0
        self.laneDeviation = 0.0

        self.distance = 0.0
        self.bumperTime = 0.0
        self.bumperDist = 0.0
        self.collisionTime = 0.0
        self.leadVehVel = 0.0

        self.numCollision = 0
        self.chassisAccel = 0.0

        self.participantID = 'Default'

        # Connecting to the netclient signal
        netclient.receiverDataSignal.connect(self.setReceiverVars,
                                             Qt.QueuedConnection)
        parID_Signal.connect(self.setReceiverParID, Qt.QueuedConnection)

        try:
            # Create a new socket, use IPv4 and UDP
            # Then bind the socket to localhost and the port
            self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            self.socket.bind(('', 1224))

        except socket.error as err:
            # Could not create the socket, bind it, or listen on the port.
            # Print the error message
            print "Could not create the socket:", err
            self.socket = None
示例#45
0
 def __init__(self):
     QThread.__init__(self)
     self.code = ""
     self.carte = Carte()
     self.planification = Cheminement(self.carte)
     self.voltageRestant = 0
     self.ileCible = -1
     self.positionTresor = []
     self.destination = []
     self.pause = True
     self.reset = False
示例#46
0
 def __init__(self, parameters=None):
     QThread.__init__(self)
     
     self.interrupt_flag = False
     self.pause_flag = False
     self.pause_time = 10
     
     if parameters is None:
         self.parameters = None
     else:
         self.set_parameters(parameters)
示例#47
0
 def __init__(self, *args, **kwargs):
     QThread.__init__(self, *args, **kwargs)
     self.app = AppClass.instance()
     self.status = STATUS_NONE
     self.last_sync = datetime.now()
     self.update_count = 0
     self.timer = QTimer()
     self.timer.timeout.connect(self.sync)
     self.update_timer()
     self.wait_condition = QWaitCondition()
     self.mutex = QMutex()
示例#48
0
文件: thread.py 项目: sgallet/pychron
    def __init__(self, name=None, target=None, args=None, kwargs=None):
        self._target = target
        if args is None:
            args = tuple()
        if kwargs is None:
            kwargs = dict()

        self._args = args
        self._kwargs = kwargs
        QThread.__init__(self)
        self.setObjectName(name)
示例#49
0
    def __init__(self, name=None, target=None, args=None, kwargs=None):
        self._target = target
        if args is None:
            args = tuple()
        if kwargs is None:
            kwargs = dict()

        self._args = args
        self._kwargs = kwargs
        QThread.__init__(self)
        self.setObjectName(name)
示例#50
0
    def __init__(self, scripts, name = None, settings = None, log_output = None, timeout = 1000000000):
        self._recording = False
        self._timeout = timeout

        Script.__init__(self, name, settings, scripts = scripts, log_output = log_output)
        QThread.__init__(self)

        self.data = deque()

        # todo: clean this up! and plot data in gui!
        self._sweep_values =  {'frequency' : [], 'x' : [], 'y' : [], 'phase': [], 'r':[]}.keys()
示例#51
0
    def __init__(self):
        QThread.__init__(self)
        
        self.running = True
        self.data_from_server = False
        self.queue = queue.Queue()

        # Data server
        if self.data_from_server:
            self.host = '188.244.51.15'
            self.port = 5000
 def __init__(self):
   QThread.__init__(self)
   self.killMe = False
   pygame.init()
   pygame.joystick.init()
   #print "Number of joysticks:", pygame.joystick.get_count()
   if pygame.joystick.get_count() == 0:
     print "No Joystick available"
     self.joystick = None
   else:
     self.joystick = pygame.joystick.Joystick(0)
     self.joystick.init()
 def __init__(self):
   QThread.__init__(self)
   self.killMe = False
   pygame.init()
   pygame.joystick.init()
   #print "Number of joysticks:", pygame.joystick.get_count()
   if pygame.joystick.get_count() == 0:
     print "No Joystick available"
     self.joystick = None
   else:
     self.joystick = pygame.joystick.Joystick(0)
     self.joystick.init()
 def __init__(self, *args, **kwargs):
     QThread.__init__(self, *args, **kwargs)
     self.input_buffer = ""  # по этой ссылке храниться все входящие данные от последовательного порта
     self.out_cmd_queue = Queue(
     )  # в очередь кладутся словари формата {"command": комманда, "expected_regexp": RegExp ожидаемого ответа,
     #  "additionTimeout": дополнительный таймут между ответами, по умоличани это 0}
     self.standart_timeout = 0.1
     # self._config_object = config_object
     self.last_answer = None  # последний ответ, на случай если произошла ошибка в процессе запросов
     self.last_request = None  # последний запрос, на случай если произошла ошибка в процессе запросов
     self.debug_msg = None  # debug сообщение, в случае неудачного запроса
     self.steps = 0  # шаги, которые нужно выполнить
     self.total_cmd_commands = 0  # полное количество последовательных команд
示例#55
0
class RendererExecutorGui(QObject):
    """A class to execute a rendering engine in Graphical User Interface mode.

    This class is designed to run a renderer in a separate thread, keeping GUI
    responsive.  Meanwhile, stdout/stderr are piped to FreeCAD console, in such
    a way it is possible to follow the evolution of the rendering.  To achieve
    that, renderer is executed in a separate thread, using **QThread**.
    Nota: in this class, it is assumed that Qt GUI is up, so it is not tested
    anywhere.
    """
    def __init__(self, cmd, img):
        """Initialize executor.

        Args:
            cmd -- command to execute (str)
            img -- path to resulting image (the renderer output) (str)
        """
        super().__init__(QCoreApplication.instance())
        self.thread = QThread()
        self.worker = Worker(cmd, img)
        self.thread.setObjectName("fcd-renderexec")

    def start(self):
        """Start executor."""
        # Move worker to thread
        self.worker.moveToThread(self.thread)

        # Connect signals and slots
        # pylint: disable=no-member
        self.thread.started.connect(self.worker.run)
        self.worker.finished.connect(self.thread.quit)
        self.worker.finished.connect(self.worker.deleteLater)
        self.worker.finished.connect(self.thread.exit)
        self.thread.finished.connect(self.thread.deleteLater)
        # self.thread.finished.connect(lambda: print("Thread finished")) # Dbg

        self.worker.result_ready.connect(display_image)

        # Start the thread
        self.thread.start()

    def join(self):
        """Join thread.

        This method is provided for consistency with CLI executor, but it
        should not be of much use in GUI context.
        """
        loop = QEventLoop()
        self.thread.finished.connect(loop.quit)  # pylint: disable=no-member
        if not self.thread.isFinished():
            loop.exec_(flags=QEventLoop.ExcludeUserInputEvents)
示例#56
0
    def __init__(self, probes, refresh_interval = 0.5):
        """
        probes: dictionary of probes where keys are names and values are Probe objects
        refresh_interval: time between reads in s
        """
        assert isinstance(probes, dict)
        assert isinstance(refresh_interval, float)

        self.refresh_interval = refresh_interval
        self._running = False
        self.probes = probes
        self.probes_values = None

        QThread.__init__(self)
示例#57
0
    def __init__(self, instruments, name = None, settings = None, log_output = None, timeout = 1000000000):

        self._recording = False
        self._timeout = timeout

        Script.__init__(self, name, settings, instruments, log_output = log_output)
        QThread.__init__(self)

        self.sweeper = self.instruments['zihf2'].daq.sweep(self._timeout)
        self.sweeper.set('sweep/device', self.instruments['zihf2'].device)

        self.data = deque()

        # todo: clean this up! and plot data in gui!
        self._sweep_values =  {'frequency' : [], 'x' : [], 'y' : [], 'phase': [], 'r':[]}.keys()
示例#58
0
 def __init__(self, dir_from, dir_to, some):
     QThread.__init__(self, None)
     box = Communicate()
     box.mBox.connect(m_box_exec)
     try:
         self.processo = subprocess.Popen(
             ["rsync", "-av", "--progress", "--size-only", "%s" % dir_from, "%s" % dir_to],
             shell=False,
             stdout=subprocess.PIPE,
             stderr=subprocess.PIPE,
         )
         self.some = some
     except Exception as e:
         box.mBox.emit(u"Error invoking rsync, please check if you have rsync installed.\n:= %s" % e.message)
         print(e)