Beispiel #1
0
def logger_log_action_to_code(config, action_id, arg_type, template_arg):
    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), [(arg_type, 'x')], return_type=void):
        yield None
    rhs = LambdaAction.new(template_arg, lambda_)
    type = LambdaAction.template(template_arg)
    yield Pvariable(action_id, rhs, type=type)
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
Beispiel #3
0
def write_cpp(config):
    _LOGGER.info("Generating C++ source...")

    CORE.add_job(core_config.to_code,
                 config[CONF_ESPHOMEYAML],
                 domain='esphomeyaml')
    for domain in PRE_INITIALIZE:
        if domain == CONF_ESPHOMEYAML 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_ESPHOMEYAML][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
Beispiel #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)
Beispiel #5
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(text_type(msg)))
        req = chr(0x00)
        req += _varuint_to_bytes(len(encoded))
        req += _varuint_to_bytes(message_type)
        req += encoded
        self._write(req)
        self._refresh_ping()
Beispiel #6
0
def humanize_error(config, validation_error):
    offending_item_summary = _nested_getitem(config, validation_error.path)
    if isinstance(offending_item_summary, dict):
        try:
            offending_item_summary = json.dumps(offending_item_summary)
        except (TypeError, ValueError):
            pass
    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:
        return validation_error
    return u"{} Got '{}'".format(validation_error, offending_item_summary)
Beispiel #7
0
def preload_core_config(config):
    if CONF_ESPHOMEYAML not in config:
        raise EsphomeyamlError(u"No esphomeyaml section in config")
    core_conf = config[CONF_ESPHOMEYAML]
    if CONF_PLATFORM not in core_conf:
        raise EsphomeyamlError("esphomeyaml.platform not specified.")
    if CONF_BOARD not in core_conf:
        raise EsphomeyamlError("esphomeyaml.board not specified.")
    if CONF_NAME not in core_conf:
        raise EsphomeyamlError("esphomeyaml.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 EsphomeyamlError(text_type(e))
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")
Beispiel #9
0
def strip_accents(string):
    return u''.join(c for c in unicodedata.normalize('NFD', text_type(string))
                    if unicodedata.category(c) != 'Mn')
Beispiel #10
0
def _lambda(loader, node):
    return Lambda(text_type(node.value))
Beispiel #11
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))
Beispiel #12
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 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):
        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
Beispiel #13
0
 def __str__(self):
     text = u", ".join(text_type(x) for x in self.args)
     return indent_all_but_first_and_last(text)
Beispiel #14
0
 def __str__(self):  # type: () -> unicode
     return text_type(self.base)
Beispiel #15
0
 def content(self):
     return u''.join(text_type(part) for part in self.parts)
Beispiel #16
0
 def __str__(self):
     return u", ".join(text_type(x) for x in self.parameters)