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
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
def validator_(obj): if CORE.esp_platform not in platforms: raise vol.Invalid(u"This feature is only available on {}".format(platforms)) return obj
def Regex(value): try: re.compile(value) except re.error as e: raise voluptuous.Invalid(str(e)) return value
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}")
def positive_timedelta(value: timedelta) -> timedelta: """Validate timedelta is positive.""" if value < timedelta(0): raise vol.Invalid('Time period should be positive') return value
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)
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.")
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
def validate_cron_pattern(pattern): """Check that the pattern is well-formed.""" if croniter.is_valid(pattern): return pattern raise vol.Invalid("Invalid pattern")
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
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
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)
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()
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
def lowercase_validator(value): """Validate value is lowercase.""" if value.lower() != value: raise vol.Invalid("Needs to be lowercase") return value
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))
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
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()
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
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")
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')
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`")
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")
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}")
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))
def ensure_dict(value): if value is None: return {} if not isinstance(value, dict): raise vol.Invalid("Expected a dictionary") return value
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
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())
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.")