Example #1
0
        def cb_lazbuild_helper(result):
            def remove_whitespace(message):
                message_old = message
                message_new = message_old.replace('\n\n\n', '\n')

                while message_old != message_new:
                    message_old = message_new
                    message_new = message_old.replace('\n\n\n', '\n')
                return message_new

            self.button_compile.setEnabled(True)
            self.button_recompile_all.setEnabled(True)
            self.button_cancel.setEnabled(False)

            aborted = self.script_instance.abort
            self.script_instance = None

            okay, message = check_script_result(result,
                                                stderr_is_redirected=True)

            if not okay:
                self.log(remove_whitespace(message), pre=True)
                self.log('...error' if not aborted else '...canceled',
                         bold=True)
                return

            for s in remove_whitespace(result.stdout.rstrip()).split('\n'):
                self.log(s, pre=True)

            if aborted:
                self.log('...canceled', bold=True)
            elif result.exit_code != 0:
                self.log('...error', bold=True)
            else:
                self.log('...done')
Example #2
0
        def cb_fpcmake_helper(result):
            self.button_make.setEnabled(True)
            self.button_clean.setEnabled(True)
            self.button_cancel.setEnabled(False)

            aborted = self.script_instance.abort
            self.script_instance = None

            okay, message = check_script_result(result,
                                                stderr_is_redirected=True)

            if not okay:
                self.log(message, pre=True)
                self.log('...error' if not aborted else '...canceled',
                         bold=True)
                return

            for s in result.stdout.rstrip().split('\n'):
                self.log(s, pre=True)

            if aborted:
                self.log('...canceled', bold=True)
            elif result.exit_code != 0:
                self.log('...error', bold=True)
            else:
                self.log('...done')
Example #3
0
            def cb_settings_services_check(result):
                okay, message = check_script_result(result)
                if not okay:
                    self.label_discovering.setText('Error getting current services status:\n\n' + message)

                services_check_result = json.loads(result.stdout)

                if services_check_result:
                    if services_check_result['gpu'] is None or \
                        services_check_result['desktopenv'] is None or \
                        services_check_result['webserver'] is None or \
                        services_check_result['splashscreen'] is None or \
                        services_check_result['ap'] is None or \
                        services_check_result['servermonitoring'] is None or \
                        services_check_result['openhab'] is None or \
                        services_check_result['mobileinternet'] is None:
                        self.label_discovering.setText('Received incomplete current services status.')
                    else:
                        self.service_state.fetched          = True
                        self.service_state.gpu              = services_check_result['gpu']
                        self.service_state.desktopenv       = services_check_result['desktopenv']
                        self.service_state.webserver        = services_check_result['webserver']
                        self.service_state.splashscreen     = services_check_result['splashscreen']
                        self.service_state.ap               = services_check_result['ap']
                        self.service_state.servermonitoring = services_check_result['servermonitoring']
                        self.service_state.openhab          = services_check_result['openhab']
                        self.service_state.mobileinternet   = services_check_result['mobileinternet']

                        if self.image_version.number < (1, 4):
                            self.service_state.desktopenv = self.image_version.flavor == 'full'

                        self.label_discovering.hide()
                        self.tab_widget.show()
                        self.tab_widget.currentWidget().tab_on_focus()
            def cb_update_tf_software_mkdtemp(result):
                if not self.dialog_session:
                    return

                okay, message = check_script_result(result)

                if not okay:
                    msg = self.MESSAGE_ERR_UPDATE + ':\n' + message + '\n\n'
                    self.set_current_state(self.STATE_INIT)
                    self.tedit_main.setText(msg)
                    return

                self.update_info['processed'] = 0
                self.update_info['error'] = False
                self.update_info['error_messages'] = ''
                self.update_info['temp_dir'] = result.stdout.strip()

                if self.update_info['brickv']['update']:
                    self.do_open_update_file(
                        REDFile(self.session), 'brickv',
                        posixpath.join(self.update_info['temp_dir'],
                                       'brickv_linux_latest.deb'))

                for d in self.update_info['bindings']:
                    if not d['update']:
                        continue

                    self.do_open_update_file(
                        REDFile(self.session), d['name'],
                        posixpath.join(
                            self.update_info['temp_dir'], 'tinkerforge_' +
                            d['name'] + '_bindings_latest.zip'))
            def cb_update_tf_software_mkdtemp(result):
                if not self.dialog_session:
                    return
                okay, message = check_script_result(result)

                if not okay:
                    msg = self.MESSAGE_ERR_UPDATE + ':\n' + message + '\n\n'
                    self.set_current_state(self.STATE_INIT)
                    self.tedit_main.setText(msg)
                    return

                self.update_info['processed'] = 0
                self.update_info['error'] = False
                self.update_info['error_messages'] = ''
                self.update_info['temp_dir'] = result.stdout.strip()

                if self.update_info['brickv']['update']:
                    self.do_open_update_file(REDFile(self.session),
                                             'brickv',
                                             posixpath.join(self.update_info['temp_dir'], 'brickv_linux_latest.deb'))

                for d in self.update_info['bindings']:
                    if not d['update']:
                        continue

                    self.do_open_update_file(REDFile(self.session),
                                             d['name'],
                                             posixpath.join(self.update_info['temp_dir'], 'tinkerforge_' + d['name'] + '_bindings_latest.zip'))
Example #6
0
    def bindings_version_success(self, result):
        okay, message = check_script_result(result)
        if not okay:
            get_main_window().show_status('Failed to query RED Brick bindings versions: '+ message, message_id='red_bindings_version_success_error')
            return

        try:
            versions = json.loads(result.stdout)
        except Exception as e:
            get_main_window().show_status('Failed to parse RED Brick bindings versions as JSON: '+ str(e), message_id='red_bindings_version_success_error')
            return

        get_main_window().hide_status('red_bindings_version_success_error')

        self.device_info.bindings_infos = []
        for url_part, version in versions['bindings'].items():
            info = brickv.infos.BindingInfo()
            info.name = brickv.infos.get_bindings_name(url_part)
            info.url_part = url_part
            info.firmware_version_installed = tuple(int(i) for i in version.split('.'))

            brickv.infos.add_latest_fw(info)
            self.device_info.bindings_infos.append(info)

        red_brickv_info = brickv.infos.ToolInfo()
        red_brickv_info.name = 'Brick Viewer'
        red_brickv_info.url_part = 'brickv'
        red_brickv_info.firmware_version_installed = tuple(int(i) for i in versions['brickv'].split('.'))

        brickv.infos.add_latest_fw(red_brickv_info)
        self.device_info.brickv_info = red_brickv_info

        brickv.infos.get_infos_changed_signal().emit(self.device_info.uid)
        def cb_openhab_configs_list(result):
            okay, message = check_script_result(result, decode_stderr=True)

            def fatal_error(text):
                self.log_error(text)
                self.action_in_progress = False
                self.update_ui_state()

            if not okay:
                fatal_error(u'Error while collecting config files: {0}'.format(message))
                return

            try:
                config_names = json.loads(result.stdout)
            except Exception as e:
                fatal_error(u'Received invalid config file collection: {0}'.format(e))
                return

            if not isinstance(config_names, dict):
                fatal_error(u'Received invalid config file collection: Not a dictionary')
                return

            try:
                configs_by_basename = {}

                for name in config_names['items']:
                    configs_by_basename.setdefault(name[:-len('.items')], []).append((name, posixpath.join('/etc/openhab/configurations/items', name)))

                for name in config_names['sitemaps']:
                    configs_by_basename.setdefault(name[:-len('.sitemap')], []).append((name, posixpath.join('/etc/openhab/configurations/sitemaps', name)))

                for name in config_names['rules']:
                    configs_by_basename.setdefault(name[:-len('.rules')], []).append((name, posixpath.join('/etc/openhab/configurations/rules', name)))
            except Exception as e:
                fatal_error(u'Received invalid config file collection: {0}'.format(e))
                return

            old_configs = {}

            for config in self.configs:
                if config != None:
                    old_configs[config.display_name] = config

            self.configs = [old_configs['openhab.cfg'], old_configs['logback.xml']]

            for key in sorted(configs_by_basename):
                value = configs_by_basename[key]

                if len(value) > 0:
                    self.configs.append(None)

                    for display_name, absolute_name in sorted(value):
                        if display_name in old_configs:
                            self.configs.append(old_configs[display_name])
                        else:
                            self.configs.append(ConfigFile(display_name, absolute_name, self))

            self.recreate_widgets()
            self.refresh_config(0, done_callback)
Example #8
0
            def cb_success(result):
                okay, message = check_script_result(result)

                if not okay:
                    op = 'reboot' if param == 1 else 'shutdown'
                    QMessageBox.critical(get_main_window(),
                                         'Failed to {} RED Brick'.format(op),
                                         message)
                def cb_openhab_set_configs_ownership(result):
                    okay, message = check_script_result(result, decode_stderr=True)

                    if not okay:
                        QMessageBox.critical(get_main_window(), 'Apply Changes Error',
                                             'Error while setting ownership of {0}: {1}'.format(config.display_name, message))
                    else:
                        config.set_content(content)
                def cb_openhab_set_configs_ownership(result):
                    okay, message = check_script_result(result, decode_stderr=True)

                    if not okay:
                        QMessageBox.critical(get_main_window(), 'Apply Changes Error',
                                             'Error while setting ownership of {0}: {1}'.format(config.display_name, message))
                    else:
                        config.set_content(content)
    def cb_settings_mobile_internet_get_status(self, result):
        self.status_refresh_timer.stop()

        if not self.is_tab_on_focus:
            return

        okay, _ = check_script_result(result)
        if not okay:
            self.status_refresh_timer.start(INTERVAL_REFRESH_STATUS)
            return

        try:
            dict_status = json.loads(result.stdout)
        except Exception as e:
            QMessageBox.critical(get_main_window(),
                                 MESSAGEBOX_TITLE,
                                 MESSAGE_ERROR_STATUS_DECODE + ':\n\n' +str(e))

            self.status_refresh_timer.start(INTERVAL_REFRESH_STATUS)
            return

        # Update status GUI elements
        if not dict_status['status']:
            self.label_mi_status_status.setText('-')
        else:
            self.label_mi_status_status.setText(dict_status['status'])

        if not dict_status['signal_quality']:
            self.label_mi_status_signal_quality.setText('-')
        else:
            self.label_mi_status_signal_quality.setText(dict_status['signal_quality'])

        if not dict_status['interface']:
            self.label_mi_status_interface.setText('-')
        else:
            self.label_mi_status_interface.setText(dict_status['interface'])

        if not dict_status['ip']:
            self.label_mi_status_ip.setText('-')
        else:
            self.label_mi_status_ip.setText(dict_status['ip'])

        if not dict_status['subnet_mask']:
            self.label_mi_status_subnet_mask.setText('-')
        else:
            self.label_mi_status_subnet_mask.setText(dict_status['subnet_mask'])

        if not dict_status['gateway']:
            self.label_mi_status_gateway.setText('-')
        else:
            self.label_mi_status_gateway.setText(dict_status['gateway'])

        if not dict_status['dns']:
            self.label_mi_status_dns.setText('-')
        else:
            self.label_mi_status_dns.setText(dict_status['dns'])

        self.status_refresh_timer.start(INTERVAL_REFRESH_STATUS)
