Exemplo n.º 1
0
 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)
Exemplo n.º 2
0
 def __init__(self, BluetoothMetadata):
     QThread.__init__(self)
     self.btmd = BluetoothMetadata
     self.isRunning = True
     self.currArtist = ""
     self.currAlbum = ""
     self.currTitle = ""
Exemplo n.º 3
0
    def get_metadata(self, gal=None):
        thread = QThread(self)
        thread.setObjectName("App.get_metadata")
        fetch_instance = fetch.Fetch()
        if gal:
            galleries = [gal]
        else:
            if gui_constants.CONTINUE_AUTO_METADATA_FETCHER:
                galleries = [g for g in self.manga_list_view.gallery_model._data if not g.exed]
            else:
                galleries = self.manga_list_view.gallery_model._data
            if not galleries:
                self.notification_bar.add_text("Looks like we've already gone through all galleries!")
                return None
        fetch_instance.galleries = galleries

        self.notification_bar.begin_show()
        fetch_instance.moveToThread(thread)

        def done(status):
            self.notification_bar.end_show()
            fetch_instance.deleteLater()

        fetch_instance.GALLERY_PICKER.connect(self._web_metadata_picker)
        fetch_instance.GALLERY_EMITTER.connect(self.manga_list_view.replace_edit_gallery)
        fetch_instance.AUTO_METADATA_PROGRESS.connect(self.notification_bar.add_text)
        thread.started.connect(fetch_instance.auto_web_metadata)
        fetch_instance.FINISHED.connect(done)
        thread.finished.connect(thread.deleteLater)
        thread.start()
Exemplo n.º 4
0
    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
Exemplo n.º 5
0
    def on_thing_requested(self, thing, callback):
        if self.quit:
            self.sig_thing_finished.emit("aborted-" + thing + "-Work", callback)
            return

        QThread.sleep(1)
        self.sig_thing_finished.emit(thing + "-Work", callback)
Exemplo n.º 6
0
 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
Exemplo n.º 7
0
 def __init__(self, countchannel, triggerchannel, binwidth, roistart, roistop, filename=None, parent = None, FPGASerial="A6VTOYBO"):
     QThread.__init__(self, parent)
     self.channel = countchannel
     self.triggerchannel = triggerchannel
     self.binwidth = binwidth
     self.roistart = roistart
     self.roistop = roistop
     self.numberOfBins = (roistop-roistart)/binwidth+1
     self.histogram = numpy.zeros(self.numberOfBins)
     self.exiting = False
     self.crc8 = crcmod.mkCrcFun(poly=0x107, initCrc=0xff, xorOut=0x00, rev=False)
     self.Connection = ftd2xx.openEx(FPGASerial);
     self.Connection.setBaudRate(3000000)
     self.Connection.setDataCharacteristics(8, 0, 0)
     self.Connection.setFlowControl(0, 0, 0)
     self.Connection.setTimeouts(500, 500)
     self.Connection.resetDevice()
     self.Connection.purge()
     self.integration_time = 100.0;
     command = struct.pack('>BBBI', 0x10, 0, 0x11, int(500*50000 )  )
     self.Connection.write(command)    
     command = struct.pack('>BB', 0x12, 0x0  )
     self.Connection.write(command)    
     self.Mutex = QMutex()
     self.filename = filename
     self.binfile = None
     if self.filename is not None:
         self.binfile = open(self.filename, 'wb')
     self.clearStatus()
     self.maxPretriggerPhotons = 1000000
Exemplo n.º 8
0
 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()
Exemplo n.º 9
0
    def direct(self, flows):
        flownum = 0
        child_types = []
        for flownum, flow in enumerate(flows, start=1):
            self.raw_line.emit("Flow {0}: {1} -> {2}".format(flownum, flow.source, flow.target))
            for rule in sorted(flow.rules):
                self.raw_line.emit("    {0}".format(rule))

            self.raw_line.emit("")

            # Generate results for flow browser
            if self.out:
                child_types.append((flow.target, sorted(str(r) for r in flow.rules)))
            else:
                child_types.append((flow.source, sorted(str(r) for r in flow.rules)))

            if QThread.currentThread().isInterruptionRequested():
                break
            else:
                QThread.yieldCurrentThread()

        self.raw_line.emit("{0} information flow(s) found.\n".format(flownum))
        self.log.info("{0} information flow(s) found.".format(flownum))

        # Update browser:
        root_type = self.query.source if self.out else self.query.target
        self.flows.emit(str(root_type), self.out, sorted(child_types))
Exemplo n.º 10
0
class PreviewParent(QObject):
    """ Class which communicates with the PlayerWorker Class (running on a separate thread) """

    # Signal when the frame position changes in the preview player
    def onPositionChanged(self, current_frame):
        self.parent.movePlayhead(current_frame)

    # Signal when the playback mode changes in the preview player (i.e PLAY, PAUSE, STOP)
    def onModeChanged(self, current_mode):
        log.info('onModeChanged')

    @pyqtSlot(object, object)
    def Init(self, parent, timeline, video_widget):
        # Important vars
        self.parent = parent
        self.timeline = timeline

        # Background Worker Thread (for preview video process)
        self.background = QThread(self)
        self.worker = PlayerWorker()  # no parent!

        # Init worker variables
        self.worker.Init(parent, timeline, video_widget)

        # Hook up signals to Background Worker
        self.worker.position_changed.connect(self.onPositionChanged)
        self.worker.mode_changed.connect(self.onModeChanged)
        self.background.started.connect(self.worker.Start)
        self.worker.finished.connect(self.background.quit)

        # Move Worker to new thread, and Start
        self.worker.moveToThread(self.background)
        self.background.start()
Exemplo n.º 11
0
 def __init__(self):
     QThread.__init__(self)
     self._queue = queue.Queue()
     self.start(QThread.LowPriority)
     self._ac = AsyncController('QThread', self)
     self._ac.defaultPriority = QThread.LowPriority
     self._SphinxInvocationCount = 1
Exemplo n.º 12
0
Arquivo: dta.py Projeto: jakev/setools
    def direct(self, transitions):
        i = 0
        child_types = []
        for i, step in enumerate(transitions, start=1):
            self.raw_line.emit("Transition {0}: {1} -> {2}\n".format(i, step.source, step.target))
            sort_transition(step)
            print_transition(self.raw_line.emit, step)

            # Generate results for flow browser
            if self.out:
                child_types.append((step.target, step))
            else:
                child_types.append((step.source, step))

            if QThread.currentThread().isInterruptionRequested():
                break
            else:
                QThread.yieldCurrentThread()

        self.raw_line.emit("{0} domain transition(s) found.".format(i))
        self.log.info("{0} domain transition(s) found.".format(i))

        # Update browser:
        root_type = self.query.source if self.out else self.query.target
        self.trans.emit(str(root_type), self.out, sorted(child_types))
Exemplo n.º 13
0
	def start_msg_thread(self, runningObjectParam, onRun = None, onDone = None, onErrorMsg = None, onSuccessMsg = None ):
		
		if self.running:
			return
					
		self.running = True
		
		thr = QThread()
		thrName = 'EndicataLabToolMainWnd start_msg_thread[%d]' % (len( self.threadPool ) + 1)
		print thrName
		thr.setObjectName( thrName )
		self.threadPool.append( thr )
		
		self.runningObject = runningObjectParam
		self.runningObject.moveToThread(thr)
		if onRun:
			thr.started.connect( onRun )
		else:
			thr.started.connect( self.runningObject.run )

		self.runningObject.finished.connect( self.onUnlock )
		
		if onDone:
			self.runningObject.done.connect( onDone )
		if onErrorMsg:
			self.runningObject.errorMsg.connect( onErrorMsg )
		if onSuccessMsg:
			self.runningObject.successMsg.connect( onSuccessMsg )
		thr.start()
Exemplo n.º 14
0
 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)
Exemplo n.º 15
0
    def __init__(self, courseName, banList, sock):
        QThread.__init__(self)

        self.courseName = courseName
        self.banList = banList
        self.sock = sock
        self.pid = os.getpid()
        self.connecList = []

        self.clientOS = platform.system()
        self.tempIndex = 0

        self.ext = ''
        self.thispid = os.getpid()

        if self.clientOS == config.config.OS_WINDOWS:
            self.dirSeperator = config.config.WINDOWS_DIRECTORY_SEPARATOR
            self.ext = '.exe'

        else:
            self.dirSeperator = config.config.LINUX_DIRECTORY_SEPARATOR

        try:
            self.pre_check()
            time.sleep(1)

        except Exception as e:
            print(e)
Exemplo n.º 16
0
 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)
Exemplo n.º 17
0
    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
Exemplo n.º 18
0
 def __init__(self, wm, processor):
     self.event_queue = list()
     self._processor = processor
     self.notifier = Notifier(wm, NinjaProcessEvent(
         self.event_queue.append))
     self.notifier.coalesce_events(True)
     self.keep_running = True
     QThread.__init__(self)
