Ejemplo n.º 1
0
 def run(self):
     try:
         result = {'switch_count': None, 'max_keys': None}
         serial_connection = serial.Serial()
         serial_connection.baudrate = 9600
         serial_connection.port = self.port
         serial_connection.open()
         if serial_connection.is_open:
             serial_connection.write(bytearray([0xEE, 0x02, 0xFF]))
             response = []
             while (len(response) == 0 or response[-1] != b'\xff'):
                 byte = serial_connection.read()
                 response.append(byte)
             result['switch_count'] = response[2][0]
             result['max_keys'] = response[3][0]
             CallAfter(pub.sendMessage,
                       "serial",
                       class_name=type(self).__name__,
                       data=result)
         else:
             raise Exception("serial_connection is closed")
         serial_connection.close()
     except Exception:
         CallAfter(pub.sendMessage,
                   "serial",
                   class_name="ConnectionError",
                   data=None)
Ejemplo n.º 2
0
 def run(self):
     try:
         url = Smms.upload(self.filename, token=self.token)
         copy(url)
         CallAfter(self.window.UploadSuccess)
     except ConnectionRefusedError:
         CallAfter(self.window.LoginAgain)
     except ConnectionAbortedError:
         CallAfter(self.window.UploadMax)
    def run(self):
        try:
            self.pipeline.loadRawData()
        except AnalysisPipelineError as err:
            PostEvent(
                self.pipeline.attachedUI.parent,
                ExecutionCompletedEvent(err,
                                        self.pipeline.EXECUTION_COMPLETE_ID))
            self.pipeline.eventProgress = -1
            return
        except Exception as err:
            PostEvent(
                self.pipeline.attachedUI.parent,
                ExecutionCompletedEvent(err,
                                        self.pipeline.EXECUTION_COMPLETE_ID))
            return

        numExecutedModules = 0
        returnedData = self.pipeline.rawData
        for module in self.pipeline.activeModules:
            self.pipeline.eventProgress = int(
                100 * float(numExecutedModules) /
                float(len(self.pipeline.activeModules)))
            try:
                module.executeModule(returnedData)
            except AnalysisModules.ModuleExecutionError as err:
                PostEvent(
                    self.pipeline.attachedUI.parent,
                    ExecutionCompletedEvent(
                        err, self.pipeline.EXECUTION_COMPLETE_ID))
                self.pipeline.eventProgress = -1
                return
            except Exception as err:
                PostEvent(
                    self.pipeline.attachedUI.parent,
                    ExecutionCompletedEvent(
                        err, self.pipeline.EXECUTION_COMPLETE_ID))
                return

            returnedData = module.getOutput()
            numExecutedModules += 1
        self.pipeline.rawData = returnedData
        self.pipeline.eventProgress = -1
        PostEvent(
            self.pipeline.attachedUI.parent,
            ExecutionCompletedEvent(None, self.pipeline.EXECUTION_COMPLETE_ID))

        # UI specific statements below. CallAfter call will execute these statements after
        # the thread terminates (I believe). UI will crash otherwise.
        CallAfter(self.pipeline.attachedUI.parent.loadDataTab.populateRunList)
        CallAfter(self.pipeline.attachedUI.parent.MainLog.WriteLogText,
                  "Done.")
        CallAfter(self.pipeline.clearAttachedUI
                  )  # Clear the attached UI so that it is not saved to file.
Ejemplo n.º 4
0
 def attach_app(self, rceapps, jobid, ad):
     try:
         CallAfter(pub.sendMessage,
                   'rce_submit.xpra_attached',
                   pid=self.rce.attach(jobid, rceapps, ad=ad),
                   excpt=None)
     except Exception as e:
         CallAfter(pub.sendMessage,
                   'rce_submit.xpra_attached',
                   pid=None,
                   excpt=e)
