forked from smarthomeNG/plugins
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path__init__.py
executable file
·390 lines (355 loc) · 13.3 KB
/
__init__.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
#!/usr/bin/env python3
# vim: set encoding=utf-8 tabstop=4 softtabstop=4 shiftwidth=4 expandtab
#########################################################################
# Copyright 2012-2013 KNX-User-Forum e.V. http://knx-user-forum.de/
#########################################################################
# This file is part of SmartHomeNG
# https://github.com/smarthomeNG/smarthome
# http://knx-user-forum.de/
#
# SmartHomeNG 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.
#
# SmartHomeNG 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 SmartHomeNG. If not, see <http://www.gnu.org/licenses/>.
#########################################################################
import sys
import logging
import socket
import threading
import struct
import time
from lib.model.smartplugin import SmartPlugin
class luxex(Exception):
pass
class LuxBase(SmartPlugin):
ALLOW_MULTIINSTANCE = False
PLUGIN_VERSION = '1.3.0'
def __init__(self, host, port=8888):
self.logger = logging.getLogger(__name__)
self.host = host
self.port = int(port)
self._sock = False
self._lock = threading.Lock()
self.is_connected = False
self._connection_attempts = 0
self._connection_errorlog = 60
self._params = []
self._attrs = []
self._calc = []
def get_attribute(self, identifier):
return self._attrs[identifier] if identifier < len(self._attrs) else None
def get_parameter(self, identifier):
return self._params[identifier] if identifier < len(self._params) else None
def get_calculated(self, identifier):
return self._calc[identifier] if identifier < len(self._calc) else None
def get_attribute_count(self):
return len(self._attrs)
def get_parameter_count(self):
return len(self._params)
def get_calculated_count(self):
return len(self._calc)
def connect(self):
self._lock.acquire()
try:
self._sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self._sock.settimeout(2)
self._sock.connect((self.host, self.port))
except Exception as e:
self._connection_attempts -= 1
if self._connection_attempts <= 0:
self.logger.error(
'Luxtronic2: could not connect to {0}:{1}: {2}'.format(self.host, self.port, e))
self._connection_attempts = self._connection_errorlog
return
finally:
self._lock.release()
self.logger.info(
'Luxtronic2: connected to {0}:{1}'.format(self.host, self.port))
self.is_connected = True
self._connection_attempts = 0
def close(self):
self.is_connected = False
try:
self._sock.close()
self._sock = False
except:
pass
def _request(self, request, length):
if not self.is_connected:
raise luxex("no connection to luxtronic.")
try:
self._sock.send(request)
except Exception as e:
self._lock.release()
self.close()
raise luxex("error sending request: {0}".format(e))
try:
answer = self._sock.recv(length)
except socket.timeout:
self._lock.release()
raise luxex("error receiving answer: timeout")
except Exception as e:
self._lock.release()
self.close()
raise luxex("error receiving answer: {0}".format(e))
return answer
def _request_more(self, length):
try:
return self._sock.recv(length)
except socket.timeout:
self._lock.release()
raise luxex("error receiving payload: timeout")
except Exception as e:
self._lock.release()
self.close()
raise luxex("error receifing payload: {0}".format(e))
def set_param(self, param, value):
param = int(param)
# old = self._params[param] if param < len(self._params) else 0
payload = struct.pack('!iii', 3002, int(param), int(value))
self._lock.acquire()
answer = self._request(payload, 8)
self._lock.release()
if len(answer) != 8:
self.close()
raise luxex("error receiving answer: no data")
answer = struct.unpack('!ii', answer)
fields = ['cmd', 'param']
answer = dict(list(zip(fields, answer)))
if answer['cmd'] == 3002 and answer['param'] == param:
self.logger.debug(
"Luxtronic2: value {0} for parameter {1} stored".format(value, param))
return True
else:
self.logger.warning(
"Luxtronic2: value {0} for parameter {1} not stored".format(value, param))
return False
def refresh_parameters(self):
request = struct.pack('!ii', 3003, 0)
self._lock.acquire()
answer = self._request(request, 8)
if len(answer) != 8:
self._lock.release()
self.close()
raise luxex("error receiving answer: no data")
answer = struct.unpack('!ii', answer)
fields = ['cmd', 'len']
answer = dict(list(zip(fields, answer)))
if answer['cmd'] == 3003:
params = []
for i in range(0, answer['len']):
param = self._request_more(4)
params.append(struct.unpack('!i', param)[0])
self._lock.release()
if len(params) > 0:
self._params = params
return True
return False
else:
self._lock.release()
self.logger.warning("Luxtronic2: failed to retrieve parameters")
return False
def refresh_attributes(self):
request = struct.pack('!ii', 3005, 0)
self._lock.acquire()
answer = self._request(request, 8)
if len(answer) != 8:
self._lock.release()
self.close()
raise luxex("error receiving answer: no data")
answer = struct.unpack('!ii', answer)
fields = ['cmd', 'len']
answer = dict(list(zip(fields, answer)))
if answer['cmd'] == 3005:
attrs = []
for i in range(0, answer['len']):
attr = self._request_more(1)
attrs.append(struct.unpack('!b', attr)[0])
self._lock.release()
if len(attrs) > 0:
self._attrs = attrs
return True
return False
else:
self._lock.release()
self.logger.warning("Luxtronic2: failed to retrieve attributes")
return False
def refresh_calculated(self):
request = struct.pack('!ii', 3004, 0)
self._lock.acquire()
answer = self._request(request, 12)
if len(answer) != 12:
self._lock.release()
self.close()
raise luxex("error receiving answer: no data")
answer = struct.unpack('!iii', answer)
fields = ['cmd', 'state', 'len']
answer = dict(list(zip(fields, answer)))
if answer['cmd'] == 3004:
calcs = []
for i in range(0, answer['len']):
calc = self._request_more(4)
calcs.append(struct.unpack('!i', calc)[0])
self._lock.release()
if len(calcs) > 0:
self._calc = calcs
return answer['state']
return 0
else:
self._lock.release()
self.logger.warning("Luxtronic2: failed to retrieve calculated")
return 0
class Luxtronic2(LuxBase):
_parameter = {}
_attribute = {}
_calculated = {}
_decoded = {}
alive = True
def __init__(self, smarthome, host, port=8888, cycle=300):
LuxBase.__init__(self, host, port)
self._sh = smarthome
self._cycle = int(cycle)
self.connect()
def run(self):
self.alive = True
self._sh.scheduler.add('Luxtronic2', self._refresh, cycle=self._cycle)
def stop(self):
self.alive = False
def _refresh(self):
if not self.is_connected:
return
start = time.time()
if len(self._parameter) > 0:
self.refresh_parameters()
for p in self._parameter:
val = self.get_parameter(p)
if val:
self._parameter[p](val, 'Luxtronic2')
if len(self._attribute) > 0:
self.refresh_attributes()
for a in self._attribute:
val = self.get_attribute(a)
if val:
self._attribute[a](val, 'Luxtronic2')
if len(self._calculated) > 0 or len(self._decoded) > 0:
self.refresh_calculated()
for c in self._calculated:
val = self.get_calculated(c)
if val is not None:
self._calculated[c](val, 'Luxtronic2')
for d in self._decoded:
val = self.get_calculated(d)
if val is not None:
self._decoded[d](self._decode(d, val), 'Luxtronic2')
cycletime = time.time() - start
self.logger.debug("cycle takes {0} seconds".format(cycletime))
def _decode(self, identifier, value):
if identifier == 119:
if value == 0:
return 'Heizbetrieb'
if value == 1:
return 'Keine Anforderung'
if value == 2:
return 'Netz- Einschaltverzoegerung'
if value == 3:
return 'SSP Zeit'
if value == 4:
return 'Sperrzeit'
if value == 5:
return 'Brauchwasser'
if value == 6:
return 'Estrich Programm'
if value == 7:
return 'Abtauen'
if value == 8:
return 'Pumpenvorlauf'
if value == 9:
return 'Thermische Desinfektion'
if value == 10:
return 'Kuehlbetrieb'
if value == 12:
return 'Schwimmbad'
if value == 13:
return 'Heizen Ext.'
if value == 14:
return 'Brauchwasser Ext.'
if value == 16:
return 'Durchflussueberwachung'
if value == 17:
return 'ZWE Betrieb'
return '???'
if identifier == 10:
return float(value) / 10
if identifier == 11:
return float(value) / 10
if identifier == 12:
return float(value) / 10
if identifier == 15:
return float(value) / 10
if identifier == 19:
return float(value) / 10
if identifier == 20:
return float(value) / 10
if identifier == 151:
return float(value) / 10
if identifier == 152:
return float(value) / 10
return value
def parse_item(self, item):
if self.has_iattr(item.conf, 'lux2'):
d = self.get_iattr_value(item.conf, 'lux2')
d = int(d)
self._decoded[d] = item
if self.has_iattr(item.conf, 'lux2_a'):
a = self.get_iattr_value(item.conf, 'lux2_a')
a = int(a)
self._attribute[a] = item
if self.has_iattr(item.conf, 'lux2_c'):
c = self.get_iattr_value(item.conf, 'lux2_c')
c = int(c)
self._calculated[c] = item
if self.has_iattr(item.conf, 'lux2_p'):
p = self.get_iattr_value(item.conf, 'lux2_p')
p = int(p)
self._parameter[p] = item
return self.update_item
def update_item(self, item, caller=None, source=None, dest=None):
if caller != 'Luxtronic2':
self.set_param(self.get_iattr_value(item.conf, 'lux2_p'), item())
def main():
try:
lux = LuxBase('192.168.178.25')
lux.connect()
if not lux.is_connected:
return 1
start = time.time()
lux.refresh_parameters()
lux.refresh_attributes()
lux.refresh_calculated()
cycletime = time.time() - start
print("{0} Parameters:".format(lux.get_parameter_count()))
for i in range(0, lux.get_parameter_count()):
print(" {0} = {1}".format(i + 1, lux.get_parameter(i)))
print("{0} Attributes:".format(lux.get_attribute_count()))
for i in range(0, lux.get_attribute_count()):
print(" {0} = {1}".format(i + 1, lux.get_attribute(i)))
print("{0} Calculated:".format(lux.get_calculated_count()))
for i in range(0, lux.get_calculated_count()):
print(" {0} = {1}".format(i + 1, lux.get_calculated(i)))
print("cycle takes {0} seconds".format(cycletime))
except Exception as e:
print("[EXCEPTION] error main: {0}".format(e))
return 1
finally:
if lux:
lux.close()
if __name__ == "__main__":
sys.exit(main())