Example #12
0
 def cb_settings_ap_apply(result):
     if self.image_version.number >= (1, 10):
         okay, _ = check_script_result(result)
         if okay:
             self.script_manager.execute_script('settings_ap_status',
                                                cb_settings_ap_status)
         else:
             gui_after_apply(result)
     else:
         gui_after_apply(result)
    def cb_update_tf_software_copy_bindings(self, result):
        if not self.dialog_session:
            return

        okay, message = check_script_result(result, add_stdout_to_message=True)
        if not okay:
            self.update_info['error'] = True
            self.update_info['error_messages'] += message + '\n\n'

        self.handle_update_tf_software_install_cb()
    def cb_update_tf_software_copy_bindings(self, result):
        if not self.dialog_session:
            return

        okay, message = check_script_result(result, add_stdout_to_message=True)

        if not okay:
            self.update_info['error'] = True
            self.update_info['error_messages'] += message + '\n\n'

        self.handle_update_tf_software_install_cb()
Example #15
0
        def cb_settings_ap_apply(result):
            if self.image_version.number >= (1, 10):
                okay, _ = check_script_result(result)

                if okay:
                    self.script_manager.execute_script('settings_ap_status',
                                                       cb_settings_ap_status)
                else:
                    gui_after_apply(result)
            else:
                gui_after_apply(result)
Example #16
0
        def cb_walk(result):
            okay, message = check_script_result(result, decode_stderr=True)

            if not okay:
                self.label_error.setText('<b>Error:</b> ' +
                                         html.escape(message))
                self.label_error.setVisible(True)
                self.refresh_files_done()
                return

            self.label_error.setVisible(False)

            def expand_async(data):
                try:
                    walk = json.loads(
                        zlib.decompress(memoryview(data)).decode('utf-8'))
                except:
                    walk = None

                if walk == None or not isinstance(walk, dict):
                    available_files = []
                    available_directories = []
                    walk = None
                else:
                    available_files, available_directories = expand_walk_to_lists(
                        walk)

                return walk, available_files, available_directories

            def cb_expand_success(result):
                walk, available_files, available_directories = result

                self.available_files = available_files
                self.available_directories = available_directories

                if walk != None:
                    expand_walk_to_model(walk, self.tree_files_model,
                                         self.folder_icon, self.file_icon)
                else:
                    self.label_error.setText(
                        '<b>Error:</b> Received invalid data')
                    self.label_error.setVisible(True)

                self.tree_files.header().setSortIndicator(0, Qt.AscendingOrder)
                self.refresh_files_done()

            def cb_expand_error():
                self.label_error.setText('<b>Error:</b> Internal async error')
                self.label_error.setVisible(True)
                self.refresh_files_done()

            async_call(expand_async, result.stdout, cb_expand_success,
                       cb_expand_error)
Example #17
0
                def cb_java_main_classes(result):
                    script_instance = script_instance_ref[0]

                    if script_instance != None:
                        aborted = script_instance.abort
                    else:
                        aborted = False

                    script_instance_ref[0] = None

                    def done():
                        progress.cancel()
                        self.combo_main_class.setEnabled(True)
                        self.completeChanged.emit()

                    if aborted:
                        done()
                        return

                    okay, message = check_script_result(result, decode_stderr=True)

                    if not okay:
                        self.label_main_class_error.setText('<b>Error:</b> ' + html.escape(message))
                        self.label_main_class_error.setVisible(True)
                        done()
                        return

                    def expand_async(data):
                        try:
                            main_classes = json.loads(zlib.decompress(memoryview(data)).decode('utf-8'))

                            if not isinstance(main_classes, dict):
                                main_classes = {}
                        except:
                            main_classes = {}

                        return main_classes

                    def cb_expand_success(main_classes):
                        self.combo_main_class.clear()

                        for cls in sorted(main_classes.keys()):
                            self.combo_main_class.addItem(cls, main_classes[cls])

                        self.combo_main_class_checker.set_current_text(program.cast_custom_option_value('java.main_class', str, ''))
                        done()

                    def cb_expand_error():
                        self.label_main_class_error.setText('<b>Error:</b> Internal async error')
                        self.label_main_class_error.setVisible(True)
                        done()

                    async_call(expand_async, result.stdout, cb_expand_success, cb_expand_error)
Example #18
0
                def cb_java_main_classes(result):
                    script_instance = script_instance_ref[0]

                    if script_instance != None:
                        aborted = script_instance.abort
                    else:
                        aborted = False

                    script_instance_ref[0] = None

                    def done():
                        progress.cancel()
                        self.combo_main_class.setEnabled(True)
                        self.completeChanged.emit()

                    if aborted:
                        done()
                        return

                    okay, message = check_script_result(result, decode_stderr=True)

                    if not okay:
                        self.label_main_class_error.setText('<b>Error:</b> ' + Qt.escape(message))
                        self.label_main_class_error.setVisible(True)
                        done()
                        return

                    def expand_async(data):
                        try:
                            main_classes = json.loads(zlib.decompress(buffer(data)).decode('utf-8'))

                            if not isinstance(main_classes, dict):
                                main_classes = {}
                        except:
                            main_classes = {}

                        return main_classes

                    def cb_expand_success(main_classes):
                        self.combo_main_class.clear()

                        for cls in sorted(main_classes.keys()):
                            self.combo_main_class.addItem(cls, main_classes[cls])

                        self.combo_main_class_checker.set_current_text(program.cast_custom_option_value('java.main_class', unicode, ''))
                        done()

                    def cb_expand_error():
                        self.label_main_class_error.setText('<b>Error:</b> Internal async error')
                        self.label_main_class_error.setVisible(True)
                        done()

                    async_call(expand_async, result.stdout, cb_expand_success, cb_expand_error)
Example #19
0
    def cb_versions(result):
        okay, _ = check_script_result(result)

        if okay:
            try:
                version = result.stderr.split('\n')[1].split(' ')[5].replace(')', '')
                callback([ExecutableVersion('/usr/bin/java', version)])
                return
            except:
                pass

        # Could not get versions, we assume that some version of java 8 is installed
        callback([ExecutableVersion('/usr/bin/java', '1.8')])
Example #20
0
    def cb_versions(result):
        okay, _ = check_script_result(result)

        if okay:
            try:
                version = result.stdout.split("\n")[0].split(" ")[1]
                callback([ExecutableVersion("/usr/bin/php", version)])
                return
            except:
                pass

        # Could not get versions, we assume that some version of php 5 is installed
        callback([ExecutableVersion("/usr/bin/php", "5.x")])
    def cb_versions(result):
        okay, _ = check_script_result(result)

        if okay:
            try:
                version = result.stdout.split('\n')[0].replace('v', '')
                callback([ExecutableVersion('/usr/local/bin/node', version)])
                return
            except:
                pass

        # Could not get versions, we assume that some version of nodejs is installed
        callback([ExecutableVersion('/usr/local/bin/node', None)])
Example #22
0
    def cb_versions(result):
        okay, _ = check_script_result(result)

        if okay:
            try:
                version = result.stdout.split('\n')[0]
                callback([ExecutableVersion('/usr/bin/lazbuild', version)])
                return
            except:
                pass

        # Could not get versions, we assume that lazbuild is not installed
        callback([ExecutableVersion('/usr/bin/lazbuild', None)])
Example #23
0
    def cb_versions(result):
        okay, _ = check_script_result(result)

        if okay:
            try:
                version = result.stderr.split('\n')[1].split(' ')[5].replace(')', '')
                callback([ExecutableVersion('/usr/bin/java', version)])
                return
            except:
                pass

        # Could not get versions, we assume that some version of java 8 is installed
        callback([ExecutableVersion('/usr/bin/java', '1.8')])
Example #24
0
    def cb_versions(result):
        okay, _ = check_script_result(result)

        if okay:
            try:
                version = result.stdout.split('\n')[1].split(' ')[8].replace('(v', '').replace('(', '').replace(')', '')
                callback([ExecutableVersion('/usr/bin/perl', version)])
                return
            except:
                pass

        # Could not get versions, we assume that some version of perl 5 is installed
        callback([ExecutableVersion('/usr/bin/perl', '5.x')])
Example #25
0
    def cb_versions(result):
        okay, _ = check_script_result(result)

        if okay:
            try:
                version = result.stdout.split('\n')[0].split(' ')[4]
                callback([ExecutableVersion('/usr/bin/mono', version)])
                return
            except:
                pass

        # Could not get versions, we assume that some version of mono 3.2 is installed
        callback([ExecutableVersion('/usr/bin/mono', '3.2')])
Example #26
0
    def cb_versions(result):
        okay, _ = check_script_result(result)

        if okay:
            try:
                version = (' '.join(result.stdout.split('\n')[0].split(' ')[:-1])).replace('version ', '')
                callback([ExecutableVersion('/bin/bash', version)])
                return
            except:
                pass

        # Could not get versions, we assume that some version of bash is installed
        callback([ExecutableVersion('/bin/bash', 'bash')])
Example #27
0
    def cb_versions(result):
        okay, _ = check_script_result(result)

        if okay:
            try:
                version = result.stdout.split('\n')[0]
                callback([ExecutableVersion('/usr/bin/lazbuild', version)])
                return
            except:
                pass

        # Could not get versions, we assume that lazbuild is not installed
        callback([ExecutableVersion('/usr/bin/lazbuild', None)])