Ejemplo n.º 5
0
 def poll_app(self, jobid):
     try:
         job_status, ad = self.rce.poll(jobid, use_local_schedd=True)
         CallAfter(pub.sendMessage,
                   'rce_submit.job_started',
                   job_status=job_status,
                   ad=ad,
                   excpt=None)
     except Exception as e:
         CallAfter(pub.sendMessage,
                   'rce_submit.job_started',
                   job_status=None,
                   ad=None,
                   excpt=e)
Ejemplo n.º 6
0
 def loop(self):
     if self._printer._pause.isSet():
         return None
     if self._printer._waiting_response.isSet():
         return None
     if not self._printer._commands_queue.empty():
         self._printer._waiting_response.set()
         name, command, args = self._printer._commands_queue.get()
         CallAfter(self._printer.OnCommand, name, command, args)
         if name == 'wait':
             time.sleep(command / 1000)
             CallAfter(self._printer.OnReadLine, 'ok')
             CallAfter(self._printer._waiting_response.clear)
         else:
             CallAfter(self._printer.Write, command)
Ejemplo n.º 7
0
 def run(self):
     try:
         result = {}
         for index, port in enumerate(serial.tools.list_ports.comports()):
             device_label = "{} - {}".format(port.device, port.description)
             result[device_label] = port.device
         CallAfter(pub.sendMessage,
                   "serial",
                   class_name=type(self).__name__,
                   data=result)
     except Exception:
         CallAfter(pub.sendMessage,
                   "serial",
                   class_name="ConnectionError",
                   data=None)
Ejemplo n.º 8
0
    def run(self):
        """
        Returns weather the update checking was successful.

        :rtype: Boolean

        """
        try:
            padfile = CHECK_UPDATE.get_pad()
            if padfile is None:
                _logger().exception('Pad could not be found in URL.')
                return
            tree = parse(padfile)
        except urllib2.URLError:
            _logger().exception('Update checker exception retrieving pad-file')
            return
        except XMLSyntaxError:
            _logger().exception('Update checker exception parsing pad-file')
            return
        except ParseError:
            _logger().exception('Update checker exception parsing pad-file')
            return
        except Exception as excp:
            logstr = 'Update checker exception, generic: {exception!s}'
            _logger().exception(logstr.format(exception=excp))
            return
        self.latest_version = tree.findtext('Program_Info/Program_Version')
        url_p = 'Web_Info/Download_URLs/Primary_Download_URL'
        url_s = 'Web_Info/Download_URLs/Secondary_Download_URL'
        url_primary = tree.findtext(url_p)
        url_secondary = tree.findtext(url_s)
        url = url_primary if url_primary else url_secondary
        if self.latest_version > diwavars.VERSION and url is not None:
            CallAfter(self.show_dialog, url)
Ejemplo n.º 9
0
    def on_press(self, key):
        try:
            if key.value.vk not in current_key_pressed:
                current_key_pressed.append(key.value.vk)
        except AttributeError:
            if key.vk not in current_key_pressed:
                current_key_pressed.append(key.vk)

        if self.is_pressed():

            status = get_pic_from_clipboard(self.window)
            # toaster = ToastNotifier()
            if status:
                CallAfter(self.window.Uploading)
            else:
                CallAfter(self.window.UploadFailed)
