Exemple #1
0
 async def wrapped(conf):
     cg.add(cg.LineComment(f"{name}:"))
     if comp.config_schema is not None:
         conf_str = yaml_util.dump(conf)
         conf_str = conf_str.replace("//", "")
         cg.add(cg.LineComment(indent(conf_str)))
     await coro(conf)
def read_config(command_line_substitutions):
    _LOGGER.info("Reading configuration %s...", CORE.config_path)
    try:
        res = load_config(command_line_substitutions)
    except EsphomeError as err:
        _LOGGER.error("Error while reading config: %s", err)
        return None
    if res.errors:
        if not CORE.verbose:
            res = strip_default_ids(res)

        safe_print(color(Fore.BOLD_RED, "Failed config"))
        safe_print("")
        for path, domain in res.output_paths:
            if not res.is_in_error_path(path):
                continue

            errstr = color(Fore.BOLD_RED, f"{domain}:")
            errline = line_info(res, path)
            if errline:
                errstr += " " + errline
            safe_print(errstr)
            safe_print(indent(dump_dict(res, path)[0]))
        return None
    return OrderedDict(res)
Exemple #3
0
def write_cpp(config):
    _LOGGER.info("Generating C++ source...")

    CORE.add_job(core_config.to_code, config[CONF_ESPHOME], domain='esphome')
    for domain in PRE_INITIALIZE:
        if domain == CONF_ESPHOME 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_ESPHOME][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
Exemple #4
0
 def wrapped(conf):
     cg.add(cg.LineComment(f"{name}:"))
     if comp.config_schema is not None:
         conf_str = yaml_util.dump(conf)
         conf_str = conf_str.replace('//', '')
         cg.add(cg.LineComment(indent(conf_str)))
     yield coro(conf)
Exemple #5
0
 def wrapped(conf):
     cg.add(cg.LineComment(u"{}:".format(name)))
     if comp.config_schema is not None:
         conf_str = yaml_util.dump(conf)
         if IS_PY2:
             conf_str = conf_str.decode('utf-8')
         cg.add(cg.LineComment(indent(conf_str)))
     yield coro(conf)
Exemple #6
0
 async def wrapped(conf):
     cg.add(cg.LineComment(f"{name}:"))
     if comp.config_schema is not None:
         conf_str = yaml_util.dump(conf)
         conf_str = conf_str.replace("//", "")
         # remove tailing \ to avoid multi-line comment warning
         conf_str = conf_str.replace("\\\n", "\n")
         cg.add(cg.LineComment(indent(conf_str)))
     await coro(conf)
Exemple #7
0
def write_cpp(config):
    _LOGGER.info("Generating C++ source...")

    for name, component, conf in iter_components(CORE.config):
        if component.to_code is not None:
            coro = wrap_to_code(name, component)
            CORE.add_job(coro, conf)

    CORE.flush_tasks()

    writer.write_platformio_project()

    code_s = indent(CORE.cpp_main_section)
    writer.write_cpp(code_s)
    return 0
    def _send_message(self, msg):
        # type: (message.Message) -> None
        for message_type, klass in MESSAGE_TYPE_TO_PROTO.items():
            if isinstance(msg, klass):
                break
        else:
            raise ValueError

        encoded = msg.SerializeToString()
        _LOGGER.debug("Sending %s:\n%s", type(msg), indent(str(msg)))
        req = bytes([0])
        req += _varuint_to_bytes(len(encoded))
        req += _varuint_to_bytes(message_type)
        req += encoded
        self._write(req)
Exemple #9
0
    def _run_once(self):
        if not self._socket_open_event.wait(0.1):
            return

        # Preamble
        if char_to_byte(self._recv(1)[0]) != 0x00:
            raise APIConnectionError("Invalid preamble")

        length = self._recv_varint()
        msg_type = self._recv_varint()

        raw_msg = self._recv(length)
        if msg_type not in MESSAGE_TYPE_TO_PROTO:
            _LOGGER.debug("Skipping message type %s", msg_type)
            return

        msg = MESSAGE_TYPE_TO_PROTO[msg_type]()
        msg.ParseFromString(raw_msg)
        _LOGGER.debug("Got message: %s:\n%s", type(msg), indent(str(msg)))
        for msg_handler in self._message_handlers[:]:
            msg_handler(msg)
        self._handle_internal_messages(msg)
Exemple #10
0
def read_config(verbose):
    _LOGGER.info("Reading configuration...")
    try:
        res = load_config()
    except EsphomeError as err:
        _LOGGER.error(u"Error while reading config: %s", err)
        return None
    if res.errors:
        if not verbose:
            res = strip_default_ids(res)

        safe_print(color('bold_red', u"Failed config"))
        safe_print('')
        for path, domain in res.domains:
            if not res.is_in_error_path(path):
                continue

            safe_print(color('bold_red', u'{}:'.format(domain)) + u' ' +
                       (line_info(res.nested_item(path)) or u''))
            safe_print(indent(dump_dict(res, path)[0]))
        return None
    return OrderedDict(res)
Exemple #11
0
def read_config():
    _LOGGER.info("Reading configuration %s...", CORE.config_path)
    try:
        res = load_config()
    except EsphomeError as err:
        _LOGGER.error("Error while reading config: %s", err)
        return None
    if res.errors:
        if not CORE.verbose:
            res = strip_default_ids(res)

        safe_print(color('bold_red', "Failed config"))
        safe_print('')
        for path, domain in res.output_paths:
            if not res.is_in_error_path(path):
                continue

            safe_print(color('bold_red', f'{domain}:') + ' ' +
                       (line_info(res.get_nested_item(path)) or ''))
            safe_print(indent(dump_dict(res, path)[0]))
        return None
    return OrderedDict(res)
Exemple #12
0
def write_cpp_file():
    writer.write_platformio_project()

    code_s = indent(CORE.cpp_main_section)
    writer.write_cpp(code_s)
    return 0
Exemple #13
0
def dump_dict(config, path, at_root=True):
    # type: (Config, ConfigPath, bool) -> Tuple[unicode, bool]
    conf = config.get_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', _format_vol_invalid(
                error, config)) + 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', _format_vol_invalid(error, config)) + 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.get_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', _format_vol_invalid(error, config)) + 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.get_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
