Exemplo n.º 1
0
  def __init__(self):
    self.op_params = opParams()
    self.params = None
    self.sleep_time = 0.75
    self.live_tuning = self.op_params.get('op_edit_live_mode')
    self.username = self.op_params.get('username')
    self.type_colors = {int: COLORS.BASE(179), float: COLORS.BASE(179),
                        bool: {False: COLORS.RED, True: COLORS.OKGREEN},
                        type(None): COLORS.BASE(177),
                        str: COLORS.BASE(77)}

    self.last_choice = None

    self.run_init()
Exemplo n.º 2
0
  def change_parameter(self, choice):
    while True:
      chosen_key = list(self.params)[choice]
      param_info = self.op_params.param_info(chosen_key)

      old_value = self.params[chosen_key]
      if param_info.live:
        self.info2('Chosen parameter: {}{} (live!)'.format(chosen_key, COLORS.BASE(207)), sleep_time=0)
      else:
        self.info2('Chosen parameter: {}'.format(chosen_key), sleep_time=0)

      to_print = []
      if param_info.has_description:
        to_print.append(COLORS.OKGREEN + '>>  Description: {}'.format(param_info.description.replace('\n', '\n  > ')) + COLORS.ENDC)
      if param_info.has_allowed_types:
        to_print.append(COLORS.RED + '>>  Allowed types: {}'.format(', '.join([at.__name__ for at in param_info.allowed_types])) + COLORS.ENDC)

      if to_print:
        print('\n{}\n'.format('\n'.join(to_print)))

      if param_info.is_list:
        self.change_param_list(old_value, param_info, chosen_key)  # TODO: need to merge the code in this function with the below to reduce redundant code
        return

      v_color = ''
      if type(old_value) in self.type_colors:
        v_color = self.type_colors[type(old_value)]
        if isinstance(old_value, bool):
          v_color = v_color[old_value]

      self.info('Current value: {}{}{} (type: {})'.format(v_color, old_value, COLORS.INFO, type(old_value).__name__), sleep_time=0)

      while True:
        self.prompt('\nEnter your new value:')
        new_value = input('>> ').strip()
        if new_value == '':
          self.info('Exiting this parameter...\n', 0.5)
          return

        new_value = self.str_eval(new_value)
        if not param_info.is_valid(new_value):
          self.error('The type of data you entered ({}) is not allowed with this parameter!'.format(type(new_value).__name__))
          continue

        if param_info.live:  # stay in live tuning interface
          self.op_params.put(chosen_key, new_value)
          self.success('Saved {} with value: {}! (type: {})'.format(chosen_key, new_value, type(new_value).__name__))
        else:  # else ask to save and break
          print('\nOld value: {} (type: {})'.format(old_value, type(old_value).__name__))
          print('New value: {} (type: {})'.format(new_value, type(new_value).__name__))
          self.prompt('\nDo you want to save this?')
          if self.input_with_options(['Y', 'n'], 'n')[0] == 0:
            self.op_params.put(chosen_key, new_value)
            self.success('Saved!')
          else:
            self.info('Not saved!', sleep_time=0)
          return
Exemplo n.º 3
0
def color_name(given_color_name):
    """Convert color name to RGB hex value."""
    # COLORS map has no spaces in it, so make the color_name have no
    # spaces in it as well for matching purposes
    rgb_value = COLORS.get(given_color_name.replace(" ", "").lower())
    if not rgb_value:
        raise vol.Invalid("Unknown color {0}".format(given_color_name))

    return rgb_value