Ejemplo n.º 10
0
    def import_db(cnx_src, cnx_dst, callback=None, force=False):
        """
        :param cnx_src: the source DVHA DB connection
        :type cnx_src: DVH_SQL
        :param cnx_dst: the destination DVHA DB connection
        :type cnx_dst: DVH_SQL
        :param callback: optional function to be called on each row insertion
        :param force: ignore duplicate StudyInstanceUIDs if False
        :type force: bool
        """
        for table in cnx_src.tables:
            columns = cnx_src.get_column_names(table)
            study_uids_1 = cnx_src.get_unique_values(table, 'study_instance_uid')

            condition = None
            if not force:
                study_uids_2 = cnx_dst.get_unique_values(table, 'study_instance_uid')
                study_uids_1 = list(set(study_uids_1) - set(study_uids_2))
                condition = "study_instance_uid IN ('%s')" % "','".join(study_uids_1)

            total_row_count = cnx_src.get_row_count(table, condition)

            counter = 0
            for uid in study_uids_1:
                study_data = cnx_src.query(table, ','.join(columns), "study_instance_uid = '%s'" % uid)
                for row in study_data:
                    if callback is not None:
                        CallAfter(callback, table, counter, total_row_count)
                        counter += 1
                    row_str = "'" + "','".join([str(v) for v in row]) + "'"
                    row_str = row_str.replace("'None'", "NULL")
                    cmd = "INSERT INTO %s (%s) VALUES (%s);\n" % (table, ','.join(columns), row_str)
                    cnx_dst.execute_str(cmd)
Ejemplo n.º 11
0
    def create_event(self, title):
        """
        Create a new event.

        :param title: Title of the event.
        :type title: String

        """
        project = self.parent.diwa_state.current_project
        session = self.parent.diwa_state.current_session
        if (project is None) or (session is None):
            return  # TODO: Define a new exception type and catch
                    #       it in the UI design to display an
                    #       informative pop-up about project and
                    #       session.
        event_id = controller.add_event(session.id, title, '')
        SNAPSHOT_THREAD(project.dir)
        try:
            self.parent.diwa_state.swnp_send('SYS', 'screenshot;0')
            if diwavars.AUDIO and self.parent.diwa_state.audio_recorder:
                log_msg = 'Buffering audio for {0} seconds.'
                _logger().debug(log_msg.format(diwavars.WINDOW_TAIL))
                #self.parent.status_text.SetLabel('Recording...')
                self.parent.diwa_state.append_swnp_data('audio')
                self.parent.UpdateScreens(update=True)
                parameters = (event_id, project.dir)
                CallAfter(self.__save_audio, parameters)
        except:
            _logger().exception('Create Event exception.')
            self.parent.diwa_state.remove_from_swnp_data('audio')
Ejemplo n.º 12
0
    def save(self, event_id, path):
        """
        Save the buffer to a file.

        """
        try:
            _logger().debug('Saving audio buffer')
            date_string = datetime.now().strftime('%d%m%Y%H%M')
            filename = '{0}_{1}.wav'.format(event_id, date_string)
            filepath = os.path.join(path, 'Audio')
            if not os.path.exists(filepath):
                os.makedirs(filepath)
            filepath = os.path.join(filepath, filename)
            sample_size = self.py_audio.get_sample_size(diwavars.FORMAT)
            wave_file = wave.open(filepath, 'wb')
            wave_file.setnchannels(diwavars.CHANNELS)
            wave_file.setsampwidth(sample_size)
            wave_file.setframerate(diwavars.RATE)
            wave_file.writeframes(b''.join(self.buffer))
            wave_file.close()
        except:
            _logger().exception('audio save exception')
        #CallAfter(self.parent.ClearStatusText)
        self.parent.diwa_state.remove_from_swnp_data('audio')
        CallAfter(self.parent.UpdateScreens(update=True))
    def update_loop(self,
                    inp_file=None,
                    force_update=False,
                    delay_time=1,
                    data_model=3.0):
        print("-I- checking for updates at {0}".format(asctime()))
        if self.inp_file is None:
            inp_file_names = self.get_all_inp_files(self.WD)

            if inp_file_names == []:
                print("-W- No inp files found in any subdirectories of "
                      "%s, aborting update checking thread" % self.WD)
                self.timer.Stop()

                return
            magic_files = {}
            update_list = []

            for inp_file_name in inp_file_names:
                update_list.append(
                    self.read_inp(self.WD, inp_file_name, magic_files,
                                  data_model))
            update_needed = any(update_list)
        else:
            inp_file_name = self.inp_file
            magic_files = {}
            update_needed = self.read_inp(self.WD, inp_file_name, magic_files,
                                          data_model)
        if update_needed or force_update:
            print("-I- Resetting...")
            self.combine_magic_files(self.WD,
                                     magic_files,
                                     data_model=data_model)
            CallAfter(self.reset_backend, warn_user=False, reset_interps=False)
            print("-I- Reset")
