Пример #1
0
def logger_log_action_to_code(config, action_id, template_arg, args):
    esp_log = LOG_LEVEL_TO_ESP_LOG[config[CONF_LEVEL]]
    args_ = [RawExpression(text_type(x)) for x in config[CONF_ARGS]]

    text = text_type(
        statement(esp_log(config[CONF_TAG], config[CONF_FORMAT], *args_)))

    for lambda_ in process_lambda(Lambda(text), args, return_type=void):
        yield None
    rhs = LambdaAction.new(template_arg, lambda_)
    type = LambdaAction.template(template_arg)
    yield Pvariable(action_id, rhs, type=type)
Пример #2
0
def write_cpp(config):
    _LOGGER.info("Generating C++ source...")

    CORE.add_job(core_config.to_code, config[CONF_PI4HOME], domain='pi4home')
    for domain in PRE_INITIALIZE:
        if domain == CONF_PI4HOME or domain not in config:
            continue
        CORE.add_job(get_component(domain).to_code,
                     config[domain],
                     domain=domain)

    for domain, component, conf in iter_components(config):
        if domain in PRE_INITIALIZE or not hasattr(component, 'to_code'):
            continue
        CORE.add_job(component.to_code, conf, domain=domain)

    CORE.flush_tasks()
    add(RawStatement(''))
    add(RawStatement(''))
    all_code = []
    for exp in CORE.expressions:
        if not config[CONF_PI4HOME][CONF_USE_CUSTOM_CODE]:
            if isinstance(exp, Expression) and not exp.required:
                continue
        all_code.append(text_type(statement(exp)))

    writer.write_platformio_project()

    code_s = indent('\n'.join(line.rstrip() for line in all_code))
    writer.write_cpp(code_s)
    return 0
Пример #3
0
def alphanumeric(value):
    if value is None:
        raise vol.Invalid("string value is None")
    value = text_type(value)
    if not value.isalnum():
        raise vol.Invalid("string value is not alphanumeric")
    return value
Пример #4
0
 def __str__(self):
     if self.i > 4294967295:
         return u'{}ULL'.format(self.i)
     if self.i > 2147483647:
         return u'{}UL'.format(self.i)
     if self.i < -2147483648:
         return u'{}LL'.format(self.i)
     return text_type(self.i)
Пример #5
0
def _secret_yaml(loader, node):
    """Load secrets and embed it into the configuration YAML."""
    secret_path = os.path.join(os.path.dirname(loader.name), SECRET_YAML)
    secrets = _load_yaml_internal(secret_path)
    if node.value not in secrets:
        raise pi4homeError(u"Secret {} not defined".format(node.value))
    val = secrets[node.value]
    _SECRET_VALUES[text_type(val)] = node.value
    return val
Пример #6
0
def humanize_error(config, validation_error):
    offending_item_summary = _nested_getitem(config, validation_error.path)
    if isinstance(offending_item_summary, dict):
        offending_item_summary = None
    validation_error = text_type(validation_error)
    m = re.match(r'^(.*?)\s*(?:for dictionary value )?@ data\[.*$',
                 validation_error)
    if m is not None:
        validation_error = m.group(1)
    validation_error = validation_error.strip()
    if not validation_error.endswith(u'.'):
        validation_error += u'.'
    if offending_item_summary is None or is_secret(offending_item_summary):
        return validation_error

    return u"{} Got '{}'".format(validation_error, offending_item_summary)
Пример #7
0
def preload_core_config(config):
    if 'pi4homeyaml' in config:
        _LOGGER.warning("The pi4homeyaml section has been renamed to pi4home in 1.11.0. "
                        "Please replace 'pi4homeyaml:' in your configuration with 'pi4home:'.")
        config[CONF_PI4HOME] = config.pop('pi4homeyaml')
    if CONF_PI4HOME not in config:
        raise pi4homeError(u"No pi4home section in config")
    core_conf = config[CONF_PI4HOME]
    if CONF_PLATFORM not in core_conf:
        raise pi4homeError("pi4home.platform not specified.")
    if CONF_BOARD not in core_conf:
        raise pi4homeError("pi4home.board not specified.")
    if CONF_NAME not in core_conf:
        raise pi4homeError("pi4home.name not specified.")

    try:
        CORE.esp_platform = validate_platform(core_conf[CONF_PLATFORM])
        CORE.board = validate_board(core_conf[CONF_BOARD])
        CORE.name = cv.valid_name(core_conf[CONF_NAME])
        CORE.build_path = CORE.relative_path(
            cv.string(core_conf.get(CONF_BUILD_PATH, default_build_path())))
    except vol.Invalid as e:
        raise pi4homeError(text_type(e))