Exemplo n.º 19
0
 def __init__(self, panel, tconfig):
     QThread.__init__(self)
     self.local_dpy = display.Display()
     self.record_dpy = display.Display()
     self.tconfig = tconfig
     self.panel = panel
     self.keymap = self.tconfig.focus_keymap
     self.received_keys = list()
Exemplo n.º 20
0
    def __init__(self, map_queue, exchange_queues, map_limits):

        QThread.__init__(self)
        self.map_queue = map_queue
        self.exchange_queues = exchange_queues
        self.map_limits = map_limits
        
        self.speed = 0.01  # In seconds
Exemplo n.º 21
0
 def __init__(self, view, function, message=None,
              on_end_function=None, on_exception_function=None):
     QThread.__init__(self)
     self._view = view
     self._function = function
     self._message = message
     self._on_end_function = on_end_function
     self._on_exception_function = on_exception_function
Exemplo n.º 22
0
    def initControllers(self):
        self.playerBinThread = QThread()
        gPlayer.moveToThread(self.playerBinThread)
        self.playerBinThread.start()

        self.dbThread = QThread()
        dbWorker.moveToThread(self.dbThread)
        self.dbThread.start()
Exemplo n.º 23
0
 def __init__(self, accurate_url, city, suffix, parent=None):
     QThread.__init__(self, parent)
     self.accurate_url = accurate_url
     # Search in any language
     self.city = city  # self.encode_utf8(city)
     self.suffix = suffix
     self.tentatives = 1
     self.settings = QSettings()
Exemplo n.º 24
0
    def __init__(self, parent = None):
        QThread.__init__(self, parent)

        self.problemMap = None
        self.population = None
        self.selector = None
        self.crosser = None
        self.mutator = None
    def __init__(self, input):
        QThread.__init__(self)

        self._input = input
        self._read_timer = QTimer()
        self._read_timer.setInterval(25)

        self._read_timer.timeout.connect(self._read_input)
Exemplo n.º 26
0
 def __init__(self, urlin, pathin, token, type, progress,  options):
     QThread.__init__(self)
     self.urlin = urlin
     self.pathin = pathin
     self.token = token
     self.type = type
     self.progressBar = progress
     self.options = options
Exemplo n.º 27
0
 def __init__(self, config, keyboard_emulation):
     StenoEngine.__init__(self, config, keyboard_emulation)
     QThread.__init__(self)
     self._signals = {}
     for hook in self.HOOKS:
         signal = getattr(self, 'signal_' + hook)
         self.hook_connect(hook, signal.emit)
         self._signals[hook] = signal
Exemplo n.º 28
0
    def __init__(self, port, baudrate, parent=None):
        QThread.__init__(self, parent)

        self.port = port
        self.baudrate = baudrate
        self.serial_connection = None
        self.exiting = False
        self.matrix = None
Exemplo n.º 29
0
 def __init__(self, files, destination, extr, shema=None, password=None, port=None, report=False):
     QThread.__init__(self)
     self.files = files
     self.destination = destination
     self.extr = extr
     self.report = report
     self.shema = shema
     self.password = password
     self.port = port
Exemplo n.º 30
0
    def run(self):
        self.pre_run(False)

        while self.running:
            self.model.dut_exist = self.check_dut()

            QThread.sleep(1)

        self.post_run(False)
Exemplo n.º 31
0
    def __init__(self, log, key):
        super().__init__('KHOPENAPI.KHOpenAPICtrl.1')
        WookLog.custom_init(self, log)
        WookUtil.__init__(self)

        # Password
        wc = WookCipher(key)
        wc.decrypt_data()
        self.login_id = wc.login_id
        self.login_password = wc.login_password
        self.account_password = wc.account_password
        self.certificate_password = wc.certificate_password

        # Eventloop
        self.login_event_loop = QEventLoop()
        self.event_loop = QEventLoop()
        self.timer_event_loop = QEventLoop()
        self.wook_timer = WookTimer(self.timer_event_loop)

        # Chart
        self.draw_chart = ChartDrawer()
        self.chart_prices = list()
        self.min_timer = QTimer()
        self.min_timer.setInterval(60000)
        self.min_timer.timeout.connect(self.on_every_min)

        # Requesters
        self.deposit_requester = QThread()
        self.moveToThread(self.deposit_requester)
        self.deposit_requester.started.connect(self.request_deposit_info)
        self.portfolio_requester = QThread()
        self.moveToThread(self.portfolio_requester)
        self.portfolio_requester.started.connect(self.request_portfolio_info)
        self.order_history_requester = QThread()
        self.moveToThread(self.order_history_requester)
        self.order_history_requester.started.connect(self.request_order_history)

        self.request_time = 0
        self.request_interval_limit = 0.5
        self.order_position = ''

        # Signals
        self.log = None
        self.signal = None
        self.status = None

        # Deposit
        self.account_list = None
        self.account_number = 0
        self.deposit = 0
        self.withdrawable_money = 0
        self.orderable_money = 0

        # Items and Orders
        self.portfolio = dict()
        self.monitoring_items = dict()
        self.balance = dict()
        self.open_orders = dict()
        self.order_history = dict()
        self.algorithm = None

        # Pending order
        self.pending_order = None
        self.cancel_confirmed = False
        self.cancel_order_number = 0

        # Request limit
        self.inquiry_count = 0
        self.previous_time = 0.0
        self.reference_time = Queue()
        self.reference_time_interval_limit = 20
        self.consecutive_interval_limit = 0.25
        self.request_block_time_limit = 5
        self.request_block_size = 10
        self.request_count = 0
        self.request_count_threshold = 90
        self.request_count_interval = 60
        self.request_count_waiting = 30

        # Fee and Tax
        self.fee_ratio = 0.0035
        self.tax_ratio = 0.0023

        # Screen numbers
        self.screen_account = '0010'
        self.screen_open_order = '0020'
        self.screen_operation_state = '0040'
        self.screen_portfolio = '0060'
        self.screen_send_order = '0080'
        self.screen_stock_price = '0120'
        self.screen_futures_stock_price = '0140'
        self.screen_test = '9999'
Exemplo n.º 32
0
 def __init__(self, adblocker):
     QThread.__init__(self)
     self.moveToThread(self)
     self.adblocker = adblocker
 def __init__(self, bn):
     self.bn = bn
     QThread.__init__(self)
Exemplo n.º 34
0
 def __init__(self, UI):
     QThread.__init__(self)
     self.UI = UI
Exemplo n.º 35
0
 def __init__(self, device='ME', tag='TAG', environment=ENV):
     QThread.__init__(self)
     SkelDataRec.__init__(self,
                          device=device,
                          tag=tag,
                          environment=environment)
Exemplo n.º 36
0
    def search(self):
        plots_found = []
        features_not_found = []

        fields = PLOTS_LAYER_DEFAULT_FIELDS + self.additional_output_fields

        self.layer_found.startEditing()
        self.layer_found.dataProvider().addAttributes(fields)
        
        self.layer_not_found.startEditing()
        self.layer_not_found.dataProvider().addAttributes([
            QgsField("tresc_bledu", QVariant.String),
        ])

        features = []
        features_iterator = self.source_layer.getSelectedFeatures() if self.selected_only else self.source_layer.getFeatures()
        source_crs = self.source_layer.sourceCrs()
        if source_crs != CRS_2180:
            transformation = (QgsCoordinateTransform(source_crs, CRS_2180, QgsCoordinateTransformContext()))
            for f in features_iterator:
                point = f.geometry().asPoint()
                point = transformation.transform(point)
                f.setGeometry(QgsGeometry.fromPointXY(point))
                features.append(f)
        else:
            transformation = None
            features = features_iterator

        uldk_search = uldk_api.ULDKSearchPoint(
            "dzialka",
            ("geom_wkt", "wojewodztwo", "powiat", "gmina", "obreb","numer","teryt"))


        found_features = []

        for source_feature in features:
            if QThread.currentThread().isInterruptionRequested():
                self.__commit()
                self.interrupted.emit(self.layer_found, self.layer_not_found)
                return

            skip = False
            for found_feature in found_features:
                if found_feature.geometry().intersects(source_feature.geometry()):
                    if not self.skip_duplicates:
                        self.layer_found.dataProvider().addFeature(found_feature)
                    skip = True
            if skip:
                self.progressed.emit(True,  1 if self.skip_duplicates else 0)
                continue

            point = source_feature.geometry().asPoint()
            uldk_point = uldk_api.ULDKPoint(point.x(), point.y(), 2180)
        
            try:
                uldk_response_row = uldk_search.search(uldk_point)
                additional_attributes = []
                for field in self.additional_output_fields:
                    additional_attributes.append(source_feature[field.name()])
                try:
                    found_feature = uldk_response_to_qgs_feature(uldk_response_row, additional_attributes)
                except BadGeometryException:
                    raise BadGeometryException("Niepoprawna geometria")
                found_features.append(found_feature)
                self.layer_found.dataProvider().addFeature(found_feature)
                self.progressed.emit(True, 0)
            except Exception as e:
                not_found_feature = self.__make_not_found_feature(source_feature.geometry(), e)
                self.layer_not_found.dataProvider().addFeature(not_found_feature)
                self.progressed.emit(False, 0)
            
        self.__commit()
        self.finished.emit(self.layer_found, self.layer_not_found)