Ejemplo n.º 14
0
 def enable_inputs(self):
     if self.__nonzero__():
         self.m_btnseek.Enable()
         self.m_staticTextcopy.Enable()
         self.m_account.Enable()
         self.is_change.Enable()
         self.m_index.Enable()
         CallAfter(self.Enable)
Ejemplo n.º 15
0
 def _on_process_ended(self):
     """ iplayer_get process has finished """
     # use CallAfter to switch back to the main GUI thread
     CallAfter(Publisher().sendMessage,
               topic=Channels.TOPIC_REFRESH_COMPLETE,
               data=self)
     self.is_refreshing = False
     self._process = None
Ejemplo n.º 16
0
    def _on_process_timer(self, event=None):
        for (episode, process) in self._processes:
            self.read_episode(episode, process)

        # use CallAfter to switch back to the main GUI thread
        CallAfter(Publisher().sendMessage, topic=self.TOPIC_DOWNLOAD_PROGRESS)

        if len(self._processes) > 0:
            self._start_process_timer()
Ejemplo n.º 17
0
 def _on_process_error(self, message):
     """ iplayer_get process returned an error """
     # use CallAfter to switch back to the main GUI thread
     CallAfter(Publisher().sendMessage,
               topic=Channels.TOPIC_REFRESH_ERROR,
               data=self)
     self.error_message = message
     self.is_refreshing = False
     self._process = None
Ejemplo n.º 18
0
    def run(self):
        try:
            serial_connection = serial.Serial()
            serial_connection.baudrate = 9600
            serial_connection.port = self.port
            serial_connection.open()
            if serial_connection.is_open:
                keys_edit = []
                for switch_index in range(0, self.switch_count):
                    serial_connection.write(
                        bytearray([0xEE, 0x00, switch_index, 0xFF]))
                    response = []
                    while (len(response) == 0 or response[-1] != b'\xff'):
                        byte = serial_connection.read()
                        response.append(byte)
                    converted_chars = []
                    for char in response[3:len(response) - 1]:
                        if char[0] >= 33 and char[0] <= 126:
                            converted_chars.append(chr(char[0]))
                        else:
                            try:
                                converted_chars.append(
                                    KEY_TO_HEX_BIDICT.inv[char[0]])
                            except KeyError:
                                continue
                    if len(converted_chars) == 0:
                        keys_edit.append(" ")
                    else:
                        keys_edit.append(" ".join(converted_chars))

                keys_edit = "\n".join(keys_edit)
                CallAfter(pub.sendMessage,
                          "serial",
                          class_name=type(self).__name__,
                          data=keys_edit)
            else:
                raise Exception("serial_connection is closed")
            serial_connection.close()
        except Exception:
            CallAfter(pub.sendMessage,
                      "serial",
                      class_name="ConnectionError",
                      data=None)
Ejemplo n.º 19
0
        def processChecker(process, procName):
            from time import sleep

            # The time interval to check for process messages [s].
            checkInterval = 2

            # The timeout limit. After this timeout the process is
            # marked as "not responding". The timeout interval should
            # be larger than the process's heartbeat interval. [s]
            timeout = 10

            procRunning = True
            isZombie = False
            self.logger.debug("Checking process...")
            lastResponse = 0
            while procRunning:
                #self.logger.debug("Waiting for message...")

                procStatus = proc.poll()

                #self.logger.debug('procStatus: %s', procStatus)

                if procStatus != None:
                    procRunning = False
                    #self.logger.debug('Process %d has stopped with return code %s.', proc.pid, procStatus)
                    msgTopic = 'state.collection.execution'
                    msg['state'] = 'stopped'
                    msg['pid'] = proc.pid
                    msg['procName'] = procName
                    msg['curTime'] = datetime.now()
                    CallAfter(pub.sendMessage, msgTopic, msg=msg)

                else:
                    #self.logger.debug('Process %d is still running.', proc.pid)
                    msgTopic = 'state.collection.execution'
                    msg['state'] = 'running'
                    msg['pid'] = proc.pid
                    msg['procName'] = procName
                    msg['curTime'] = datetime.now()
                    CallAfter(pub.sendMessage, msgTopic, msg=msg)

                sleep(checkInterval)
