def run(self): try: req = requests.get( UrlGetAppsByCategory.format(category=self.category, pageno=1, count=20, time=time())) content = req.json() errno = content.get('errno', 0) AppLog.debug('errno: %s', errno) AppLog.debug('msg: %s', content.get('msg', '')) if errno != 0: return content = content.get('data', {}) AppLog.debug('total_count: %s', content.get('total_count', '')) AppLog.debug('total_page: %s', content.get('total_page', '')) items = content.get('list', []) for i, item in enumerate(items): title = item.get('title', '') url = item.get('image', None) if not url: continue self.download(i, title, url) QThread.msleep(200) QThread.yieldCurrentThread() except Exception as e: AppLog.exception(e) Signals.pictureDownFinished.emit(self.widget)
def __compileAllProtocols(self, grpc=False): """ Private method to compile all protocols to Python. @param grpc flag indicating to compile as gRPC files @type bool """ if self.__getCompilerCommand(grpc)[0] is not None: numProtos = len(self.project.pdata["PROTOCOLS"]) progress = E5ProgressDialog(self.tr("Compiling Protocols..."), self.tr("Abort"), 0, numProtos, self.tr("%v/%m Protocols"), self) progress.setModal(True) progress.setMinimumDuration(0) progress.setWindowTitle(self.tr("Protocols")) i = 0 for fn in self.project.pdata["PROTOCOLS"]: progress.setValue(i) if progress.wasCanceled(): break proc = self.__compileProto(fn, True, progress, grpc=grpc) if proc is not None: while proc.state() == QProcess.Running: QApplication.processEvents() QThread.msleep(300) QApplication.processEvents() else: break i += 1 progress.setValue(numProtos)
def __rawOn(self): """ Private method to switch the connected device to 'raw' mode. Note: switching to raw mode is done with synchronous writes. @return flag indicating success @@rtype bool """ if not self.__serial: return False rawReplMessage = b"raw REPL; CTRL-B to exit\r\n>" self.__serial.write(b"\x02") # end raw mode if required self.__serial.waitForBytesWritten() for _i in range(3): # CTRL-C three times to break out of loops self.__serial.write(b"\r\x03") self.__serial.waitForBytesWritten() QThread.msleep(10) self.__serial.readAll() # read all data and discard it self.__serial.write(b"\r\x01") # send CTRL-A to enter raw mode self.__serial.readUntil(rawReplMessage) if self.__serial.hasTimedOut(): # it timed out; try it again and than fail self.__serial.write(b"\r\x01") # send CTRL-A again self.__serial.readUntil(rawReplMessage) if self.__serial.hasTimedOut(): return False QCoreApplication.processEvents(QEventLoop.ExcludeUserInputEvents) self.__serial.readAll() # read all data and discard it return True
def show_progress_bar(self): percent = 0 is_exits = False self.result = None progressDialog = QProgressDialog(self.files_list_dialog) progressDialog.setAutoReset(True) progressDialog.setWindowModality(Qt.WindowModal) progressDialog.setMinimumDuration(5) progressDialog.setWindowTitle('Downloading') progressDialog.setWindowIcon(QIcon(':/res/favicon.ico')) progressDialog.setLabelText('Current speed: ') progressDialog.setCancelButtonText('Cancel') progressDialog.setRange(0, 100) while percent < 100 and not is_exits: percent = status.get_percent() is_exits = status.get_exist() if is_exits: self.result = 'Files already exists (..•˘_˘•..)' progressDialog.close() break progressDialog.setValue(percent) progressDialog.setLabelText('Current speed: ' + str(status.get_speed())) QThread.msleep(100) if progressDialog.wasCanceled(): status.set_stop_thread(True) self.download_thread.wait() mlog.debug('stop the download thread') mlog.debug('download_thread.isRunning ' + str(self.download_thread.isRunning())) progressDialog.close() self.result = 'Paused Σ(っ °Д °;)っ' break
def run(self): if DEBUG: import pydevd pydevd.settrace(suspend=False) try: self.cam.open(camera.Resolution.A_REALLY_HIGH_RES, framerate=10) self.camInitialized.emit() if self.ispause: self.cam.pause() self.isinit = True except Exception as ex: self.error.emit(str(ex)) return while (not self.stopped): if self.ispause: QThread.msleep(100) continue f = self.cam.grab() sl = round(min(self.cam.imgwidth, self.cam.imgheight) * self.zoom) sx = round((self.cam.imgwidth - sl) / 2) sy = round((self.cam.imgheight - sl) / 2) roi = f[sy:sy + sl, sx:sx + sl] resized = cv2.resize(roi, (512, 512)) img = QImage(resized.data, resized.shape[1], resized.shape[0], QImage.Format_RGB888) pixmap = QPixmap.fromImage(img) self.newFrame.emit(pixmap) self.cam.close()
def prepareData(self): for i in range(0, 8): if self.selCbList[i].isChecked(): data = self.hexEditList[i].text() self.dataReady.emit(data, True) QThread.msleep(int(self.strInterTimeEdit.text())) pass
def compileChangedForms(self): """ Public method to compile all changed forms to source files. """ if self.hooks["compileChangedForms"] is not None: self.hooks["compileChangedForms"](self.project.pdata["FORMS"]) else: if self.project.getProjectType() not in \ ["Qt4", "PyQt5", "E4Plugin", "E6Plugin", "PySide"]: # ignore the request for non Qt GUI projects return progress = E5ProgressDialog( self.tr("Determining changed forms..."), None, 0, 100, self.tr("%v/%m Forms")) progress.setMinimumDuration(0) progress.setWindowTitle(self.tr("Forms")) i = 0 # get list of changed forms changedForms = [] progress.setMaximum(len(self.project.pdata["FORMS"])) for fn in self.project.pdata["FORMS"]: progress.setValue(i) QApplication.processEvents() ifn = os.path.join(self.project.ppath, fn) if self.project.pdata["PROGLANGUAGE"][0] in \ ["Python", "Python2", "Python3"]: dirname, filename = os.path.split(os.path.splitext(ifn)[0]) ofn = os.path.join(dirname, "Ui_" + filename + ".py") elif self.project.pdata["PROGLANGUAGE"][0] == "Ruby": ofn = os.path.splitext(ifn)[0] + '.rb' if not os.path.exists(ofn) or \ os.stat(ifn).st_mtime > os.stat(ofn).st_mtime: changedForms.append(fn) i += 1 progress.setValue(i) QApplication.processEvents() if changedForms: progress.setLabelText( self.tr("Compiling changed forms...")) progress.setMaximum(len(changedForms)) i = 0 progress.setValue(i) QApplication.processEvents() for fn in changedForms: progress.setValue(i) proc = self.__compileUI(fn, True, progress) if proc is not None: while proc.state() == QProcess.Running: QApplication.processEvents() QThread.msleep(300) QApplication.processEvents() else: break i += 1 progress.setValue(len(changedForms)) QApplication.processEvents()
def run(self): self.w.queryStatusTag.setText('查询中') self.w.queryStatusTag.setStyleSheet("color:black") headers = { 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.87 Safari/537.36', 'authorization': self.wApiKey, 'Content-Type': 'application/json' } r = requests.post(self.mUrl, json=self.mJson, headers=headers) QThread.msleep(1000) print(r) try: if len(r.json()['data']['result']) == 0: self.w.queryStatusTag.setText('无结果!等待查询') self.w.queryStatusTag.setStyleSheet("color:green") return for solution in r.json()['data']['result']: QMetaObject.invokeMethod(self.w, "addSolution", Qt.QueuedConnection, Q_ARG(dict, solution)) self.w.queryStatusTag.setText('等待查询') self.w.queryStatusTag.setStyleSheet("color:green") except Exception as e: self.w.queryStatusTag.setText('查询失败(%s)' % r.json()['code']) self.w.queryStatusTag.setStyleSheet("color:red") return
def grab_data(self, Naverage=1, **kwargs): """ | For each integer step of naverage range set mock data. | Construct the data matrix and send the data_grabed_signal once done. =============== ======== =============================================== **Parameters** **Type** **Description** *Naverage* int The number of images to average. specify the threshold of the mean calculation =============== ======== =============================================== See Also -------- set_Mock_data """ "live is an attempt to export data as fast as possible" if 'live' in kwargs: if kwargs['live']: self.live = True self.live = False #don't want to use that for the moment if self.live: while self.live: data = self.average_data(Naverage) QThread.msleep(100) self.data_grabed_signal.emit(data) QtWidgets.QApplication.processEvents() else: data = self.average_data(Naverage) QThread.msleep(000) self.data_grabed_signal.emit(data)
def run(self): print(QThread.currentThread(), ' is running ...') print(QDir.homePath(), QDir.currentPath()) rootdir = QDir.homePath() + '/pics' list = os.listdir(rootdir) #列出文件夹下所有的目录与文件 for i in range(0, min(len(list), 200)): path = os.path.join(rootdir, list[i]) types = ('.bmp', '.jpg', '.tif', '.png') if os.path.isfile(path) and path.endswith(types): # self.image_list[path] = QImage(path) self.image_list.append((path, QImage(path))) self.image_list.sort() sorted(self.image_list, key=operator.itemgetter(0)) if len(self.image_list) == 0: return self.bStop = False while self.isRunning(): # break # for (k,v) in self.image_list.items(): # 字典类型遍历 随机访问 会乱序 for k, v in enumerate(self.image_list): # print(k,v) # print(type(k),type(v)) # self.evt_showImg.emit(k,v) self.evt_showImg.emit(v[0], v[1]) ## 发射自定义信号 if (self.isInterruptionRequested()): print("----> get isInterruptionRequested") self.bStop = True break QThread.msleep(25) if self.bStop: break print("----> thread quit here!!")
def __compileAllInterfaces(self): """ Private method to compile all interfaces to python. """ if self.omniidl is not None: numIDLs = len(self.project.pdata["INTERFACES"]) progress = E5ProgressDialog(self.tr("Compiling interfaces..."), self.tr("Abort"), 0, numIDLs, self.tr("%v/%m Interfaces"), self) progress.setModal(True) progress.setMinimumDuration(0) progress.setWindowTitle(self.tr("Interfaces")) i = 0 for fn in self.project.pdata["INTERFACES"]: progress.setValue(i) if progress.wasCanceled(): break proc = self.__compileIDL(fn, True, progress) if proc is not None: while proc.state() == QProcess.Running: QApplication.processEvents() QThread.msleep(300) QApplication.processEvents() else: break i += 1 progress.setValue(numIDLs)
def move_Rel(self, position): """ Make the hardware relative move of the Piezo instrument from the given position after thread command signal was received in DAQ_Move_main. =============== ========= ======================= **Parameters** **Type** **Description** *position* float The absolute position =============== ========= ======================= See Also -------- DAQ_Move_base.set_position_with_scaling, DAQ_Move_base.poll_moving """ position = self.check_bound(self.current_position + position) - self.current_position self.target_position = position + self.current_position position = self.set_position_relative_with_scaling(position) pos = Position(self.settings.child('multiaxes', 'axis').value(), position * 1000, unit='n') # always use microns for simplicity out = self.controller.move_axis('REL', pos) QThread.msleep(50) # to make sure the closed loop converged self.poll_moving()
def move_Abs(self, position): """ Parameters ---------- position: (float) target position of the given axis in um (or scaled units) Returns ------- """ position = self.check_bound( position ) #limits the position within the specified bounds (-100,100) self.target_position = position #get positions in controller units position = self.set_position_with_scaling(position) pos = Position(self.settings.child('multiaxes', 'axis').value(), int(position * 1000), unit='n') out = self.controller.move_axis('ABS', pos) #self.move_is_done = True QThread.msleep(50) #to make sure the closed loop converged self.poll_moving()
def run(self): show = True try: req = requests.get(self.Url) AppLog.info(req.text) if req.status_code != 200: AppLog.info('update thread end') UpgradeThread.quit() return content = req.json() for version, text in content: if Version.version < version: if show: Signals.updateDialogShowed.emit() QThread.msleep(1000) show = False Signals.updateTextChanged.emit( str(Version.version), str(version), text) self.download(Constants.UpgradeFile.format( version), self.ZipUrl.format(version)) Signals.updateFinished.emit(self.tr('update completed')) except Exception as e: Signals.updateFinished.emit( self.tr('update failed: {}').format(str(e))) AppLog.exception(e) AppLog.info('update thread end') UpgradeThread.quit()
def __compileSelectedInterfaces(self): """ Private method to compile selected interfaces to python. """ if self.omniidl is not None: items = self.getSelectedItems() files = [ self.project.getRelativePath(itm.fileName()) for itm in items ] numIDLs = len(files) progress = E5ProgressDialog(self.tr("Compiling interfaces..."), self.tr("Abort"), 0, numIDLs, self.tr("%v/%m Interfaces"), self) progress.setModal(True) progress.setMinimumDuration(0) progress.setWindowTitle(self.tr("Interfaces")) i = 0 for fn in files: progress.setValue(i) if progress.wasCanceled(): break proc = self.__compileIDL(fn, True, progress) if proc is not None: while proc.state() == QProcess.Running: QApplication.processEvents() QThread.msleep(300) QApplication.processEvents() else: break i += 1 progress.setValue(numIDLs)
def __runcommand(self, args, inputChannels, outputChannels): """ Private method to run a command in the server (low level). @param args list of arguments for the command (list of string) @param inputChannels dictionary of input channels. The dictionary must have the keys 'I' and 'L' and each entry must be a function receiving the number of bytes to write. @param outputChannels dictionary of output channels. The dictionary must have the keys 'o' and 'e' and each entry must be a function receiving the data. @return result code of the command, -1 if the command server wasn't started or -10, if the command was canceled (integer) @exception RuntimeError raised to indicate an unexpected command channel """ if not self.__started: return -1 self.__server.write(QByteArray(b'runcommand\n')) self.__writeDataBlock('\0'.join(args)) while True: QCoreApplication.processEvents() if self.__cancel: return -10 if self.__server is None: return -1 if self.__server is None or self.__server.bytesAvailable() == 0: QThread.msleep(50) continue channel, data = self.__readChannel() # input channels if channel in inputChannels: input = inputChannels[channel](data) if channel == "L": # echo the input to the output if it was a prompt outputChannels["o"](input) self.__writeDataBlock(input) # output channels elif channel in outputChannels: outputChannels[channel](data) # result channel, command is finished elif channel == "r": return struct.unpack(HgClient.ReturnFormat, data)[0] # unexpected but required channel elif channel.isupper(): raise RuntimeError( "Unexpected but required channel '{0}'.".format(channel)) # optional channels or no channel at all else: pass
def __compileSelectedForms(self): """ Private method to compile selected forms to source files. """ items = self.getSelectedItems() files = [self.project.getRelativePath(itm.fileName()) for itm in items] if self.hooks["compileSelectedForms"] is not None: self.hooks["compileSelectedForms"](files) else: numForms = len(files) progress = E5ProgressDialog(self.tr("Compiling forms..."), self.tr("Abort"), 0, numForms, self.tr("%v/%m Forms"), self) progress.setModal(True) progress.setMinimumDuration(0) progress.setWindowTitle(self.tr("Forms")) i = 0 for fn in files: progress.setValue(i) if progress.wasCanceled(): break proc = self.__compileUI(fn, True, progress) if proc is not None: while proc.state() == QProcess.Running: QApplication.processEvents() QThread.msleep(300) QApplication.processEvents() else: break i += 1 progress.setValue(numForms)
def __compileSelectedInterfaces(self): """ Private method to compile selected interfaces to python. """ if self.omniidl is not None: items = self.getSelectedItems() files = [self.project.getRelativePath(itm.fileName()) for itm in items] numIDLs = len(files) progress = E5ProgressDialog( self.tr("Compiling interfaces..."), self.tr("Abort"), 0, numIDLs, self.tr("%v/%m Interfaces"), self) progress.setModal(True) progress.setMinimumDuration(0) progress.setWindowTitle(self.tr("Interfaces")) i = 0 for fn in files: progress.setValue(i) if progress.wasCanceled(): break proc = self.__compileIDL(fn, True, progress) if proc is not None: while proc.state() == QProcess.Running: QApplication.processEvents() QThread.msleep(300) QApplication.processEvents() else: break i += 1 progress.setValue(numIDLs)
def terminate(self): self.inferenceEngine.terminate() self.receiver_thread.quit() for count in range(10): QThread.msleep(50) self.close()
def showHint(self, hint, show_ms): self.on_lock.emit(self) self.set_hint.emit(self, hint) if show_ms >= 0: QThread.msleep(show_ms) self.off_lock.emit(self) pass
def record(self, start): print("pressure recording started") save_directory = self._parent.save_directory PS1 = [] timing = [] start = time.time() while self.isrecording: # Read pressure controller and emit pressure measurements timestamp = time.time() - start response = self.pressurecontroller.readFlush() response = response.split() if len(response) > 0: if response[0] == "PS": try: PS1.append(float(response[1])) timing.append(timestamp) self.measurement.emit(np.array([PS1[-1], timestamp])) except ValueError: pass # Determines the sampling rate QThread.msleep(5) # Save measurements and close the serial port np.save(save_directory + 'pressure_recording_sensor1', PS1) np.save(save_directory + 'pressure_recording_timing', timing) print('pressure recording stopped')
def start(self): # do work here for num in range(self.min, self.max): QThread.msleep(300) self.sig_update.emit(num) self.sig_result.emit(100)
def compileChangedForms(self): """ Public method to compile all changed forms to source files. """ if self.hooks["compileChangedForms"] is not None: self.hooks["compileChangedForms"](self.project.pdata["FORMS"]) else: if self.project.getProjectType() not in \ ["Qt4", "PyQt5", "E6Plugin", "PySide"]: # ignore the request for non Qt GUI projects return progress = E5ProgressDialog( self.tr("Determining changed forms..."), None, 0, 100, self.tr("%v/%m Forms")) progress.setMinimumDuration(0) progress.setWindowTitle(self.tr("Forms")) i = 0 # get list of changed forms changedForms = [] progress.setMaximum(len(self.project.pdata["FORMS"])) for fn in self.project.pdata["FORMS"]: progress.setValue(i) QApplication.processEvents() ifn = os.path.join(self.project.ppath, fn) if self.project.pdata["PROGLANGUAGE"][0] in \ ["Python", "Python2", "Python3"]: dirname, filename = os.path.split(os.path.splitext(ifn)[0]) ofn = os.path.join(dirname, "Ui_" + filename + ".py") elif self.project.pdata["PROGLANGUAGE"][0] == "Ruby": ofn = os.path.splitext(ifn)[0] + '.rb' if not os.path.exists(ofn) or \ os.stat(ifn).st_mtime > os.stat(ofn).st_mtime: changedForms.append(fn) i += 1 progress.setValue(i) QApplication.processEvents() if changedForms: progress.setLabelText( self.tr("Compiling changed forms...")) progress.setMaximum(len(changedForms)) i = 0 progress.setValue(i) QApplication.processEvents() for fn in changedForms: progress.setValue(i) proc = self.__compileUI(fn, True, progress) if proc is not None: while proc.state() == QProcess.Running: QApplication.processEvents() QThread.msleep(300) QApplication.processEvents() else: break i += 1 progress.setValue(len(changedForms)) QApplication.processEvents()
def run(self): for root, dirs, files in os.walk(self.folder): self.updateSignal.emit([ "\n{}:".format(root), ], self.indPbar) for file in files: if self.cons == 1: self.indPbar += 1 self.updateSignal.emit([ file, ], self.indPbar) else: self.files.append("{}".format(file)) self.ind += 1 if self.ind >= 100: self.indPbar += 1 self.updateSignal.emit(self.files, self.indPbar) self.ind = 0 self.cons -= 1 self.files = [] QThread.msleep(1) self.updateSignal.emit(self.files, self.indPbar) self.files = [] self.updateSignal.emit(self.files, 100)
def run(self): # print("run") with open(LOGFILE, "r", encoding="utf-8") as f: f.seek(0, 2) self.writeLog.emit("Reading file...") while self.continue_run: # print("test") logline = f.readline() if COMMAND in logline: # STRIP NEW LINES AT START AND END logline = logline.strip("\n") logline = logline.strip('\t') self.writeLog.emit(logline) print(logline) string = self.splicer(logline, COMMAND) print(string) string2 = string.split() print(string2) if string[len(string2[0]):].isspace(): print("No input found") self.URLinput.emit(string[len(string2[0]):].lstrip()) QThread.msleep(10) self.finished.emit()
def __compileAllResources(self): """ Private method to compile all resources to source files. """ if self.hooks["compileAllResources"] is not None: self.hooks["compileAllResources"](self.project.pdata["RESOURCES"]) else: numResources = len(self.project.pdata["RESOURCES"]) progress = E5ProgressDialog( self.tr("Compiling resources..."), self.tr("Abort"), 0, numResources, self.tr("%v/%m Resources"), self) progress.setModal(True) progress.setMinimumDuration(0) progress.setWindowTitle(self.tr("Resources")) i = 0 for fn in self.project.pdata["RESOURCES"]: progress.setValue(i) if progress.wasCanceled(): break proc = self.__compileQRC(fn, True, progress) if proc is not None: while proc.state() == QProcess.Running: QApplication.processEvents() QThread.msleep(300) QApplication.processEvents() else: break i += 1 progress.setValue(numResources)
def live(self): print('camera thread started') self.camera.isLiving = True self.camera.hcam.acquisition_mode = "run_till_abort" # Wait a second for camera acquisition to start self.camera.hcam.startAcquisition() QThread.msleep(1000) # Emit and get frames from the camera at a rate of 1/sleeptime self.isrunning = True while self.isrunning: QThread.msleep(int(self.sleeptime *1000)) try: [frames, dims] = self.camera.hcam.getFrames() self.mutex.lock() self.frame = np.resize(frames[-1].np_array, (dims[1], dims[0])) self.livesignal.emit(self.frame) self.mutex.unlock() except: pass self.camera.hcam.stopAcquisition() self.camera.isLiving = False self.camera.Exit() print('camera thread stopped')
def __compileAllInterfaces(self): """ Private method to compile all interfaces to python. """ if self.omniidl is not None: numIDLs = len(self.project.pdata["INTERFACES"]) progress = E5ProgressDialog( self.tr("Compiling interfaces..."), self.tr("Abort"), 0, numIDLs, self.tr("%v/%m Interfaces"), self) progress.setModal(True) progress.setMinimumDuration(0) progress.setWindowTitle(self.tr("Interfaces")) i = 0 for fn in self.project.pdata["INTERFACES"]: progress.setValue(i) if progress.wasCanceled(): break proc = self.__compileIDL(fn, True, progress) if proc is not None: while proc.state() == QProcess.Running: QApplication.processEvents() QThread.msleep(300) QApplication.processEvents() else: break i += 1 progress.setValue(numIDLs)
def close(self): """ close the current instance of the visa session. """ self.status_timer.stop() QThread.msleep(1000) self.controller.close_communication()
def grab_data(self, Naverage=1, **kwargs): """ | Start new acquisition | For each integer step of naverage range: * set mock data * wait 100 ms * update the data_tot array | | Send the data_grabed_signal once done. =============== ======== =============================================== **Parameters** **Type** **Description** *Naverage* int Number of spectrum to average. Specify the threshold of the mean calculation =============== ======== =============================================== See Also -------- set_Mock_data """ Naverage=1 data_tot=self.set_Mock_data() for ind in range(Naverage-1): data_tmp=self.set_Mock_data() QThread.msleep(100) for ind,data in enumerate(data_tmp): data_tot[ind]+=data data_tot=[data/Naverage for data in data_tot] self.data_grabed_signal.emit([OrderedDict(name='Mock1',data=data_tot, type='Data1D')])
def __compileAllForms(self): """ Private method to compile all forms to source files. """ if self.hooks["compileAllForms"] is not None: self.hooks["compileAllForms"](self.project.pdata["FORMS"]) else: numForms = len(self.project.pdata["FORMS"]) progress = E5ProgressDialog(self.tr("Compiling forms..."), self.tr("Abort"), 0, numForms, self.tr("%v/%m Forms"), self) progress.setModal(True) progress.setMinimumDuration(0) progress.setWindowTitle(self.tr("Forms")) i = 0 for fn in self.project.pdata["FORMS"]: progress.setValue(i) if progress.wasCanceled(): break proc = self.__compileUI(fn, True, progress) if proc is not None: while proc.state() == QProcess.Running: QApplication.processEvents() QThread.msleep(300) QApplication.processEvents() else: break i += 1 progress.setValue(numForms)
def poll_moving(self): """ Poll the current moving. In case of timeout emit the raise timeout Thread command. See Also -------- DAQ_utils.ThreadCommand, move_done """ sleep_ms = 50 ind = 0 while np.abs(self.check_position() - self.target_position) > self.settings.child( ('epsilon')).value(): if self.move_is_done: self.emit_status(ThreadCommand('Move has been stopped')) break QThread.msleep(sleep_ms) ind += 1 if ind * sleep_ms >= self.settings.child(('timeout')).value(): self.emit_status(ThreadCommand('raise_timeout')) break self.current_position = self.check_position() QtWidgets.QApplication.processEvents() self.move_done()
def commit_settings(self, param): """ Activate parameters changes on the hardware. =============== ================================ =========================== **Parameters** **Type** **Description** *param* instance of pyqtgraph Parameter the parameter to activate =============== ================================ =========================== See Also -------- set_Mock_data """ try: if param.name() in custom_tree.iter_children( self.settings.child(('cam_settings')), []): self.stop() while self.controller.is_acquiring_images: self.stop() QtWidgets.QApplication.processEvents() feature = self.controller.device.node_map.get_node( param.name()) interface_type = feature.node.principal_interface_type if interface_type == EInterfaceType.intfIInteger: val = int((param.value() // param.opts['step']) * param.opts['step']) else: val = param.value() feature.value = val #set the desired value param.setValue(feature.value) # retrieve the actually set one #self.update_features() if param.name() in ['Height', 'Width', 'OffsetX', 'OffsetY']: if param.name() in ['Height', 'Width' ] and not self.settings.child( 'ROIselect', 'use_ROI').value(): self.width = self.controller.device.node_map.get_node( 'Width').value self.height = self.controller.device.node_map.get_node( 'Height').value self.data = np.zeros((self.height, self.width)) if param.name() in custom_tree.iter_children( self.settings.child(('ROIselect')), []): while self.controller.is_acquiring_images: QThread.msleep(50) self.stop() QtWidgets.QApplication.processEvents() self.set_ROI() except Exception as e: self.emit_status( ThreadCommand('Update_Status', [getLineInfo() + str(e), 'log']))
def grab_data(self, Naverage=1, **kwargs): """ """ # start moves self.data = np.zeros((len(self.x_axis), len(self.y_axis), len(self.signal_axis))) self.data_grabed_signal_temp.emit([OrderedDict(name='Mock1', nav_axes=[0, 1], data=self.data, type='DataND', nav_x_axis=self.x_axis, nav_y_axis=self.y_axis, labels=['Mock1'], x_axis=self.signal_axis)]) QtWidgets.QApplication.processEvents() for ind, (xpos, ypos) in enumerate(self.scan_parameters.positions): self.data[self.scan_parameters.axis_2D_1_indexes[ind], self.scan_parameters.axis_2D_2_indexes[ind], :] = self.set_Mock_data() if ind%10 == 0: self.data_grabed_signal_temp.emit([OrderedDict(name='Mock1', nav_axes=[0, 1], data=self.data, type='DataND', nav_x_axis=self.x_axis, nav_y_axis=self.y_axis, labels=['Mock1'], x_axis=self.signal_axis)]) QtWidgets.QApplication.processEvents() QThread.msleep(100) self.data_grabed_signal.emit([OrderedDict(name='Mock1', nav_axes=[0, 1], data=self.data, type='DataND', nav_x_axis=self.x_axis, nav_y_axis=self.y_axis, labels=['Mock1'], x_axis=self.signal_axis)])
def doWork(self): self.syst = int(time.time() * 1000.0) self.fixdt = self.simdt while self.running: # Update screen logic self.screenio.update() # Update the Mode-S beast parsing self.beastfeed.update() # Simulation starts as soon as there is traffic, or pending commands if self.state == Simulation.init: if self.traf.ntraf > 0 or len(self.stack.scencmd) > 0: self.start() if self.benchdt > 0.0: self.fastforward(self.benchdt) self.bencht = time.time() if self.state == Simulation.op: self.stack.checkfile(self.simt) # Always update stack self.stack.process(self, self.traf, self.screenio) if self.state == Simulation.op: self.traf.update(self.simt, self.simdt) # Update metrics self.metric.update(self) # Update log self.datalog.update(self) # Update time for the next timestep self.simt += self.simdt # Process Qt events self.manager.processEvents() # When running at a fixed rate, or when in hold/init, increment system time with sysdt and calculate remainder to sleep if not self.ffmode or not self.state == Simulation.op: self.syst += self.sysdt remainder = self.syst - int(1000.0 * time.time()) if remainder > 0: QThread.msleep(remainder) elif self.ffstop is not None and self.simt >= self.ffstop: if self.benchdt > 0.0: self.screenio.echo('Benchmark complete: %d samples in %.3f seconds.' % (self.screenio.samplecount, time.time() - self.bencht)) self.benchdt = -1.0 self.pause() else: self.start() # Inform main of our state change if not self.state == self.prevstate: self.sendState() self.prevstate = self.state
def doWork(self): # Start the telnet input server for stack commands self.telnet_in.start() self.syst = int(time.time() * 1000.0) self.fixdt = self.simdt self.fastforward() #Alexander. Always run simulations in fast-time if len(sys.argv)>1: #Alexander self.stack.openfile(str(sys.argv[1]) + '.scn') #Alexander. Open .scn file automatically while not self.mode == Simulation.end: # Timing bookkeeping self.samplecount += 1 # Update the Mode-S beast parsing self.beastfeed.update() # TODO: what to do with init if self.mode == Simulation.init: self.mode = Simulation.op if self.mode == Simulation.op: self.stack.checkfile(self.simt) # Always update stack self.stack.process(self, self.traf, self.screenio) if self.mode == Simulation.op: self.traf.update(self.simt, self.simdt) # Update metrics if self.metric is not None: self.metric.update(self, self.traf) # Update time for the next timestep self.simt += self.simdt if self.simt>50E3 and len(sys.argv)>1: #Alexander. Stop simulation if simt larger than 50000 s. self.stop() # Process Qt events QCoreApplication.processEvents() # When running at a fixed rate, increment system time with sysdt and calculate remainder to sleep if not self.ffmode: self.syst += self.sysdt remainder = self.syst - int(1000.0 * time.time()) if remainder > 0: QThread.msleep(remainder) elif self.ffstop is not None and self.simt >= self.ffstop: self.start()
def doWork(self): self.syst = int(time.time() * 1000.0) self.fixdt = self.simdt while self.running: # Timing bookkeeping self.samplecount += 1 # Update the Mode-S beast parsing self.beastfeed.update() # TODO: what to do with init if self.state == Simulation.init: if self.traf.ntraf > 0 or len(self.stack.scencmd) > 0: self.start() if self.state == Simulation.op: self.stack.checkfile(self.simt) # Always update stack self.stack.process(self, self.traf, self.screenio) if self.state == Simulation.op: self.traf.update(self.simt, self.simdt) # Update metrics self.metric.update(self, self) # Update log if self.datalog is not None: self.datalog.update(self) # Update time for the next timestep self.simt += self.simdt # Process Qt events self.manager.processEvents() # When running at a fixed rate, or when in hold/init, increment system time with sysdt and calculate remainder to sleep if not self.ffmode or not self.state == Simulation.op: self.syst += self.sysdt remainder = self.syst - int(1000.0 * time.time()) if remainder > 0: QThread.msleep(remainder) elif self.ffstop is not None and self.simt >= self.ffstop: self.start() # Inform main of our state change if not self.state == self.prevstate: self.sendState() self.prevstate = self.state
def __onlineStateChanged(self, online): """ Private slot handling online state changes. @param online online state @type bool """ self.connectButton.setEnabled(online) if online: # delay a bit because the signal seems to be sent before the # network interface is fully up QThread.msleep(200) self.__autoConnect() else: network = self.networkCombo.currentText() self.connectNetwork.emit(network, online, True)
def _read(self): self.inBlockingRead = True data = '' _data = None currTime = startTime = time.clock() while currTime < startTime+20: while self._inputQueue.qsize()>0: _data = self._inputQueue.get( block=True, timeout=20 ) data += str(_data ) if data: break currTime = time.clock() QThread.msleep(2) self.inBlockingRead = False if not data: raise ReaderCommunicationException( 'Timeout while reading after 20 second!') return data
def _threadedWrite(self): while self._doWork: if self._outputQueue.qsize()>0: bytes_written = 0 buffer = self._outputQueue.get() #send data to correct port if self._connectionType == EndicataConnectionType.RS232: bytes_written = self._connection.write( buffer ) elif self._connectionType == EndicataConnectionType.TCP: bytes_written = self._connection.send( buffer ) elif self._connectionType == EndicataConnectionType.USB: self._connection.put( buffer ) #raise ReaderCommunicationException("USB communication not implemented yet1!") else: raise ReaderCommunicationException("Unknown port type %s!", repr(self._connectionType)) #check correct size of written data if bytes_written < len(buffer): raise ReaderCommunicationException("Write to reader did not suceed, should write %d bytes insted of %d!" % (len(buffer), bytes_written)) logger.debug( 'BYTES SENT: %r', buffer ) print 'HEXBUFFER WRITE: ', hexify( buffer ) QThread.msleep(5) else: QThread.msleep(5)
def __compileSelectedResources(self): """ Private method to compile selected resources to source files. """ items = self.getSelectedItems() files = [self.project.getRelativePath(itm.fileName()) for itm in items] if self.hooks["compileSelectedResources"] is not None: self.hooks["compileSelectedResources"](files) else: numResources = len(files) progress = E5ProgressDialog( self.tr("Compiling resources..."), self.tr("Abort"), 0, numResources, self.tr("%v/%m Resources"), self) progress.setModal(True) progress.setMinimumDuration(0) progress.setWindowTitle(self.tr("Resources")) i = 0 for fn in files: progress.setValue(i) if progress.wasCanceled(): break if not fn.endswith('.ui.h'): proc = self.__compileQRC(fn, True, progress) if proc is not None: while proc.state() == QProcess.Running: QApplication.processEvents() QThread.msleep(300) QApplication.processEvents() else: break i += 1 progress.setValue(numResources)
def startSynchronizedProcess(self, proc, program, arguments, workingDir=None): """ Public method to start a synchroneous process. This method starts a process and waits for its end while still serving the Qt event loop. @param proc process to start (QProcess) @param program path of the executable to start (string) @param arguments list of arguments for the process (list of strings) @param workingDir working directory for the process (string) @return flag indicating normal exit (boolean) """ if proc is None: return if workingDir: proc.setWorkingDirectory(workingDir) proc.start(program, arguments) procStarted = proc.waitForStarted(5000) if not procStarted: E5MessageBox.critical( None, self.tr('Process Generation Error'), self.tr( 'The process {0} could not be started. ' 'Ensure, that it is in the search path.' ).format(program)) return False else: while proc.state() == QProcess.Running: QApplication.processEvents() QThread.msleep(300) QApplication.processEvents() return (proc.exitStatus() == QProcess.NormalExit) and \ (proc.exitCode() == 0)
def _threadedRead(self ): while self._doWork: data = None if self._connectionType == EndicataConnectionType.RS232: while self._doWork: if self._connection.in_waiting >= self.minBytes2Fetch: data = self._connection.read( self.minBytes2Fetch ) fullLength = self.calculatePackageSize( data ) b2r = fullLength - self.minBytes2Fetch while len(data)< fullLength: _buf = self._connection.read( b2r ) if _buf: _bufLen = len(_buf) data += _buf b2r = fullLength - _bufLen QThread.msleep(5) break else: QThread.msleep(5) elif self._connectionType == EndicataConnectionType.TCP: while self._doWork: data = self._connection.recv(1024) if data: break elif self._connectionType == EndicataConnectionType.USB: data = 'do not touch' else: raise ReaderCommunicationException("Unknown port type %s!" % repr(self._connectionType)) #put data into queue if self._doWork: if data <> 'do not touch': logger.debug( 'CHUNK BYTES RECEIVED: %r', data ) print 'HEXBUFFER RECV: ', hexify( data ) self._inputQueue.put( data ) if self.OnDataReceived: self.OnDataReceived( data )
def run( self ): cmd1, cmd2 = self.endicatorCmd.getCommands() tagInfo = self.tagInfo writeLagTime = 0.1 counter = 1 st = time.time() parseLoopExceptionCounter = 0 try: while parseLoopExceptionCounter < 10: val = '\xAA' data = '' rr = cmd1 if self.endicatorCmd.TO_FIX or self.endicatorCmd.TO_FIX_BR: rr += cmd2 + '\xFF' elif self.endicatorCmd.TO_FIX_ALSO: rr += cmd2 + '\x00\x00' elif self.endicatorCmd.TO_FIX_MORE: rr += cmd2 + '\x00\x00\x00' else: rr += cmd2 QThread.msleep( int(writeLagTime*150) ) if isinstance( self.reader, rfid.TMReader.TMReader): logger.debug( 'DATA SENT: %r', rr ) print 'HEXBUFFER SENT: ', hexify( rr ) result = self.reader.WriteToTag( tagInfo, 3, 0, rr) print 'Write Passed' if self.noRead: self.result = True break #wait for specified time before checking returned data print 'Waiting on endicator command for at least %d seconds' % self.endicatorCmd.expectedExecutionTime #logger.info( 'Waiting on endicator command for at least %d seconds', self.endicatorCmd.expectedExecutionTime ) startTime = time.time() while time.time() < startTime + self.endicatorCmd.expectedExecutionTime: QThread.msleep(500) print '.', notFound = True while val <> '\x55': data = self.reader.ReadFromTag( tagInfo, 3, 0, 1 ) if isinstance( self.reader, rfid.TMReader.TMReader): val = data[0] else: val = data.Value[0] if val == '\x55': notFound = False else: print repr(val) QThread.msleep(1000) print '.', counter += 1 if counter>20: data = None break if not notFound: if self.endicatorCmd.TO_FIX_ALSO: data = self.reader.ReadFromTag( tagInfo, 3, 0, self.endicatorCmd.expectedLength()+2 ) else: print 'EXPLEN', self.endicatorCmd.expectedLength() if isinstance( self.reader, rfid.TMReader.TMReader): data = self.reader.ReadFromTag( tagInfo, 3, 0, self.endicatorCmd.expectedLength()+1 ) else: data = self.reader.ReadFromTag( tagInfo, 3, 0, self.endicatorCmd.expectedLength()) if data: et = time.time() if self.endicatorCmd.TO_FIX_ALSO: if isinstance( self.reader, rfid.TMReader.TMReader): eData = data[1:-1] else: eData = data.Value[1:-1] else: if isinstance( self.reader, rfid.TMReader.TMReader): eData = data[1:] else: eData = data.Value[1:] self.endicatorCmd.receivedData = eData if isinstance( self.reader, rfid.TMReader.TMReader): logger.debug( 'CHUNK BYTES RECEIVED: %r, %r', data, eData ) print 'HEXBUFFER RECV: ', hexify( data ), hexify(eData) try: results = self.endicatorCmd.parseResponse() print 'Execution time: %.3f seconds (%d times)' % (et-st, counter) logger.info('Execution time: %.3f seconds (%d times)', et-st, counter) print self.result = results break except ParseException as e: logger.debug( 'ParseException: Parsing of result failed with msg: %s', e.message ) except ParseLoopException as p: print 'ParseLoopException: Parsing of result failed with loop msg: %s' % p.message logger.debug('ParseLoopException: Parsing of result failed with loop msg: %s', p.message) writeLagTime += 0.1 parseLoopExceptionCounter += 1 else: raise EndicataDataException( "Looped for 20 times without succesful response!" ) if parseLoopExceptionCounter >= 10: raise EndicataDataException( "10 repetitions of looped exception!" ) except Exception as e: print 'Exception in EE', e.message, traceback.format_exc() self.bucket.put( e )
def compileChangedResources(self): """ Public method to compile all changed resources to source files. """ if self.hooks["compileChangedResources"] is not None: self.hooks["compileChangedResources"]( self.project.pdata["RESOURCES"]) else: progress = E5ProgressDialog( self.tr("Determining changed resources..."), None, 0, 100, self.tr("%v/%m Resources")) progress.setMinimumDuration(0) progress.setWindowTitle(self.tr("Resources")) i = 0 # get list of changed resources changedResources = [] progress.setMaximum(len(self.project.pdata["RESOURCES"])) for fn in self.project.pdata["RESOURCES"]: progress.setValue(i) QApplication.processEvents() ifn = os.path.join(self.project.ppath, fn) if self.project.pdata["PROGLANGUAGE"][0] in \ ["Python", "Python2", "Python3"]: dirname, filename = os.path.split(os.path.splitext(ifn)[0]) ofn = os.path.join( dirname, self.RCFilenameFormatPython.format(filename)) elif self.project.pdata["PROGLANGUAGE"][0] == "Ruby": dirname, filename = os.path.split(os.path.splitext(ifn)[0]) ofn = os.path.join( dirname, self.RCFilenameFormatRuby.format(filename)) else: return if not os.path.exists(ofn) or \ os.stat(ifn).st_mtime > os.stat(ofn).st_mtime: changedResources.append(fn) elif self.__checkResourcesNewer(ifn, os.stat(ofn).st_mtime): changedResources.append(fn) i += 1 progress.setValue(i) QApplication.processEvents() if changedResources: progress.setLabelText( self.tr("Compiling changed resources...")) progress.setMaximum(len(changedResources)) i = 0 progress.setValue(i) QApplication.processEvents() for fn in changedResources: progress.setValue(i) proc = self.__compileQRC(fn, True, progress) if proc is not None: while proc.state() == QProcess.Running: QApplication.processEvents() QThread.msleep(300) QApplication.processEvents() else: break i += 1 progress.setValue(len(changedResources)) QApplication.processEvents()
def run(self): while self._do_run: self.tick() QThread.msleep(1000) self.deleteLater()
def __init__(self, navdb): super(Gui, self).__init__([]) self.acdata = ACDataEvent() self.navdb = navdb self.radarwidget = [] self.command_history = [] self.cmdargs = [] self.history_pos = 0 self.command_mem = '' self.command_line = '' self.prev_cmdline = '' self.simevent_target = 0 self.mousepos = (0, 0) self.prevmousepos = (0, 0) self.panzoomchanged = False # Register our custom pan/zoom event for etype in [PanZoomEventType, ACDataEventType, SimInfoEventType, StackTextEventType, ShowDialogEventType, DisplayFlagEventType, RouteDataEventType, DisplayShapeEventType]: reg_etype = QEvent.registerEventType(etype) if reg_etype != etype: print('Warning: Registered event type differs from requested type id (%d != %d)' % (reg_etype, etype)) self.splash = Splash() self.splash.show() self.splash.showMessage('Constructing main window') self.processEvents() # Install error message handler handler = QErrorMessage.qtHandler() handler.setWindowFlags(Qt.WindowStaysOnTopHint) # Check and set OpenGL capabilities if not QGLFormat.hasOpenGL(): raise RuntimeError('No OpenGL support detected for this system!') else: f = QGLFormat() f.setVersion(3, 3) f.setProfile(QGLFormat.CoreProfile) f.setDoubleBuffer(True) QGLFormat.setDefaultFormat(f) print('QGLWidget initialized for OpenGL version %d.%d' % (f.majorVersion(), f.minorVersion())) # Create the main window and related widgets self.radarwidget = RadarWidget(navdb) self.win = MainWindow(self, self.radarwidget) self.nd = ND(shareWidget=self.radarwidget) # Enable HiDPI support (Qt5 only) if QT_VERSION == 5: self.setAttribute(Qt.AA_UseHighDpiPixmaps) timer = QTimer(self) timer.timeout.connect(self.radarwidget.updateGL) timer.timeout.connect(self.nd.updateGL) timer.start(50) # Load geo data if False: pb = QProgressDialog('Binary buffer file not found, or file out of date: Constructing vertex buffers from geo data.', 'Cancel', 0, 100) pb.setWindowFlags(Qt.WindowStaysOnTopHint) pb.show() for i in range(101): pb.setValue(i) self.processEvents() QThread.msleep(100) pb.close()
def doWork(self): self.syst = int(time.time() * 1000.0) self.fixdt = self.simdt # Open scenario file automatically if '--node' in sys.argv: stack.openfile(str(var_name)+'.scn') else: stack.openfile('scenariotest.scn') while self.running: # Stop simulation automatically if self.simt > 40E3: self.stop() # Datalog pre-update (communicate current sim time to loggers) datalog.preupdate(self.simt) # Update screen logic self.screenio.update() # Update the Mode-S beast parsing self.beastfeed.update() # Simulation starts as soon as there is traffic, or pending commands if self.state == Simulation.init: if self.traf.ntraf > 0 or len(stack.get_scendata()[0]) > 0: self.start() if self.benchdt > 0.0: self.fastforward(self.benchdt) self.bencht = time.time() if self.state == Simulation.op: stack.checkfile(self.simt) # Always update stack stack.process(self, self.traf, self.screenio) if self.state == Simulation.op: self.traf.update(self.simt, self.simdt) # Update metrics self.metric.update(self) # Update loggers datalog.postupdate() # Update time for the next timestep self.simt += self.simdt # Update clock self.simtclock = (self.deltclock + self.simt) % onedayinsec # Process Qt events self.manager.processEvents() # When running at a fixed rate, or when in hold/init, increment system time with sysdt and calculate remainder to sleep if not self.ffmode or not self.state == Simulation.op: self.syst += self.sysdt remainder = self.syst - int(1000.0 * time.time()) if remainder > 0: QThread.msleep(remainder) elif self.ffstop is not None and self.simt >= self.ffstop: if self.benchdt > 0.0: self.screenio.echo('Benchmark complete: %d samples in %.3f seconds.' % (self.screenio.samplecount, time.time() - self.bencht)) self.benchdt = -1.0 self.pause() else: self.start() # Inform main of our state change if not self.state == self.prevstate: self.sendState() self.prevstate = self.state