Exemplo n.º 4
0
  def run_loop(self):
    while True:
      if not self.live_tuning:
        self.info('Here are your parameters:', end='\n', sleep_time=0)
      else:
        self.info('Here are your live parameters:', sleep_time=0)
        self.info('(changes take effect within {} seconds)'.format(self.op_params.read_frequency), end='\n', sleep_time=0)
      self.params = self.op_params.get(force_live=True)
      if self.live_tuning:  # only display live tunable params
        self.params = {k: v for k, v in self.params.items() if self.op_params.fork_params[k].live}

      values_list = []
      for k, v in self.params.items():
        if len(str(v)) < 20:
          v_color = ''
          if type(v) in self.type_colors:
            v_color = self.type_colors[type(v)]
            if isinstance(v, bool):
              v_color = v_color[v]
          v = '{}{}{}'.format(v_color, v, COLORS.ENDC)
        else:
          v = '{} ... {}'.format(str(v)[:30], str(v)[-15:])
        values_list.append(v)

      live = [COLORS.INFO + '(live!)' + COLORS.ENDC if self.op_params.fork_params[k].live else '' for k in self.params]

      to_print = []
      blue_gradient = [33, 39, 45, 51, 87]
      for idx, param in enumerate(self.params):
        line = '{}. {}: {}  {}'.format(idx + 1, param, values_list[idx], live[idx])
        if idx == self.last_choice and self.last_choice is not None:
          line = COLORS.OKGREEN + line
        else:
          _color = blue_gradient[min(round(idx / len(self.params) * len(blue_gradient)), len(blue_gradient) - 1)]
          line = COLORS.BASE(_color) + line
        to_print.append(line)

      extras = {'l': ('Toggle live tuning', COLORS.WARNING),
                'e': ('Exit opEdit', COLORS.PINK)}

      to_print += ['---'] + ['{}. {}'.format(ext_col + e, ext_txt + COLORS.ENDC) for e, (ext_txt, ext_col) in extras.items()]
      print('\n'.join(to_print))
      self.prompt('\nChoose a parameter to edit (by index or name):')

      choice = input('>> ').strip().lower()
      parsed, choice = self.parse_choice(choice, len(to_print) - len(extras))
      if parsed == 'continue':
        continue
      elif parsed == 'change':
        self.last_choice = choice
        self.change_parameter(choice)
      elif parsed == 'live':
        self.last_choice = None
        self.live_tuning = not self.live_tuning
        self.op_params.put('op_edit_live_mode', self.live_tuning)  # for next opEdit startup
      elif parsed == 'exit':
        return
Exemplo n.º 5
0
  def str_color(msg, style, surround=False):
    if style == 'success':
      style = COLORS.SUCCESS
    elif style == 'fail':
      style = COLORS.FAIL
    elif style == 'prompt':
      style = COLORS.PROMPT
    elif style == 'info':
      style = COLORS.INFO
    elif style == 'cyan':
      style = COLORS.CYAN
    elif isinstance(style, int):
      style = COLORS.BASE(86)

    if surround:
      msg = '{}--------\n{}\n{}--------{}'.format(style, msg, COLORS.ENDC + style, COLORS.ENDC)
    else:
      msg = '{}{}{}'.format(style, msg, COLORS.ENDC)

    return msg
Exemplo n.º 6
0
    def run_loop(self):
        while True:
            if not self.live_tuning:
                self.info('Here are your parameters:', end='\n', sleep_time=0)
            else:
                self.info('Here are your live parameters:', sleep_time=0)
                self.info('(changes take effect within {} seconds)'.format(
                    self.op_params.read_frequency),
                          end='\n',
                          sleep_time=0)
            self.params = self.op_params.get(force_live=True)
            if self.live_tuning:  # only display live tunable params
                self.params = {
                    k: v
                    for k, v in self.params.items()
                    if self.op_params.param_info(k).live
                }

            self.params = OrderedDict(
                sorted(self.params.items(), key=self.sort_params))

            values_list = []
            for k, v in self.params.items():
                if len(str(v)) < 30 or len(str(v)) <= len('{} ... {}'.format(
                        str(v)[:30],
                        str(v)[-15:])):
                    v_color = ''
                    if type(v) in self.type_colors:
                        v_color = self.type_colors[type(v)]
                        if isinstance(v, bool):
                            v_color = v_color[v]
                    v = '{}{}{}'.format(v_color, v, COLORS.ENDC)
                else:
                    v = '{} ... {}'.format(str(v)[:30], str(v)[-15:])
                values_list.append(v)

            live = [
                COLORS.INFO + '(live!)' +
                COLORS.ENDC if self.op_params.param_info(k).live else ''
                for k in self.params
            ]

            to_print = []
            blue_gradient = [33, 39, 45, 51, 87]
            last_key = ''
            last_info = None
            shown_dots = False
            for idx, param in enumerate(self.params):
                info = self.op_params.param_info(param)
                indent = self.get_sort_key(param).count(',')
                line = ''
                if not info.depends_on or param in last_info.children and \
                  self.op_params.get(last_key) and self.op_params.get(info.depends_on):
                    line = '{}. {}: {}  {}'.format(idx + 1, param,
                                                   values_list[idx], live[idx])
                    line = indent * '.' + line
                elif not shown_dots and last_info and param in last_info.children:
                    line = '...'
                    shown_dots = True
                if line:
                    if idx == self.last_choice and self.last_choice is not None:
                        line = COLORS.OKGREEN + line
                    else:
                        _color = blue_gradient[min(
                            round(idx / len(self.params) * len(blue_gradient)),
                            len(blue_gradient) - 1)]
                        line = COLORS.BASE(_color) + line
                    if last_info and len(last_info.children) and indent == 0:
                        line = '\n' + line
                        shown_dots = False
                    to_print.append(line)

                if indent == 0:
                    last_key = param
                    last_info = info

            extras = {
                'a': ('Add new parameter', COLORS.OKGREEN),
                'd': ('Delete parameter', COLORS.FAIL),
                'l': ('Toggle live tuning', COLORS.WARNING),
                'e': ('Exit opEdit', COLORS.PINK)
            }

            to_print += ['---'] + [
                '{}. {}'.format(ext_col + e, ext_txt + COLORS.ENDC)
                for e, (ext_txt, ext_col) in extras.items()
            ]
            print('\n'.join(to_print))
            self.prompt('\nChoose a parameter to edit (by index or name):')

            choice = input('>> ').strip().lower()
            parsed, choice = self.parse_choice(choice,
                                               len(self.params) + len(extras))
            if parsed == 'continue':
                continue
            elif parsed == 'add':
                self.add_parameter()
            elif parsed == 'change':
                self.last_choice = choice
                self.change_parameter(choice)
            elif parsed == 'delete':
                self.delete_parameter()
            elif parsed == 'live':
                self.last_choice = None
                self.live_tuning = not self.live_tuning
                self.op_params.put('op_edit_live_mode',
                                   self.live_tuning)  # for next opEdit startup
            elif parsed == 'exit':
                return
