예제 #1
0
def validate_fingerprint(value):
    value = cv.string(value)
    if re.match(r'^[0-9a-f]{40}$', value) is None:
        raise vol.Invalid(u"fingerprint must be valid SHA1 hash")
    return value
예제 #2
0
def validate_config(config):
    """Validate that the configuration is valid, throws if it isn't."""
    if config.get(CONF_MIN) >= config.get(CONF_MAX):
        raise vol.Invalid(f"'{CONF_MAX}' must be > '{CONF_MIN}'")

    return config
예제 #3
0
 def validator_(obj):
     if CORE.esp_platform not in platforms:
         raise vol.Invalid(u"This feature is only available on {}".format(platforms))
     return obj
예제 #4
0
def Regex(value):
    try:
        re.compile(value)
    except re.error as e:
        raise voluptuous.Invalid(str(e))
    return value
예제 #5
0
def valid_date(value: Any) -> datetime.date:
    """Validate if a given object is a date."""
    try:
        return datetime.datetime.strptime(value, "%d.%m.%Y")
    except ValueError:
        raise vol.Invalid(f"Invalides Datum: {value}")
예제 #6
0
def positive_timedelta(value: timedelta) -> timedelta:
    """Validate timedelta is positive."""
    if value < timedelta(0):
        raise vol.Invalid('Time period should be positive')
    return value
예제 #7
0
def _included(ranges, set_to, values):
    for rng in ranges:
        if not rng[0] <= rng[1] <= len(values):
            raise vol.Invalid(f"Invalid range {rng}")
        values[rng[0] - 1 : rng[1]] = [set_to] * (rng[1] - rng[0] + 1)
예제 #8
0
def valid_isy_commands(value: Any) -> str:
    """Validate the command is valid."""
    value = str(value).upper()
    if value in COMMAND_FRIENDLY_NAME:
        return value
    raise vol.Invalid("Invalid ISY Command.")
예제 #9
0
def valid_discovery_service(service):
    """Validate service name."""
    service_file = Path(__file__).parent.joinpath(f"services/{service}.py")
    if not service_file.exists():
        raise vol.Invalid(f"Service {service} not found")
    return service
예제 #10
0
def validate_cron_pattern(pattern):
    """Check that the pattern is well-formed."""
    if croniter.is_valid(pattern):
        return pattern
    raise vol.Invalid("Invalid pattern")
예제 #11
0
def valid_color_configuration(config):
    """Test color_mode is not combined with deprecated config."""
    deprecated = {CONF_COLOR_TEMP, CONF_HS, CONF_RGB, CONF_WHITE_VALUE, CONF_XY}
    if config[CONF_COLOR_MODE] and any(config.get(key) for key in deprecated):
        raise vol.Invalid(f"color_mode must not be combined with any of {deprecated}")
    return config
예제 #12
0
def _validate_test_mode(obj: Dict) -> Dict:
    """Validate that id is provided outside of test mode."""
    if ATTR_ID not in obj and obj[ATTR_TRIGGER] != "test":
        raise vol.Invalid("Location id not specified")
    return obj
예제 #13
0
def script_action(value: Any) -> dict:
    """Validate a script action."""
    if not isinstance(value, dict):
        raise vol.Invalid("expected dictionary")

    return ACTION_TYPE_SCHEMAS[determine_script_action(value)](value)
예제 #14
0
def x10_address(value: str) -> str:
    """Validate an x10 address."""
    regex = re.compile(r"([A-Pa-p]{1})(?:[2-9]|1[0-6]?)$")
    if not regex.match(value):
        raise vol.Invalid("Invalid X10 Address")
    return str(value).lower()
예제 #15
0
def filename_is_present_if_logging_to_file(obj: dict) -> dict:
    """Validate that filename is provided if log_to_file is True."""
    if obj.get(LOG_TO_FILE, False) and FILENAME not in obj:
        raise vol.Invalid("`filename` must be provided if logging to file")
    return obj
예제 #16
0
def lowercase_validator(value):
    """Validate value is lowercase."""
    if value.lower() != value:
        raise vol.Invalid("Needs to be lowercase")

    return value
