Home Assistant Unofficial Reference 2024.12.1
scaling.py
Go to the documentation of this file.
1 """Scaling util functions."""
2 
3 from __future__ import annotations
4 
5 
7  source_low_high_range: tuple[float, float],
8  target_low_high_range: tuple[float, float],
9  value: float,
10 ) -> int:
11  """Given a range of low and high values convert a single value to another range.
12 
13  Given a source low value of 1 and a high value of 255 and
14  a target range from 1 to 100 this function
15  will return:
16 
17  (1,255), (1,100), 255: 100
18  (1,255), (1,100), 127: 49
19  (1,255), (1,100), 10: 3
20  """
21  source_offset = source_low_high_range[0] - 1
22  target_offset = target_low_high_range[0] - 1
23  return int(
24  (value - source_offset)
25  * states_in_range(target_low_high_range)
26  // states_in_range(source_low_high_range)
27  + target_offset
28  )
29 
30 
32  source_low_high_range: tuple[float, float],
33  target_low_high_range: tuple[float, float],
34  value: float,
35 ) -> float:
36  """Given a range of low and high values convert a single value to another range.
37 
38  Do not include 0 in a range if 0 means off,
39  e.g. for brightness or fan speed.
40 
41  Given a source low value of 1 and a high value of 255 and
42  a target range from 1 to 100 this function
43  will return:
44 
45  (1,255), 255: 100
46  (1,255), 127: ~49.8039
47  (1,255), 10: ~3.9216
48  """
49  source_offset = source_low_high_range[0] - 1
50  target_offset = target_low_high_range[0] - 1
51  return (value - source_offset) * (
52  states_in_range(target_low_high_range)
53  ) / states_in_range(source_low_high_range) + target_offset
54 
55 
56 def states_in_range(low_high_range: tuple[float, float]) -> float:
57  """Given a range of low and high values return how many states exist."""
58  return low_high_range[1] - low_high_range[0] + 1
59 
60 
61 def int_states_in_range(low_high_range: tuple[float, float]) -> int:
62  """Given a range of low and high values return how many integer states exist."""
63  return int(states_in_range(low_high_range))
int scale_ranged_value_to_int_range(tuple[float, float] source_low_high_range, tuple[float, float] target_low_high_range, float value)
Definition: scaling.py:10
int int_states_in_range(tuple[float, float] low_high_range)
Definition: scaling.py:61
float scale_to_ranged_value(tuple[float, float] source_low_high_range, tuple[float, float] target_low_high_range, float value)
Definition: scaling.py:35
float states_in_range(tuple[float, float] low_high_range)
Definition: scaling.py:56