Exemplo n.º 7
0
    def change_parameter(self, choice):
        while True:
            chosen_key = list(self.params)[choice]
            param_info = self.op_params.fork_params[chosen_key]

            old_value = self.params[chosen_key]
            if not param_info.static:
                self.info2('Chosen parameter: {}{} (live!)'.format(
                    chosen_key, COLORS.BASE(207)),
                           sleep_time=0)
            else:
                self.info2('Chosen parameter: {}{} (static)'.format(
                    chosen_key, COLORS.BASE(207)),
                           sleep_time=0)

            to_print = []
            if param_info.has_description:
                to_print.append(COLORS.OKGREEN + '>>  Description: {}'.format(
                    param_info.description.replace('\n', '\n  > ')) +
                                COLORS.ENDC)
            if param_info.static:
                to_print.append(
                    COLORS.WARNING +
                    '>>  A reboot is required for changes to this parameter!' +
                    COLORS.ENDC)
            if not param_info.static and not param_info.live:
                to_print.append(
                    COLORS.WARNING +
                    '>>  Changes take effect within 10 seconds for this parameter!'
                    + COLORS.ENDC)
            if param_info.has_allowed_types:
                to_print.append(COLORS.RED + '>>  Allowed types: {}'.format(
                    ', '.join([at.__name__
                               for at in param_info.allowed_types])) +
                                COLORS.ENDC)
            to_print.append(COLORS.WARNING + '>>  Default value: {}'.format(
                self.color_from_type(param_info.default_value)) + COLORS.ENDC)

            if to_print:
                print('\n{}\n'.format('\n'.join(to_print)))

            if param_info.is_list:
                self.change_param_list(
                    old_value, param_info, chosen_key
                )  # TODO: need to merge the code in this function with the below to reduce redundant code
                return

            self.info('Current value: {}{} (type: {})'.format(
                self.color_from_type(old_value), COLORS.INFO,
                type(old_value).__name__),
                      sleep_time=0)

            while True:
                self.prompt('\nEnter your new value (enter to exit):')
                new_value = input('>> ').strip()
                if new_value == '':
                    self.info('Exiting this parameter...\n')
                    return

                new_value = self.str_eval(new_value)
                if not param_info.is_valid(new_value):
                    self.error(
                        'The type of data you entered ({}) is not allowed with this parameter!'
                        .format(type(new_value).__name__))
                    continue

                if not param_info.static:  # stay in live tuning interface
                    self.op_params.put(chosen_key, new_value)
                    self.success(
                        'Saved {} with value: {}{}! (type: {})'.format(
                            chosen_key, self.color_from_type(new_value),
                            COLORS.SUCCESS,
                            type(new_value).__name__))
                else:  # else ask to save and break
                    self.warning('\nOld value: {}{} (type: {})'.format(
                        self.color_from_type(old_value), COLORS.WARNING,
                        type(old_value).__name__))
                    self.success('New value: {}{} (type: {})'.format(
                        self.color_from_type(new_value), COLORS.OKGREEN,
                        type(new_value).__name__),
                                 sleep_time=0)
                    self.prompt('\nDo you want to save this?')
                    if self.input_with_options(['Y', 'N'], 'N')[0] == 0:
                        self.op_params.put(chosen_key, new_value)
                        self.success('Saved!')
                    else:
                        self.info('Not saved!')
                    return