-
-
Notifications
You must be signed in to change notification settings - Fork 27
/
command_types.py
602 lines (457 loc) · 14.8 KB
/
command_types.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
"""python library for accessing the openHAB REST API."""
#
# Georges Toth (c) 2016-present <georges@trypill.org>
#
# python-openhab is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# python-openhab is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with python-openhab. If not, see <http://www.gnu.org/licenses/>.
#
# pylint: disable=bad-indentation
import abc
import datetime
import re
import typing
import dateutil.parser
__author__ = 'Georges Toth <georges@trypill.org>'
__license__ = 'AGPLv3+'
class CommandType(metaclass=abc.ABCMeta):
"""Base command type class."""
TYPENAME = ''
SUPPORTED_TYPENAMES: typing.List[str] = []
UNDEF = 'UNDEF'
NULL = 'NULL'
UNDEFINED_STATES = [UNDEF, NULL]
@classmethod
def is_undefined(cls, value: typing.Any) -> bool:
"""Return true if given value is an undefined value in openHAB (i.e. UNDEF/NULL)."""
return value in CommandType.UNDEFINED_STATES
@classmethod
def get_type_for(
cls,
typename: str,
parent_cls: typing.Optional[typing.Type['CommandType']] = None,
) -> typing.Union[typing.Type['CommandType'], None]:
"""Get a class type for a given typename."""
if parent_cls is None:
parent_cls = CommandType
for a_type in parent_cls.__subclasses__():
if typename in a_type.SUPPORTED_TYPENAMES:
return a_type
# maybe a subclass of a subclass
result = a_type.get_type_for(typename, a_type)
if result is not None:
return result
return None
@classmethod
@abc.abstractmethod
def parse(cls, value: str) -> typing.Optional[typing.Any]:
"""Parse a given value."""
raise NotImplementedError
@classmethod
@abc.abstractmethod
def validate(cls, value: typing.Any) -> None:
"""Value validation method. As this is the base class which should not be used\
directly, we throw a NotImplementedError exception.
Args:
value (Object): The value to validate. The data_type of the value depends on the item
data_type and is checked accordingly.
Raises:
NotImplementedError: Raises NotImplementedError as the base class should never
be used directly.
"""
raise NotImplementedError
class UndefType(CommandType):
"""Undefined type."""
TYPENAME = 'UnDef'
SUPPORTED_TYPENAMES = [TYPENAME]
@classmethod
def parse(cls, value: str) -> typing.Optional[str]:
"""Parse a given value."""
if value in UndefType.UNDEFINED_STATES:
return None
return value
@classmethod
def validate(cls, value: str) -> None:
"""Value validation method."""
class GroupType(CommandType):
"""Group type."""
TYPENAME = 'Group'
SUPPORTED_TYPENAMES = [TYPENAME]
@classmethod
def parse(cls, value: str) -> typing.Optional[str]:
"""Parse a given value."""
if value in GroupType.UNDEFINED_STATES:
return None
return value
@classmethod
def validate(cls, value: str) -> None:
"""Value validation method."""
class StringType(CommandType):
"""StringType data_type class."""
TYPENAME = 'String'
SUPPORTED_TYPENAMES = [TYPENAME]
@classmethod
def parse(cls, value: str) -> typing.Optional[str]:
"""Parse a given value."""
if value in StringType.UNDEFINED_STATES:
return None
if not isinstance(value, str):
raise ValueError
return value
@classmethod
def validate(cls, value: str) -> None:
"""Value validation method.
Valid values are any of data_type string.
Args:
value (str): The value to validate.
Raises:
ValueError: Raises ValueError if an invalid value has been specified.
"""
StringType.parse(value)
class OnOffType(StringType):
"""OnOffType data_type class."""
TYPENAME = 'OnOff'
SUPPORTED_TYPENAMES = [TYPENAME]
ON = 'ON'
OFF = 'OFF'
POSSIBLE_VALUES = [ON, OFF]
@classmethod
def parse(cls, value: str) -> typing.Optional[str]:
"""Parse a given value."""
if value in OnOffType.UNDEFINED_STATES:
return None
if value not in OnOffType.POSSIBLE_VALUES:
raise ValueError
return value
@classmethod
def validate(cls, value: str) -> None:
"""Value validation method.
Valid values are ``ON`` and ``OFF``.
Args:
value (str): The value to validate.
Raises:
ValueError: Raises ValueError if an invalid value has been specified.
"""
super().validate(value)
OnOffType.parse(value)
class OpenCloseType(StringType):
"""OpenCloseType data_type class."""
TYPENAME = 'OpenClosed'
SUPPORTED_TYPENAMES = [TYPENAME]
OPEN = 'OPEN'
CLOSED = 'CLOSED'
POSSIBLE_VALUES = [OPEN, CLOSED]
@classmethod
def parse(cls, value: str) -> typing.Optional[str]:
"""Parse a given value."""
if value in OpenCloseType.UNDEFINED_STATES:
return None
if value not in OpenCloseType.POSSIBLE_VALUES:
raise ValueError
return value
@classmethod
def validate(cls, value: str) -> None:
"""Value validation method.
Valid values are ``OPEN`` and ``CLOSED``.
Args:
value (str): The value to validate.
Raises:
ValueError: Raises ValueError if an invalid value has been specified.
"""
super().validate(value)
OpenCloseType.parse(value)
class ColorType(CommandType):
"""ColorType data_type class."""
TYPENAME = 'HSB'
SUPPORTED_TYPENAMES = [TYPENAME]
@classmethod
def parse(cls, value: str) -> typing.Optional[typing.Tuple[float, float, float]]:
"""Parse a given value."""
if value in ColorType.UNDEFINED_STATES:
return None
if not isinstance(value, str):
raise ValueError
str_split = value.split(',')
if len(str_split) != 3:
raise ValueError
hs, ss, bs = value.split(',', 3)
h = float(hs)
s = float(ss)
b = float(bs)
if not ((0 <= h <= 360) and (0 <= s <= 100) and (0 <= b <= 100)):
raise ValueError
return h, s, b
@classmethod
def validate(cls, value: typing.Union[str, typing.Tuple[float, float, float]]) -> None:
"""Value validation method.
Valid values are in format H,S,B.
Value ranges:
H(ue): 0-360
S(aturation): 0-100
B(rightness): 0-100
Args:
value (str): The value to validate.
Raises:
ValueError: Raises ValueError if an invalid value has been specified.
"""
if isinstance(value, str):
str_value = str(value)
elif isinstance(value, tuple) and len(value) == 3:
str_value = f'{value[0]},{value[1]},{value[2]}'
else:
raise ValueError
ColorType.parse(str_value)
class DecimalType(CommandType):
"""DecimalType data_type class."""
TYPENAME = 'Decimal'
SUPPORTED_TYPENAMES = [TYPENAME, 'Quantity']
@classmethod
def parse(cls, value: str) -> typing.Union[None, typing.Tuple[typing.Union[int, float], str]]:
"""Parse a given value."""
if value in DecimalType.UNDEFINED_STATES:
return None
m = re.match(r'(-?[0-9.]+(?:[eE]-?[0-9]+)?)\s?(.*)?$', value)
if m:
value_value = m.group(1)
value_unit_of_measure = m.group(2)
try:
if '.' in value:
return_value: typing.Union[int, float] = float(value_value)
else:
return_value = int(value_value)
except ArithmeticError as exc:
raise ValueError(exc) from exc
return return_value, value_unit_of_measure
raise ValueError
@classmethod
def validate(cls, value: typing.Union[int, float, typing.Tuple[typing.Union[int, float], str], str]) -> None:
"""Value validation method.
Valid values are any of data_type:
- ``int``
- ``float``
- a tuple of (``int`` or ``float``, ``str``) for numeric value, unit of measure
- a ``str`` that can be parsed to one of the above by ``DecimalType.parse``
Args:
value (int, float, tuple, str): The value to validate.
Raises:
ValueError: Raises ValueError if an invalid value has been specified.
"""
if isinstance(value, str):
DecimalType.parse(value)
elif isinstance(value, tuple) and len(value) == 2:
DecimalType.parse(f'{value[0]} {value[1]}')
elif not isinstance(value, (int, float)):
raise ValueError
class PercentType(CommandType):
"""PercentType data_type class."""
TYPENAME = 'Percent'
SUPPORTED_TYPENAMES = [TYPENAME]
@classmethod
def parse(cls, value: str) -> typing.Optional[float]:
"""Parse a given value."""
if value in PercentType.UNDEFINED_STATES:
return None
try:
f = float(value)
if not 0 <= f <= 100:
raise ValueError
return f
except Exception as e:
raise ValueError(e) from e
@classmethod
def validate(cls, value: typing.Union[float, int]) -> None:
"""Value validation method.
Valid values are any of data_type ``float`` or ``int`` and must be greater of equal to 0
and smaller or equal to 100.
Args:
value (float): The value to validate.
Raises:
ValueError: Raises ValueError if an invalid value has been specified.
"""
if not (isinstance(value, (float, int)) and 0 <= value <= 100):
raise ValueError
class IncreaseDecreaseType(StringType):
"""IncreaseDecreaseType data_type class."""
TYPENAME = 'IncreaseDecrease'
SUPPORTED_TYPENAMES = [TYPENAME]
INCREASE = 'INCREASE'
DECREASE = 'DECREASE'
POSSIBLE_VALUES = [INCREASE, DECREASE]
@classmethod
def parse(cls, value: str) -> typing.Optional[str]:
"""Parse a given value."""
if value in IncreaseDecreaseType.UNDEFINED_STATES:
return None
if value not in IncreaseDecreaseType.POSSIBLE_VALUES:
raise ValueError
return value
@classmethod
def validate(cls, value: str) -> None:
"""Value validation method.
Valid values are ``INCREASE`` and ``DECREASE``.
Args:
value (str): The value to validate.
Raises:
ValueError: Raises ValueError if an invalid value has been specified.
"""
super().validate(value)
IncreaseDecreaseType.parse(value)
class DateTimeType(CommandType):
"""DateTimeType data_type class."""
TYPENAME = 'DateTime'
SUPPORTED_TYPENAMES = [TYPENAME]
@classmethod
def parse(cls, value: str) -> typing.Optional[datetime.datetime]:
"""Parse a given value."""
if value in DateTimeType.UNDEFINED_STATES:
return None
return dateutil.parser.parse(value)
@classmethod
def validate(cls, value: datetime.datetime) -> None:
"""Value validation method.
Valid values are any of data_type ``datetime.datetime``.
Args:
value (datetime.datetime): The value to validate.
Raises:
ValueError: Raises ValueError if an invalid value has been specified.
"""
if not isinstance(value, datetime.datetime):
raise ValueError
class UpDownType(StringType):
"""UpDownType data_type class."""
TYPENAME = 'UpDown'
SUPPORTED_TYPENAMES = [TYPENAME]
UP = 'UP'
DOWN = 'DOWN'
POSSIBLE_VALUES = [UP, DOWN]
@classmethod
def parse(cls, value: str) -> typing.Optional[str]:
"""Parse a given value."""
if value in UpDownType.UNDEFINED_STATES:
return None
if value not in UpDownType.POSSIBLE_VALUES:
raise ValueError
return value
@classmethod
def validate(cls, value: str) -> None:
"""Value validation method.
Valid values are ``UP`` and ``DOWN``.
Args:
value (str): The value to validate.
Raises:
ValueError: Raises ValueError if an invalid value has been specified.
"""
super().validate(value)
UpDownType.parse(value)
class StopMoveType(StringType):
"""UpDownType data_type class."""
TYPENAME = 'StopMove'
SUPPORTED_TYPENAMES = [TYPENAME]
STOP = 'STOP'
POSSIBLE_VALUES = [STOP]
@classmethod
def parse(cls, value: str) -> typing.Optional[str]:
"""Parse a given value."""
if value in StopMoveType.UNDEFINED_STATES:
return None
if value not in StopMoveType.POSSIBLE_VALUES:
raise ValueError
return value
@classmethod
def validate(cls, value: str) -> None:
"""Value validation method.
Valid values are ``UP`` and ``DOWN``.
Args:
value (str): The value to validate.
Raises:
ValueError: Raises ValueError if an invalid value has been specified.
"""
super().validate(value)
StopMoveType.parse(value)
class PlayPauseType(StringType):
"""PlayPauseType data_type class."""
TYPENAME = 'PlayPause'
SUPPORTED_TYPENAMES = [TYPENAME]
PLAY = 'PLAY'
PAUSE = 'PAUSE'
POSSIBLE_VALUES = [PLAY, PAUSE]
@classmethod
def parse(cls, value: str) -> typing.Optional[str]:
"""Parse a given value."""
if value in PlayPauseType.UNDEFINED_STATES:
return None
if value not in PlayPauseType.POSSIBLE_VALUES:
raise ValueError
return value
@classmethod
def validate(cls, value: str) -> None:
"""Value validation method.
Valid values are ``PLAY``, ``PAUSE``
Args:
value (str): The value to validate.
Raises:
ValueError: Raises ValueError if an invalid value has been specified.
"""
super().validate(value)
PlayPauseType.parse(value)
class NextPrevious(StringType):
"""NextPrevious data_type class."""
TYPENAME = 'NextPrevious'
SUPPORTED_TYPENAMES = [TYPENAME]
NEXT = 'NEXT'
PREVIOUS = 'PREVIOUS'
POSSIBLE_VALUES = [NEXT, PREVIOUS]
@classmethod
def parse(cls, value: str) -> typing.Optional[str]:
"""Parse a given value."""
if value in NextPrevious.UNDEFINED_STATES:
return None
if value not in NextPrevious.POSSIBLE_VALUES:
raise ValueError
return value
@classmethod
def validate(cls, value: str) -> None:
"""Value validation method.
Valid values are ``PLAY``, ``PAUSE``
Args:
value (str): The value to validate.
Raises:
ValueError: Raises ValueError if an invalid value has been specified.
"""
super().validate(value)
NextPrevious.parse(value)
class RewindFastforward(StringType):
"""RewindFastforward data_type class."""
TYPENAME = 'RewindFastforward'
SUPPORTED_TYPENAMES = [TYPENAME]
REWIND = 'REWIND'
FASTFORWARD = 'FASTFORWARD'
POSSIBLE_VALUES = [REWIND, FASTFORWARD]
@classmethod
def parse(cls, value: str) -> typing.Optional[str]:
"""Parse a given value."""
if value in RewindFastforward.UNDEFINED_STATES:
return None
if value not in RewindFastforward.POSSIBLE_VALUES:
raise ValueError
return value
@classmethod
def validate(cls, value: str) -> None:
"""Value validation method.
Valid values are ``REWIND``, ``FASTFORWARD``
Args:
value (str): The value to validate.
Raises:
ValueError: Raises ValueError if an invalid value has been specified.
"""
super().validate(value)
RewindFastforward.parse(value)