Ejemplo n.º 20
0
    def run(self):
        try:
            serial_connection = serial.Serial()
            serial_connection.baudrate = 9600
            serial_connection.port = self.port
            serial_connection.open()
            if serial_connection.is_open:
                key_lines = self.keys_edit.splitlines()
                while len(key_lines) < self.switch_count:
                    key_lines.append('')
                for index, key_list in enumerate(key_lines):
                    serial_request = [0xEE, 0x01, index]
                    for index, key in enumerate(key_list.split()):
                        if index >= self.max_keys:
                            break

                        if len(key) > 1:
                            try:
                                serial_request.append(KEY_TO_HEX_BIDICT[key])
                            except KeyError:
                                continue
                        elif ord(key) >= 33 and ord(key) <= 126:
                            serial_request.append(ord(key))

                    serial_request.append(0xFF)
                    serial_connection.write(bytearray(serial_request))
                    time.sleep(0.1)
                    serial_connection.reset_input_buffer()

                CallAfter(pub.sendMessage,
                          "serial",
                          class_name=type(self).__name__,
                          data=True)
            else:
                raise Exception("serial_connection is closed")
            serial_connection.close()
        except Exception:
            CallAfter(pub.sendMessage,
                      "serial",
                      class_name="ConnectionError",
                      data=None)
Ejemplo n.º 21
0
    def _on_process_ended(self, episode):
        episode.download_state = self.DOWNLOAD_COMPLETE

        if episode.error_message is None:
            episode.download_message = "Downloaded"
            topic = self.TOPIC_DOWNLOAD_COMPLETE
        else:
            episode.download_message = "Error: %s" % episode.error_message
            topic = self.TOPIC_DOWNLOAD_ERROR

        # use CallAfter to switch back to the main GUI thread
        CallAfter(Publisher().sendMessage, topic=topic, data=episode)
Ejemplo n.º 22
0
 def __init__(self, parent, context, send_file, handle_file):
     DIWA_THREAD.__init__(self, name='CMFH')
     self.parent = parent
     self.send_file = send_file
     self.handle_file = handle_file
     self.context = context
     try:
         self.socket = context.socket(zmq.REP)
         self.socket.setsockopt(zmq.LINGER, 0)
         self.socket.bind('tcp://*:5555')
     except zmq.ZMQError:
         CallAfter(parent.OnExit, ContextMenuFailure())
Ejemplo n.º 23
0
 def __login(self, **kwargs):
     print "login"
     password = kwargs.get('password')
     account = kwargs.get('account')
     code, response, traceback = JIRA.authorization(account=account,
                                                    password=password)
     if code == 0:
         CallAfter(self.update, )
         kwargs.get('dialog').Destroy()
     # 下面代码没有调试过
     elif code == 1:
         pass
     elif code == 2:
         print 'Please visit the \'https://jira-cstm.qualcomm.com/\' and check the connection.'
