mirror of
https://github.com/esphome/esphome.git
synced 2024-11-24 12:06:26 +01:00
convert input value to desired unit
This commit is contained in:
parent
ea4e618f2a
commit
ac68e1726b
@ -895,16 +895,19 @@ METRIC_SUFFIXES = {
|
|||||||
|
|
||||||
|
|
||||||
def float_with_unit(quantity, regex_suffix, optional_unit=False):
|
def float_with_unit(quantity, regex_suffix, optional_unit=False):
|
||||||
pattern = re.compile(
|
unit_regex = f"\\s*(\\w*?){regex_suffix}"
|
||||||
f"^([-+]?[0-9]*\\.?[0-9]*)\\s*(\\w*?){regex_suffix}$", re.UNICODE
|
|
||||||
)
|
|
||||||
|
|
||||||
def validator(value):
|
unit_pattern = re.compile(f"^{unit_regex}$", re.UNICODE)
|
||||||
|
|
||||||
|
pattern = re.compile(f"^([-+]?[0-9]*\\.?[0-9]*){unit_regex}$", re.UNICODE)
|
||||||
|
|
||||||
|
def validator(value, to=None):
|
||||||
if optional_unit:
|
if optional_unit:
|
||||||
try:
|
try:
|
||||||
return float_(value)
|
return float_(value)
|
||||||
except Invalid:
|
except Invalid:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
match = pattern.match(string(value))
|
match = pattern.match(string(value))
|
||||||
|
|
||||||
if match is None:
|
if match is None:
|
||||||
@ -915,6 +918,15 @@ def float_with_unit(quantity, regex_suffix, optional_unit=False):
|
|||||||
raise Invalid(f"Invalid {quantity} suffix {match.group(2)}")
|
raise Invalid(f"Invalid {quantity} suffix {match.group(2)}")
|
||||||
|
|
||||||
multiplier = METRIC_SUFFIXES[match.group(2)]
|
multiplier = METRIC_SUFFIXES[match.group(2)]
|
||||||
|
|
||||||
|
if to is not None:
|
||||||
|
unit_match = unit_pattern.match(string(to))
|
||||||
|
|
||||||
|
if unit_match is None:
|
||||||
|
raise Invalid(f"Invalid conversion suffix {unit_match.group(1)}")
|
||||||
|
|
||||||
|
multiplier /= METRIC_SUFFIXES[unit_match.group(1)]
|
||||||
|
|
||||||
return mantissa * multiplier
|
return mantissa * multiplier
|
||||||
|
|
||||||
return validator
|
return validator
|
||||||
@ -934,6 +946,10 @@ decibel = float_with_unit("decibel", "(dB|dBm|db|dbm)", optional_unit=True)
|
|||||||
pressure = float_with_unit("pressure", "(bar|Bar)", optional_unit=True)
|
pressure = float_with_unit("pressure", "(bar|Bar)", optional_unit=True)
|
||||||
|
|
||||||
|
|
||||||
|
def to_unit(value):
|
||||||
|
print(value)
|
||||||
|
|
||||||
|
|
||||||
def temperature(value):
|
def temperature(value):
|
||||||
err = None
|
err = None
|
||||||
try:
|
try:
|
||||||
|
Loading…
Reference in New Issue
Block a user