Example #28
0
    def cb_versions(result):
        okay, _ = check_script_result(result)

        if okay:
            try:
                version = result.stdout.split('\n')[1].split(' ')[8].replace('(v', '').replace('(', '').replace(')', '')
                callback([ExecutableVersion('/usr/bin/perl', version)])
                return
            except:
                pass

        # Could not get versions, we assume that some version of perl 5 is installed
        callback([ExecutableVersion('/usr/bin/perl', '5.x')])
Example #29
0
    def cb_versions(result):
        okay, _ = check_script_result(result)

        if okay:
            try:
                version = result.stdout.split('\n')[0].split(' ')[1]
                callback([ExecutableVersion('/usr/bin/ruby', version)])
                return
            except:
                pass

        # Could not get versions, we assume that some version of ruby 1.9 is installed
        callback([ExecutableVersion('/usr/bin/ruby', '1.9')])
Example #30
0
    def cb_versions(result):
        okay, _ = check_script_result(result)

        if okay:
            try:
                version = result.stdout.split('\n')[0].replace('v', '')
                callback([ExecutableVersion('/usr/local/bin/node', version)])
                return
            except:
                pass

        # Could not get versions, we assume that some version of nodejs is installed
        callback([ExecutableVersion('/usr/local/bin/node', None)])
Example #31
0
    def cb_versions(result):
        okay, _ = check_script_result(result)

        if okay:
            try:
                version = (' '.join(
                    result.stdout.split('\n')[0].split(' ')[:-1])).replace(
                        'version ', '')
                callback([ExecutableVersion('/bin/bash', version)])
                return
            except:
                pass

        # Could not get versions, we assume that some version of bash is installed
        callback([ExecutableVersion('/bin/bash', 'bash')])
Example #32
0
        def cb_settings_ap_status(result):
            okay, _ = check_script_result(result)
            if okay:
                ap_mode_status = json.loads(result.stdout)

                if ap_mode_status['ap_incomplete_config'] or \
                   ap_mode_status['ap_hardware_or_config_problem']:
                    apply_dict['hostapd_driver'] = 'driver=rtl871xdrv'
                    self.script_manager.execute_script('settings_ap_apply',
                                                       cb_settings_ap_apply_2,
                                                       [json.dumps(apply_dict)])
                else:
                    gui_after_apply(result)
            else:
                gui_after_apply(result)
Example #33
0
        def cb_settings_ap_status(result):
            okay, _ = check_script_result(result)

            if okay:
                ap_mode_status = json.loads(result.stdout)

                if ap_mode_status['ap_incomplete_config'] or \
                   ap_mode_status['ap_hardware_or_config_problem']:
                    apply_dict['hostapd_driver'] = 'driver=rtl871xdrv'
                    self.script_manager.execute_script(
                        'settings_ap_apply', cb_settings_ap_apply_2,
                        [json.dumps(apply_dict)])
                else:
                    gui_after_apply(result)
            else:
                gui_after_apply(result)
    def cb_versions(result):
        okay, _ = check_script_result(result)

        if okay:
            try:
                versions = result.stdout.split('\n')
                callback([ExecutableVersion('/usr/bin/python2', versions[0].split(' ')[1]),
                          ExecutableVersion('/usr/bin/python3', versions[1].split(' ')[1])])
                return
            except:
                pass

        # Could not get versions, we assume that some version
        # of python 2.7 and some version of python 3 is installed
        callback([ExecutableVersion('/usr/bin/python2', '2.7'),
                  ExecutableVersion('/usr/bin/python3', '3.x')])
Example #35
0
        def cb_walk(result):
            okay, message = check_script_result(result, decode_stderr=True)

            if not okay:
                self.label_error.setText('<b>Error:</b> ' + html.escape(message))
                self.label_error.setVisible(True)
                self.refresh_files_done()
                return

            self.label_error.setVisible(False)

            def expand_async(data):
                try:
                    walk = json.loads(zlib.decompress(memoryview(data)).decode('utf-8'))
                except:
                    walk = None

                if walk == None or not isinstance(walk, dict):
                    available_files       = []
                    available_directories = []
                    walk                  = None
                else:
                    available_files, available_directories = expand_walk_to_lists(walk)

                return walk, available_files, available_directories

            def cb_expand_success(result):
                walk, available_files, available_directories = result

                self.available_files       = available_files
                self.available_directories = available_directories

                if walk != None:
                    expand_walk_to_model(walk, self.tree_files_model, self.folder_icon, self.file_icon)
                else:
                    self.label_error.setText('<b>Error:</b> Received invalid data')
                    self.label_error.setVisible(True)

                self.tree_files.header().setSortIndicator(0, Qt.AscendingOrder)
                self.refresh_files_done()

            def cb_expand_error():
                self.label_error.setText('<b>Error:</b> Internal async error')
                self.label_error.setVisible(True)
                self.refresh_files_done()

            async_call(expand_async, result.stdout, cb_expand_success, cb_expand_error)
Example #36
0
        def cb_update_main(result):
            okay, _ = check_script_result(result)
            if not okay:
                return

            versions = result.stdout.split('\n')
            num_versions = len(self.package_list[0])

            if len(versions) < num_versions:
                # TODO: Error for user?
                return

            for i in range(num_versions):
                self.package_list[0][i]['version'] = versions[i]

            self.tab_data[0]['updated'] = True
            self.update_table()
Example #37
0
    def cb_versions(result):
        okay, _ = check_script_result(result)

        if okay:
            try:
                versions    = result.stdout.split('\n\n')
                version_gcc = versions[0].split('\n')[0].split(' ')
                version_gpp = versions[1].split('\n')[0].split(' ')
                callback([ExecutableVersion('/usr/bin/' + version_gcc[0], version_gcc[3]),
                          ExecutableVersion('/usr/bin/' + version_gpp[0], version_gpp[3])])
                return
            except:
                pass

        # Could not get versions, we assume that some version of gcc/g++ is installed
        callback([ExecutableVersion('/usr/bin/gcc', None),
                  ExecutableVersion('/usr/bin/g++', None)])
Example #38
0
        def cb_update_main(result):
            okay, _ = check_script_result(result)

            if not okay:
                return

            versions = result.stdout.split('\n')
            num_versions = len(self.package_list[0])

            if len(versions) < num_versions:
                # TODO: Error for user?
                return

            for i in range(num_versions):
                self.package_list[0][i]['version'] = versions[i]

            self.tab_data[0]['updated'] = True
            self.update_table()
Example #39
0
            def cb_settings_services_check(result):
                okay, message = check_script_result(result)

                if not okay:
                    self.label_discovering.setText(
                        'Error getting current services status:\n\n' + message)
                    return

                services_check_result = json.loads(result.stdout)

                if services_check_result:
                    if services_check_result['gpu'] is None or \
                        services_check_result['desktopenv'] is None or \
                        services_check_result['webserver'] is None or \
                        services_check_result['splashscreen'] is None or \
                        services_check_result['ap'] is None or \
                        services_check_result['servermonitoring'] is None or \
                        services_check_result['openhab'] is None or \
                        services_check_result['mobileinternet'] is None:
                        self.label_discovering.setText(
                            'Received incomplete current services status.')
                    else:
                        self.service_state.fetched = True
                        self.service_state.gpu = services_check_result['gpu']
                        self.service_state.desktopenv = services_check_result[
                            'desktopenv']
                        self.service_state.webserver = services_check_result[
                            'webserver']
                        self.service_state.splashscreen = services_check_result[
                            'splashscreen']
                        self.service_state.ap = services_check_result['ap']
                        self.service_state.servermonitoring = services_check_result[
                            'servermonitoring']
                        self.service_state.openhab = services_check_result[
                            'openhab']
                        self.service_state.mobileinternet = services_check_result[
                            'mobileinternet']

                        if self.image_version.number < (1, 4):
                            self.service_state.desktopenv = self.image_version.flavor == 'full'

                        self.label_discovering.hide()
                        self.tab_widget.show()
                        self.tab_widget.currentWidget().tab_on_focus()
Example #40
0
    def bindings_version_success(self, result):
        okay, message = check_script_result(result)

        if not okay:
            get_main_window().show_status(
                'Failed to query RED Brick bindings versions: ' + message,
                message_id='red_bindings_version_success_error')
            return

        try:
            versions = json.loads(result.stdout)
        except Exception as e:
            get_main_window().show_status(
                'Failed to parse RED Brick bindings versions as JSON: ' +
                str(e),
                message_id='red_bindings_version_success_error')
            return

        get_main_window().hide_status('red_bindings_version_success_error')

        self.device_info.bindings_infos = []

        for url_part, version in versions['bindings'].items():
            bindings_info = BindingsInfo()
            bindings_info.name = get_bindings_name(url_part)
            bindings_info.url_part = url_part
            bindings_info.firmware_version_installed = tuple(
                int(i) for i in version.split('.'))

            bindings_info.update_firmware_version_latest()

            self.device_info.bindings_infos.append(bindings_info)

        brickv_info = ToolInfo()
        brickv_info.name = 'Brick Viewer'
        brickv_info.url_part = 'brickv'
        brickv_info.firmware_version_installed = tuple(
            int(i) for i in versions['brickv'].split('.'))

        brickv_info.update_firmware_version_latest()

        self.device_info.brickv_info = brickv_info

        inventory.sync()
    def cb_update_tf_software_install(self, is_binding, name, result):
        if not self.dialog_session:
            return

        display_name = ''
        self.update_info['processed'] = self.update_info['processed'] + 1

        if name == 'brickv':
            display_name = self.update_info['brickv']['display_name']
        else:
            for d in self.update_info['bindings']:
                if d['name'] != name:
                    continue

                display_name = d['display_name']
                break

        okay, message = check_script_result(result, add_stdout_to_message=True)

        if not okay:
            self.update_info['error'] = True
            self.update_info[
                'error_messages'] += 'Error while installing ' + display_name + ':\n' + message + '\n\n'

            self.handle_update_tf_software_install_cb()
        else:
            self.label_pbar.setText('Installed ' + display_name)

            if is_binding:
                '''
                Copy the bindings from the temp directory to the target directory.

                This copy will update the changelog which is the basis of update detection.
                It is important to ensure that the copying is done *AFTER* the update process was successful.
                '''
                self.script_manager.execute_script(
                    'update_tf_software_copy_bindings',
                    self.cb_update_tf_software_copy_bindings, [
                        posixpath.join(self.update_info['temp_dir'],
                                       'bindings'), name
                    ])
            else:
                self.handle_update_tf_software_install_cb()
