redzed 25.12.30__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,262 @@
1
+ """
2
+ Conversion routines for time periods/durations using multiple units.
3
+
4
+ Example: "20h15m10" = 20 hours + 15 minutes + 10 seconds = 72910 seconds
5
+ """
6
+ from __future__ import annotations
7
+
8
+ __all__ = [
9
+ 'SEC_PER_DAY', 'SEC_PER_HOUR', 'SEC_PER_MIN',
10
+ 'fmt_period', 'parse_interval', 'time_period']
11
+
12
+ from collections.abc import Callable, Sequence
13
+ import re
14
+ import typing as t
15
+
16
+ from .data_utils import to_tuple
17
+
18
+
19
+ SEC_PER_DAY = 86_400
20
+ SEC_PER_HOUR = 3_600
21
+ SEC_PER_MIN = 60
22
+
23
+
24
+ def _fmt_parameters(seconds: float, approx: bool) -> tuple[int, int]:
25
+ """Internal parameters for formatting."""
26
+ # first value = exclusion of smallest units:
27
+ # 6 = include everything, 5 = exclude: MS, 4 = exclude: S+MS, 3 = exclude: M+S+MS
28
+ # second value = rounding unit in ms:
29
+ if approx:
30
+ if seconds >= 3 * SEC_PER_DAY:
31
+ return (3, 1000 * SEC_PER_HOUR)
32
+ if seconds >= SEC_PER_HOUR:
33
+ return (4, 1000 * SEC_PER_MIN)
34
+ if seconds >= SEC_PER_MIN:
35
+ return (5, 1000)
36
+ if seconds >= 10:
37
+ return (6, 100)
38
+ if seconds >= 3:
39
+ return (6, 10)
40
+ return (6, 1)
41
+
42
+
43
+ _UNITS = [('w', 'd', 'h', 'm', 's', 'ms'), ('W', 'D', 'H', 'M', 'S', 'MS')]
44
+ def fmt_period(
45
+ seconds: float,
46
+ iso8601: bool = False, sep: str = '', upper: bool = False, approx: bool = False
47
+ ) -> str:
48
+ """
49
+ Return seconds as a string using units w, d, h, m, s and ms.
50
+
51
+ The individual parts are separated with the 'sep' string.
52
+ """
53
+ if seconds < 0.0:
54
+ raise ValueError("Number of seconds cannot be negative")
55
+ if iso8601:
56
+ upper = True
57
+ sep = ''
58
+ if seconds == 0.0:
59
+ if iso8601:
60
+ return "PT0S"
61
+ return "0S" if upper else "0s"
62
+ fmt_last, fmt_rounding = _fmt_parameters(seconds, approx)
63
+ ms = int(1000 * seconds / fmt_rounding + 0.5) * fmt_rounding
64
+ if ms == 0:
65
+ if iso8601:
66
+ return "PT0.001S"
67
+ return "1MS" if upper else "1ms"
68
+ s: int|float # float only in iso8601 mode
69
+ s, ms = divmod(ms, 1000)
70
+ d, s = divmod(s, SEC_PER_DAY)
71
+ if iso8601:
72
+ w = 0
73
+ else:
74
+ w, d = divmod(d, 7)
75
+ h, s = divmod(s, SEC_PER_HOUR)
76
+ m, s = divmod(s, SEC_PER_MIN)
77
+ if iso8601 and ms != 0:
78
+ s += ms / 1000
79
+ ms = 0
80
+ numbers = [w, d, h, m, s, ms]
81
+ units = _UNITS[bool(upper)] # True == 1, False == 0
82
+ for idx, value in enumerate(numbers):
83
+ if value > 0:
84
+ first = idx
85
+ break
86
+ for idx in range(fmt_last, 0, -1):
87
+ if numbers[idx - 1] > 0:
88
+ last = idx
89
+ break
90
+ assert first < last
91
+ parts = [(str(n) + u) for n, u in zip(numbers[first:last], units[first:last], strict=True)]
92
+ if iso8601:
93
+ if last >= 3:
94
+ # time units are included, must prepend 'T' before the first one
95
+ parts.insert(max(0, 2 - first), 'T')
96
+ parts.insert(0, 'P')
97
+ return sep.join(parts)
98
+
99
+
100
+ _NUM = r'(\d+(?:[.,]\d*)?)' # a match group for a number with optional fractional part
101
+ _RE_ISO_DURATION = re.compile(rf"""
102
+ P
103
+ (?: 0+Y)?
104
+ (?: 0+M)?
105
+ (?: {_NUM} W)?
106
+ (?: {_NUM} D)?
107
+ (?: T
108
+ (?: {_NUM} H)?
109
+ (?: {_NUM} M)?
110
+ (?: {_NUM} S)?
111
+ )?
112
+ """, flags = re.ASCII | re.VERBOSE)
113
+ _RE_DURATION = re.compile(rf"""
114
+ (?: {_NUM} \s* w \s*)?
115
+ (?: {_NUM} \s* d \s*)?
116
+ (?: {_NUM} \s* h \s*)?
117
+ (?: {_NUM} \s* m \s*)?
118
+ (?: {_NUM} \s* s \s*)?
119
+ (?: {_NUM} \s* ms )?
120
+ """, flags = re.ASCII | re.IGNORECASE | re.VERBOSE)
121
+
122
+ COEF = [0.001, 1, SEC_PER_MIN, SEC_PER_HOUR, SEC_PER_DAY, 7*SEC_PER_DAY]
123
+ ISO_COEF = COEF[1:]
124
+ def _str_to_period(tstr: str) -> float:
125
+ """Convert string to number of seconds."""
126
+ tstr = tstr.strip()
127
+ iso = tstr.startswith("P")
128
+ regex = _RE_ISO_DURATION if iso else _RE_DURATION
129
+ if (match := regex.fullmatch(tstr)) is None:
130
+ raise ValueError("Invalid time representation")
131
+
132
+ result = 0.0
133
+ smallest_unit = True
134
+ for value, scale_factor in zip(reversed(match.groups()), ISO_COEF if iso else COEF):
135
+ if value is None:
136
+ continue
137
+ if (decimal_comma := ',' in value) or ('.' in value):
138
+ if not smallest_unit:
139
+ raise ValueError("Only the smallest unit may have a fractional part")
140
+ if decimal_comma:
141
+ value = value.replace(',', '.', 1)
142
+ num = float(value)
143
+ smallest_unit = False
144
+ if num == 0.0:
145
+ continue
146
+ if scale_factor is None:
147
+ raise ValueError("Calendar years/months are not supported as duration units")
148
+ result += num * scale_factor
149
+ if smallest_unit:
150
+ raise ValueError("At least one part must be present")
151
+ return result
152
+
153
+
154
+ def time_period(
155
+ period: t.Any,
156
+ passthrough:None|type[object]|Sequence[None|type[object]] = (),
157
+ zero_ok: bool = False) -> t.Any:
158
+ """
159
+ Convenience wrapper for convert().
160
+
161
+ Return 'period' unchanged if its type is present in the
162
+ 'passthrough'. Otherwise convert a number or string to float.
163
+
164
+ Argument 'passthrough' can be a type or a sequence of types.
165
+ For convenience None is accepted as a type. Technically correct
166
+ is NoneType, but in typing None is widely used.
167
+ """
168
+ if passthrough != ():
169
+ passthrough = to_tuple(passthrough)
170
+ if None in passthrough:
171
+ if period is None:
172
+ return None
173
+ passthrough = tuple(t for t in passthrough if t is not None)
174
+ if isinstance(period, t.cast(tuple[type[object], ...], passthrough)):
175
+ return period
176
+ saved_period = period
177
+ if isinstance(period, str):
178
+ try:
179
+ period = _str_to_period(period)
180
+ except Exception as err:
181
+ err.add_note(f"Converted string was: '{period}'")
182
+ raise
183
+ elif isinstance(period, int):
184
+ period = float(period)
185
+ elif not isinstance(period, float):
186
+ raise TypeError(f"Invalid type for time period specification: {period!r}")
187
+ if period < 0:
188
+ raise ValueError(f"Time period cannot be negative, got {saved_period}")
189
+ if period == 0.0 and not zero_ok:
190
+ raise ValueError("Time period must be positive, zero is not allowed.")
191
+ return period
192
+
193
+
194
+ # integer sequence length limits for validation
195
+ _limits = {
196
+ 'date': (2, 2),
197
+ 'time': (2, 4),
198
+ 'datetime': (5, 7),
199
+ None: (2, 7), # unknown
200
+ }
201
+
202
+
203
+ def _sd_split(sd: str|Sequence[str], parsed_string:str) -> list[str]:
204
+ """
205
+ Choose a separator/deliemiter and split the *parsed_string*.
206
+
207
+ If there are multiple choices, use the first one
208
+ that is present in the *parsed_string*.
209
+ """
210
+ if not sd:
211
+ raise ValueError("Got an empty separator or delimiter")
212
+ if isinstance(sd, str):
213
+ return parsed_string.split(sd)
214
+ for try_sd in sd:
215
+ if try_sd in parsed_string:
216
+ return parsed_string.split(try_sd)
217
+ return [parsed_string]
218
+
219
+
220
+ def parse_interval(
221
+ interval: str, *,
222
+ parser: Callable[[str], Sequence[int]],
223
+ sep: str = "/", delim: str = ";", # endpoint separator, range delimiter
224
+ datatype: t.Literal['date', 'time', 'datetime'] | None = None,
225
+ ) -> list[list[Sequence[int]]]:
226
+ """
227
+ Parse a string representation of a time/date/timedate interval.
228
+
229
+ Intented for usage with TimeDate and TimeSpan blocks.
230
+ """
231
+ is_date = datatype == 'date'
232
+ try:
233
+ imin, imax = _limits[datatype]
234
+ except KeyError:
235
+ raise ValueError(
236
+ "argument 'datatype' must be one of: 'date', 'time', 'datetime' or None, "
237
+ + f"but got {datatype!r}") from None
238
+
239
+ # wrap the parser
240
+ def wparser(endpoint: str) -> Sequence[int]:
241
+ value = parser(endpoint)
242
+ if not imin <= len(value) <= imax:
243
+ raise ValueError(
244
+ f"Interval endpoint {endpoint} was not parsed correctly, "
245
+ "please check the parser function")
246
+ return value
247
+
248
+ ranges = _sd_split(delim, interval)
249
+ if ranges and not ranges[-1].strip():
250
+ del ranges[-1]
251
+ result = []
252
+ for rng in ranges:
253
+ elen = len(endpoints := _sd_split(sep, rng))
254
+ if is_date and elen == 1:
255
+ begin_end = wparser(rng.strip())
256
+ result.append([begin_end, begin_end])
257
+ continue
258
+ if elen == 2:
259
+ result.append([wparser(endpoints[0].strip()), wparser(endpoints[1].strip())])
260
+ continue
261
+ raise ValueError(f"A range cannot have {elen} endpoint(s): {rng}")
262
+ return result
@@ -0,0 +1,52 @@
1
+ Metadata-Version: 2.4
2
+ Name: redzed
3
+ Version: 25.12.30
4
+ Summary: An asyncio-based library for building small automated systems
5
+ Author-email: Vlado Potisk <redzed@poti.sk>
6
+ License-Expression: MIT
7
+ Project-URL: homepage, https://github.com/xitop/redzed
8
+ Project-URL: repository, https://github.com/xitop/redzed
9
+ Project-URL: documentation, https://redzed.readthedocs.io/en/latest/
10
+ Keywords: automation,finite-state machine
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
14
+ Classifier: Programming Language :: Python :: 3
15
+ Requires-Python: >=3.11
16
+ Description-Content-Type: text/markdown
17
+ License-File: LICENSE.txt
18
+ Provides-Extra: tests
19
+ Requires-Dist: pytest>=8.4.0; extra == "tests"
20
+ Requires-Dist: pytest-asyncio>=0.26.0; extra == "tests"
21
+ Requires-Dist: pytest-xdist; extra == "tests"
22
+ Dynamic: license-file
23
+
24
+ # Redzed
25
+
26
+ Redzed is an asyncio-based library for building small automated systems,
27
+ i.e. systems that control outputs according to input values,
28
+ system’s internal state, date and time. Redzed was written in Python.
29
+ It is free and open source.
30
+
31
+ Included are pre-defined logic blocks for general use. There are memory cells,
32
+ timers, programmable finite-state machines, outputs and many more.
33
+ Blocks have outputs and react to events. Blocks are complemented by triggers
34
+ running user-supplied functions when certain outputs change. Triggered functions
35
+ evaluate outputs, make decisions and can send events to other blocks.
36
+
37
+ The mutual interaction of blocks and triggers allows to build modular
38
+ automated systems of small to middle complexity.
39
+
40
+ What is not included:
41
+ The application code must connect the system with outside world.
42
+
43
+ ## Documentation
44
+
45
+ Please read the [online documentation](https://redzed.readthedocs.io/en/latest/)
46
+ for more information.
47
+
48
+ ### Note:
49
+
50
+ Redzed is intended to replace Edzed (an older library from the same author).
51
+ It has the same capabilities, but is based on simpler concepts and that's why
52
+ it is easier to learn and to use.
@@ -0,0 +1,28 @@
1
+ redzed/__init__.py,sha256=eyvuX8qwxEFuiP6jOu4x1qv-AmHJAGKOziV1dKCNWWA,1098
2
+ redzed/base_block.py,sha256=NzJhY0POAJUyfp9EcQG2RvXM472vAV5iWG5LdsScpso,5191
3
+ redzed/block.py,sha256=0iwK8Pb5LJ0xzoOt5dkx-FeWplzUzAWHOWfah368u7s,12012
4
+ redzed/circuit.py,sha256=VkcAZZg5HfEdboUZ_vMnElI9E4MprwaoBveN8-hUvZw,31095
5
+ redzed/cron_service.py,sha256=f-YR0w2U0dpipX271cyUYXvsvJunpE3mywuV7SkFE_k,10581
6
+ redzed/debug.py,sha256=QeWHpfTZADPB6nY0zrj1Aqo91Wd9HB9bAJVgq_d3hCo,2767
7
+ redzed/formula_trigger.py,sha256=0_TVbR1wCQ0Wv7NlJtcfD-iDUbmTBlbVCSdbKDw_tX0,7516
8
+ redzed/initializers.py,sha256=oF5Wkdu2REFdfuCEdo8kS-9N2uW2dhdzYWoibILB3ks,7804
9
+ redzed/signal_shutdown.py,sha256=KjL6Kq9K0m_2nerjo7hryNFPhgdNTmSyTOfDi-SMsjA,2081
10
+ redzed/undef.py,sha256=iPxcUIKBDh5wqjdr8qvs9EQkx5s52ryNDY22at-PF0c,896
11
+ redzed/blocklib/__init__.py,sha256=au7jbjO_RUFzK5U4STk-7pc1DTVA0OVh2W_aKsx1Y3s,557
12
+ redzed/blocklib/counter.py,sha256=XvJPOarg6RZ9H-GrWFQrt3JJnGk9YGc1B7NOpF6ju4A,1125
13
+ redzed/blocklib/fsm.py,sha256=6Qv4pOsF-FOEBm9NQUSD6F2yLfb0chvbpvbrgg3sIk8,23492
14
+ redzed/blocklib/inputs.py,sha256=hhfU2Id7oJfmhZB-_PoowXBfYDuw9OQyceg_AprJVVs,7218
15
+ redzed/blocklib/outputs.py,sha256=hoBPr_978PyhR6OzD0rxou34PFukIRD1pIpK6JNgqQE,12894
16
+ redzed/blocklib/repeat.py,sha256=hkIO7qgm4wS32dcKkkfL_DjnoKWf-l3k2DfRiRUk6iE,2500
17
+ redzed/blocklib/timedate.py,sha256=78wqiH1mUz5zoz3ZgDOmsPaYYmQLypgt9IfmLUcH9Cw,5196
18
+ redzed/blocklib/timeinterval.py,sha256=hxPhao1Gm9q_NOp6WdjmsStkrfwkadH5uJh-Hli9D-4,6752
19
+ redzed/blocklib/timer.py,sha256=X3CoqwGJ46oLw0R5u0HK1a11VpcZdTWvPbWOkFjZrDI,1520
20
+ redzed/utils/__init__.py,sha256=Yo8cj1f1HQj862UOdCsXOkMg4kfq1c5S3HJDhuiE5os,326
21
+ redzed/utils/async_utils.py,sha256=Vknijh9rABL8GcJbYv6a7I4qO2VLerMsGTr5wiGWbjo,4486
22
+ redzed/utils/data_utils.py,sha256=xiaVnEJF7Q9oGFqqTOyiVyzI-sG0lYHxImfyFcXjwFI,3542
23
+ redzed/utils/time_utils.py,sha256=eCqk4T4ipn4hgzL8-4Usn1W6kkTyRCuQ9-BMSvnELww,8524
24
+ redzed-25.12.30.dist-info/licenses/LICENSE.txt,sha256=HwuPxdAOIKlSWHESVtk6Zov7d0BZaPu74eruoZc5UN8,1086
25
+ redzed-25.12.30.dist-info/METADATA,sha256=LiyTs38Xa48jh2ozWNw1uUICaNKrTg7xWSUd1vEHTK0,2058
26
+ redzed-25.12.30.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
27
+ redzed-25.12.30.dist-info/top_level.txt,sha256=7Rt0BRMqaJ0AGAmrd2JDqmqSY4cmQeW--7u6KDV1gZg,7
28
+ redzed-25.12.30.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (80.9.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Vlado Potisk <redzed@poti.sk>
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ redzed