Exemplo n.º 37
0
 def __init__(self, time):
     QThread.__init__(self)
     self.time = float(int(time) / 1000)
Exemplo n.º 38
0
    win = QtWidgets.QMainWindow()
    area = DockArea()
    win.setCentralWidget(area)
    win.resize(1000, 500)
    win.setWindowTitle('pymodaq main')

    prog = DAQ_Viewer(area, title="Testing2D", DAQ_type='DAQ2D')
    prog2 = DAQ_Viewer(area, title="Testing1D", DAQ_type='DAQ1D')
    prog3 = DAQ_Viewer(area, title="Testing0D", DAQ_type='DAQ0D')

    act1_widget = QtWidgets.QWidget()
    act2_widget = QtWidgets.QWidget()
    act1 = DAQ_Move(act1_widget, title='X_axis')
    act2 = DAQ_Move(act2_widget, title='Y_axis')

    QThread.msleep(1000)
    prog.ui.IniDet_pb.click()
    prog2.ui.IniDet_pb.click()
    prog3.ui.IniDet_pb.click()

    dock1 = Dock('actuator 1')
    dock1.addWidget(act1_widget)
    area.addDock(dock1)

    dock2 = Dock('actuator 2')
    dock2.addWidget(act2_widget)
    area.addDock(dock2)

    act1.ui.IniStage_pb.click()
    act2.ui.IniStage_pb.click()
 def __init__(self):
     QThread.__init__(self)
Exemplo n.º 40
0
 def _reset_thread(self):
     if self.thread:
         self.thread.terminate()
     self.thread = QThread(self)
     return self.thread
Exemplo n.º 41
0
 def __init__(self, drinkId):
     QThread.__init__(self)
     self.drinkId = drinkId
Exemplo n.º 42
0
 def __init__(self, main_window):
     QThread.__init__(self)
     Logger.__init__(self)
     self.main_window = main_window
Exemplo n.º 43
0
 def __init__(self, raimixer_object: RaiMixer) -> None:
     QThread.__init__(self)
     self.mixer = raimixer_object
     self.mixer.set_print_func(lambda txt: self.text_available.emit(txt))
Exemplo n.º 44
0
 def __init__(self, wallet, account, delete_empty=False) -> None:
     QThread.__init__(self)
     self.wallet = wallet
     self.account = account
     self.delete_empty = delete_empty
Exemplo n.º 45
0
class Mid(QObject):
    sig_settings = pyqtSignal(dict)

    def __init__(self, parent=None):
        super(self.__class__, self).__init__(parent)

        self.gui = QtWidgets.QDialog()
        self.ui = Ui_Dialog()
        self.ui.setupUi(self.gui)

        self.worker = Worker()
        self.worker_thread = QThread()
        self.worker.moveToThread(self.worker_thread)
        self.worker_thread.start()
        # self.worker_thread.daemon = True

        self._connectSignals()
        self.gui.show()

    def transmit(self):
        if self.ui.inputValidation() == False:
            return

        d = {}
        d['checkbox'] = {
            'image': self.ui.imageCheck.isChecked(),
            'tag': self.ui.tagCheck.isChecked(),
            'youtube': self.ui.youtubeCheck.isChecked()
        }
        d['blogName'] = self.ui.blogName.text()
        d['accessToken'] = self.ui.accessToken.text()
        d['dir'] = self.ui.saveDir.text()
        d['startNum'] = int(self.ui.startNum.text())
        d['endNum'] = int(self.ui.endNum.text())

        self.ui.pushSettingBtn()
        self.sig_settings.emit(d)

    def _connectSignals(self):
        self.ui.startBtn.clicked.connect(self.worker.startWork)
        self.ui.settingBtn.clicked.connect(self.transmit)
        self.ui.stopBtn.clicked.connect(self.forceWorkerReset)
        self.ui.saveDirBtn.clicked.connect(self.openDir)

        self.sig_settings.connect(self.worker.set)

        self.worker.sig_clearStatus.connect(self.pushStart)
        self.worker.sig_message.connect(self.ui.status.appendPlainText)
        self.worker.sig_end.connect(self.forceWorkerReset)

    def openDir(self):
        fname = QFileDialog.getExistingDirectory(self.gui, 'Open Folder',
                                                 os.getcwd())
        self.ui.saveDir.setText(fname)

    @pyqtSlot()
    def pushStart(self):
        self.ui.pushStartBtn()

    def forceWorkerReset(self):
        if self.worker_thread.isRunning():
            self.worker_thread.terminate()
            self.worker_thread.wait()
            self.worker_thread.start()
        self.ui.buttonInit()
        f = open('log.txt', 'w')
        f.write(self.ui.status.toPlainText())
Exemplo n.º 46
0
 def __init__(self, var):
     QThread.__init__(self)
     self.moveToThread(self)
     self.value = 0
     self.var = var
Exemplo n.º 47
0
class ResCalc(QtWidgets.QWidget, output.Ui_Form):
    def __init__(self, func, pos, path):
        super().__init__()
        self.setupUi(self)

        self.lang = None
        self.func = func

        self.is_process = False
        self.text = []  #Soutput
        self.ind = [0, 11]
        self.output.setStyleSheet("color: white;")

        self.recv.connect(self.reciver)

        self.path = os.path.abspath(__file__)
        self.curdir = os.path.dirname(self.path)
        self.img = QtGui.QImage(self.curdir + "/init.jpg")
        self.palette = QtGui.QPalette()
        self.palette.setBrush(QtGui.QPalette.Window, QtGui.QBrush(self.img))
        self.setPalette(self.palette)

        self.convertor = morse_handler.Convertor(self, path, self.lang)

        self.thread = QThread()
        self.thread.start()
        self.convertor.moveToThread(self.thread)

        self.setWindowFlags(Qt.FramelessWindowHint)
        self.move(pos["x"], pos["y"])

        self.pushButton.setFlat(True)
        self.pushButton.setStyleSheet("color: white;")
        self.pushButton.clicked.connect(self.presHandl)

        self.output.setWordWrap(True)

    recv = pyqtSignal(str)

    def path_update(self, path):
        self.convertor.srFile = path

    def lang_update(self, lang):
        self.convertor.lang = lang

    def presHandl(self):
        if len(self.text) > 0:
            self.func("rescalc close")
        else:
            self.is_process = True
            self.pushButton.setText("computing")
            self.pushButton.setStyleSheet("color: rgb(157, 100, 255);")
            self.pushButton.setEnabled(False)
            self.convertor.run_trigger.emit()

    def reciver(self, msg):
        buff = []
        if msg[:4] == "info":
            buff.append(msg[4:])

        elif msg[:4] == "puls":
            buff.append("\n------- binary representation--------\n")
            buff = self.msg_split(buff, msg[4:], 100)

        elif msg[:4] == "mesg":
            buff.append("\n------- decoded text-------\n")
            buff = self.msg_split(buff, msg[4:], 50)

        elif msg == "finished":
            self.is_process = False
            self.pushButton.setEnabled(True)
            self.pushButton.setText("CLOSE")

        elif msg == "err":
            buff.append("\n\nIncorrect file")
            self.is_process = False

        elif msg == "force qiut":
            self.func("rescalc return")

        self.output_update(buff=buff)

    def msg_split(self, buff, msg, tresh):
        while len(msg) > tresh:
            buff.append(msg[:tresh])
            msg = msg[tresh:]
        buff.append(msg)
        return buff

    def output_update(self, buff=None, move=None):
        if not move is None and len(self.text) > 11:
            if move and self.ind[0] > 0:
                self.ind[0], self.ind[1] = self.ind[0] - 1, self.ind[1] - 1
            elif not move and self.ind[1] < len(self.text) - 1:
                self.ind[0], self.ind[1] = self.ind[0] + 1, self.ind[1] + 1
        else:
            for i in range(len(buff)):
                self.text.append(buff[i])

            self.ind[0], self.ind[1] = len(self.text) - 11, len(self.text) - 1
        out_str = ""
        if len(self.text) > 11:
            for i in range(self.ind[0], self.ind[1] + 1):
                out_str += self.text[i] + "\n"
        else:
            for i in range(len(self.text)):
                out_str += self.text[i] + "\n"
        self.output.setText(out_str)

    def reset(self):
        self.text = ""
        self.output.setText(self.text)
        self.pushButton.setText("START")

    def keyPressEvent(self, event):
        if event.key() == Qt.Key_Enter or event.key() == Qt.Key_Return:
            if not self.is_process: self.presHandl()

        if event.key() == Qt.Key_Escape:
            if self.is_process:
                reply = QtWidgets.QMessageBox.question(
                    self, 'Action',
                    "Do you want to stop recording\nand\nreturn to Start window?",
                    QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No,
                    QtWidgets.QMessageBox.No)
                if reply == QtWidgets.QMessageBox.Yes:
                    self.convertor.stop_trigger.emit()

            else:
                reply = QtWidgets.QMessageBox.question(
                    self, 'Action', "Close APP?",
                    QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No,
                    QtWidgets.QMessageBox.No)
                if reply == QtWidgets.QMessageBox.Yes:
                    self.func("rescalc close")
        elif event.key() == Qt.Key_Up:
            self.output_update(move=True)

        elif event.key() == Qt.Key_Down:
            self.output_update(move=False)

        elif event.modifiers() == Qt.ControlModifier:
            if event.key() == Qt.Key_R:
                self.pushButton.setStyleSheet("color: rgb(255, 10, 80);")
                self.convertor.report = "pdf"
 def __init__(self):
     QThread.__init__(self)
     self.url = ""
     self.secim = 0
     self.d_ses = ''
     self.d_video = ''