Example #42
0
    def cb_versions(result):
        okay, _ = check_script_result(result, stderr_is_redirected=True)

        if okay:
            try:
                versions = result.stdout.split('\n')
                callback([
                    ExecutableVersion('/usr/bin/python2',
                                      versions[0].split(' ')[1]),
                    ExecutableVersion('/usr/bin/python3',
                                      versions[1].split(' ')[1])
                ])
                return
            except:
                pass

        # Could not get versions, we assume that some version
        # of python 2.7 and some version of python 3 is installed
        callback([
            ExecutableVersion('/usr/bin/python2', '2.7'),
            ExecutableVersion('/usr/bin/python3', '3.x')
        ])
    def cb_update_tf_software_install(self, is_binding, name, result):
        if not self.dialog_session:
            return

        display_name = ''
        self.update_info['processed'] = self.update_info['processed'] + 1

        if name == 'brickv':
            display_name = self.update_info['brickv']['display_name']
        else:
            for d in self.update_info['bindings']:
                if d['name'] != name:
                    continue

                display_name = d['display_name']

                break

        okay, message = check_script_result(result, add_stdout_to_message=True)
        if not okay:
            self.update_info['error'] = True
            self.update_info['error_messages'] += 'Error while installing ' + display_name + ':\n' + message + '\n\n'

            self.handle_update_tf_software_install_cb()
        else:
            self.label_pbar.setText('Installed ' + display_name)

            if is_binding:
                '''
                Copy the bindings from the temp directory to the target directory.

                This copy will update the changelog which is the basis of update detection.
                It is important to ensure that the copying is done *AFTER* the update process was successful.
                '''
                self.script_manager.execute_script('update_tf_software_copy_bindings',
                                                   self.cb_update_tf_software_copy_bindings,
                                                   [posixpath.join(self.update_info['temp_dir'], 'bindings'), name])
            else:
                self.handle_update_tf_software_install_cb()
Example #44
0
    def cb_versions(result):
        okay, _ = check_script_result(result)

        if okay:
            try:
                versions = result.stdout.split('\n\n')
                version_gcc = versions[0].split('\n')[0].split(' ')
                version_gpp = versions[1].split('\n')[0].split(' ')
                callback([
                    ExecutableVersion('/usr/bin/' + version_gcc[0],
                                      version_gcc[3]),
                    ExecutableVersion('/usr/bin/' + version_gpp[0],
                                      version_gpp[3])
                ])
                return
            except:
                pass

        # Could not get versions, we assume that some version of gcc/g++ is installed
        callback([
            ExecutableVersion('/usr/bin/gcc', None),
            ExecutableVersion('/usr/bin/g++', None)
        ])
Example #45
0
        def cb_program_logs_list(result):
            okay, message = check_script_result(result, decode_stderr=True)

            if not okay:
                self.label_error.setText('<b>Error:</b> ' + html.escape(message))
                self.label_error.setVisible(True)
                self.refresh_logs_done()
                return

            try:
                # FIXME: do decompress in an async_call
                program_logs_list = json.loads(zlib.decompress(memoryview(result.stdout)).decode('utf-8'))
            except:
                program_logs_list = None

            if program_logs_list == None or not isinstance(program_logs_list, dict):
                self.label_error.setText('<b>Error:</b> Received invalid data')
                self.label_error.setVisible(True)
                self.refresh_logs_done()
                return

            self.label_error.setVisible(False)

            def create_file_size_item(size):
                item = QStandardItem(get_file_display_size(size))
                item.setData(size, USER_ROLE_SIZE)

                return item

            def update_file_size_item(item, additional_size):
                current_size = item.data(USER_ROLE_SIZE)
                new_size     = current_size + additional_size

                item.setText(get_file_display_size(new_size))
                item.setData(new_size, USER_ROLE_SIZE)

            continuous_row = None
            date_rows      = {}
            time_rows      = {}

            for file_name, file_size in program_logs_list.items():
                QApplication.processEvents()

                file_name_parts = file_name.split('_')

                if file_name_parts[0] == "continuous":
                    if len(file_name_parts) != 2:
                        continue

                    if continuous_row == None:
                        continuous_item = QStandardItem("Continuous")
                        continuous_item.setData(ITEM_TYPE_PARENT_CONT, USER_ROLE_ITEM_TYPE)

                        continuous_row = [continuous_item, create_file_size_item(0)]

                        self.tree_logs_model.appendRow(continuous_row)

                    log_item = QStandardItem(file_name_parts[1])
                    log_item.setData(self.file_icon, Qt.DecorationRole)
                    log_item.setData(file_name, USER_ROLE_FILE_NAME)
                    log_item.setData(ITEM_TYPE_LOG_FILE_CONT, USER_ROLE_ITEM_TYPE)

                    continuous_row[0].appendRow([log_item, create_file_size_item(file_size)])
                    update_file_size_item(continuous_row[1], file_size)
                else:
                    if len(file_name_parts) != 3:
                        continue

                    try:
                        timestamp = int(file_name_parts[1].split('+')[0]) // 1000000
                    except ValueError:
                        continue

                    #FIXME: fromTime_t is obsolete: https://doc.qt.io/qt-5/qdatetime-obsolete.html#toTime_t
                    date      = QDateTime.fromTime_t(timestamp).toString('yyyy-MM-dd')
                    time      = QDateTime.fromTime_t(timestamp).toString('HH:mm:ss')
                    date_time = date + 'T' + time

                    if date in date_rows:
                        date_row = date_rows[date]
                    else:
                        date_item = QStandardItem(date)
                        date_item.setData(ITEM_TYPE_PARENT_DATE, USER_ROLE_ITEM_TYPE)

                        date_row        = [date_item, create_file_size_item(0)]
                        date_rows[date] = date_row

                        self.tree_logs_model.appendRow(date_row)

                    if date_time in time_rows:
                        time_row = time_rows[date_time]
                    else:
                        time_item = QStandardItem(time)
                        time_item.setData(ITEM_TYPE_PARENT_TIME, USER_ROLE_ITEM_TYPE)

                        time_row             = [time_item, create_file_size_item(0)]
                        time_rows[date_time] = time_row

                        date_row[0].appendRow(time_row)

                    log_item = QStandardItem(file_name_parts[2])
                    log_item.setData(self.file_icon, Qt.DecorationRole)
                    log_item.setData(file_name, USER_ROLE_FILE_NAME)
                    log_item.setData(ITEM_TYPE_LOG_FILE, USER_ROLE_ITEM_TYPE)

                    time_row[0].appendRow([log_item, create_file_size_item(file_size)])
                    update_file_size_item(time_row[1], file_size)
                    update_file_size_item(date_row[1], file_size)

            self.tree_logs.header().setSortIndicator(0, Qt.DescendingOrder)
            self.refresh_logs_done()
            def cb_update_tf_software_get_installed_versions(result):
                if not self.dialog_session:
                    return

                self.set_current_state(self.STATE_NO_UPDATES_AVAILABLE)

                okay, message = check_script_result(result)

                if not okay:
                    msg = self.MESSAGE_ERR_GET_INSTALLED_VERSIONS + ':\n' + message + '\n\n'
                    self.set_current_state(self.STATE_INIT)
                    self.tedit_main.setText(msg)
                    return

                updates_available_main = False
                update_info = {
                    'brickv': {},
                    'processed': 0,
                    'temp_dir': '',
                    'bindings': [],
                    'error': False,
                    'updates_total': 0,
                    'error_messages': ''
                }

                installed_versions = json.loads(result.stdout)

                if not isinstance(installed_versions, dict):
                    self.set_current_state(self.STATE_INIT)
                    self.tedit_main.setText(
                        self.MESSAGE_ERR_GET_INSTALLED_VERSIONS + '.')

                    return

                for key, value in installed_versions.items():
                    if key == 'brickv':
                        update_info['brickv']['to'] = '0'
                        update_info['brickv']['name'] = '-'
                        update_info['brickv']['from'] = '0'
                        update_info['brickv']['data'] = None
                        update_info['brickv']['update'] = False
                        update_info['brickv']['display_name'] = '-'

                        if isinstance(value,
                                      str) and value != '' and value != '-':
                            update_info['brickv']['from'] = value
                            update_info['brickv']['name'] = 'brickv'

                            continue
                        else:
                            self.set_current_state(self.STATE_INIT)
                            self.tedit_main.setText(
                                self.MESSAGE_ERR_GET_INSTALLED_VERSIONS + '.')

                            return

                    elif key == 'bindings':
                        if isinstance(value, dict) and value:
                            for k, v in value.items():
                                d = {}

                                d['to'] = '0'
                                d['name'] = '-'
                                d['from'] = '0'
                                d['data'] = None
                                d['update'] = False
                                d['display_name'] = '-'

                                if isinstance(v, str) and v != '' and v != '-':
                                    d['from'] = v
                                    d['name'] = k.strip()

                                    update_info['bindings'].append(d)
                                else:
                                    self.set_current_state(self.STATE_INIT)
                                    self.tedit_main.setText(
                                        self.MESSAGE_ERR_GET_INSTALLED_VERSIONS
                                        + '.')

                                    return
                            continue
                        else:
                            self.set_current_state(self.STATE_INIT)
                            self.tedit_main.setText(
                                self.MESSAGE_ERR_GET_INSTALLED_VERSIONS + '.')

                            return
                    else:
                        self.set_current_state(self.STATE_INIT)
                        self.tedit_main.setText(
                            self.MESSAGE_ERR_GET_INSTALLED_VERSIONS + '.')

                        return

                # Try to get the latest version numbers.
                try:
                    response = urlopen(self.URL_LATEST_VERSIONS, timeout=10)
                    response_data = response.read().decode('utf-8')
                except urllib.error.URLError:
                    self.set_current_state(self.STATE_INIT)
                    self.tedit_main.setText(
                        self.MESSAGE_ERR_CHECK_LATEST_VERSIONS)

                    return

                response_data_lines = response_data.splitlines()

                if len(response_data_lines) < 1:
                    self.set_current_state(self.STATE_INIT)
                    self.tedit_main.setText(
                        self.MESSAGE_ERR_CHECK_LATEST_VERSIONS)

                    return

                for l in response_data_lines:
                    l_split = l.strip().split(':')

                    if len(l_split) != 3:
                        self.set_current_state(self.STATE_INIT)
                        self.tedit_main.setText(
                            self.MESSAGE_ERR_CHECK_LATEST_VERSIONS)

                        return
                    else:
                        if l_split[0] == 'tools' and l_split[1] == 'brickv':
                            update_info['brickv']['to'] = l_split[2]
                            update_info['brickv'][
                                'display_name'] = 'Brick Viewer'
                            version_to = StrictVersion(l_split[2].strip())
                            version_from = StrictVersion(
                                update_info['brickv']['from'].strip())

                            if version_to > version_from:
                                updates_available_main = True
                                update_info['brickv']['update'] = True
                            else:
                                update_info['brickv']['update'] = False

                            continue

                        elif l_split[0] == 'bindings':
                            if l_split[1] == 'c':
                                found, updates_available = self.update_latest_version_info(
                                    update_info, l_split[1], l_split[2],
                                    'C/C++ Bindings')

                                if not found:
                                    self.set_current_state(self.STATE_INIT)
                                    self.tedit_main.setText(
                                        self.MESSAGE_ERR_CHECK_LATEST_VERSIONS)

                                    return

                                if updates_available:
                                    updates_available_main = True

                            elif l_split[1] == 'csharp':
                                found, updates_available = self.update_latest_version_info(
                                    update_info, l_split[1], l_split[2],
                                    'C#/Mono Bindings')

                                if not found:
                                    self.set_current_state(self.STATE_INIT)
                                    self.tedit_main.setText(
                                        self.MESSAGE_ERR_CHECK_LATEST_VERSIONS)

                                    return

                                if updates_available:
                                    updates_available_main = True

                            elif l_split[1] == 'delphi':
                                found, updates_available = self.update_latest_version_info(
                                    update_info, l_split[1], l_split[2],
                                    'Delphi/Lazarus Bindings')

                                if not found:
                                    self.set_current_state(self.STATE_INIT)
                                    self.tedit_main.setText(
                                        self.MESSAGE_ERR_CHECK_LATEST_VERSIONS)

                                    return

                                if updates_available:
                                    updates_available_main = True

                            elif l_split[1] == 'java':
                                found, updates_available = self.update_latest_version_info(
                                    update_info, l_split[1], l_split[2],
                                    'Java Bindings')

                                if not found:
                                    self.set_current_state(self.STATE_INIT)
                                    self.tedit_main.setText(
                                        self.MESSAGE_ERR_CHECK_LATEST_VERSIONS)

                                    return

                                if updates_available:
                                    updates_available_main = True

                            elif l_split[1] == 'javascript':
                                found, updates_available = self.update_latest_version_info(
                                    update_info, l_split[1], l_split[2],
                                    'JavaScript Bindings')

                                if not found:
                                    self.set_current_state(self.STATE_INIT)
                                    self.tedit_main.setText(
                                        self.MESSAGE_ERR_CHECK_LATEST_VERSIONS)

                                    return

                                if updates_available:
                                    updates_available_main = True

                            elif l_split[1] == 'matlab':
                                found, updates_available = self.update_latest_version_info(
                                    update_info, l_split[1], l_split[2],
                                    'Octave Bindings')

                                if not found:
                                    self.set_current_state(self.STATE_INIT)
                                    self.tedit_main.setText(
                                        self.MESSAGE_ERR_CHECK_LATEST_VERSIONS)

                                    return

                                if updates_available:
                                    updates_available_main = True

                            elif l_split[1] == 'perl':
                                found, updates_available = self.update_latest_version_info(
                                    update_info, l_split[1], l_split[2],
                                    'Perl Bindings')

                                if not found:
                                    self.set_current_state(self.STATE_INIT)
                                    self.tedit_main.setText(
                                        self.MESSAGE_ERR_CHECK_LATEST_VERSIONS)

                                    return

                                if updates_available:
                                    updates_available_main = True

                            elif l_split[1] == 'php':
                                found, updates_available = self.update_latest_version_info(
                                    update_info, l_split[1], l_split[2],
                                    'PHP Bindings')

                                if not found:
                                    self.set_current_state(self.STATE_INIT)
                                    self.tedit_main.setText(
                                        self.MESSAGE_ERR_CHECK_LATEST_VERSIONS)

                                    return

                                if updates_available:
                                    updates_available_main = True

                            elif l_split[1] == 'python':
                                found, updates_available = self.update_latest_version_info(
                                    update_info, l_split[1], l_split[2],
                                    'Python Bindings')

                                if not found:
                                    self.set_current_state(self.STATE_INIT)
                                    self.tedit_main.setText(
                                        self.MESSAGE_ERR_CHECK_LATEST_VERSIONS)

                                    return

                                if updates_available:
                                    updates_available_main = True

                            elif l_split[1] == 'ruby':
                                found, updates_available = self.update_latest_version_info(
                                    update_info, l_split[1], l_split[2],
                                    'Ruby Bindings')

                                if not found:
                                    self.set_current_state(self.STATE_INIT)
                                    self.tedit_main.setText(
                                        self.MESSAGE_ERR_CHECK_LATEST_VERSIONS)

                                    return

                                if updates_available:
                                    updates_available_main = True

                            elif l_split[1] == 'shell':
                                found, updates_available = self.update_latest_version_info(
                                    update_info, l_split[1], l_split[2],
                                    'Shell Bindings')

                                if not found:
                                    self.set_current_state(self.STATE_INIT)
                                    self.tedit_main.setText(
                                        self.MESSAGE_ERR_CHECK_LATEST_VERSIONS)

                                    return

                                if updates_available:
                                    updates_available_main = True

                            elif l_split[1] == 'vbnet':
                                found, updates_available = self.update_latest_version_info(
                                    update_info, l_split[1], l_split[2],
                                    'VB.NET Bindings')

                                if not found:
                                    self.set_current_state(self.STATE_INIT)
                                    self.tedit_main.setText(
                                        self.MESSAGE_ERR_CHECK_LATEST_VERSIONS)

                                    return

                                if updates_available:
                                    updates_available_main = True

                self.red_plugin.bindings_version_success(result)

                _check_update_available = self.check_update_available(
                    update_info)

                if not _check_update_available:
                    self.set_current_state(self.STATE_INIT)
                    self.tedit_main.setText(
                        self.MESSAGE_ERR_GET_INSTALLED_VERSIONS + '.')

                    return

                if updates_available_main:
                    self.set_current_state(self.STATE_UPDATES_AVAILABLE)
                    self.do_update_available_message(update_info)
                else:
                    self.set_current_state(self.STATE_NO_UPDATES_AVAILABLE)
                    self.tedit_main.setText(
                        self.MESSAGE_INFO_STATE_NO_UPDATES_AVAILABLE)