def dump_dict(config, path, at_root=True):
    # type: (Config, ConfigPath, bool) -> Tuple[str, bool]
    conf = config.get_nested_item(path)
    ret = ""
    multiline = False

    if at_root:
        error = config.get_error_for_path(path)
        if error is not None:
            ret += ("\n" +
                    color(Fore.BOLD_RED, _format_vol_invalid(error, config)) +
                    "\n")

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

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

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

        for k in conf.keys():
            path_ = path + [k]
            error = config.get_error_for_path(path_)
            if error is not None:
                ret += ("\n" + color(
                    Fore.BOLD_RED, _format_vol_invalid(error, config)) + "\n")

            st = f"{k}: "
            if config.is_in_error_path(path_):
                st = color(Fore.RED, st)
            msg, m = dump_dict(config, path_, at_root=False)

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

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

        if len(conf) > 80:
            conf = "|-\n" + indent(conf)
        error = config.get_error_for_path(path)
        col = Fore.BOLD_RED if error else Fore.KEEP
        ret += color(col, str(conf))
    elif isinstance(conf, core.Lambda):
        if is_secret(conf):
            conf = "!secret {}".format(is_secret(conf))

        conf = "!lambda |-\n" + indent(str(conf.value))
        error = config.get_error_for_path(path)
        col = Fore.BOLD_RED if error else Fore.KEEP
        ret += color(col, conf)
    elif conf is None:
        pass
    else:
        error = config.get_error_for_path(path)
        col = Fore.BOLD_RED if error else Fore.KEEP
        ret += color(col, str(conf))
        multiline = "\n" in ret

    return ret, multiline
Exemple #15
0
def test_indent(text, expected):
    actual = helpers.indent(text)

    assert actual == expected