Exemplo n.º 49
0
 def __init__(self, mw):
     self.mw = mw
     QThread.__init__(self)
Exemplo n.º 50
0
class DefaultQueryTab(AnalysisTab):

    """Default browser and query tab."""

    section = AnalysisSection.Other
    tab_title = "Defaults"
    mlsonly = False

    def __init__(self, parent, policy, perm_map):
        super(DefaultQueryTab, self).__init__(parent)
        self.log = logging.getLogger(__name__)
        self.policy = policy
        self.query = DefaultQuery(policy)
        self.setupUi()

    def __del__(self):
        with suppress(RuntimeError):
            self.thread.quit()
            self.thread.wait(5000)

        logging.getLogger("setools.defaultquery").removeHandler(self.handler)

    def setupUi(self):
        self.load_ui("apol/defaultquery.ui")

        # set up results
        self.table_results_model = DefaultTableModel(self)
        self.sort_proxy = QSortFilterProxyModel(self)
        self.sort_proxy.setSourceModel(self.table_results_model)
        self.table_results.setModel(self.sort_proxy)
        self.table_results.sortByColumn(1, Qt.AscendingOrder)

        # populate class list
        self.class_model = SEToolsListModel(self)
        self.class_model.item_list = sorted(self.policy.classes())
        self.tclass.setModel(self.class_model)

        # these two lists have empty string as their first item
        # (in the .ui file):
        # populate default value list
        for i, e in enumerate(DefaultValue, start=1):
            self.default_value.insertItem(i, e.name, e)

        # populate default range value list
        for i, e in enumerate(DefaultRangeValue, start=1):
            self.default_range_value.insertItem(i, e.name, e)

        # set up processing thread
        self.thread = QThread()
        self.worker = QueryResultsUpdater(self.query, self.table_results_model)
        self.worker.moveToThread(self.thread)
        self.worker.raw_line.connect(self.raw_results.appendPlainText)
        self.worker.finished.connect(self.update_complete)
        self.worker.finished.connect(self.thread.quit)
        self.thread.started.connect(self.worker.update)

        # create a "busy, please wait" dialog
        self.busy = QProgressDialog(self)
        self.busy.setModal(True)
        self.busy.setRange(0, 0)
        self.busy.setMinimumDuration(0)
        self.busy.canceled.connect(self.thread.requestInterruption)
        self.busy.reset()

        # update busy dialog from query INFO logs
        self.handler = LogHandlerToSignal()
        self.handler.message.connect(self.busy.setLabelText)
        logging.getLogger("setools.defaultquery").addHandler(self.handler)

        # Ensure settings are consistent with the initial .ui state
        self.default_range_value.setEnabled(self.default_range.isChecked())
        self.notes.setHidden(not self.notes_expander.isChecked())

        # connect signals
        self.default_range.toggled.connect(self.default_range_value.setEnabled)
        self.clear_ruletypes.clicked.connect(self.clear_all_ruletypes)
        self.all_ruletypes.clicked.connect(self.set_all_ruletypes)
        self.tclass.selectionModel().selectionChanged.connect(self.set_tclass)
        self.invert_class.clicked.connect(self.invert_tclass_selection)
        self.buttonBox.clicked.connect(self.run)

    #
    # Ruletype criteria
    #
    def _set_ruletypes(self, value):
        self.default_user.setChecked(value)
        self.default_role.setChecked(value)
        self.default_type.setChecked(value)
        self.default_range.setChecked(value)

    def set_all_ruletypes(self):
        self._set_ruletypes(True)

    def clear_all_ruletypes(self):
        self._set_ruletypes(False)

    #
    # Class criteria
    #
    def set_tclass(self):
        selected_classes = []
        for index in self.tclass.selectionModel().selectedIndexes():
            selected_classes.append(self.class_model.data(index, Qt.UserRole))

        self.query.tclass = selected_classes

    def invert_tclass_selection(self):
        invert_list_selection(self.tclass.selectionModel())

    #
    # Save/Load tab
    #
    def save(self):
        """Return a dictionary of settings."""
        settings = {}
        save_checkboxes(self, settings, ["criteria_expander", "notes_expander", "default_user",
                                         "default_role", "default_type", "default_range"])
        save_comboboxes(self, settings, ["default_value", "default_range_value"])
        save_listviews(self, settings, ["tclass"])
        save_textedits(self, settings, ["notes"])
        return settings

    def load(self, settings):
        load_checkboxes(self, settings, ["criteria_expander", "notes_expander", "default_user",
                                         "default_role", "default_type", "default_range"])
        load_comboboxes(self, settings, ["default_value", "default_range_value"])
        load_listviews(self, settings, ["tclass"])
        load_textedits(self, settings, ["notes"])

    #
    # Results runner
    #
    def run(self, button):
        # right now there is only one button.
        rule_types = []

        for mode in [self.default_user, self.default_role, self.default_type, self.default_range]:
            if mode.isChecked():
                rule_types.append(mode.objectName())

        self.query.ruletype = rule_types
        self.query.default = self.default_value.currentData(Qt.UserRole)

        if self.default_range_value.isEnabled():
            self.query.default_range = self.default_range_value.currentData(Qt.UserRole)
        else:
            self.query.default_range = None

        # start processing
        self.busy.setLabelText("Processing query...")
        self.busy.show()
        self.raw_results.clear()
        self.thread.start()

    def update_complete(self, count):
        self.log.info("{0} default(s) found.".format(count))

        # update sizes/location of result displays
        if not self.busy.wasCanceled():
            self.busy.setLabelText("Resizing the result table's columns; GUI may be unresponsive")
            self.busy.repaint()
            self.table_results.resizeColumnsToContents()

        if not self.busy.wasCanceled():
            self.busy.setLabelText("Resizing the result table's rows; GUI may be unresponsive")
            self.busy.repaint()
            self.table_results.resizeRowsToContents()

        if not self.busy.wasCanceled():
            self.busy.setLabelText("Moving the raw result to top; GUI may be unresponsive")
            self.busy.repaint()
            self.raw_results.moveCursor(QTextCursor.Start)

        self.busy.reset()
Exemplo n.º 51
0
class RecordWin(QtWidgets.QWidget, record.Ui_Form):
    def __init__(self, func, pos):
        super().__init__()
        self.setupUi(self)

        self.func = func

        self.path = os.path.abspath(__file__)
        self.curdir = os.path.dirname(self.path)
        self.img = QtGui.QImage(self.curdir + "/init.jpg")
        self.palette = QtGui.QPalette()
        self.palette.setBrush(QtGui.QPalette.Window, QtGui.QBrush(self.img))
        self.setPalette(self.palette)

        self.recording_now = False

        self.reciver.connect(self.status_reciver)

        self.selectFile = os.path.abspath(os.curdir) + "/output.wav"

        self.setWindowFlags(Qt.FramelessWindowHint)
        self.move(pos["x"], pos["y"])

        self.stopSignal = threading.Event()
        self.ready = threading.Event()

        self.morseWriter = reclib.MorseWriter(self, self.selectFile,
                                              self.ready)
        self.thread = QThread()
        self.thread.start()
        self.morseWriter.moveToThread(self.thread)

        self.pushButton.clicked.connect(self.REC_control)

    reciver = pyqtSignal(str)

    def REC_control(self):
        if self.recording_now:
            self.morseWriter.stop_trigger.emit(True)

        else:
            if self.morseWriter.recorded:
                self.func("record next")
            else:
                self.morseWriter.run_trigger.emit()

    #@pyqtSlot()
    def status_reciver(self, msg):
        if msg == "started":
            self.recording_now = True
            self.pushButton.setText("REC")

        elif msg == "REC":
            self.pushButton.setStyleSheet("color: red;")
            th = threading.Thread(target=self.counter)
            th.start()

        elif msg == "saving":
            self.stopSignal.set()
            self.pushButton.setText("saving...")
            self.pushButton.setStyleSheet("color: blue;")

        elif msg == "finished":
            self.pushButton.setText("continue")
            self.pushButton.setStyleSheet("color: rgb(228, 227, 239);")
            self.ready.set()
            self.recording_now = False

        elif msg == "force quit":
            self.func("record return")

    def counter(self):
        timer = time.time()
        while not self.stopSignal.is_set():
            time.sleep(1)
            dif = int(time.time() - timer)
            minute = dif % 100 // 60
            second = dif % 60
            label = "{}{}:{}{}".format(minute // 10, minute % 10, second // 10,
                                       second % 10)
            self.label_2.setText(label)

    def reset(self):
        self.recording_now = False
        self.stopSignal.clear()
        self.ready.clear()
        self.pushButton.setText("START")
        self.label_2.setText("-:--")

    def keyPressEvent(self, event):
        if event.key() == Qt.Key_Escape:
            if self.recording_now:
                reply = QtWidgets.QMessageBox.question(
                    self, 'Action',
                    "Do you want to stop recording\nand\nreturn to Start window?",
                    QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No,
                    QtWidgets.QMessageBox.No)
                if reply == QtWidgets.QMessageBox.Yes:
                    self.morseWriter.stop_trigger.emit(False)
                    #self.ready.wait()
                    #self.func("record return")

            else:
                reply = QtWidgets.QMessageBox.question(
                    self, 'Action', "Return to\nStart window?",
                    QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No,
                    QtWidgets.QMessageBox.No)
                if reply == QtWidgets.QMessageBox.Yes:
                    self.func("record return")