Example #47
0
    def cb_overview(self, result):
        # check if the tab is still on view or not
        if not self.is_tab_on_focus:
            self.refresh_timer.stop()
            return

        self.refresh_counter = 0
        self.refresh_timer.start(REFRESH_TIMEOUT)

        okay, message = check_script_result(result, decode_stderr=True)

        if not okay:
            self.label_error.setText('<b>Error:</b> ' + QtCore.Qt.escape(message))
            self.label_error.show()
            return

        self.label_error.hide()

        try:
            data = json.loads(zlib.decompress(buffer(result.stdout)).decode('utf-8'))

            days, days_remainder = divmod(int(data['uptime']), 24 * 60 * 60)
            hours, hours_remainder = divmod(days_remainder, 60 * 60)
            minutes, _ = divmod(hours_remainder, 60)
            uptime = ''

            if days > 0:
                uptime += str(days)

                if days == 1:
                    uptime += ' day '
                else:
                    uptime += ' days '

            if hours > 0:
                uptime += str(hours)

                if hours == 1:
                    uptime += ' hour '
                else:
                    uptime += ' hours '

            uptime += str(minutes)

            if minutes == 1:
                uptime += ' minute'
            else:
                uptime += ' minutes'

            cpu_percent = data['cpu_used']
            cpu_percent_v = int(data['cpu_used'])

            memory_used = self.bytes2human(int(data['mem_used']))
            memory_total = self.bytes2human(int(data['mem_total']))
            memory_percent = "%.1f" % ((float(memory_used) / float(memory_total)) * 100)
            memory_percent_v = int(memory_percent.split('.')[0])

            storage_used = self.bytes2human(int(data['disk_used']))
            storage_total = self.bytes2human(int(data['disk_total']))
            storage_percent = "%.1f" % ((float(storage_used) / float(storage_total)) * 100)
            storage_percent_v = int(storage_percent.split('.')[0])

            nic_data_dict = data['ifaces']
            processes_data_list = data['processes']
        except:
            # some parsing error due to malfromed or incomplete output occured.
            # ignore it and wait for the next update
            return

        self.label_uptime_value.setText(uptime)

        pbar_cpu_fmt = "{0}%".format(cpu_percent)
        pbar_memory_fmt = "{0}% [{1} of {2} MiB]".format(memory_percent, memory_used, memory_total)
        pbar_storage_fmt = "{0}% [{1} of {2} GiB]".format(storage_percent, storage_used, storage_total)

        if sys.platform == 'darwin':
            self.label_pbar_cpu.show()
            self.label_pbar_memory.show()
            self.label_pbar_storage.show()
            self.label_pbar_cpu.setText(pbar_cpu_fmt)
            self.label_pbar_memory.setText(pbar_memory_fmt)
            self.label_pbar_storage.setText(pbar_storage_fmt)
        else:
            self.pbar_cpu.setFormat(pbar_cpu_fmt)
            self.pbar_memory.setFormat(pbar_memory_fmt)
            self.pbar_storage.setFormat(pbar_storage_fmt)

        self.pbar_cpu.setValue(cpu_percent_v)
        self.pbar_memory.setValue(memory_percent_v)
        self.pbar_storage.setValue(storage_percent_v)

        self.nic_item_model.removeRows(0, self.nic_item_model.rowCount())

        def _get_nic_transfer_rate(bytes_now, bytes_previous, delta_time):
            return "%.1f" % float(((bytes_now - bytes_previous) / delta_time) / 1024)

        new_time = time.time()
        delta = new_time - self.nic_time
        self.nic_time = new_time

        for i, key in enumerate(nic_data_dict):
            if key not in self.nic_previous_bytes:
                self.nic_time = time.time()
                self.nic_item_model.setItem(i, 0, QtGui.QStandardItem(key))
                self.nic_item_model.setItem(i, 1, QtGui.QStandardItem("Collecting data..."))
                self.nic_item_model.setItem(i, 2, QtGui.QStandardItem("Collecting data..."))
            else:
                download_rate = _get_nic_transfer_rate(nic_data_dict[key][1],
                                                       self.nic_previous_bytes[key]['received'],
                                                       delta)

                upload_rate = _get_nic_transfer_rate(nic_data_dict[key][0],
                                                     self.nic_previous_bytes[key]['sent'],
                                                     delta)

                self.nic_item_model.setItem(i, 0, QtGui.QStandardItem(key))
                self.nic_item_model.setItem(i, 1, QtGui.QStandardItem(download_rate + " KiB/s"))
                self.nic_item_model.setItem(i, 2, QtGui.QStandardItem(upload_rate + " KiB/s"))

            self.nic_previous_bytes[key] = {'sent': nic_data_dict[key][0],
                                            'received': nic_data_dict[key][1]}

        self.nic_item_model.sort(self.tview_nic_previous_sort['column_index'],
                                 self.tview_nic_previous_sort['order'])

        self.process_item_model.removeRows(0, self.process_item_model.rowCount())

        if self.cbox_based_on.currentIndex() == 0:
            processes_data_list_sorted = sorted(processes_data_list,
                                                key=itemgetter('cpu'),
                                                reverse=True)
        elif self.cbox_based_on.currentIndex() == 1:
            processes_data_list_sorted = sorted(processes_data_list,
                                                key=itemgetter('mem'),
                                                reverse=True)

        processes_data_list_sorted = processes_data_list_sorted[:self.sbox_number_of_process.value()]

        for i, p in enumerate(processes_data_list_sorted):
            name = unicode(p['name'])
            cmdline = unicode(p['cmd'])

            if len(cmdline) == 0:
                cmdline = name

            item_name = QtGui.QStandardItem(name)
            item_name.setToolTip(cmdline)
            self.process_item_model.setItem(i, 0, item_name)

            item_pid = QtGui.QStandardItem(unicode(p['pid']))
            self.process_item_model.setItem(i, 1, item_pid)

            item_user = QtGui.QStandardItem(unicode(p['user']))
            self.process_item_model.setItem(i, 2, item_user)

            cpu = p['cpu']
            item_cpu = QtGui.QStandardItem(unicode(cpu / 10.0)+'%')
            item_cpu.setData(cpu)
            self.process_item_model.setItem(i, 3, item_cpu)

            mem = p['mem']
            item_mem = QtGui.QStandardItem(unicode(mem / 10.0)+'%')
            item_mem.setData(mem)
            self.process_item_model.setItem(i, 4, item_mem)

        self.process_item_model.sort(self.tview_process_previous_sort['column_index'],
                                     self.tview_process_previous_sort['order'])
            def cb_update_tf_software_get_installed_versions(result):
                if not self.dialog_session:
                    return

                self.set_current_state(self.STATE_NO_UPDATES_AVAILABLE)

                okay, message = check_script_result(result)
                if not okay:
                    msg = self.MESSAGE_ERR_GET_INSTALLED_VERSIONS + ':\n' + message + '\n\n'
                    self.set_current_state(self.STATE_INIT)
                    self.tedit_main.setText(msg)
                    return

                updates_available_main = False
                update_info = {'brickv': {},
                               'processed': 0,
                               'temp_dir': '',
                               'bindings': [],
                               'error': False,
                               'updates_total': 0,
                               'error_messages': ''}

                installed_versions = json.loads(result.stdout)

                if not isinstance(installed_versions, dict):
                    self.set_current_state(self.STATE_INIT)
                    self.tedit_main.setText(self.MESSAGE_ERR_GET_INSTALLED_VERSIONS + '.')

                    return

                for key, value in installed_versions.items():
                    if key == 'brickv':
                        update_info['brickv']['to'] = '0'
                        update_info['brickv']['name'] = '-'
                        update_info['brickv']['from'] = '0'
                        update_info['brickv']['data'] = None
                        update_info['brickv']['update'] = False
                        update_info['brickv']['display_name'] = '-'

                        if isinstance(value, str) and value != '' and value != '-':
                            update_info['brickv']['from'] = value
                            update_info['brickv']['name'] = 'brickv'

                            continue
                        else:
                            self.set_current_state(self.STATE_INIT)
                            self.tedit_main.setText(self.MESSAGE_ERR_GET_INSTALLED_VERSIONS + '.')

                            return

                    elif key == 'bindings':
                        if isinstance(value, dict) and value:
                            for k, v in value.items():
                                d = {}

                                d['to'] = '0'
                                d['name'] = '-'
                                d['from'] = '0'
                                d['data'] = None
                                d['update'] = False
                                d['display_name'] = '-'

                                if isinstance(v, str) and v != '' and v != '-':
                                    d['from'] = v
                                    d['name'] = k.strip()

                                    update_info['bindings'].append(d)
                                else:
                                    self.set_current_state(self.STATE_INIT)
                                    self.tedit_main.setText(self.MESSAGE_ERR_GET_INSTALLED_VERSIONS + '.')

                                    return
                            continue
                        else:
                            self.set_current_state(self.STATE_INIT)
                            self.tedit_main.setText(self.MESSAGE_ERR_GET_INSTALLED_VERSIONS + '.')

                            return
                    else:
                        self.set_current_state(self.STATE_INIT)
                        self.tedit_main.setText(self.MESSAGE_ERR_GET_INSTALLED_VERSIONS + '.')

                        return

                # Try to get the latest version numbers.
                try:
                    response = urllib.request.urlopen(self.URL_LATEST_VERSIONS, timeout=10)
                    response_data = response.read().decode('utf-8')
                except urllib.error.URLError:
                    self.set_current_state(self.STATE_INIT)
                    self.tedit_main.setText(self.MESSAGE_ERR_CHECK_LATEST_VERSIONS)

                    return

                response_data_lines = response_data.splitlines()

                if len(response_data_lines) < 1:
                    self.set_current_state(self.STATE_INIT)
                    self.tedit_main.setText(self.MESSAGE_ERR_CHECK_LATEST_VERSIONS)

                    return

                for l in response_data_lines:
                    l_split = l.strip().split(':')

                    if len(l_split) != 3:
                        self.set_current_state(self.STATE_INIT)
                        self.tedit_main.setText(self.MESSAGE_ERR_CHECK_LATEST_VERSIONS)

                        return
                    else:
                        if l_split[0] == 'tools' and l_split[1] == 'brickv':
                            update_info['brickv']['to'] = l_split[2]
                            update_info['brickv']['display_name'] = 'Brick Viewer'
                            version_to = StrictVersion(l_split[2].strip())
                            version_from = StrictVersion(update_info['brickv']['from'].strip())

                            if version_to > version_from:
                                updates_available_main = True
                                update_info['brickv']['update'] = True
                            else:
                                update_info['brickv']['update'] = False

                            continue

                        elif l_split[0] == 'bindings':
                            if l_split[1] == 'c':
                                found, updates_available = self.update_latest_version_info(update_info,
                                                                                           l_split[1],
                                                                                           l_split[2],
                                                                                           'C/C++ Bindings')

                                if not found:
                                    self.set_current_state(self.STATE_INIT)
                                    self.tedit_main.setText(self.MESSAGE_ERR_CHECK_LATEST_VERSIONS)

                                    return

                                if updates_available:
                                    updates_available_main = True

                            elif l_split[1] == 'csharp':
                                found, updates_available = self.update_latest_version_info(update_info,
                                                                                           l_split[1],
                                                                                           l_split[2],
                                                                                           'C#/Mono Bindings')

                                if not found:
                                    self.set_current_state(self.STATE_INIT)
                                    self.tedit_main.setText(self.MESSAGE_ERR_CHECK_LATEST_VERSIONS)

                                    return

                                if updates_available:
                                    updates_available_main = True

                            elif l_split[1] == 'delphi':
                                found, updates_available = self.update_latest_version_info(update_info,
                                                                                           l_split[1],
                                                                                           l_split[2],
                                                                                           'Delphi/Lazarus Bindings')

                                if not found:
                                    self.set_current_state(self.STATE_INIT)
                                    self.tedit_main.setText(self.MESSAGE_ERR_CHECK_LATEST_VERSIONS)

                                    return

                                if updates_available:
                                    updates_available_main = True

                            elif l_split[1] == 'java':
                                found, updates_available = self.update_latest_version_info(update_info,
                                                                                           l_split[1],
                                                                                           l_split[2],
                                                                                           'Java Bindings')

                                if not found:
                                    self.set_current_state(self.STATE_INIT)
                                    self.tedit_main.setText(self.MESSAGE_ERR_CHECK_LATEST_VERSIONS)

                                    return

                                if updates_available:
                                    updates_available_main = True

                            elif l_split[1] == 'javascript':
                                found, updates_available = self.update_latest_version_info(update_info,
                                                                                           l_split[1],
                                                                                           l_split[2],
                                                                                           'JavaScript Bindings')

                                if not found:
                                    self.set_current_state(self.STATE_INIT)
                                    self.tedit_main.setText(self.MESSAGE_ERR_CHECK_LATEST_VERSIONS)

                                    return

                                if updates_available:
                                    updates_available_main = True

                            elif l_split[1] == 'matlab':
                                found, updates_available = self.update_latest_version_info(update_info,
                                                                                           l_split[1],
                                                                                           l_split[2],
                                                                                           'Octave Bindings')

                                if not found:
                                    self.set_current_state(self.STATE_INIT)
                                    self.tedit_main.setText(self.MESSAGE_ERR_CHECK_LATEST_VERSIONS)

                                    return

                                if updates_available:
                                    updates_available_main = True

                            elif l_split[1] == 'perl':
                                found, updates_available = self.update_latest_version_info(update_info,
                                                                                           l_split[1],
                                                                                           l_split[2],
                                                                                           'Perl Bindings')

                                if not found:
                                    self.set_current_state(self.STATE_INIT)
                                    self.tedit_main.setText(self.MESSAGE_ERR_CHECK_LATEST_VERSIONS)

                                    return

                                if updates_available:
                                    updates_available_main = True

                            elif l_split[1] == 'php':
                                found, updates_available = self.update_latest_version_info(update_info,
                                                                                           l_split[1],
                                                                                           l_split[2],
                                                                                           'PHP Bindings')

                                if not found:
                                    self.set_current_state(self.STATE_INIT)
                                    self.tedit_main.setText(self.MESSAGE_ERR_CHECK_LATEST_VERSIONS)

                                    return

                                if updates_available:
                                    updates_available_main = True

                            elif l_split[1] == 'python':
                                found, updates_available = self.update_latest_version_info(update_info,
                                                                                           l_split[1],
                                                                                           l_split[2],
                                                                                           'Python Bindings')

                                if not found:
                                    self.set_current_state(self.STATE_INIT)
                                    self.tedit_main.setText(self.MESSAGE_ERR_CHECK_LATEST_VERSIONS)

                                    return

                                if updates_available:
                                    updates_available_main = True

                            elif l_split[1] == 'ruby':
                                found, updates_available = self.update_latest_version_info(update_info,
                                                                                           l_split[1],
                                                                                           l_split[2],
                                                                                           'Ruby Bindings')

                                if not found:
                                    self.set_current_state(self.STATE_INIT)
                                    self.tedit_main.setText(self.MESSAGE_ERR_CHECK_LATEST_VERSIONS)

                                    return

                                if updates_available:
                                    updates_available_main = True

                            elif l_split[1] == 'shell':
                                found, updates_available = self.update_latest_version_info(update_info,
                                                                                           l_split[1],
                                                                                           l_split[2],
                                                                                           'Shell Bindings')

                                if not found:
                                    self.set_current_state(self.STATE_INIT)
                                    self.tedit_main.setText(self.MESSAGE_ERR_CHECK_LATEST_VERSIONS)

                                    return

                                if updates_available:
                                    updates_available_main = True

                            elif l_split[1] == 'vbnet':
                                found, updates_available = self.update_latest_version_info(update_info,
                                                                                           l_split[1],
                                                                                           l_split[2],
                                                                                           'VB.NET Bindings')

                                if not found:
                                    self.set_current_state(self.STATE_INIT)
                                    self.tedit_main.setText(self.MESSAGE_ERR_CHECK_LATEST_VERSIONS)

                                    return

                                if updates_available:
                                    updates_available_main = True

                self.red_plugin.bindings_version_success(result)

                _check_update_available = self.check_update_available(update_info)

                if not _check_update_available:
                    self.set_current_state(self.STATE_INIT)
                    self.tedit_main.setText(self.MESSAGE_ERR_GET_INSTALLED_VERSIONS + '.')

                    return

                if updates_available_main:
                    self.set_current_state(self.STATE_UPDATES_AVAILABLE)
                    self.do_update_available_message(update_info)
                else:
                    self.set_current_state(self.STATE_NO_UPDATES_AVAILABLE)
                    self.tedit_main.setText(self.MESSAGE_INFO_STATE_NO_UPDATES_AVAILABLE)