Ejemplo n.º 24
0
 def __on_save_audio(self, id_, param):
     """ Save audio handler. """
     id_ = id_
     param = param
     project = self.parent.diwa_state.current_project
     if project is None:
         return 'OK'
     if self.parent.diwa_state.is_responsive and diwavars.AUDIO:
         event_id = controller.get_latest_event_id()
         timer = threading.Timer(diwavars.WINDOW_TAIL * 1000,
                                 self.parent.audio_recorder.save, event_id,
                                 project.dir)
         timer.start()
         CallAfter(self.parent.status_text.SetLabel, 'Recording...')
     return 'OK'
    def _talk_to_gui(self, data):
        """Send data back to the GUI using wxCallAfter and wxPublisher.

        Args:
            data (string): Unique signal string that informs the GUI for the
                download process.

        Note:
            DownloadManager supports 3 signals.
                1) closing: The download process is closing.
                2) closed: The download process has closed.
                3) finished: The download process was completed normally.

        """
        CallAfter(Publisher.sendMessage, MANAGER_PUB_TOPIC, data)
Ejemplo n.º 26
0
    def _on_finished(self):

        if self.error_message is None:
            self._episode.download_message = "Finished"
            topic = self.TOPIC_STREAMING_COMPLETE
        else:
            self._episode.download_message = ("Error: %s" 
                                              % self.error_message)
            topic = self.TOPIC_STREAMING_ERROR

        # use CallAfter to switch back to the main GUI thread
        CallAfter(Publisher().sendMessage, 
                  topic=topic,
                  data=self._episode)

            
Ejemplo n.º 27
0
    def save_to_json(self, file_path, callback=None):
        """
        :param file_path: file_path to new JSON file
        :type file_path: str
        :param callback: optional function to be called on each table insertion
        """
        json_data = {'columns': {'categorical': categorical,
                                 'numerical': numerical}}
        for i, table in enumerate(self.tables):
            if callback is not None:
                CallAfter(callback, table, i, len(self.tables))
            columns = self.get_column_names(table)
            json_data[table] = self.query(table, ','.join(columns), bokeh_cds=True)

        with open(file_path, 'w') as fp:
            json.dump(json_data, fp)
Ejemplo n.º 28
0
    def _talk_to_gui(self, data):
        """Send data back to the GUI using wxCallAfter and wxPublisher.

        Args:
            data (string): Unique signal string that informs the GUI for the
                download process.

        Note:
            DownloadManager supports 4 signals.
                1) closing: The download process is closing.
                2) closed: The download process has closed.
                3) finished: The download process was completed normally.
                4) report_active: Signal the gui to read the number of active
                    downloads using the active() method.

        """
        CallAfter(Publisher.sendMessage, MANAGER_PUB_TOPIC, msg=data)
Ejemplo n.º 29
0
 def __query(self, **kwargs):
     start = kwargs.get('start')
     search = kwargs.get('query')
     end = start + GlobalVariable.max_result
     self.data.set_search_string(search)
     code, response, traceback = JIRA.qurey(search=search, start=start)
     if code == 0:
         self.parse_response(response=response)
         self.data.set_data(start=start, end=end)
         CallAfter(self.update, )
         kwargs.get('dialog').stop()
     # 下面代码没有调试过
     elif code == 1:
         JIRA.authorization(account=GlobalVariable.account,
                            password=GlobalVariable.password)
         self.__query(**kwargs)
     elif code == 2:
         print 'Please visit the \'https://jira-cstm.qualcomm.com/\' and check the connection.'
    def uiCalibrateCamera(self):
        imdata = self.acquireImage()
        if 'dose rate' not in self.results or self.results['dose rate'] is None:
            e = 'Unable to calibrate camera sensitivity: no dose measurement'
            self.logger.error(e)
            return
        try:
            sens = self.calclient.sensitivity_from_imagedata(
                imdata, self.results['dose rate'])
        except ValueError:
            e = 'Unable to calibrate camera sensitivity: invalid dose measurement'
            self.logger.error(e)
            return

        self.sens = sens
        ht = imdata['scope']['high tension']
        self.calclient.storeSensitivity(ht, sens)
        CallAfter(self.panel.dialog.scrsettings._setSensitivityResults, sens)