Exemplo n.º 52
0
class TerytSearch(QObject):

    lpis_bbox_found = pyqtSignal()

    def __init__(self, parent, target_layout, result_collector,
                 result_collector_precinct_unknown_factory, layer_factory):
        super().__init__()
        self.parent = parent
        self.canvas = iface.mapCanvas()
        self.ui = UI(target_layout)

        self.result_collector = result_collector
        self.result_collector_precinct_unknown_factory = result_collector_precinct_unknown_factory
        self.layer_factory = layer_factory

        self.provinces_downloaded = False

        self.message_bar_item = None
        self.__init_ui()

        self.uldk_search = ULDKSearchParcel(
            "dzialka", ("geom_wkt", "wojewodztwo", "powiat", "gmina", "obreb",
                        "numer", "teryt"))

        self.uldk_search = ULDKSearchLogger(self.uldk_search)

    def search(self, teryt):
        if self.ui.checkbox_precinct_unknown.checkState():
            self.__search_without_precinct()
        else:
            teryt = self.ui.lineedit_full_teryt.text()
            self.__search([teryt])

    def search_lpis(self):
        teryt = self.ui.lineedit_full_teryt.text()
        key = QSettings().value('gissupport/api/key')
        if not key:
            messageBox = QMessageBox.warning(
                None, "Wtyczka GIS Support",
                "Korzystanie z danych historycznych wymaga uzupełnienia klucza GIS Support. Więcej informacji w menu wtyczki w zakładce <b>Klucz GIS Support</b>."
            )
            return
        lpis_response = lpis_api.search(teryt, key)
        if len(lpis_response) == 0:
            iface.messageBar().pushCritical(
                "Wtyczka ULDK",
                f"Nie znaleziono przybliżonej lokacji działki{teryt}")
        elif len(lpis_response) > 1:
            combobox = self.ui.combobox_sheet

            def _zoom_to_lpis_wrapper():
                self._zoom_to_lpis(combobox.currentData())
                self.lpis_bbox_found.emit()
                combobox.clear()
                combobox.setEnabled(False)

            self.message_bar_item = QgsMessageBarItem(
                "Wtyczka ULDK",
                "Wybrana działka znajduje się na różnych arkuszach map. Wybierz z listy jedną z nich."
            )
            iface.messageBar().pushWidget(self.message_bar_item)

            combobox.setEnabled(True)
            combobox.clear()
            for row in lpis_response:
                combobox.addItem(row["arkusz"], row)

            try:
                combobox.activated.disconnect()
            except TypeError:
                pass  #w przypadku braku przypiętych slotów rzuca wyjątkiem
            combobox.activated.connect(_zoom_to_lpis_wrapper)
        else:
            self._zoom_to_lpis(lpis_response[0])
            self.lpis_bbox_found.emit()

    def _zoom_to_lpis(self, lpis_response):
        teryt = lpis_response["identyfikator"]
        iface.messageBar().pushSuccess(
            "Wtyczka ULDK",
            f"Znaleziono historyczną lokację działki '{teryt}'")
        canvas_crs = self.canvas.mapSettings().destinationCrs()
        lpis_bbox = extract_lpis_bbox(lpis_response, canvas_crs)
        self.canvas.setExtent(lpis_bbox)

    def __search(self, teryts):
        self.ui.button_search_uldk.setEnabled(False)
        self.ui.button_search_uldk.setText("Wyszukiwanie...")

        self.uldk_search_worker = ULDKSearchWorker(self.uldk_search, teryts)
        self.thread = QThread()
        self.uldk_search_worker.moveToThread(self.thread)

        if self.ui.checkbox_precinct_unknown.checkState():
            self.ui.progress_bar_precinct_unknown.setValue(0)
            self.uldk_search_worker.finished.connect(
                self.__handle_finished_precinct_unknown)
            self.uldk_search_worker.found.connect(
                self.__handle_found_precinct_unknown)
            self.uldk_search_worker.found.connect(
                self.__handle_progress_precinct_unknown)
            self.uldk_search_worker.not_found.connect(
                self.__handle_progress_precinct_unknown)
        else:
            self.uldk_search_worker.finished.connect(self.__handle_finished)
            self.uldk_search_worker.found.connect(self.__handle_found)
            self.uldk_search_worker.not_found.connect(self.__handle_not_found)

        self.uldk_search_worker.finished.connect(self.__handle_finished)
        self.uldk_search_worker.finished.connect(self.thread.quit)

        self.uldk_search_worker.finished.connect(
            self.uldk_search_worker.deleteLater)
        self.uldk_search_worker.finished.connect(self.thread.deleteLater)

        self.thread.started.connect(self.uldk_search_worker.search)
        self.thread.start()

    def __search_without_precinct(self):
        self.precincts_progressed = 0
        self.plots_found = []
        combobox = self.ui.combobox_precinct
        plot_id = self.ui.lineedit_plot_id.text()
        municipality_name = self.ui.combobox_municipality.currentText().split(
            " | ")[0]
        plots_teryts = []
        for i in range(1, combobox.count()):
            municipality_teryt = combobox.itemText(i).split(" | ")[1]
            plot_teryt = f"{municipality_teryt}.{plot_id}"
            plots_teryts.append(plot_teryt)

        layer_name = f"{municipality_name} - Działki '{plot_id}'"
        layer = self.layer_factory(name=layer_name,
                                   custom_properties={"ULDK": layer_name})
        self.result_collector_precinct_unknown = self.result_collector_precinct_unknown_factory(
            self.parent, layer)
        self.ui.button_search_uldk.hide()
        self.ui.progress_bar_precinct_unknown.show()
        self.__search(plots_teryts)

    @classmethod
    def is_plot_id_valid(cls, plot_id):

        if plot_id.endswith(".") or plot_id.startswith("."):
            return False
        if plot_id != plot_id.strip():
            return False

        return len(plot_id.split(".")) >= 3

    def get_administratives(self, level, teryt=""):
        search = ULDKSearchTeryt(level, ("nazwa", "teryt"))
        search = ULDKSearchLogger(search)
        result = search.search(teryt)
        result = [r.replace("|", " | ") for r in result]
        return result

    def parse_combobox_current_text(self, source):
        text = source.currentText()
        return text.split(" | ")[1] if text else ""

    def fill_combobox_province(self):
        # Wypełnienie listy województ odbywa się tylko raz w momencie kliknięcia na listę
        # QComboBox nie posiada sygnału emitowanego w czasie kliknięcia,
        # dlatego lista wstępnie wypełniona jest jednym pustym napisem, aby było możliwe jej rozwinięcie.
        # Po rozwinięciu listy następuje samoistne najechanie na element listy i wywoływana jest ta metoda
        if not self.provinces_downloaded:
            print("fill")
            provinces = self.get_administratives("wojewodztwo")
            self.ui.combobox_province.clear()
            self.ui.combobox_province.addItems([""] + provinces)
            self.provinces_downloaded = True

    def fill_combobox_county(self, province_teryt):
        counties = self.get_administratives(
            "powiat", province_teryt) if province_teryt else []
        self.ui.combobox_county.clear()
        self.ui.combobox_county.addItems([""] + counties)

    def fill_combobox_municipality(self, county_teryt):
        municipalities = self.get_administratives(
            "gmina", county_teryt) if county_teryt else []
        self.ui.combobox_municipality.clear()
        self.ui.combobox_municipality.addItems([""] + municipalities)

    def fill_combobox_precinct(self, municipality_teryt):
        precincts = self.get_administratives(
            "obreb", municipality_teryt) if municipality_teryt else []
        self.ui.combobox_precinct.clear()
        self.ui.combobox_precinct.addItems([""] + precincts)

    def fill_lineedit_full_teryt(self):
        current_plot_id = self.ui.lineedit_plot_id.text()
        current_municipality = self.ui.combobox_municipality.currentText()
        current_precinct = self.ui.combobox_precinct.currentText()
        if self.ui.checkbox_precinct_unknown.checkState(
        ) and current_municipality:
            current_municipality = current_municipality.split(" | ")[1]
            current_precinct_dummy = f"{current_municipality}.?"
            self.ui.lineedit_full_teryt.setText(
                f"{current_precinct_dummy}.{current_plot_id}")

        elif current_plot_id and current_precinct:
            current_precinct = current_precinct.split(" | ")[1]
            self.ui.lineedit_full_teryt.setText(
                f"{current_precinct}.{current_plot_id}")
        else:
            self.ui.lineedit_full_teryt.setText("")

    def _handle_input_changed(self, fill=True):
        if fill:
            self.fill_lineedit_full_teryt()
        self.ui.combobox_sheet.clear()

    def __init_ui(self):

        self.combobox_province_highlighted = self.ui.combobox_province.highlighted.connect(
            self.fill_combobox_province)

        self.ui.combobox_province.currentIndexChanged.connect(
            lambda i: self.fill_combobox_county(
                self.parse_combobox_current_text(self.ui.combobox_province))
            if i else self.ui.combobox_county.setCurrentIndex(0))
        self.ui.combobox_county.currentIndexChanged.connect(
            lambda i: self.fill_combobox_municipality(
                self.parse_combobox_current_text(self.ui.combobox_county))
            if i else self.ui.combobox_municipality.setCurrentIndex(0))
        self.ui.combobox_municipality.currentIndexChanged.connect(
            lambda i: self.fill_combobox_precinct(
                self.parse_combobox_current_text(self.ui.combobox_municipality)
            ) if i else self.ui.combobox_precinct.setCurrentIndex(0))
        self.ui.combobox_precinct.currentTextChanged.connect(
            self._handle_input_changed)
        self.ui.lineedit_plot_id.textChanged.connect(
            self._handle_input_changed)
        self.ui.lineedit_full_teryt.textChanged.connect(
            lambda text: self._search_buttons_set_enabled(
                self.is_plot_id_valid(text)))
        self.ui.lineedit_full_teryt.textEdited.connect(
            lambda: self._handle_input_changed(False))
        self.ui.button_search_uldk.setShortcut(QKeySequence(Qt.Key_Return))
        self.ui.button_search_uldk.clicked.connect(self.search)
        self.ui.checkbox_precinct_unknown.stateChanged.connect(
            self.__on_checkbox_precinct_unknown_switched)
        self.ui.button_search_lpis.clicked.connect(self.search_lpis)
        self.ui.combobox_province.addItems([""])

    def __search_from_sheet(self):
        self.__handle_found([self.ui.combobox_sheet.currentData()])

    def _search_lpis_from_sheet(self):
        self.search_lpis(self.ui.combobox_sheet.currentData())

    def __handle_finished(self):
        self.ui.button_search_uldk.setEnabled(True)
        self.ui.button_search_uldk.setText("Szukaj")
        self.ui.button_search_uldk.setShortcut(QKeySequence(Qt.Key_Return))

    def __handle_finished_precinct_unknown(self):
        self.result_collector_precinct_unknown.update_with_features(
            self.plots_found)
        iface.messageBar().pushWidget(
            QgsMessageBarItem(
                "Wtyczka ULDK",
                f"Wyszukiwanie działek: zapisano znalezione działki do warstwy <b>{self.result_collector_precinct_unknown.layer.sourceName()}</b>"
            ))
        self.ui.button_search_uldk.show()
        self.ui.progress_bar_precinct_unknown.hide()

    def __handle_found(self, uldk_response_rows):
        uldk_response_rows = validators.duplicate_rows(uldk_response_rows)
        if len(uldk_response_rows) > 1:
            try:
                self.ui.combobox_sheet.activated.disconnect()
            except TypeError:
                pass  #w przypadku braku przypiętych slotów rzuca wyjątkiem
            self.ui.combobox_sheet.activated.connect(self.__search_from_sheet)
            self.ui.combobox_sheet.setEnabled(True)
            self.ui.combobox_sheet.clear()
            for row in uldk_response_rows:
                row_split = row.split("|")
                sheet_name = row_split[-1].split('.')[2]

                self.ui.combobox_sheet.addItem(sheet_name, row)
            self.message_bar_item = QgsMessageBarItem(
                "Wtyczka ULDK",
                "Wybrana działka znajduje się na różnych arkuszach map. Wybierz z listy jedną z nich."
            )
            iface.messageBar().widgetRemoved.connect(self.__delete_message_bar)
            iface.messageBar().pushWidget(self.message_bar_item)
        else:
            result = uldk_response_rows[0]

            try:
                added_feature = self.result_collector.update(result)
            except self.result_collector.BadGeometryException:
                iface.messageBar().pushCritical(
                    "Wtyczka ULDK", f"Działka posiada niepoprawną geometrię")
                return
            self.result_collector.zoom_to_feature(added_feature)

            if self.message_bar_item:
                iface.messageBar().popWidget(self.message_bar_item)

            iface.messageBar().pushSuccess(
                "Wtyczka ULDK", "Zaaktualizowano warstwę '{}'".format(
                    self.result_collector.layer.sourceName()))

    def __handle_not_found(self, teryt, exception):
        iface.messageBar().pushCritical(
            "Wtyczka ULDK",
            f"Nie znaleziono działki - odpowiedź serwera: '{str(exception)}'")

    def __handle_found_precinct_unknown(self, uldk_response_rows):
        for row in uldk_response_rows:
            try:
                feature = self.result_collector_precinct_unknown.uldk_response_to_qgs_feature(
                    row)
            except self.result_collector_precinct_unknown.BadGeometryException:
                return
            self.plots_found.append(feature)

    def __handle_progress_precinct_unknown(self):
        self.precincts_progressed += 1
        precincts_count = self.ui.combobox_precinct.count()
        self.ui.progress_bar_precinct_unknown.setValue(
            self.precincts_progressed / precincts_count * 100)

    def __on_checkbox_precinct_unknown_switched(self, new_state):
        self._handle_input_changed()
        self.ui.label_precinct.setEnabled(not new_state)
        self.ui.combobox_precinct.setEnabled(not new_state)

    def _search_buttons_set_enabled(self, new_state):
        self.ui.button_search_lpis.setEnabled(new_state)
        self.ui.button_search_uldk.setEnabled(new_state)

    def __delete_message_bar(self):
        self.message_bar_item = None