Example #49
0
        def cb_openhab_configs_list(result):
            okay, message = check_script_result(result, decode_stderr=True)

            def fatal_error(text):
                self.log_error(text)
                self.action_in_progress = False
                self.update_ui_state()

            if not okay:
                fatal_error(
                    'Error while collecting config files: {0}'.format(message))
                return

            try:
                config_names = json.loads(result.stdout)
            except Exception as e:
                fatal_error(
                    'Received invalid config file collection: {0}'.format(e))
                return

            if not isinstance(config_names, dict):
                fatal_error(
                    'Received invalid config file collection: Not a dictionary'
                )
                return

            try:
                configs_by_basename = {}

                for name in config_names['items']:
                    if self.image_version.number < (1, 10):
                        configs_by_basename.setdefault(
                            name[:-len('.items')], []).append(
                                (name,
                                 posixpath.join(
                                     '/etc/openhab/configurations/items',
                                     name)))
                    else:
                        configs_by_basename.setdefault(
                            name[:-len('.items')], []).append(
                                (name,
                                 posixpath.join('/etc/openhab2/items', name)))

                for name in config_names['sitemaps']:
                    if self.image_version.number < (1, 10):
                        configs_by_basename.setdefault(
                            name[:-len('.sitemap')], []).append(
                                (name,
                                 posixpath.join(
                                     '/etc/openhab/configurations/sitemaps',
                                     name)))
                    else:
                        configs_by_basename.setdefault(
                            name[:-len('.sitemap')], []).append(
                                (name,
                                 posixpath.join('/etc/openhab2/sitemaps',
                                                name)))

                for name in config_names['rules']:
                    if self.image_version.number < (1, 10):
                        configs_by_basename.setdefault(
                            name[:-len('.rules')], []).append(
                                (name,
                                 posixpath.join(
                                     '/etc/openhab/configurations/rules',
                                     name)))
                    else:
                        configs_by_basename.setdefault(
                            name[:-len('.rules')], []).append(
                                (name,
                                 posixpath.join('/etc/openhab2/rules', name)))

                for name in config_names['persistence']:
                    if self.image_version.number < (1, 10):
                        configs_by_basename.setdefault(
                            name[:-len('.persist')], []).append(
                                (name,
                                 posixpath.join(
                                     '/etc/openhab/configurations/persistence',
                                     name)))
                    else:
                        configs_by_basename.setdefault(
                            name[:-len('.persist')], []).append(
                                (name,
                                 posixpath.join('/etc/openhab2/persistence',
                                                name)))

                for name in config_names['scripts']:
                    if self.image_version.number < (1, 10):
                        configs_by_basename.setdefault(
                            name[:-len('.script')], []).append(
                                (name,
                                 posixpath.join(
                                     '/etc/openhab/configurations/scripts',
                                     name)))
                    else:
                        configs_by_basename.setdefault(
                            name[:-len('.script')], []).append(
                                (name,
                                 posixpath.join('/etc/openhab2/scripts',
                                                name)))

                for name in config_names['transform']:
                    if self.image_version.number < (1, 10):
                        configs_by_basename.setdefault(
                            name[:-len('.transform')], []).append(
                                (name,
                                 posixpath.join(
                                     '/etc/openhab/configurations/transform',
                                     name)))
                    else:
                        configs_by_basename.setdefault(
                            name[:-len('.transform')], []).append(
                                (name,
                                 posixpath.join('/etc/openhab2/transform',
                                                name)))

            except Exception as e:
                fatal_error(
                    'Received invalid config file collection: {0}'.format(e))
                return

            old_configs = {}

            for config in self.configs:
                if config != None:
                    old_configs[config.display_name] = config

            if self.image_version.number < (1, 10):
                self.configs = [
                    old_configs['openhab.cfg'], old_configs['logback.xml']
                ]
            else:
                self.configs = [
                    old_configs['tinkerforge.cfg'],
                    old_configs['org.ops4j.pax.logging.cfg']
                ]

            for key in sorted(configs_by_basename):
                value = configs_by_basename[key]

                if len(value) > 0:
                    self.configs.append(None)

                    for display_name, absolute_name in sorted(value):
                        if display_name in old_configs:
                            self.configs.append(old_configs[display_name])
                        else:
                            self.configs.append(
                                ConfigFile(display_name, absolute_name, self))

            self.recreate_widgets()
            self.refresh_config(0, done_callback)
