-
Notifications
You must be signed in to change notification settings - Fork 66
/
command.py
254 lines (207 loc) · 7.62 KB
/
command.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
"""Declaration of base types for dali commands and their responses."""
from __future__ import unicode_literals
from __future__ import division
from __future__ import absolute_import
from dali import address
from dali import frame
from dali.compat import add_metaclass
from dali.compat import python_2_unicode_compatible
from dali.exceptions import MissingResponse
from dali.exceptions import ResponseError
class CommandTracker(type):
"""Metaclass keeping track of all the types of Command we understand.
Commands that have names starting with '_' are treated as abstract
base classes that will never be instantiated because they do not
correspond to a DALI frame.
"""
def __init__(cls, name, bases, attrs):
if not hasattr(cls, '_commands'):
cls._commands = []
else:
if cls.__name__[0] != '_':
cls._commands.append(cls)
@classmethod
def commands(cls):
"""
:return: List of known commands if there's any
"""
return cls._commands
@python_2_unicode_compatible
class Response(object):
"""Some DALI commands cause a response from the addressed devices.
The response is either an 8-bit backward frame encoding 8-bit data
or 0xff for "Yes", or a lack of response encoding "No". If
multiple devices respond at once the backward frame may be
received with a framing error; this shall be interpreted as "more
than one device answered "Yes".
Initialise this class by passing a BackwardFrame object, or None
if there was no response.
"""
_expected = False
_error_acceptable = False
def __init__(self, val):
if val is not None and not isinstance(val, frame.BackwardFrame):
raise TypeError("Response must be passed None or a BackwardFrame")
self._value = val
@property
def value(self):
if self._value is None and self._expected:
raise MissingResponse()
if self._value and self._value.error and not self._error_acceptable:
raise ResponseError()
return self._value
def __str__(self):
try:
return "{}".format(self.value)
except MissingResponse or ResponseError as e:
return "{}".format(e)
class YesNoResponse(Response):
_error_acceptable = True
@property
def value(self):
return self._value is not None
class BitmapResponseBitDict(type):
"""Metaclass adding dict of status bits."""
def __init__(cls, name, bases, attrs):
if hasattr(cls, "bits"):
bd = {}
bit = 0
for b in cls.bits:
if b:
mangled = b.replace(' ', '_').replace('-', '')
bd[mangled] = bit
bit = bit + 1
cls._bit_properties = bd
@python_2_unicode_compatible
@add_metaclass(BitmapResponseBitDict)
class BitmapResponse(Response):
"""A response that consists of several named bits.
Bits are listed in subclasses with the least-sigificant bit first.
"""
_expected = True
bits = []
@property
def status(self):
if self._value is None:
raise MissingResponse()
if self._value.error:
return ["response received with framing error"]
v = self._value[7:0]
l = []
for b in self.bits:
if v & 0x01 and b:
l.append(b)
v = (v >> 1)
return l
@property
def error(self):
if self._value is None:
return False
return self._value.error
def __getattr__(self, name):
if name in self._bit_properties:
if self._value is None:
return
if self._value.error:
return
return self._value[self._bit_properties[name]]
raise AttributeError
def __str__(self):
try:
return ",".join(self.status)
# XXX: be more explicit which exception to catch
except Exception as e:
return "{}".format(e)
@python_2_unicode_compatible
@add_metaclass(CommandTracker)
class Command(object):
"""A command frame.
Subclasses must provide a class method "from_frame" which, when
passed a Frame returns a new instance of the class corresponding
to that command, or "None" if there is no match.
"""
# Override this as appropriate
_framesize = 0
# The following flags correspond to the columns in tables 15 and
# 16 of IEC 62386-102 and tables 21 and 22 of IEC 62386-103.
# Override them in subclasses if there is a tick in the
# appropriate column.
_appctrl = False
_inputdev = False
_uses_dtr0 = False
_uses_dtr1 = False
_uses_dtr2 = False
_response = None
_sendtwice = False
# 16-bit frames may be interpreted differently if they are
# preceded by the EnableDeviceType command. If a command needs
# EnableDeviceType(foo) to be sent first, override _devicetype to
# foo. This parameter is ignored for all other frame lengths.
_devicetype = 0
def __init__(self, f):
assert isinstance(f, frame.ForwardFrame)
self._data = f
@classmethod
def from_frame(cls, f, devicetype=0):
"""Return a Command instance corresponding to the supplied frame.
If the device type the command is intended for is known
(i.e. the previous command was EnableDeviceType(foo)) then
specify it here.
:parameter frame: a forward frame
:parameter devicetype: type of device frame is intended for
:returns: Return a Command instance corresponding to the
frame. Returns None if there is no match.
"""
if cls != Command:
return
for dc in cls._commands:
if dc._devicetype != devicetype:
continue
r = dc.from_frame(f)
if r:
return r
# At this point we can simply wrap the frame. We don't know
# what kind of command this is (config, query, etc.) so we're
# unlikely ever to want to transmit it!
return cls(f)
@property
def frame(self):
"""The forward frame to be transmitted for this command."""
return self._data
# XXX rename to send_twice ?
@property
def is_config(self):
"""Is this a configuration command? (Does it need repeating to
take effect?)
"""
return self._sendtwice
@property
def is_query(self):
"""Does this command return a result?"""
return self._response is not None
@property
def response(self):
"""If this command returns a result, use this class for the response.
"""
return self._response
@staticmethod
def _check_destination(destination):
"""Check that a valid destination has been specified.
destination can be a dali.bus.Device object with
_addressobj attribute, a dali.address.Address object with
add_to_frame method, or an integer which will be wrapped in a
dali.address.Address object.
"""
if hasattr(destination, "_addressobj"):
destination = destination._addressobj
if isinstance(destination, int):
destination = address.Short(destination)
if hasattr(destination, "add_to_frame"):
return destination
raise ValueError("destination must be an integer, dali.bus.Device "
"object or dali.address.Address object")
def __str__(self):
joined = ":".join(
"{:02x}".format(c) for c in self._data.as_byte_sequence)
return "({0}){1}".format(type(self), joined)
from_frame = Command.from_frame