Exemplo n.º 53
0
 def __init__(self, iface, DHCPconf):
     QThread.__init__(self)
     self.iface = iface
     self.dhcp_conf = DHCPconf
     self.DHCPProtocol = DHCPProtocol(self.dhcp_conf)
     self.started = False
class PostDownloader:
    def __init__(self, appWindow):
        self.saveLocation = None
        self.targetPostCount = None
        self.responses_raw = None
        self.appWindow = appWindow
        self.currentRequest = 0
        self.totalRequests = 0

        self.netManager = QtNetwork.QNetworkAccessManager()
        self.postProcessor = ResponsePostProcessor()
        self.additionalPostProcessor = AdditionalPostProcessor()
        self.thread = QThread()
        self.postProcessor.cleanProgressSignal.connect(
            self.cleanProgressCallback)
        self.postProcessor.cleanCompleteSignal.connect(
            self.cleanCompleteCallback)
        self.postProcessor.dumpCompleteSignal.connect(self.killThread)

        self.additionalPostProcessor.dumpCompleteSignal.connect(
            self.killThread)
        self.additionalPostProcessor.cleanCompleteSignal.connect(
            self.cleanCompleteCallback)

    def resetDownloader(self):
        self.currentRequest = 0
        self.totalRequests = 0
        self.responses_raw = list()

    def updateProgressBar(self):
        return

    def cleanProgressCallback(self, completeness):
        print('cleaning: ', completeness)
        return

    def cleanCompleteCallback(self):
        print('clean complete')
        return

    #kill thread not being called
    def killThread(self):
        print('killing thread')
        self.thread.quit()
        # self.thread.wait()

    def __startPP(self, processor, enablePP, connectFunc):
        print('starting post processor')
        #TODO: generate post processor on the fly?
        processor.saveLocation = self.saveLocation
        processor.jsonList = self.responses_raw
        processor.targetPostCount = self.targetPostCount
        processor.enablePP = enablePP
        self.thread.started.connect(connectFunc)
        self.postProcessor.moveToThread(self.thread)
        self.thread.start()

    def __probeRequest(self, url):
        RequestInfo = namedtuple('RequestInfo', 'code totalPosts')
        url.args['per_page'] = 1
        connection = urllib.request.urlopen(url.url)
        return RequestInfo(connection.getcode(),
                           int(connection.getheader('x-wp-total')))

    #sets up relevant parameters for downloading and callback function, then starts first download
    #subsequent downloads are done by the callback function/handler
    def __downloadChunk(self, url, handler):
        self.appWindow.ui.statusBar.showMessage(
            'Downloading, this may take a while... ')
        self.resetDownloader()
        assert (self.targetPostCount >=
                -1), 'Assertion failed: postCount invalid'
        if (self.targetPostCount == -1):
            self.targetPostCount = sys.maxsize  #this might be very bad practice D:

        info = self.__probeRequest(url)
        if (info.code != 200):
            print('Error: server responded with code {}'.format(info.code))
            raise ConnectionError('Server responded with code {}'.format(
                info.code))
        elif (info.totalPosts == 0):
            print('Error: no posts found with the given parameter')
            raise ValueError('No posts found with the given parameter')

        print('{} posts found'.format(info.totalPosts))

        self.totalRequests = math.ceil(
            min(info.totalPosts, self.targetPostCount) / 100)
        self.netManager.finished.connect(handler)
        url.args['per_page'] = 100
        url.args['offset'] = 0
        print('Request: ', url.url)
        self.currentRequest += 1
        self.netManager.get(QtNetwork.QNetworkRequest(QUrl(url.url)))

    def getAdditional(self, url, outfile, convertCsv):
        self.saveLocation = outfile
        self.targetPostCount = -1

        def addRespHandler(reply):
            if (reply.error() == QtNetwork.QNetworkReply.NoError):
                response_string = str(reply.readAll(), 'utf-8').strip()
                if (not response_string):
                    raise ValueError(
                        'Response string is empty'
                    )  #this error happens when we call the function a second time D:

                response_array = json.loads(
                    response_string
                )  #not sure why we need strip() here but not in getJsonList
                self.responses_raw += response_array

                #TODO: might be better to send signal to AppWindow and let it handle this?
                self.appWindow.ui.progressBar.setValue(
                    self.currentRequest / self.totalRequests * 80.0)

                if (len(response_array) == 100):
                    url.args['offset'] += 100
                    print('Request: ', url.url)
                    self.currentRequest += 1
                    self.netManager.get(
                        QtNetwork.QNetworkRequest(QUrl(url.url)))
                else:
                    self.appWindow.ui.statusBar.showMessage(
                        'Cleaning up posts, this may take a while... ')
                    self.__startPP(
                        self.additionalPostProcessor, convertCsv,
                        self.additionalPostProcessor.cleanResponseList)
            else:
                print('Error occurred: ', reply.error())
                print(reply().errorString())
                #TODO: raise exception here and let AppWindow handle it

        self.__downloadChunk(url, addRespHandler)

    # url is a furl object
    # use -1 for no postCount limit
    def getJsonList(self, url, postCount, saveLocation, enablePP):
        self.saveLocation = saveLocation
        self.targetPostCount = postCount

        def respHandler(reply):
            if (reply.error() == QtNetwork.QNetworkReply.NoError):
                response_array = json.loads(str(reply.readAll(), 'utf-8'))
                self.responses_raw += response_array

                #TODO: might be better to send signal to AppWindow and let it handle this?
                self.appWindow.ui.progressBar.setValue(
                    self.currentRequest / self.totalRequests * 80.0)

                if (len(self.responses_raw) < self.targetPostCount
                        and len(response_array) == 100):
                    url.args['offset'] += 100
                    print('Request: ', url.url)
                    self.currentRequest += 1
                    self.netManager.get(
                        QtNetwork.QNetworkRequest(QUrl(url.url)))
                else:
                    self.appWindow.ui.statusBar.showMessage(
                        'Cleaning up posts, this may take a while... ')
                    self.__startPP(self.postProcessor, enablePP,
                                   self.postProcessor.cleanResponseList)
            else:
                print('Error occurred: ', reply.error())
                print(reply().errorString())
                #TODO: raise exception here and let AppWindow handle it

        self.__downloadChunk(url, respHandler)