Example #50
0
        def cb_program_logs_list(result):
            okay, message = check_script_result(result, decode_stderr=True)

            if not okay:
                self.label_error.setText('<b>Error:</b> ' + html.escape(message))
                self.label_error.setVisible(True)
                self.refresh_logs_done()
                return

            try:
                # FIXME: do decompress in an async_call
                program_logs_list = json.loads(zlib.decompress(memoryview(result.stdout)).decode('utf-8'))
            except:
                program_logs_list = None

            if program_logs_list == None or not isinstance(program_logs_list, dict):
                self.label_error.setText('<b>Error:</b> Received invalid data')
                self.label_error.setVisible(True)
                self.refresh_logs_done()
                return

            self.label_error.setVisible(False)

            def create_file_size_item(size):
                item = QStandardItem(get_file_display_size(size))
                item.setData(size, USER_ROLE_SIZE)

                return item

            def update_file_size_item(item, additional_size):
                current_size = item.data(USER_ROLE_SIZE)
                new_size     = current_size + additional_size

                item.setText(get_file_display_size(new_size))
                item.setData(new_size, USER_ROLE_SIZE)

            continuous_row = None
            date_rows      = {}
            time_rows      = {}

            for file_name, file_size in program_logs_list.items():
                QApplication.processEvents()

                file_name_parts = file_name.split('_')

                if file_name_parts[0] == "continuous":
                    if len(file_name_parts) != 2:
                        continue

                    if continuous_row == None:
                        continuous_item = QStandardItem("Continuous")
                        continuous_item.setData(ITEM_TYPE_PARENT_CONT, USER_ROLE_ITEM_TYPE)

                        continuous_row = [continuous_item, create_file_size_item(0)]

                        self.tree_logs_model.appendRow(continuous_row)

                    log_item = QStandardItem(file_name_parts[1])
                    log_item.setData(self.file_icon, Qt.DecorationRole)
                    log_item.setData(file_name, USER_ROLE_FILE_NAME)
                    log_item.setData(ITEM_TYPE_LOG_FILE_CONT, USER_ROLE_ITEM_TYPE)

                    continuous_row[0].appendRow([log_item, create_file_size_item(file_size)])
                    update_file_size_item(continuous_row[1], file_size)
                else:
                    if len(file_name_parts) != 3:
                        continue

                    try:
                        timestamp = int(file_name_parts[1].split('+')[0]) // 1000000
                    except ValueError:
                        continue

                    #FIXME: fromTime_t is obsolete: https://doc.qt.io/qt-5/qdatetime-obsolete.html#toTime_t
                    date      = QDateTime.fromTime_t(timestamp).toString('yyyy-MM-dd')
                    time      = QDateTime.fromTime_t(timestamp).toString('HH:mm:ss')
                    date_time = date + 'T' + time

                    if date in date_rows:
                        date_row = date_rows[date]
                    else:
                        date_item = QStandardItem(date)
                        date_item.setData(ITEM_TYPE_PARENT_DATE, USER_ROLE_ITEM_TYPE)

                        date_row        = [date_item, create_file_size_item(0)]
                        date_rows[date] = date_row

                        self.tree_logs_model.appendRow(date_row)

                    if date_time in time_rows:
                        time_row = time_rows[date_time]
                    else:
                        time_item = QStandardItem(time)
                        time_item.setData(ITEM_TYPE_PARENT_TIME, USER_ROLE_ITEM_TYPE)

                        time_row             = [time_item, create_file_size_item(0)]
                        time_rows[date_time] = time_row

                        date_row[0].appendRow(time_row)

                    log_item = QStandardItem(file_name_parts[2])
                    log_item.setData(self.file_icon, Qt.DecorationRole)
                    log_item.setData(file_name, USER_ROLE_FILE_NAME)
                    log_item.setData(ITEM_TYPE_LOG_FILE, USER_ROLE_ITEM_TYPE)

                    time_row[0].appendRow([log_item, create_file_size_item(file_size)])
                    update_file_size_item(time_row[1], file_size)
                    update_file_size_item(date_row[1], file_size)

            self.tree_logs.header().setSortIndicator(0, Qt.DescendingOrder)
            self.refresh_logs_done()
    def cb_settings_mobile_internet_get_status(self, result):
        self.status_refresh_timer.stop()

        if not self.is_tab_on_focus:
            return

        okay, _ = check_script_result(result)

        if not okay:
            self.status_refresh_timer.start(INTERVAL_REFRESH_STATUS)
            return

        try:
            dict_status = json.loads(result.stdout)
        except Exception as e:
            QMessageBox.critical(
                get_main_window(), MESSAGEBOX_TITLE,
                MESSAGE_ERROR_STATUS_DECODE + ':\n\n' + str(e))

            self.status_refresh_timer.start(INTERVAL_REFRESH_STATUS)
            return

        # Update status GUI elements
        if not dict_status['status']:
            self.label_mi_status_status.setText('-')
        else:
            self.label_mi_status_status.setText(dict_status['status'])

        if not dict_status['signal_quality']:
            self.label_mi_status_signal_quality.setText('-')
        else:
            self.label_mi_status_signal_quality.setText(
                dict_status['signal_quality'])

        if not dict_status['interface']:
            self.label_mi_status_interface.setText('-')
        else:
            self.label_mi_status_interface.setText(dict_status['interface'])

        if not dict_status['ip']:
            self.label_mi_status_ip.setText('-')
        else:
            self.label_mi_status_ip.setText(dict_status['ip'])

        if not dict_status['subnet_mask']:
            self.label_mi_status_subnet_mask.setText('-')
        else:
            self.label_mi_status_subnet_mask.setText(
                dict_status['subnet_mask'])

        if not dict_status['gateway']:
            self.label_mi_status_gateway.setText('-')
        else:
            self.label_mi_status_gateway.setText(dict_status['gateway'])

        if not dict_status['dns']:
            self.label_mi_status_dns.setText('-')
        else:
            self.label_mi_status_dns.setText(dict_status['dns'])

        self.status_refresh_timer.start(INTERVAL_REFRESH_STATUS)