예제 #17
0
def time_period_seconds(value: Union[int, str]) -> timedelta:
    """Validate and transform seconds to a time offset."""
    try:
        return timedelta(seconds=int(value))
    except (ValueError, TypeError):
        raise vol.Invalid('Expected seconds, got {}'.format(value))
예제 #18
0
def validate_integration_time(value):
    value = cv.positive_time_period_milliseconds(value).total_milliseconds
    if value not in INTEGRATION_TIMES:
        raise vol.Invalid(u"Unsupported integration time {}.".format(value))
    return value
예제 #19
0
def x10_address(value):
    """Validate an x10 address."""
    regex = re.compile(r'([A-Pa-p]{1})(?:[2-9]|1[0-6]?)$')
    if not regex.match(value):
        raise vol.Invalid('Invalid X10 Address')
    return str(value).lower()
예제 #20
0
def validate_name_pattern(value: str) -> str:
    """Validate that the naming pattern contains {}."""
    regex = re.compile(r"\{\}")
    if not regex.search(value):
        raise vol.Invalid("Naming pattern must contain {}")
    return value
예제 #21
0
 def _housecode_to_int(val):
     match = re.search(r"^([a-p])(0[1-9]|1[0-6]|[1-9])$", val.lower())
     if match:
         return (ord(match.group(1)) - ord("a")) * 16 + int(match.group(2))
     raise vol.Invalid("Invalid range")
예제 #22
0
def valid_subscribe_topic(value, invalid_chars='\0'):
    """Validate that we can subscribe using this MQTT topic."""
    value = cv.string(value)
    if all(c not in value for c in invalid_chars):
        return vol.Length(min=1, max=65535)(value)
    raise vol.Invalid('Invalid MQTT topic name')
예제 #23
0
def is_persistence_file(value):
    """Validate that persistence file path ends in either .pickle or .json."""
    if value.endswith((".json", ".pickle")):
        return value
    raise vol.Invalid(f"{value} does not end in either `.json` or `.pickle`")
예제 #24
0
def validate_statistic_id(value: str) -> str:
    """Validate statistic ID."""
    if valid_statistic_id(value):
        return value

    raise vol.Invalid(f"Statistics ID {value} is an invalid statistic ID")
예제 #25
0
def valid_time(value: Any) -> datetime.datetime:
    """Validate if a given object is a time."""
    try:
        return datetime.datetime.strptime(value, "%H:%M:%S")
    except ValueError:
        raise vol.Invalid(f"Invalide Uhrzeit: {value}")
예제 #26
0
def entity_id(value: Any) -> str:
    """Validate Entity ID."""
    value = string(value).lower()
    if valid_entity_id(value):
        return value
    raise vol.Invalid('Entity ID {} is an invalid entity id'.format(value))
예제 #27
0
def ensure_dict(value):
    if value is None:
        return {}
    if not isinstance(value, dict):
        raise vol.Invalid("Expected a dictionary")
    return value
예제 #28
0
def validate_pin_number(value):
    valid_pins = [0, 2, 4, 12, 13, 14, 15, 25, 26, 27, 32, 39]
    if value[CONF_NUMBER] not in valid_pins:
        raise vol.Invalid(u"Only pins {} support wakeup"
                          u"".format(', '.join(str(x) for x in valid_pins)))
    return value
예제 #29
0
def time_period_in_seconds_(value):
    if value.microseconds is not None and value.microseconds != 0:
        raise vol.Invalid("Maximum precision is seconds")
    if value.milliseconds is not None and value.milliseconds != 0:
        raise vol.Invalid("Maximum precision is seconds")
    return TimePeriodSeconds(**value.as_dict())
예제 #30
0
파일: schema.py 프로젝트: iligiddi/xknx
def sensor_type_validator(value: Any) -> str | int:
    """Validate that value is parsable as sensor type."""
    if isinstance(value,
                  (str, int)) and DPTBase.parse_transcoder(value) is not None:
        return value
    raise vol.Invalid(f"value '{value}' is not a valid sensor type.")