def run(self): if self.DEBUG: dprint( "Worker_send %s run : thread %s" % (self.dev.name, curThreadName()), self.DEBUG_color) while self.running: locker_worker = QtCore.QMutexLocker(self.mutex) if self.DEBUG: dprint( "Worker_send %s: waiting for trigger" % self.dev.name, self.DEBUG_color) self.qwc.wait(self.mutex) if self.DEBUG: dprint("Worker_send %s: trigger received" % self.dev.name, self.DEBUG_color) """Process all jobs until the queue is empty. We must iterate 2 times because we use a sentinel in a FIFO queue. First iter removes the old sentinel. Second iter processes the remaining queue items and will put back a new sentinel again. """ for i in range(2): for job in iter(self.queue.get_nowait, self.sentinel): ard = job[0] func = ard.write args = job[1:] if self.DEBUG: dprint( "Worker_send %s: %s %s" % (ard.name, func.__name__, args), self.DEBUG_color) # Send I/O operation to the device locker = QtCore.QMutexLocker(ard.mutex) try: func(*args) except Exception as err: pft(err) locker.unlock() # Put sentinel back in self.queue.put(self.sentinel) locker_worker.unlock() if self.DEBUG: dprint("Worker_send %s: done running" % self.dev.name, self.DEBUG_color)
def is_sleeping(self): """ Checks if the thread is sleeping (waiting for wake up/refresh requests) :return: """ _ = QtCore.QMutexLocker(self._mutex) return self._sleep
def receive_messages(): for k in keyboards.keyboards: if k.interface: while True: try: with QtCore.QMutexLocker(k.interface_mutex): m = k.interface.read(32) except: log('%s: Messages may not be received.' % k.name) m = [] if not m: break while m and m[-1] == 0: m.pop(-1) if m: m = ''.join([chr(c) for c in m]) log('%s: "%s" is being received.' % (k.name, m)) m = m.split() try: m = easydict.EasyDict(session_id=int(m[0]), command=m[1], arguments=m[2:]) except: log('%s: This messages is corrupted.' % k.name) continue if not handle_message(k, m): log('%s: This messages can\'t be recognized.' % k.name)
def wake_up(self, wake_up=True): """ Wake up the thread and performs a status refresh for all repositories in the repositories list. """ _ = QtCore.QMutexLocker(self._mutex) self._sleep = not wake_up
def process_qpbt_ackn_errors(self): # Lock the dev mutex because string operations are not atomic locker = QtCore.QMutexLocker(self.dev.mutex) self.dev.state.all_errors = [] self.qpte_errors.setPlainText("") self.qpte_errors.setReadOnly(False) # To change back to regular colors locker.unlock()
def onStartScan(self, globalOverrides=list()): """Start the scan globalOverrrides is list of (name, magnitude) values or list of (name, (value, unit)) values that will override global variables during the scan """ logger = logging.getLogger(__name__) with QtCore.QMutexLocker(self.script.mutex): self.script.scanIsRunning = True self.script.analysisReady = False self.script.dataReady = False self.script.allDataReady = False # make sure we hand on a list of (key, magnitude) pairs myGlobalOverrides = list() for key, value in globalOverrides: if not is_Q(value): if isinstance(value, collections.Sized): value = Q(value[0], value[1]) else: value = Q(value) myGlobalOverrides.append((key, value)) self.experimentUi.onStart(globalOverrides=myGlobalOverrides) scan = self.scanControlWidget.settingsName evaluation = self.evaluationControlWidget.settingsName analysis = self.analysisControlWidget.currentAnalysisName message = "Scan started at {0} with scan = {1}, evaluation = {2}, analysis = {3}".format( str(datetime.now()), scan, evaluation, analysis) logger.info(message) self.writeToConsole(message, color='green') return (False, None)
def update_curve(self): """Creates a snapshot of the buffered data, which is a fast operation, followed by updating the data behind the curve and redrawing it, which is a slow operation. Hence, the use of a snapshot creation, which is locked my a mutex, followed by a the mutex unlocked redrawing. """ # First create a snapshot of the buffered data. Fast. locker = QtCore.QMutexLocker(self.mutex) self._x_snapshot = np.copy(self._x) self._y_snapshot = np.copy(self._y) #print("numel x: %d, numel y: %d" % # (self._x_snapshot.size, self._y_snapshot.size)) locker.unlock() # Now update the data behind the curve and redraw the curve. Slow if self.curve is not None: if ((len(self._x_snapshot) == 0) or (np.alltrue(np.isnan(self._y_snapshot)))): self.curve.setData([0], [0]) else: self.curve.setData( (self._x_snapshot - self._x_snapshot[-1]) / float(self.x_axis_divisor), self._y_snapshot / float(self.y_axis_divisor))
def dprint(str_msg, ANSI_color=None): """'Debug' print a single line to the terminal with optional ANSI color codes. The line will be terminated with a newline character and the terminal output buffer is forced to flush before and after every print. In addition, if PyQt5 is present in the Python environment, then a mutex lock will be obtained and released again for each dprint execution. There is a lot of overhead using this print statement, but it is particularly well suited for multithreaded PyQt programs where multiple threads are printing information to the same terminal. On the contrary, a regular print statement will likely result in mixed up text output. """ # Explicitly ending the string with a newline '\n' character, instead # of letting the print statement end it for you (end='\n'), fixes the # problem of single lines getting printed to the terminal with # intermittently delayed newlines when coming from different threads. # I.e. it prevents: # >: Output line of thread 1Output line of thread 2 (\n) # >: (\n) # and makes sure we get: # >: Output line of thread 1 (\n) # >: Output line of thread 2 (\n) if PYQT5_IS_PRESENT: locker = QtCore.QMutexLocker(dprint_mutex) sys.stdout.flush() if ANSI_color is None: print("%s\n" % str_msg, end='') else: print("%s%s%s\n" % (ANSI_color, str_msg, ANSI.WHITE), end='') sys.stdout.flush() if PYQT5_IS_PRESENT: locker.unlock()
def onFit(self, fitName, traceName): fitName = str(fitName) traceName = str(traceName) fitAnalysisIndex = self.fitWidget.analysisNameComboBox.findText( fitName) if fitAnalysisIndex < 0: message = "Fit '{0}' does not exist.".format(fitName) error = True elif traceName not in self.scriptTraces: message = "Trace '{0}' does not exist".format(traceName) error = True else: plottedTrace = self.scriptTraces[traceName] self.fitWidget.analysisNameComboBox.setCurrentIndex( fitAnalysisIndex) message = "Fitting trace '{0}' using fit '{1}'".format( traceName, fitName) self.fitWidget.fit(plottedTrace) with QtCore.QMutexLocker(self.script.mutex): for index, parameter in enumerate( plottedTrace.fitFunction.parameterNames): self.script.fitResults[ parameter] = plottedTrace.fitFunction.parameters[index] error = False return (error, message)
def baseScriptFunction(self, *args, **kwds): """The base script function that wraps all the other script functions""" with QtCore.QMutexLocker( self.mutex ): #Acquire mutex before inspecting any variables if (not self.stopped) or ( self.stopped and runIfStopped): #if stopped, don't do anything if self.scanIsRunning and self.waitOnScan: self.scanWait.wait(self.mutex) if self.paused: self.pauseWait.wait(self.mutex) self.emitLocation() if self.slow: self.mutex.unlock() time.sleep( 0.4) #On slow, we wait on each line for 0.4 s self.mutex.lock() if waitForAnalysis and not self.analysisReady: self.analysisWait.wait(self.mutex) if waitForAllData and not self.allDataReady: self.allDataWait.wait(self.mutex) if waitForData and not self.dataReady: self.dataWait.wait(self.mutex) returnData = func(self, *args, **kwds) #This is the actual function if waitForGui: self.guiWait.wait(self.mutex) if self.exception: raise self.exception return returnData
def onAbortScan(self): self.experimentUi.actionAbort.trigger() with QtCore.QMutexLocker(self.script.mutex): self.script.scanIsRunning = False error = False message = "Scan aborted" return (error, message)
def run(self): if self.DEBUG: dprint( "Worker_DAQ %s run : thread %s" % (self.dev.name, curThreadName()), self.DEBUG_color) # INTERNAL TIMER if self.trigger_by == DAQ_trigger.INTERNAL_TIMER: self.timer = QtCore.QTimer() self.timer.setInterval(self.update_interval_ms) self.timer.timeout.connect(self.update) self.timer.setTimerType(self.timer_type) self.timer.start() # EXTERNAL WAKE UP elif self.trigger_by == DAQ_trigger.EXTERNAL_WAKE_UP_CALL: while self.running: locker_wait = QtCore.QMutexLocker(self.mutex_wait) if self.DEBUG: dprint( "Worker_DAQ %s: waiting for trigger" % self.dev.name, self.DEBUG_color) self.qwc.wait(self.mutex_wait) self.update() locker_wait.unlock() if self.DEBUG: dprint("Worker_DAQ %s: done running" % self.dev.name, self.DEBUG_color)
def print_lock(self,_s_str): try: o_mutex = self.t_workerParameters['print_lock'] o_locker = QtCore.QMutexLocker(o_mutex) print(_s_str) except KeyError: print(_s_str)
def five_secondly_routine(): global current_application old_application = current_application if sys.platform == 'darwin': current_application = subprocess.run([ 'osascript', '-e', 'tell application "System Events"', '-e', 'set t to name of first application process whose frontmost is true', '-e', 'end tell' ], stdout=subprocess.PIPE ).stdout.strip().decode() else: log('%s is not a supported OS.' % sys.platform) log('The current application is %s.' % current_application) if current_application != old_application and False: subprocess.call([ path + '/swim/.build/release/swim', 'use', 'com.apple.keylayout.ABC' ]) for k in keyboards.keyboards: with QtCore.QMutexLocker(k.interface_mutex): if k.interface: send_message( k, easydict.EasyDict(session_id=int(time.time()), command='application', arguments=[{ 'Terminal': 1 }.get(current_application, 0)]))
def toggle_handness(checked): with QtCore.QMutexLocker(k.handness_session_id_mutex): k.handness_session_id = int(time.time()) send_message( k, easydict.EasyDict(session_id=k.handness_session_id, command='handness', arguments=[int(checked)]))
def change_x(self): with QtCore.QMutexLocker(MyThread.mutex): print("x=", MyThread.x, "id = ", self.id) MyThread.x += 5 self.sleep(2) print("x=", MyThread.x, "id = ", self.id) MyThread.x += 34 print("x=", MyThread.x, "id = ", self.id)
def setMinDist(self, dist: float) -> None: _ = qc.QMutexLocker(self._mutex) self.tracker.setMinDist(dist) metric = settings.value('sortracker/metric', 'iou', type=str) if metric == 'iou': settings.setValue('sortracker/iou_mindist', dist) else: settings.setValue('sortracker/euclidean_mindist', dist)
def toggle_backlight(checked): with QtCore.QMutexLocker(k.backlight_session_id_mutex): k.backlight_session_id = int(time.time()) send_message( k, easydict.EasyDict(session_id=k.backlight_session_id, command='backlight', arguments=[int(checked)]))
def setData(self, x_list, y_list): """Set the (x, y)-data of the regular array buffer. """ if not self._use_ringbuffer: locker = QtCore.QMutexLocker(self._mutex) self._buffer_x = x_list self._buffer_y = y_list locker.unlock()
def extendData(self, x_list, y_list): """Extend the ring buffer with a list of (x, y)-data points. """ if self._use_ringbuffer: locker = QtCore.QMutexLocker(self._mutex) self._buffer_x.extend(x_list) self._buffer_y.extend(y_list) locker.unlock()
def appendData(self, x, y): """Append a single (x, y)-data point to the ring buffer. """ if self._use_ringbuffer: locker = QtCore.QMutexLocker(self._mutex) self._buffer_x.append(x) self._buffer_y.append(y) locker.unlock()
def set_parameters(self, dict): ''' Sometimes, several parameters should be set at once without allowing the state being updated while a parameter is read. ''' with QtCore.QMutexLocker(self.mutex): for key, value in dict.items(): self._state_dict.__setitem__(key, value) self.sig_updated.emit()
def run(self): print(f'hashing {self.infile}') self.hasher.reset() with open(self.infile, 'rb') as fh: self.hasher.addData(fh.read()) hash_string = bytes(self.hasher.result().toHex()).decode('UTF-8') with qtc.QMutexLocker(self.file_lock): with open(self.outfile, 'a', encoding='utf-8') as out: out.write(f'{self.infile}\t{hash_string}\n')
def run(self): with QtCore.QMutexLocker(self.mutex): self.stoped = False while True: if self.stoped: return self.emit(QtCore.SIGNAL(self.signal)) # 40毫秒发送一次信号 time.sleep(0.04)
def daily_routine(): with QtCore.QMutexLocker(stdout_mutex): if '--debug' not in sys.argv: sys.stdout.close() lines = open('/tmp/matroid_computer.log').readlines() lines = lines[-1024:] sys.stdout = open('/tmp/matroid_computer.log', 'w') for line in lines: sys.stdout.write(line)
def reset(self): """Clear the received blocks counter and clear all ring buffers.""" locker = QtCore.QMutexLocker(self.mutex) self.blocks_received = 0 for rb in self.ringbuffers: rb.clear() locker.unlock()
def run(self): while True: now = time.perf_counter() for i, k in enumerate(keyboards.keyboards): log('%s: The review of %s is starting.' % (k.name, k.name)) if k.interface: with QtCore.QMutexLocker(k.heartbeat_session_id_mutex): if k.heartbeat_session_id != -1: log('%s: The keyboard is lost.' % k.name) with QtCore.QMutexLocker(k.interface_mutex): k.interface.close() k.interface = None self.lost.emit(i) else: log('%s: The keyboard is alive.' % k.name) else: for j in range(16): try: with QtCore.QMutexLocker(k.interface_mutex): d = hid.device() d.open(k.vendor_id, k.product_id) d.set_nonblocking(1) k.interface = d log('%s: The keyboard is connected.' % k.name) send_message( k, easydict.EasyDict(session_id=int(time.time()), command='time', arguments=[])) self.connected.emit(i) break except OSError: pass if k.interface: with QtCore.QMutexLocker(k.heartbeat_session_id_mutex): k.heartbeat_session_id = int(time.time()) send_message( k, easydict.EasyDict( session_id=k.heartbeat_session_id, command='heartbeat', arguments=[])) log('%s: The review of %s is ending.' % (k.name, k.name)) time.sleep(max(self.interval - (time.perf_counter() - now), 0))
def __setitem__(self, key, value): ''' Custom __setitem__ method to allow mutexed access to a state parameter. After the state has been changed, the updated signal is emitted. ''' with QtCore.QMutexLocker(self.mutex): self._state_dict.__setitem__(key, value) self.sig_updated.emit()
def onStartScript(self): """Runs when start script button clicked. Starts the script and disables some aspects of the script GUI""" if not self.script.isRunning(): self.globalVariablesRevertDict.clear() with QtCore.QMutexLocker(self.script.mutex): self.script.paused = False self.script.stopped = False self.script.exception = None self.script.start() self.namedTraceList = set()
def __getitem__(self, key): ''' Custom __getitem__ method to allow mutexed access to a state parameter. To avoid the state being updated while a parameter is read. ''' with QtCore.QMutexLocker(self.mutex): return self._state_dict.__getitem__(key)