Exemplo n.º 55
0
    def btn_event(self):
        if (self.btn_flag == 0):
            self.btn_flag = 1

            self.startBtn.setIcon(QtGui.QIcon('stop.png'))
            self.startBtn.setIconSize(QtCore.QSize(100, 100))

            self.__threads = []

            # create a recorder object
            record = Recorder()
            record_thread = QThread()
            record_thread.setObjectName('record thread')
            self.__threads.append(
                (record_thread,
                 record))  # need to store worker too otherwise will be gc'd

            record.moveToThread(record_thread)

            # get progress messages from worker:
            record.sig_step.connect(self.on_recorder_worker_step)

            # control worker:
            self.sig_recorder_abort_workers.connect(record.abort)

            # get read to start worker:record

            record_thread.started.connect(record.work)
            record_thread.start(
            )  # this will emit 'started' and start thread's event loop
        else:
            self.btn_flag = 0

            self.startBtn.setIcon(QtGui.QIcon('record.png'))
            self.startBtn.setIconSize(QtCore.QSize(100, 100))

            self.sig_recorder_abort_workers.emit()
            print('Asking each worker to abort')
            for record_thread, record in self.__threads:  # note nice unpacking by Python, avoids indexing
                record_thread.quit(
                )  # this will quit **as soon as thread event loop unblocks**
                record_thread.wait(
                )  # <- so you need to wait for it to *actually* quit
            self.startBtn.setDisabled(True)
            self.statusLabel.show()

            inference = Inference()
            inference_thread = QThread()
            inference_thread.setObjectName('Inference Thread')
            self.__threads.append(
                (inference_thread,
                 inference))  # need to store worker too otherwise will be gc'd

            inference.moveToThread(inference_thread)
            inference.sig_result.connect(self.on_inference_worker_end)

            self.sig_inference_abort_workers.connect(inference.abort)

            inference_thread.started.connect(inference.work)
            inference_thread.start(
            )  # this will emit 'started' and start thread's event loop
Exemplo n.º 56
0
class Window(QWidget):
    def __init__(self):
        super().__init__()
        # set up window
        self.title = 'Ready to Rock'
        self.top = 100
        self.left = 100
        self.width = 1280
        self.height = 1280
        self.init_window()
        self.init_thread()
        #self.init_worker()

    def init_window(self):
        self.setWindowTitle(self.title)
        self.setGeometry(self.top, self.left, self.width, self.height)
        self.init_rgbd_layout()
        self.show()

    def init_worker(self):
        self.thread = QThread()
        self.worker = FrameObject()
        self.worker.moveToThread(self.thread)
        self.worker.frame_signal.connect(
            lambda frame_store: self.display_pixmap(frame_store, 'rgb'))
        self.worker.frame_signal.connect(
            lambda frame_store: self.display_pixmap(frame_store, 'seg'))
        self.thread.started.connect(self.worker.run)
        self.thread.start()

    def init_thread(self):
        self.f_thread = FrameThread()
        # propagate segmentation color-name mapping to this window
        self.seg_names = self.f_thread.model_config.names
        self.seg_colors = self.f_thread.model_config.colors
        # emit picture to 3 widgets (pixmap)
        self.f_thread.frame_signal.connect(
            lambda frame_store: self.display_pixmap(frame_store, 'rgb'))
        self.f_thread.frame_signal.connect(
            lambda frame_store: self.display_pixmap(frame_store, 'seg'))
        self.f_thread.start()

    def init_rgbd_layout(self):
        vbox_layout = QVBoxLayout()
        # set up label
        WIDGET_WIDTH = 484  # 484
        WIDGET_HEIGHT = 240  # 240
        rgb_label = QLabel(self)
        rgb_label.resize(WIDGET_WIDTH, WIDGET_HEIGHT)
        seg_label = QLabel(self)
        seg_label.resize(WIDGET_WIDTH, WIDGET_HEIGHT)
        # assign labels as attribute
        self.rgb_label = rgb_label
        self.seg_label = seg_label
        # stack widgets
        vbox_layout.addWidget(self.rgb_label)
        vbox_layout.addWidget(self.seg_label)
        # logging
        self.setLayout(vbox_layout)

    def display_pixmap(self, frame_store, img_type):
        """
        input:
            frame_store -- FrameStore instance
            img_type -- str, 'rgb', 'depth' or 'seg'
        """
        assert img_type in ['rgb', 'seg'], 'WRONG ARGUMENT img_type'
        if img_type == 'rgb':
            qimg = convert_qimg(frame_store.rgb_img)
            self.rgb_label.setPixmap(QtGui.QPixmap.fromImage(qimg))
        else:
            self.seg_qimg = convert_qimg(frame_store.seg_out)
            self.seg_label.setPixmap(QtGui.QPixmap.fromImage(self.seg_qimg))
Exemplo n.º 57
0
 def __init__(self, dir_name, form):
     QThread.__init__(self)
     self.dir_name = dir_name
     self.form = form
Exemplo n.º 58
0
Arquivo: t1.py Projeto: innotax/AutoDz
 def __init__(self):
     QThread.__init__(self)
     self.cond = QWaitCondition()
     self.mutex = QMutex()
     self.cnt = 0
     self._status = False