Пример #8
0
 def content(self):
     return u''.join(text_type(part) for part in self.parts)
Пример #9
0
 def __str__(self):
     return u", ".join(text_type(x) for x in self.parameters)
Пример #10
0
def _lambda(loader, node):
    return Lambda(text_type(node.value))
Пример #11
0
def is_secret(value):
    try:
        return _SECRET_VALUES[text_type(value)]
    except (KeyError, ValueError):
        return None
Пример #12
0
def string(value):
    if isinstance(value, (dict, list)):
        raise vol.Invalid("string value cannot be dictionary or list.")
    if value is not None:
        return text_type(value)
    raise vol.Invalid("string value is None")
Пример #13
0
 def add_error(self, message, path):
     # type: (basestring, ConfigPath) -> None
     if not isinstance(message, text_type):
         message = text_type(message)
     self.errors.append((message, path))
Пример #14
0
def dump_dict(config, path, at_root=True):
    # type: (Config, ConfigPath, bool) -> Tuple[unicode, bool]
    conf = config.nested_item(path)
    ret = u''
    multiline = False

    if at_root:
        error = config.get_error_for_path(path)
        if error is not None:
            ret += u'\n' + color('bold_red', error) + u'\n'

    if isinstance(conf, (list, tuple)):
        multiline = True
        if not conf:
            ret += u'[]'
            multiline = False

        for i in range(len(conf)):
            path_ = path + [i]
            error = config.get_error_for_path(path_)
            if error is not None:
                ret += u'\n' + color('bold_red', error) + u'\n'

            sep = u'- '
            if config.is_in_error_path(path_):
                sep = color('red', sep)
            msg, _ = dump_dict(config, path_, at_root=False)
            msg = indent(msg)
            inf = line_info(config.nested_item(path_),
                            highlight=config.is_in_error_path(path_))
            if inf is not None:
                msg = inf + u'\n' + msg
            elif msg:
                msg = msg[2:]
            ret += sep + msg + u'\n'
    elif isinstance(conf, dict):
        multiline = True
        if not conf:
            ret += u'{}'
            multiline = False

        for k in conf.keys():
            path_ = path + [k]
            error = config.get_error_for_path(path_)
            if error is not None:
                ret += u'\n' + color('bold_red', error) + u'\n'

            st = u'{}: '.format(k)
            if config.is_in_error_path(path_):
                st = color('red', st)
            msg, m = dump_dict(config, path_, at_root=False)

            inf = line_info(config.nested_item(path_),
                            highlight=config.is_in_error_path(path_))
            if m:
                msg = u'\n' + indent(msg)

            if inf is not None:
                if m:
                    msg = u' ' + inf + msg
                else:
                    msg = msg + u' ' + inf
            ret += st + msg + u'\n'
    elif isinstance(conf, str):
        if is_secret(conf):
            conf = u'!secret {}'.format(is_secret(conf))
        if not conf:
            conf += u"''"

        if len(conf) > 80:
            conf = u'|-\n' + indent(conf)
        error = config.get_error_for_path(path)
        col = 'bold_red' if error else 'white'
        ret += color(col, text_type(conf))
    elif isinstance(conf, core.Lambda):
        if is_secret(conf):
            conf = u'!secret {}'.format(is_secret(conf))

        conf = u'!lambda |-\n' + indent(text_type(conf.value))
        error = config.get_error_for_path(path)
        col = 'bold_red' if error else 'white'
        ret += color(col, conf)
    elif conf is None:
        pass
    else:
        error = config.get_error_for_path(path)
        col = 'bold_red' if error else 'white'
        ret += color(col, text_type(conf))
        multiline = u'\n' in ret

    return ret, multiline
Пример #15
0
 def read_utf(self, offset, length):
     """Reads a UTF-8 string of a given length from the packet"""
     return text_type(self.data[offset:offset + length], 'utf-8', 'replace')
Пример #16
0
 def __str__(self):  # type: () -> unicode
     return text_type(self.base)
Пример #17
0
 def __str__(self):
     text = u", ".join(text_type(x) for x in self.args)
     return indent_all_but_first_and_last(text)
Пример #18
0
def strip_accents(string):
    return u''.join(c for c in unicodedata.normalize('NFD', text_type(string))
                    if unicodedata.category(c) != 'Mn')