Example #52
0
            def cb_success(result):
                okay, message = check_script_result(result)

                if not okay:
                    op = 'reboot' if param == 1 else 'shutdown'
                    QMessageBox.critical(get_main_window(), 'Failed to {} RED Brick'.format(op), message)
Example #53
0
    def cb_overview(self, result):
        # check if the tab is still on view or not
        if not self.is_tab_on_focus:
            self.refresh_timer.stop()
            return

        self.refresh_counter = 0
        self.refresh_timer.start(REFRESH_TIMEOUT)

        okay, message = check_script_result(result, decode_stderr=True)

        if not okay:
            self.label_error.setText('<b>Error:</b> ' + QtCore.Qt.escape(message))
            self.label_error.show()
            return

        self.label_error.hide()

        try:
            data = json.loads(zlib.decompress(buffer(result.stdout)).decode('utf-8'))

            days, days_remainder = divmod(int(data['uptime']), 24 * 60 * 60)
            hours, hours_remainder = divmod(days_remainder, 60 * 60)
            minutes, _ = divmod(hours_remainder, 60)
            uptime = ''

            if days > 0:
                uptime += str(days)

                if days == 1:
                    uptime += ' day '
                else:
                    uptime += ' days '

            if hours > 0:
                uptime += str(hours)

                if hours == 1:
                    uptime += ' hour '
                else:
                    uptime += ' hours '

            uptime += str(minutes)

            if minutes == 1:
                uptime += ' minute'
            else:
                uptime += ' minutes'

            cpu_percent = data['cpu_used']
            cpu_percent_v = int(data['cpu_used'])

            memory_used = self.bytes2human(int(data['mem_used']))
            memory_total = self.bytes2human(int(data['mem_total']))
            memory_percent = "%.1f" % ((float(memory_used) / float(memory_total)) * 100)
            memory_percent_v = int(memory_percent.split('.')[0])

            storage_used = self.bytes2human(int(data['disk_used']))
            storage_total = self.bytes2human(int(data['disk_total']))
            storage_percent = "%.1f" % ((float(storage_used) / float(storage_total)) * 100)
            storage_percent_v = int(storage_percent.split('.')[0])

            nic_data_dict = data['ifaces']
            processes_data_list = data['processes']
        except:
            # some parsing error due to malfromed or incomplete output occured.
            # ignore it and wait for the next update
            return

        self.label_uptime_value.setText(uptime)

        pbar_cpu_fmt = "{0}%".format(cpu_percent)
        pbar_memory_fmt = "{0}% [{1} of {2} MiB]".format(memory_percent, memory_used, memory_total)
        pbar_storage_fmt = "{0}% [{1} of {2} GiB]".format(storage_percent, storage_used, storage_total)

        if sys.platform == 'darwin':
            self.label_pbar_cpu.show()
            self.label_pbar_memory.show()
            self.label_pbar_storage.show()
            self.label_pbar_cpu.setText(pbar_cpu_fmt)
            self.label_pbar_memory.setText(pbar_memory_fmt)
            self.label_pbar_storage.setText(pbar_storage_fmt)
        else:
            self.pbar_cpu.setFormat(pbar_cpu_fmt)
            self.pbar_memory.setFormat(pbar_memory_fmt)
            self.pbar_storage.setFormat(pbar_storage_fmt)

        self.pbar_cpu.setValue(cpu_percent_v)
        self.pbar_memory.setValue(memory_percent_v)
        self.pbar_storage.setValue(storage_percent_v)

        self.nic_item_model.removeRows(0, self.nic_item_model.rowCount())

        def _get_nic_transfer_rate(bytes_now, bytes_previous, delta_time):
            return "%.1f" % float(((bytes_now - bytes_previous) / delta_time) / 1024)

        new_time = time.time()
        delta = new_time - self.nic_time
        self.nic_time = new_time

        for i, key in enumerate(nic_data_dict):
            if key not in self.nic_previous_bytes:
                self.nic_time = time.time()
                self.nic_item_model.setItem(i, 0, QtGui.QStandardItem(key))
                self.nic_item_model.setItem(i, 1, QtGui.QStandardItem("Collecting data..."))
                self.nic_item_model.setItem(i, 2, QtGui.QStandardItem("Collecting data..."))
            else:
                download_rate = _get_nic_transfer_rate(nic_data_dict[key][1],
                                                       self.nic_previous_bytes[key]['received'],
                                                       delta)

                upload_rate = _get_nic_transfer_rate(nic_data_dict[key][0],
                                                     self.nic_previous_bytes[key]['sent'],
                                                     delta)

                self.nic_item_model.setItem(i, 0, QtGui.QStandardItem(key))
                self.nic_item_model.setItem(i, 1, QtGui.QStandardItem(download_rate + " KiB/s"))
                self.nic_item_model.setItem(i, 2, QtGui.QStandardItem(upload_rate + " KiB/s"))

            self.nic_previous_bytes[key] = {'sent': nic_data_dict[key][0],
                                            'received': nic_data_dict[key][1]}

        self.nic_item_model.sort(self.tview_nic_previous_sort['column_index'],
                                 self.tview_nic_previous_sort['order'])

        self.process_item_model.removeRows(0, self.process_item_model.rowCount())

        if self.cbox_based_on.currentIndex() == 0:
            processes_data_list_sorted = sorted(processes_data_list,
                                                key=itemgetter('cpu'),
                                                reverse=True)
        elif self.cbox_based_on.currentIndex() == 1:
            processes_data_list_sorted = sorted(processes_data_list,
                                                key=itemgetter('mem'),
                                                reverse=True)

        processes_data_list_sorted = processes_data_list_sorted[:self.sbox_number_of_process.value()]

        for i, p in enumerate(processes_data_list_sorted):
            name = unicode(p['name'])
            cmdline = unicode(p['cmd'])

            if len(cmdline) == 0:
                cmdline = name

            item_name = QtGui.QStandardItem(name)
            item_name.setToolTip(cmdline)
            self.process_item_model.setItem(i, 0, item_name)

            item_pid = QtGui.QStandardItem(unicode(p['pid']))
            self.process_item_model.setItem(i, 1, item_pid)

            item_user = QtGui.QStandardItem(unicode(p['user']))
            self.process_item_model.setItem(i, 2, item_user)

            cpu = p['cpu']
            item_cpu = QtGui.QStandardItem(unicode(cpu / 10.0)+'%')
            item_cpu.setData(cpu)
            self.process_item_model.setItem(i, 3, item_cpu)

            mem = p['mem']
            item_mem = QtGui.QStandardItem(unicode(mem / 10.0)+'%')
            item_mem.setData(mem)
            self.process_item_model.setItem(i, 4, item_mem)

        self.process_item_model.sort(self.tview_process_previous_sort['column_index'],
                                     self.tview_process_previous_sort['order'])