Exemplo n.º 59
0
class MainWindow(QMainWindow):
    def __init__(self, parent=None):
        super().__init__(parent)

        # TODO put these in a data model object and xml file
        self.column_order = [
            SampleTypes.Time, SampleTypes.Pressure, SampleTypes.Temperature
        ]
        self.sample_types_requested_ordered = []
        self.delimiter = ','

        self.current_row = 0
        self.setWindowTitle("P-T Tester")
        self.arduino_thread = None
        self.arduino_worker = None
        self.test_state = State.ReadyNotRan
        self.output_file = None
        self.ax = None
        self.ax_secondaries = dict()
        self.plot_colors = dict()

        # CONFIG DOCK
        self.config_dock = ConfigDock("Test Options", self)
        self.config_dock.start_button_slot(self.start_test)
        self.addDockWidget(Qt.LeftDockWidgetArea, self.config_dock)

        # FILE OUTPUT DOCK
        self.outfile_dock = OutfileDock("Output Selection", self)
        self.addDockWidget(Qt.LeftDockWidgetArea, self.outfile_dock)

        # TABLE Window
        # TODO TableWidget members private, put table editing functions in TableWidget, not here
        self.table_view_tbl = TableWidget(self)

        # PLOT window
        self.plot_window = PlotWindow(self)

        # MDI SETUP
        self.mdi_area = QMdiArea()
        self.setCentralWidget(self.mdi_area)
        self.mdi_area.addSubWindow(self.table_view_tbl)
        self.mdi_area.addSubWindow(self.plot_window)
        self.mdi_area.tileSubWindows()

        # set initial state of window
        self.update_status(State.ReadyNotRan)

    def initialize_plot(self):
        plt.ion()
        self.plot_colors[
            SampleTypes.Pressure] = self.config_dock.pressure_color_name
        self.plot_colors[
            SampleTypes.Temperature] = self.config_dock.temperature_color_name
        self.plot_window.figure.clear()
        self.ax = self.plot_window.figure.add_subplot(111)
        self.ax.set_xlabel('time (s)')
        self.ax.set_ylabel(
            SampleNames.names[self.sample_types_requested_ordered[0]],
            color=self.plot_colors[self.sample_types_requested_ordered[0]])
        if len(self.sample_types_requested_ordered) > 1:
            for sample_type in self.sample_types_requested_ordered[1:]:
                self.ax_secondaries[sample_type] = self.ax.twinx()
                self.ax_secondaries[sample_type].set_ylabel(
                    SampleNames.names[sample_type],
                    color=self.plot_colors[sample_type])

    def plot_sample(self, current_time, sample):
        # TODO why doesn't it show the line?, only markers are shown.
        marker = dict()
        marker[SampleTypes.Pressure] = self.config_dock.pressure_marker()
        marker[SampleTypes.Temperature] = self.config_dock.temp_marker()
        self.ax.plot(
            current_time,
            sample.values[self.sample_types_requested_ordered[0]],
            color=self.plot_colors[self.sample_types_requested_ordered[0]],
            marker=marker[self.sample_types_requested_ordered[0]],
            linewidth='2',
            linestyle='-')

        for sample_type in self.sample_types_requested_ordered[1:]:
            self.ax_secondaries[sample_type].plot(current_time, sample.values[sample_type],\
                                                  color=self.plot_colors[sample_type], marker=marker[sample_type])

    def start_test(self):
        # is at least 1 type of reading set
        record_p = self.config_dock.record_pressure_is_checked()
        record_t = self.config_dock.record_temperature_is_checked()
        if not record_p and not record_t:
            QMessageBox.warning(self, "Invalid Test Parameters",
                                "Must select at least 1 reading type",
                                QMessageBox.Ok)
            return
        # check test parameters
        sample_rate = self.config_dock.sample_rate()
        nb_samples = self.config_dock.number_of_samples()
        if nb_samples <= 1:
            QMessageBox.warning(
                self, "Invalid Test Parameters",
                "Duration too short or sampling rate too large",
                QMessageBox.Ok)
            return
        if not self.config_dock.record_pressure_is_checked(
        ) and not self.config_dock.record_temperature_is_checked():
            QMessageBox(self, "Invalid Selection",
                        "At least one type of measurement must be selected",
                        QMessageBox.Ok)
            return
        # check if there is already a test in progress
        if self.test_state == State.InProgress:
            return
        # worker thread will check connection, not done here
        # if test(s) were run before, table may contain data
        if self.test_state != State.ReadyNotRan and self.current_row > 1:
            choice = QMessageBox.question(
                self, "Starting New Test",
                "Starting new test will erase current data,\
                                          do you want to continue?",
                QMessageBox.Yes | QMessageBox.No)
            if choice == QMessageBox.No:
                return
            else:
                self.table_view_tbl.clearContents()
        # check given folder+file can be created
        if not self.outfile_dock.is_file_ok():
            return
        # if here, test can begin
        self.sample_types_requested_ordered = []
        for samp_type in self.column_order:
            if samp_type == SampleTypes.Pressure and record_p:
                self.sample_types_requested_ordered.append(
                    SampleTypes.Pressure)
            if samp_type == SampleTypes.Temperature and record_t:
                self.sample_types_requested_ordered.append(
                    SampleTypes.Temperature)

        self.initialize_table()
        self.initialize_file()
        self.initialize_plot()

        # set up arduino worker and signal-slots
        self.initialize_worker(nb_samples, record_p, record_t, sample_rate)
        # reading of measurements starts here
        # TODO make sure QThread terminates successfully upon quitting app while second thread is running
        self.arduino_thread.start()

        # gui updates
        # timer is started by worker thread, not here
        # update_gui called by update_status
        self.update_status(State.InProgress)

    def initialize_worker(self, nb_samples, record_p, record_t, sample_rate):
        self.arduino_worker = ArduinoWorker(sample_rate, nb_samples, record_p,
                                            record_t)
        self.arduino_thread = QThread()
        self.arduino_worker.moveToThread(self.arduino_thread)
        self.arduino_thread.started.connect(self.arduino_worker.run)
        self.arduino_worker.sample_received.connect(self.process_sample)
        self.arduino_worker.timer_start.connect(self.update_test_timers)
        self.config_dock.stop_button_slot(
            self.arduino_thread.requestInterruption)
        self.arduino_worker.stopped.connect(self.stop_test)

    def update_gui(self, test_state):
        # config_dock runs its own update_gui through its update_label
        # so, no need to call it
        self.outfile_dock.update_gui(test_state)

    def update_test_timers(self):
        cur_time = QTime.currentTime()
        end_time = cur_time.addSecs(self.config_dock.duration())
        self.config_dock.set_start_time(cur_time.toString("hh:mm:ss"))
        self.config_dock.set_end_time(end_time.toString("hh:mm:ss"))

    def initialize_table(self):
        number_of_columns = len(
            self.sample_types_requested_ordered) + 1  # +1 for time
        number_of_samples = self.config_dock.number_of_samples()
        self.table_view_tbl.setColumnCount(number_of_columns)
        self.table_view_tbl.setRowCount(number_of_samples)
        headers = []
        headers.append(SampleNames.names[SampleTypes.Time])
        for sample_type in self.sample_types_requested_ordered:
            headers.append(SampleNames.names[sample_type])
        self.table_view_tbl.setHorizontalHeaderLabels(headers)
        self.table_view_tbl.clearContents()
        self.current_row = 0

    def initialize_file(self):
        self.output_file = open(self.outfile_dock.full_path(), "w")
        headers = []
        headers.append(SampleNames.names[SampleTypes.Time])
        for sample_type in self.sample_types_requested_ordered:
            headers.append(SampleNames.names[sample_type])
        for index, header in enumerate(headers):
            self.output_file.write(header)
            if index != len(headers) - 1:
                self.output_file.write(self.delimiter)
        self.output_file.write("\n")

    def process_sample(self, sample):
        current_time = self.current_row * self.config_dock.sample_rate()

        self.print_sample_qtable(current_time, sample)
        self.print_sample_csv(current_time, sample)
        self.plot_sample(current_time, sample)

        self.table_view_tbl.selectRow(self.current_row)
        self.current_row += 1

    def print_sample_qtable(self, current_time, sample):
        self.table_view_tbl.setItem(
            self.current_row, 0,
            QTableWidgetItem("{:.2f}".format(current_time)))
        for i, sample_type in enumerate(self.sample_types_requested_ordered,
                                        start=1):
            self.table_view_tbl.setItem(
                self.current_row, i,
                QTableWidgetItem("{:.2f}".format(sample.values[sample_type])))

    def print_sample_csv(self, current_time, sample):
        self.output_file.write("{:.2f}".format(current_time) + self.delimiter)
        for index, sample_type in enumerate(
                self.sample_types_requested_ordered):
            self.output_file.write("{:.2f}".format(sample.values[sample_type]))
            if index != len(self.sample_types_requested_ordered) - 1:
                self.output_file.write(self.delimiter)
        self.output_file.write("\n")
        logger.info(
            "P and T readings being written to csv: {:.2f}, {:.2f}".format(
                sample.values[SampleTypes.Pressure],
                sample.values[SampleTypes.Temperature]))

    def stop_test(self, state):
        if self.test_state == State.InProgress:
            self.update_status(state)
            self.test_state = state
            self.output_file.close()
            self.arduino_thread.quit()
            self.arduino_worker = None
            self.arduino_thread = None

    def update_status(self, test_state):
        self.test_state = test_state
        self.update_gui(test_state)
        self.config_dock.update_status(self.test_state)
Exemplo n.º 60
0
 def __init__(self, data, model, form):
     QThread.__init__(self)
     self.data = data
     self.model = model
     self.form = form
     self.history = None