Переглянути джерело

test and simulation extracted to own project space

videv_dev
Dirk Alders 1 рік тому
джерело
коміт
dd178d81a6

+ 0
- 0
__simulation__/__init__.py Переглянути файл


+ 0
- 832
__simulation__/devices.py Переглянути файл

@@ -1,832 +0,0 @@
1
-import colored
2
-import copy
3
-import json
4
-import task
5
-import time
6
-
7
-COLOR_GUI_ACTIVE = colored.fg("light_blue")
8
-COLOR_GUI_PASSIVE = COLOR_GUI_ACTIVE + colored.attr("dim")
9
-COLOR_SHELLY = colored.fg("light_magenta")
10
-COLOR_POWERPLUG = colored.fg("light_cyan")
11
-COLOR_LIGHT_ACTIVE = colored.fg("yellow")
12
-COLOR_LIGHT_PASSIVE = COLOR_LIGHT_ACTIVE + colored.attr("dim")
13
-COLOR_MOTION_SENSOR = colored.fg("dark_orange_3b")
14
-COLOR_HEATING_VALVE = colored.fg("red")
15
-COLOR_REMOTE = colored.fg("green")
16
-
17
-
18
-def payload_filter(payload):
19
-    try:
20
-        return json.loads(payload)
21
-    except json.decoder.JSONDecodeError:
22
-        return payload.decode("utf-8")
23
-
24
-
25
-def command_int_value(value):
26
-    try:
27
-        return int(value)
28
-    except TypeError:
29
-        print("You need to give a integer parameter not '%s'" % str(value))
30
-
31
-
32
-def command_float_value(value):
33
-    try:
34
-        return float(value)
35
-    except TypeError:
36
-        print("You need to give a integer parameter not '%s'" % str(value))
37
-
38
-
39
-def devicename(topic):
40
-    return " - ".join(topic.split('/')[1:])
41
-
42
-
43
-def percent_bar(value):
44
-    rv = ""
45
-    for i in range(0, 10):
46
-        rv += u"\u25ac" if (value - 5) > 10*i else u"\u25ad"
47
-    return rv
48
-
49
-
50
-def print_light(color, state, topic, description, led=False):
51
-    if led is True:
52
-        if state is True:
53
-            icon = colored.fg('green') + "\u2b24" + color
54
-        else:
55
-            icon = colored.fg('light_gray') + "\u2b24" + color
56
-    else:
57
-        icon = u'\u2b24' if state is True else u'\u25ef'
58
-    print(color + 10 * ' ' + icon + 9 * ' ' + devicename(topic), description + colored.attr("reset"))
59
-
60
-
61
-def print_switch(color, state, topic, description):
62
-    icon = u'\u25a0' if state is True else u'\u25a1'
63
-    print(color + 10 * ' ' + icon + 9 * ' ' + devicename(topic), description + colored.attr("reset"))
64
-
65
-
66
-def print_percent(color, prefix, perc_value, value_str, topic, description):
67
-    if len(prefix) > 1 or len(value_str) > 7:
68
-        raise ValueError("Length of prefix (%d) > 1 or length of value_str (%d) > 7" % (len(prefix), len(value_str)))
69
-    print(color + prefix + percent_bar(perc_value), value_str + (8 - len(value_str)) * ' ' + devicename(topic), description + colored.attr("reset"))
70
-
71
-
72
-class base(object):
73
-    AUTOSEND = True
74
-    COMMANDS = []
75
-
76
-    def __init__(self, mqtt_client, topic):
77
-        self.mqtt_client = mqtt_client
78
-        self.topic = topic
79
-        #
80
-        self.data = {}
81
-        self.callbacks = {}
82
-        self.names = {}
83
-        self.commands = self.COMMANDS[:]
84
-        #
85
-        self.mqtt_client.add_callback(self.topic, self.__rx__)
86
-        self.mqtt_client.add_callback(self.topic + '/#', self.__rx__)
87
-
88
-    def add_callback(self, key, callback, value):
89
-        if self.callbacks.get(key) is None:
90
-            self.callbacks[key] = []
91
-        self.callbacks[key].append((callback, value))
92
-
93
-    def add_channel_name(self, key, name):
94
-        self.names[key] = name
95
-
96
-    def capabilities(self):
97
-        return self.commands
98
-
99
-    def store_data(self, *args, **kwargs):
100
-        keys_changed = []
101
-        for key in kwargs:
102
-            if kwargs[key] is not None and kwargs[key] != self.data.get(key):
103
-                keys_changed.append(key)
104
-                self.data[key] = kwargs[key]
105
-                for callback, value in self.callbacks.get(key, [(None, None)]):
106
-                    if callback is not None and (value is None or value == kwargs[key]):
107
-                        callback(self, key, kwargs[key])
108
-        if self.AUTOSEND and len(keys_changed) > 0:
109
-            self.__tx__(keys_changed)
110
-
111
-    def get_data(self, key, default=None):
112
-        rv = self.data.get(key, default)
113
-        try:
114
-            rv = True if rv.lower() == 'on' else rv
115
-            rv = False if rv.lower() == 'off' else rv
116
-        except AttributeError:
117
-            pass
118
-        return rv
119
-
120
-    def __tx__(self, keys_changed):
121
-        self.mqtt_client.send(self.topic, json.dumps(self.data))
122
-
123
-    def __rx__(self, client, userdata, message):
124
-        print("%s: __rx__ not handled!" % self.__class__.__name__)
125
-
126
-
127
-class shelly(base):
128
-    KEY_OUTPUT_0 = "relay/0"
129
-    KEY_OUTPUT_1 = "relay/1"
130
-    KEY_INPUT_0 = "input/0"
131
-    KEY_INPUT_1 = "input/1"
132
-    KEY_LONGPUSH_0 = "longpush/0"
133
-    KEY_LONGPUSH_1 = "longpush/1"
134
-    #
135
-    INPUT_FUNC_OUT1_FOLLOW = "out1_follow"
136
-    INPUT_FUNC_OUT1_TRIGGER = "out1_trigger"
137
-    INPUT_FUNC_OUT2_FOLLOW = "out2_follow"
138
-    INPUT_FUNC_OUT2_TRIGGER = "out2_trigger"
139
-    #
140
-    COMMANDS = [
141
-        "get_relay_0", "toggle_relay_0",
142
-        "get_relay_1", "toggle_relay_1",
143
-        "get_input_0", "toggle_input_0",
144
-        "get_input_1", "toggle_input_1",
145
-        "trigger_long_input_0", "trigger_long_input_1",
146
-    ]
147
-
148
-    def __init__(self, mqtt_client, topic, input_0_func=None, input_1_func=None, output_0_auto_off=None):
149
-        super().__init__(mqtt_client, topic)
150
-        #
151
-        self.store_data(**{self.KEY_OUTPUT_0: False, self.KEY_OUTPUT_1: False, self.KEY_INPUT_0: False, self.KEY_INPUT_1: False})
152
-        self.__input_0_func = input_0_func
153
-        self.__input_1_func = input_1_func
154
-        self.__output_0_auto_off__ = output_0_auto_off
155
-        if self.__output_0_auto_off__ is not None:
156
-            self.__delayed_off__ = task.delayed(float(self.__output_0_auto_off__), self.__auto_off__, self.KEY_OUTPUT_0)
157
-        #
158
-        self.add_callback(self.KEY_OUTPUT_0, self.print_formatted, None)
159
-        self.add_callback(self.KEY_OUTPUT_0, self.__start_auto_off__, True)
160
-        self.add_callback(self.KEY_OUTPUT_0, self.__stop_auto_off__, True)
161
-        self.add_callback(self.KEY_OUTPUT_1, self.print_formatted, None)
162
-        #
163
-        self.add_callback(self.KEY_INPUT_0, self.__input_function__, None)
164
-        self.add_callback(self.KEY_INPUT_1, self.__input_function__, None)
165
-
166
-    def __rx__(self, client, userdata, message):
167
-        value = payload_filter(message.payload)
168
-        if message.topic.startswith(self.topic) and message.topic.endswith("/command"):
169
-            key = '/'.join(message.topic.split('/')[-3:-1])
170
-            if value == 'toggle':
171
-                self.__toggle_data__(key)
172
-            else:
173
-                self.__set_data__(key, value)
174
-
175
-    def __tx__(self, keys_changed):
176
-        for key in keys_changed:
177
-            self.mqtt_client.send(self.topic + '/' + key, "on" if self.data.get(key) else "off")
178
-
179
-    def __input_function__(self, device, key, data):
180
-        if key == self.KEY_INPUT_0:
181
-            func = self.__input_0_func
182
-        elif key == self.KEY_INPUT_1:
183
-            func = self.__input_1_func
184
-        else:
185
-            func = None
186
-        if func == self.INPUT_FUNC_OUT1_FOLLOW:
187
-            self.__set_data__(self.KEY_OUTPUT_0, data)
188
-        elif func == self.INPUT_FUNC_OUT1_TRIGGER:
189
-            self.__toggle_data__(self.KEY_OUTPUT_0)
190
-        elif func == self.INPUT_FUNC_OUT2_FOLLOW:
191
-            self.__set_data__(self.KEY_OUTPUT_1, data)
192
-        elif func == self.INPUT_FUNC_OUT2_TRIGGER:
193
-            self.__toggle_data__(self.KEY_OUTPUT_1)
194
-
195
-    def __start_auto_off__(self, device, key, data):
196
-        self.__stop_auto_off__(device, key, data)
197
-        if self.__output_0_auto_off__ is not None:
198
-            self.__delayed_off__.run()
199
-
200
-    def __stop_auto_off__(self, device, key, data):
201
-        if self.__output_0_auto_off__ is not None:
202
-            if not self.__delayed_off__._stopped:
203
-                self.__delayed_off__.stop()
204
-
205
-    def __auto_off__(self, key):
206
-        if key == self.KEY_OUTPUT_0:
207
-            self.__set_data__(key, 'off')
208
-
209
-    def __set_data__(self, key, value):
210
-        self.store_data(**{key: value == "on"})
211
-
212
-    def __toggle_data__(self, key):
213
-        if key in self.data:
214
-            self.__set_data__(key, "on" if not self.data.get(key) else "off")
215
-
216
-    def command(self, command):
217
-        if command in self.COMMANDS:
218
-            if command == self.COMMANDS[0]:
219
-                self.print_formatted(self, self.KEY_OUTPUT_0, self.data.get(self.KEY_OUTPUT_0))
220
-            elif command == self.COMMANDS[1]:
221
-                self.__toggle_data__(self.KEY_OUTPUT_0)
222
-            elif command == self.COMMANDS[2]:
223
-                self.print_formatted(self, self.KEY_OUTPUT_1, self.data.get(self.KEY_OUTPUT_1))
224
-            elif command == self.COMMANDS[3]:
225
-                self.__toggle_data__(self.KEY_OUTPUT_1)
226
-            elif command == self.COMMANDS[4]:
227
-                self.print_formatted(self, self.KEY_INPUT_0, self.data.get(self.KEY_INPUT_0))
228
-            elif command == self.COMMANDS[5]:
229
-                self.__toggle_data__(self.KEY_INPUT_0)
230
-            elif command == self.COMMANDS[6]:
231
-                self.print_formatted(self, self.KEY_INPUT_1, self.data.get(self.KEY_INPUT_1))
232
-            elif command == self.COMMANDS[7]:
233
-                self.__toggle_data__(self.KEY_INPUT_1)
234
-            elif command == self.COMMANDS[8]:
235
-                self.__toggle_data__(self.KEY_INPUT_0)
236
-                time.sleep(0.4)
237
-                self.__set_data__(self.KEY_LONGPUSH_0, True)
238
-                time.sleep(0.1)
239
-                self.__set_data__(self.KEY_LONGPUSH_0, False)
240
-            elif command == self.COMMANDS[9]:
241
-                self.__toggle_data__(self.KEY_INPUT_1)
242
-                time.sleep(0.4)
243
-                self.__set_data__(self.KEY_LONGPUSH_1, True)
244
-                time.sleep(0.1)
245
-                self.__set_data__(self.KEY_LONGPUSH_1, False)
246
-            else:
247
-                print("%s: not yet implemented!" % command)
248
-        else:
249
-            print("Unknown command!")
250
-
251
-    def print_formatted(self, device, key, value):
252
-        if value is not None:
253
-            info = (" - %ds" % self.__output_0_auto_off__) if self.__output_0_auto_off__ is not None and value else ""
254
-            channel = "(%s%s)" % (self.names.get(key, key), info)
255
-            print_light(COLOR_SHELLY, value, self.topic, channel)
256
-
257
-
258
-class my_powerplug(base):
259
-    KEY_OUTPUT_0 = "state"
260
-    COMMANDS = [
261
-        "get_output", "toggle_output",
262
-    ]
263
-
264
-    def __init__(self, mqtt_client, topic, channel):
265
-        super().__init__(mqtt_client, topic + '/' + "output/%d" % (channel + 1))
266
-        #
267
-        self.data[self.KEY_OUTPUT_0] = False
268
-        self.add_callback(self.KEY_OUTPUT_0, self.print_formatted, None)
269
-
270
-    def __rx__(self, client, userdata, message):
271
-        if message.topic == self.topic + '/set':
272
-            payload = payload_filter(message.payload)
273
-            if payload == "toggle":
274
-                payload = not self.data.get(self.KEY_OUTPUT_0)
275
-            self.store_data(**{self.KEY_OUTPUT_0: payload})
276
-
277
-    def __tx__(self, keys_changed):
278
-        for key in keys_changed:
279
-            self.mqtt_client.send(self.topic, json.dumps(self.data.get(key)))
280
-
281
-    def command(self, command):
282
-        if command in self.COMMANDS:
283
-            if command == self.COMMANDS[0]:
284
-                self.print_formatted(self, self.KEY_OUTPUT_0, self.data.get(self.KEY_OUTPUT_0))
285
-            elif command == self.COMMANDS[1]:
286
-                self.store_data(**{self.KEY_OUTPUT_0: not self.data.get(self.KEY_OUTPUT_0)})
287
-            else:
288
-                print("%s: not yet implemented!" % command)
289
-        else:
290
-            print("Unknown command!")
291
-
292
-    def print_formatted(self, device, key, value):
293
-        if value is not None:
294
-            print_light(COLOR_POWERPLUG, value, self.topic, "(%s)" % self.names.get(key, "State"))
295
-
296
-
297
-class silvercrest_powerplug(base):
298
-    KEY_OUTPUT_0 = "state"
299
-    #
300
-    COMMANDS = [
301
-        "get_state", "set_state", "unset_state",
302
-    ]
303
-
304
-    def __init__(self, mqtt_client, topic):
305
-        super().__init__(mqtt_client, topic)
306
-        self.add_callback(self.KEY_OUTPUT_0, self.print_formatted, None)
307
-        #
308
-        self.store_data(**{self.KEY_OUTPUT_0: False})
309
-
310
-    def __rx__(self, client, userdata, message):
311
-        if message.topic == self.topic + '/set':
312
-            STATES = ["on", "off", "toggle"]
313
-            #
314
-            state = json.loads(message.payload).get('state').lower()
315
-            if state in STATES:
316
-                if state == STATES[0]:
317
-                    self.store_data(**{self.KEY_OUTPUT_0: True})
318
-                elif state == STATES[1]:
319
-                    self.store_data(**{self.KEY_OUTPUT_0: False})
320
-                else:
321
-                    self.store_data(**{not self.data.get(self.KEY_OUTPUT_0)})
322
-
323
-    def __tx__(self, keys_changed):
324
-        for key in keys_changed:
325
-            self.mqtt_client.send(self.topic + '/' + key, "on" if self.data.get(key) else "off")
326
-
327
-    def command(self, command):
328
-        if command in self.COMMANDS:
329
-            if command == self.COMMANDS[0]:
330
-                self.print_formatted(self, self.KEY_OUTPUT_0, self.data.get(self.KEY_OUTPUT_0))
331
-            elif command == self.COMMANDS[1]:
332
-                self.store_data(**{self.KEY_OUTPUT_0: True})
333
-            elif command == self.COMMANDS[2]:
334
-                self.store_data(**{self.KEY_OUTPUT_0: False})
335
-            else:
336
-                print("%s: not yet implemented!" % command)
337
-        else:
338
-            print("Unknown command!")
339
-
340
-    def print_formatted(self, device, key, value):
341
-        if value is not None:
342
-            print_light(COLOR_POWERPLUG, value, self.topic, "(%s)" % self.names.get(key, key))
343
-
344
-
345
-class tradfri_light(base):
346
-    KEY_OUTPUT_0 = "state"
347
-    KEY_BRIGHTNESS = "brightness"
348
-    KEY_COLOR_TEMP = "color_temp"
349
-    KEY_BRIGHTNESS_MOVE = "brightness_move"
350
-    #
351
-    STATE_COMMANDS = ("get_state", "toggle_state", )
352
-    BRIGHTNESS_COMMANDS = ("get_brightness", "set_brightness",)
353
-    COLOR_TEMP_COMMANDS = ("get_color_temp", "set_color_temp",)
354
-
355
-    def __init__(self, mqtt_client, topic, enable_state=True, enable_brightness=False, enable_color_temp=False, send_on_power_on=True):
356
-        super().__init__(mqtt_client, topic)
357
-        self.send_on_power_on = send_on_power_on
358
-        self.add_callback(self.KEY_OUTPUT_0, self.print_formatted, None)
359
-        self.add_callback(self.KEY_BRIGHTNESS, self.print_formatted, None)
360
-        self.add_callback(self.KEY_COLOR_TEMP, self.print_formatted, None)
361
-        #
362
-        self.commands = []
363
-        if enable_state:
364
-            self.commands.extend(self.STATE_COMMANDS)
365
-        if enable_brightness:
366
-            self.commands.extend(self.BRIGHTNESS_COMMANDS)
367
-        if enable_color_temp:
368
-            self.commands.extend(self.COLOR_TEMP_COMMANDS)
369
-        self.__init_data__(enable_state, enable_brightness, enable_color_temp)
370
-
371
-    def __init_data__(self, enable_state, enable_brightness, enable_color_temp):
372
-        data = {}
373
-        if enable_state:
374
-            data[self.KEY_OUTPUT_0] = False
375
-            self.commands.extend(self.STATE_COMMANDS)
376
-        if enable_brightness:
377
-            data[self.KEY_BRIGHTNESS] = 50
378
-            self.brightnes_move = (0, time.time())
379
-            self.commands.extend(self.BRIGHTNESS_COMMANDS)
380
-        if enable_color_temp:
381
-            data[self.KEY_COLOR_TEMP] = 5
382
-            self.commands.extend(self.COLOR_TEMP_COMMANDS)
383
-        self.store_data(**data)
384
-
385
-    def __rx__(self, client, userdata, message):
386
-        data = json.loads(message.payload)
387
-        if self.data.get(self.KEY_OUTPUT_0) or data.get(self.KEY_OUTPUT_0) in ['on', 'toggle']:
388
-            if message.topic.startswith(self.topic) and message.topic.endswith('/set'):
389
-                for targetkey in data:
390
-                    value = data[targetkey]
391
-                    if targetkey in self.data.keys():
392
-                        if targetkey == self.KEY_OUTPUT_0:
393
-                            if value == "toggle":
394
-                                value = not self.data.get(self.KEY_OUTPUT_0)
395
-                            else:
396
-                                value = value == "on"
397
-                        elif targetkey == self.KEY_BRIGHTNESS:
398
-                            value = round((value - 1) / 2.53, 0)
399
-                        elif targetkey == self.KEY_COLOR_TEMP:
400
-                            value = round((value - 250) / 20.4, 0)
401
-                        self.store_data(**{targetkey: value})
402
-                    else:
403
-                        if targetkey == self.KEY_BRIGHTNESS_MOVE:
404
-                            new_value = self.data.get(self.KEY_BRIGHTNESS) + (time.time() - self.brightnes_move[1]) * self.brightnes_move[0]
405
-                            if new_value < 0:
406
-                                new_value = 0
407
-                            if new_value > 256:
408
-                                new_value = 256
409
-                            self.store_data(**{self.KEY_BRIGHTNESS: int(new_value)})
410
-                            self.brightnes_move = (value, time.time())
411
-                        else:
412
-                            print("%s: UNKNOWN KEY %s" % (message.topic, targetkey))
413
-            elif message.topic == self.topic + '/get':
414
-                self.__tx__(None)
415
-
416
-    def __tx__(self, keys_changed):
417
-        tx_data = copy.copy(self.data)
418
-        if self.KEY_OUTPUT_0 in tx_data:
419
-            tx_data[self.KEY_OUTPUT_0] = "on" if tx_data[self.KEY_OUTPUT_0] else "off"
420
-        if self.KEY_BRIGHTNESS in tx_data:
421
-            tx_data[self.KEY_BRIGHTNESS] = 1 + round(2.53 * tx_data[self.KEY_BRIGHTNESS], 0)
422
-        if self.KEY_COLOR_TEMP in tx_data:
423
-            tx_data[self.KEY_COLOR_TEMP] = 250 + round(20.4 * tx_data[self.KEY_COLOR_TEMP], 0)
424
-        self.mqtt_client.send(self.topic, json.dumps(tx_data))
425
-
426
-    def command(self, command):
427
-        try:
428
-            command, value = command.split(' ')
429
-        except ValueError:
430
-            value = None
431
-        if command in self.capabilities():
432
-            if command == self.STATE_COMMANDS[0]:
433
-                self.print_formatted(self, self.KEY_OUTPUT_0, self.data.get(self.KEY_OUTPUT_0))
434
-            elif command == self.STATE_COMMANDS[1]:
435
-                self.store_data(**{self.KEY_OUTPUT_0: not self.data.get(self.KEY_OUTPUT_0)})
436
-            elif command == self.BRIGHTNESS_COMMANDS[0]:
437
-                self.print_formatted(self, self.KEY_BRIGHTNESS, self.data.get(self.KEY_BRIGHTNESS))
438
-            elif command == self.BRIGHTNESS_COMMANDS[1]:
439
-                self.store_data(**{self.KEY_BRIGHTNESS: command_int_value(value)})
440
-            elif command == self.COLOR_TEMP_COMMANDS[0]:
441
-                self.print_formatted(self, self.KEY_COLOR_TEMP, self.data.get(self.KEY_COLOR_TEMP))
442
-            elif command == self.COLOR_TEMP_COMMANDS[1]:
443
-                self.store_data(**{self.KEY_COLOR_TEMP: command_int_value(value)})
444
-            else:
445
-                print("%s: not yet implemented!" % command)
446
-        else:
447
-            print("Unknown command!")
448
-
449
-    def power_off(self, device, key, value):
450
-        self.data[self.KEY_OUTPUT_0] = False
451
-        self.print_formatted(self, self.KEY_OUTPUT_0, False)
452
-
453
-    def power_on(self, device, key, value):
454
-        if self.send_on_power_on:
455
-            self.store_data(**{self.KEY_OUTPUT_0: True})
456
-        else:
457
-            self.data[self.KEY_OUTPUT_0] = True
458
-            self.print_formatted(self, self.KEY_OUTPUT_0, True)
459
-
460
-    def print_formatted(self, device, key, value):
461
-        if value is not None:
462
-            color = COLOR_LIGHT_ACTIVE
463
-            if key == self.KEY_OUTPUT_0:
464
-                print_light(COLOR_LIGHT_ACTIVE, value, self.topic, "")
465
-                self.print_formatted(device, self.KEY_BRIGHTNESS, self.data.get(self.KEY_BRIGHTNESS))
466
-                self.print_formatted(device, self.KEY_COLOR_TEMP, self.data.get(self.KEY_COLOR_TEMP))
467
-            elif key in [self.KEY_BRIGHTNESS, self.KEY_COLOR_TEMP]:
468
-                perc_value = round(value, 0) if key == self.KEY_BRIGHTNESS else round(10 * value, 0)
469
-                print_percent(
470
-                    COLOR_LIGHT_PASSIVE if not self.data.get(self.KEY_OUTPUT_0) else COLOR_LIGHT_ACTIVE,
471
-                    'B' if key == self.KEY_BRIGHTNESS else 'C',
472
-                    perc_value,
473
-                    "%3d%%" % perc_value,
474
-                    self.topic,
475
-                    ""
476
-                )
477
-
478
-
479
-class brennenstuhl_heating_valve(base):
480
-    TEMP_RANGE = [10, 30]
481
-    #
482
-    KEY_TEMPERATURE_SETPOINT = "current_heating_setpoint"
483
-    KEY_TEMPERATURE = "local_temperature"
484
-    #
485
-    COMMANDS = [
486
-        "get_temperature_setpoint", "set_temperature_setpoint", "set_local_temperature",
487
-    ]
488
-
489
-    def __init__(self, mqtt_client, topic):
490
-        super().__init__(mqtt_client, topic)
491
-        self.store_data(**{
492
-            self.KEY_TEMPERATURE_SETPOINT: 20,
493
-            self.KEY_TEMPERATURE: 20.7,
494
-        })
495
-        self.add_callback(self.KEY_TEMPERATURE_SETPOINT, self.print_formatted, None)
496
-
497
-    def __rx__(self, client, userdata, message):
498
-        if message.topic.startswith(self.topic) and message.topic.endswith("/set"):
499
-            payload = payload_filter(message.payload)
500
-            self.store_data(**payload)
501
-
502
-    def command(self, command):
503
-        try:
504
-            command, value = command.split(' ')
505
-        except ValueError:
506
-            value = None
507
-        if command in self.COMMANDS:
508
-            if command == self.COMMANDS[0]:
509
-                self.print_formatted(self, self.KEY_TEMPERATURE_SETPOINT, self.data.get(self.KEY_TEMPERATURE_SETPOINT))
510
-            elif command == self.COMMANDS[1]:
511
-                self.store_data(**{self.KEY_TEMPERATURE_SETPOINT: command_float_value(value)})
512
-            elif command == self.COMMANDS[2]:
513
-                self.store_data(**{self.KEY_TEMPERATURE: command_float_value(value)})
514
-
515
-    def print_formatted(self, device, key, value):
516
-        devicename = ' - '.join(self.topic.split('/')[1:])
517
-        if key == self.KEY_TEMPERATURE_SETPOINT:
518
-            perc = 100 * (value - self.TEMP_RANGE[0]) / (self.TEMP_RANGE[1] - self.TEMP_RANGE[0])
519
-            perc = 100 if perc > 100 else perc
520
-            perc = 0 if perc < 0 else perc
521
-            print_percent(COLOR_HEATING_VALVE, '\u03d1', perc, "%4.1f°C" % value, self.topic, "")
522
-
523
-
524
-class videv_light(base):
525
-    AUTOSEND = False
526
-    #
527
-    KEY_STATE = "state"
528
-    KEY_BRIGHTNESS = "brightness"
529
-    KEY_COLOR_TEMP = "color_temp"
530
-    KEY_TIMER = "timer"
531
-    #
532
-    STATE_COMMANDS = ("get_state", "toggle_state", )
533
-    BRIGHTNESS_COMMANDS = ("get_brightness", "set_brightness", )
534
-    COLOR_TEMP_COMMANDS = ("get_color_temp", "set_color_temp", )
535
-    TIMER_COMMANDS = ("get_timer", )
536
-
537
-    def __init__(self, mqtt_client, topic, enable_state=True, enable_brightness=False, enable_color_temp=False, enable_timer=False):
538
-        super().__init__(mqtt_client, topic)
539
-        self.enable_state = enable_state
540
-        self.enable_brightness = enable_brightness
541
-        self.enable_color_temp = enable_color_temp
542
-        self.enable_timer = enable_timer
543
-        #
544
-        self.maxvalue = None
545
-        # add commands to be available
546
-        if enable_state:
547
-            # init default value
548
-            self.data[self.KEY_STATE] = False
549
-            # add print callback
550
-            self.add_callback(self.KEY_STATE, self.print_formatted, None)
551
-            # add commands to be available
552
-            self.commands.extend(self.STATE_COMMANDS)
553
-        if enable_brightness:
554
-            # init default value
555
-            self.data[self.KEY_BRIGHTNESS] = 50
556
-            # add print callback
557
-            self.add_callback(self.KEY_BRIGHTNESS, self.print_formatted, None)
558
-            # add commands to be available
559
-            self.commands.extend(self.BRIGHTNESS_COMMANDS)
560
-        if enable_color_temp:
561
-            # init default value
562
-            self.data[self.KEY_COLOR_TEMP] = 5
563
-            # add print callback
564
-            self.add_callback(self.KEY_COLOR_TEMP, self.print_formatted, None)
565
-            # add commands to be available
566
-            self.commands.extend(self.COLOR_TEMP_COMMANDS)
567
-        if enable_timer:
568
-            # init default value
569
-            self.data[self.KEY_TIMER] = 0
570
-            # add print callback
571
-            self.add_callback(self.KEY_TIMER, self.print_formatted, None)
572
-            # add commands to be available
573
-            self.commands.extend(self.TIMER_COMMANDS)
574
-
575
-    def __rx__(self, client, userdata, message):
576
-        value = payload_filter(message.payload)
577
-        if message.topic.startswith(self.topic):
578
-            targetkey = message.topic.split('/')[-1]
579
-            if targetkey in self.data.keys():
580
-                self.store_data(**{targetkey: value})
581
-            elif targetkey != "__info__":
582
-                print("Unknown key %s in %s::%s" % (targetkey, message.topic, self.__class__.__name__))
583
-        elif message.topic == self.topic + '/get':
584
-            self.__tx__(None)
585
-
586
-    def send(self, key, data):
587
-        if data is not None:
588
-            topic = self.topic + '/' + key
589
-            self.mqtt_client.send(topic, json.dumps(data))
590
-
591
-    def command(self, command):
592
-        try:
593
-            command, value = command.split(' ')
594
-        except ValueError:
595
-            value = None
596
-        if command in self.capabilities():
597
-            if command == self.STATE_COMMANDS[0]:
598
-                self.print_formatted(self, self.KEY_STATE, self.data.get(self.KEY_STATE))
599
-            elif command == self.STATE_COMMANDS[1]:
600
-                self.send(self.KEY_STATE, not self.data.get(self.KEY_STATE))
601
-            elif command == self.BRIGHTNESS_COMMANDS[0]:
602
-                self.print_formatted(self, self.KEY_BRIGHTNESS, self.data.get(self.KEY_BRIGHTNESS))
603
-            elif command == self.BRIGHTNESS_COMMANDS[1]:
604
-                self.send(self.KEY_BRIGHTNESS, command_int_value(value))
605
-            elif command == self.COLOR_TEMP_COMMANDS[0]:
606
-                self.print_formatted(self, self.KEY_COLOR_TEMP, self.data.get(self.KEY_COLOR_TEMP))
607
-            elif command == self.COLOR_TEMP_COMMANDS[1]:
608
-                self.send(self.KEY_COLOR_TEMP, command_int_value(value))
609
-            elif command == self.TIMER_COMMANDS[0]:
610
-                self.print_formatted(self, self.KEY_TIMER, self.data.get(self.KEY_TIMER))
611
-            else:
612
-                print("%s: not yet implemented!" % command)
613
-        else:
614
-            print("Unknown command!")
615
-
616
-    def print_formatted(self, device, key, value):
617
-        if value is not None:
618
-            device = " - ".join(self.topic.split('/')[1:])
619
-            if key == self.KEY_STATE:
620
-                print_switch(COLOR_GUI_ACTIVE, value, self.topic, "")
621
-            elif key in [self.KEY_BRIGHTNESS, self.KEY_COLOR_TEMP]:
622
-                perc_value = round(value * 10 if key == self.KEY_COLOR_TEMP else value, 0)
623
-                print_percent(
624
-                    COLOR_GUI_ACTIVE,
625
-                    'B' if key == self.KEY_BRIGHTNESS else 'C',
626
-                    perc_value,
627
-                    "%3d%%" % perc_value,
628
-                    self.topic,
629
-                    ""
630
-                )
631
-            elif key == self.KEY_TIMER:
632
-                if value > 0:
633
-                    if self.maxvalue is None and value != 0:
634
-                        self.maxvalue = value
635
-                    disp_value = value
636
-                    try:
637
-                        perc = disp_value / self.maxvalue * 100
638
-                    except ZeroDivisionError:
639
-                        perc = 0
640
-                else:
641
-                    disp_value = 0
642
-                    perc = 0
643
-                    self.maxvalue = None
644
-                print_percent(COLOR_GUI_ACTIVE, 't', perc, '%3d%%' % perc, self.topic, '(%.1f)' % disp_value)
645
-
646
-
647
-# class silvercrest_motion_sensor(base):
648
-#     KEY_OCCUPANCY = "occupancy"
649
-#     COMMANDS = ['motion']
650
-
651
-#     def __init__(self, mqtt_client, topic):
652
-#         super().__init__(mqtt_client, topic)
653
-#         self.data[self.KEY_OCCUPANCY] = False
654
-#         self.add_callback(self.KEY_OCCUPANCY, self.print_formatted, None)
655
-
656
-#     def __rx__(self, client, userdata, message):
657
-#         pass
658
-
659
-#     def command(self, command):
660
-#         try:
661
-#             command, value = command.split(' ')
662
-#         except ValueError:
663
-#             value = None
664
-#         else:
665
-#             value = json.loads(value)
666
-#         if command == self.COMMANDS[0]:
667
-#             self.store_data(**{self.KEY_OCCUPANCY: True})
668
-#             time.sleep(value or 10)
669
-#             self.store_data(**{self.KEY_OCCUPANCY: False})
670
-
671
-#     def print_formatted(self, device, key, value):
672
-#         if value is not None:
673
-#             print_light(COLOR_MOTION_SENSOR, value, self.topic, "")
674
-
675
-
676
-# class tradfri_button(base):
677
-#     KEY_ACTION = "action"
678
-#     #
679
-#     ACTION_TOGGLE = "toggle"
680
-#     ACTION_BRIGHTNESS_UP = "brightness_up_click"
681
-#     ACTION_BRIGHTNESS_DOWN = "brightness_down_click"
682
-#     ACTION_RIGHT = "arrow_right_click"
683
-#     ACTION_LEFT = "arrow_left_click"
684
-#     ACTION_BRIGHTNESS_UP_LONG = "brightness_up_hold"
685
-#     ACTION_BRIGHTNESS_DOWN_LONG = "brightness_down_hold"
686
-#     ACTION_RIGHT_LONG = "arrow_right_hold"
687
-#     ACTION_LEFT_LONG = "arrow_left_hold"
688
-#     #
689
-#     COMMANDS = [ACTION_TOGGLE, ACTION_LEFT, ACTION_RIGHT, ACTION_BRIGHTNESS_UP, ACTION_BRIGHTNESS_DOWN,
690
-#                 ACTION_LEFT_LONG, ACTION_RIGHT_LONG, ACTION_BRIGHTNESS_UP_LONG, ACTION_BRIGHTNESS_DOWN_LONG]
691
-
692
-#     def __init__(self, mqtt_client, topic):
693
-#         super().__init__(mqtt_client, topic)
694
-
695
-#     def __rx__(self, client, userdata, message):
696
-#         pass
697
-
698
-#     def command(self, command):
699
-#         try:
700
-#             command, value = command.split(' ')
701
-#         except ValueError:
702
-#             value = None
703
-#         else:
704
-#             value = json.loads(value)
705
-#         if command in self.capabilities():
706
-#             action = self.COMMANDS[self.COMMANDS.index(command)]
707
-#             if self.COMMANDS.index(command) <= 4:
708
-#                 self.mqtt_client.send(self.topic, json.dumps({self.KEY_ACTION: action}))
709
-#             elif self.COMMANDS.index(command) <= 8:
710
-#                 self.mqtt_client.send(self.topic, json.dumps({self.KEY_ACTION: action}))
711
-#                 time.sleep(value or 0.5)
712
-#                 action = '_'.join(action.split('_')[:-1] + ['release'])
713
-#                 self.mqtt_client.send(self.topic, json.dumps({self.KEY_ACTION: action}))
714
-
715
-
716
-# class remote(base):
717
-#     def __rx__(self, client, userdata, message):
718
-#         if message.topic == self.topic + "/VOLUP":
719
-#             if payload_filter(message.payload):
720
-#                 icon = u'\u1403'
721
-#             else:
722
-#                 icon = u'\u25a1'
723
-#         elif message.topic == self.topic + "/VOLDOWN":
724
-#             if payload_filter(message.payload):
725
-#                 icon = u'\u1401'
726
-#             else:
727
-#                 icon = u'\u25a1'
728
-#         else:
729
-#             return
730
-#         devicename = ' - '.join(self.topic.split('/')[1:-1])
731
-#         print(COLOR_REMOTE + 10 * ' ' + icon + 6 * ' ' + devicename + colored.attr("reset"))
732
-
733
-
734
-# class gui_heating_valve(base):
735
-#     AUTOSEND = False
736
-#     #
737
-#     TEMP_RANGE = [10, 30]
738
-#     #
739
-#     KEY_TIMER = "timer"
740
-#     KEY_TEMPERATURE = "temperature"
741
-#     KEY_SETPOINT_TEMP = "setpoint_temp"
742
-#     KEY_SETPOINT_TO_DEFAULT = "setpoint_to_default"
743
-#     KEY_BOOST = 'boost'
744
-#     KEY_AWAY = "away"
745
-#     KEY_SUMMER = "summer"
746
-#     KEY_ENABLE = "enable"
747
-#     #
748
-#     COMMANDS = [
749
-#         "get_temperature",
750
-#         "get_temperature_setpoint", "set_temperature_setpoint",
751
-#         "trigger_boost", "trigger_setpoint_to_default",
752
-#         "toggle_away", "toggle_summer",
753
-#     ]
754
-
755
-#     def __init__(self, mqtt_client, topic):
756
-#         super().__init__(mqtt_client, topic)
757
-#         self.add_callback(self.KEY_SETPOINT_TEMP, self.print_formatted, None)
758
-#         self.add_callback(self.KEY_TIMER, self.print_formatted, None)
759
-#         self.add_callback(self.KEY_AWAY, self.print_formatted, None)
760
-#         self.add_callback(self.KEY_SUMMER, self.print_formatted, None)
761
-#         #
762
-#         self.store_data(**{
763
-#             self.KEY_TEMPERATURE: 20.7,
764
-#             self.KEY_SETPOINT_TEMP: 20,
765
-#             self.KEY_TIMER: 0,
766
-#             self.KEY_AWAY: False,
767
-#             self.KEY_SUMMER: False,
768
-#             self.KEY_ENABLE: True
769
-#         })
770
-
771
-#     def __rx__(self, client, userdata, message):
772
-#         value = payload_filter(message.payload)
773
-#         if message.topic.startswith(self.topic) and message.topic.endswith('/set'):
774
-#             targetkey = message.topic.split('/')[-2]
775
-#             if targetkey in self.data.keys():
776
-#                 self.store_data(**{targetkey: value})
777
-#             else:
778
-#                 print("Unknown key %s in %s::%s" % (targetkey, message.topic, self.__class__.__name__))
779
-#         elif message.topic == self.topic + '/get':
780
-#             self.__tx__(None)
781
-
782
-#     def send(self, key, data):
783
-#         if data is not None:
784
-#             topic = self.topic + '/' + key
785
-#             self.mqtt_client.send(topic, json.dumps(data))
786
-
787
-#     def command(self, command):
788
-#         try:
789
-#             command, value = command.split(' ')
790
-#         except ValueError:
791
-#             value = None
792
-#         if command in self.COMMANDS:
793
-#             if command == self.COMMANDS[0]:
794
-#                 self.print_formatted(self, self.KEY_TEMPERATURE, self.data.get(self.KEY_TEMPERATURE))
795
-#             elif command == self.COMMANDS[1]:
796
-#                 self.print_formatted(self, self.KEY_SETPOINT_TEMP, self.data.get(self.KEY_SETPOINT_TEMP))
797
-#             elif command == self.COMMANDS[2]:
798
-#                 self.send(self.KEY_SETPOINT_TEMP, command_float_value(value))
799
-#             elif command == self.COMMANDS[3]:
800
-#                 self.send(self.KEY_BOOST, True)
801
-#             elif command == self.COMMANDS[4]:
802
-#                 self.send(self.KEY_SETPOINT_TO_DEFAULT, True)
803
-#             elif command == self.COMMANDS[5]:
804
-#                 self.send(self.KEY_AWAY, not self.data.get(self.KEY_AWAY))
805
-#             elif command == self.COMMANDS[6]:
806
-#                 self.send(self.KEY_SUMMER, not self.data.get(self.KEY_SUMMER))
807
-
808
-#     def print_formatted(self, device, key, value):
809
-#         devicename = ' - '.join(self.topic.split('/')[1:])
810
-#         if key == self.KEY_TIMER:
811
-#             value /= 60
812
-#             try:
813
-#                 perc = 100 * value / 60
814
-#             except TypeError:
815
-#                 value = 0
816
-#                 perc = 0
817
-#             print_percent(COLOR_GUI_ACTIVE, 't', perc, "%4.1fmin" % value, self.topic, "(Timer)")
818
-#         elif key == self.KEY_TEMPERATURE:
819
-#             perc = 100 * (value - self.TEMP_RANGE[0]) / (self.TEMP_RANGE[1] - self.TEMP_RANGE[0])
820
-#             perc = 100 if perc > 100 else perc
821
-#             perc = 0 if perc < 0 else perc
822
-#             print_percent(COLOR_GUI_ACTIVE, '\u03d1', perc, "%4.1f°C" % value, self.topic, "(Temperature)")
823
-#         elif key == self.KEY_SETPOINT_TEMP:
824
-#             perc = 100 * (value - self.TEMP_RANGE[0]) / (self.TEMP_RANGE[1] - self.TEMP_RANGE[0])
825
-#             perc = 100 if perc > 100 else perc
826
-#             perc = 0 if perc < 0 else perc
827
-#             print_percent(COLOR_GUI_ACTIVE if self.data.get(self.KEY_ENABLE) else COLOR_GUI_PASSIVE,
828
-#                           '\u03d1', perc, "%4.1f°C" % value, self.topic, "(Setpoint)")
829
-#         elif key == self.KEY_AWAY:
830
-#             print_switch(COLOR_GUI_ACTIVE, value, self.topic, "(Away Mode)")
831
-#         elif key == self.KEY_SUMMER:
832
-#             print_switch(COLOR_GUI_ACTIVE, value, self.topic, "(Summer Mode)")

+ 0
- 263
__simulation__/rooms.py Переглянути файл

@@ -1,263 +0,0 @@
1
-import config
2
-from __simulation__.devices import shelly, silvercrest_powerplug, tradfri_light, my_powerplug, brennenstuhl_heating_valve
3
-from __simulation__.devices import videv_light
4
-import inspect
5
-
6
-
7
-class base(object):
8
-    def getmembers(self, prefix=''):
9
-        rv = []
10
-        for name, obj in inspect.getmembers(self):
11
-            if prefix:
12
-                full_name = prefix + '.' + name
13
-            else:
14
-                full_name = name
15
-            if not name.startswith('_'):
16
-                try:
17
-                    if obj.__module__.endswith('devices'):
18
-                        rv.append(full_name)
19
-                    else:
20
-                        rv.extend(obj.getmembers(full_name))
21
-                except AttributeError:
22
-                    pass
23
-        return rv
24
-
25
-    def getobjbyname(self, name):
26
-        obj = self
27
-        for subname in name.split('.'):
28
-            obj = getattr(obj, subname)
29
-        return obj
30
-
31
-    def command(self, full_command):
32
-        try:
33
-            parameter = " " + full_command.split(' ')[1]
34
-        except IndexError:
35
-            parameter = ""
36
-        command = full_command.split(' ')[0].split('.')[-1] + parameter
37
-        device_name = '.'.join(full_command.split(' ')[0].split('.')[:-1])
38
-        self.getobjbyname(device_name).command(command)
39
-
40
-
41
-class gfw_floor(base):
42
-    def __init__(self, mqtt_client):
43
-        self.main_light = shelly(mqtt_client, config.TOPIC_GFW_FLOOR_MAIN_LIGHT_SHELLY, input_0_func=shelly.INPUT_FUNC_OUT1_TRIGGER)
44
-        self.main_light.add_channel_name(shelly.KEY_OUTPUT_0, "Main Light")
45
-        self.main_light_zigbee = tradfri_light(mqtt_client, config.TOPIC_GFW_FLOOR_MAIN_LIGHT_ZIGBEE % 1, True, True, True, False)
46
-        self.main_light.add_callback(shelly.KEY_OUTPUT_0, self.main_light_zigbee.power_on, True)
47
-        self.main_light.add_callback(shelly.KEY_OUTPUT_0, self.main_light_zigbee.power_off, False)
48
-        self.main_light_zigbee_2 = tradfri_light(mqtt_client, config.TOPIC_GFW_FLOOR_MAIN_LIGHT_ZIGBEE % 2, True, True, True, False)
49
-        self.main_light.add_callback(shelly.KEY_OUTPUT_0, self.main_light_zigbee_2.power_on, True)
50
-        self.main_light.add_callback(shelly.KEY_OUTPUT_0, self.main_light_zigbee_2.power_off, False)
51
-
52
-        #
53
-        self.videv_main_light = videv_light(mqtt_client, config.TOPIC_GFW_FLOOR_MAIN_LIGHT_VIDEV, True, True, True)
54
-
55
-
56
-class gfw_marion(base):
57
-    def __init__(self, mqtt_client):
58
-        self.main_light = shelly(mqtt_client, config.TOPIC_GFW_MARION_MAIN_LIGHT_SHELLY, input_0_func=shelly.INPUT_FUNC_OUT1_TRIGGER)
59
-        self.main_light.add_channel_name(shelly.KEY_OUTPUT_0, "Main Light")
60
-
61
-        self.heating_valve = brennenstuhl_heating_valve(mqtt_client, config.TOPIC_GFW_MARION_HEATING_VALVE_ZIGBEE)
62
-
63
-        #
64
-        self.videv_main_light = videv_light(mqtt_client, config.TOPIC_GFW_MARION_MAIN_LIGHT_VIDEV, True, False, False)
65
-
66
-
67
-class gfw_dirk(base):
68
-    def __init__(self, mqtt_client):
69
-        self.main_light = shelly(mqtt_client, config.TOPIC_GFW_DIRK_MAIN_LIGHT_SHELLY, input_0_func=shelly.INPUT_FUNC_OUT1_TRIGGER)
70
-        self.main_light.add_channel_name(shelly.KEY_OUTPUT_0, "Main Light")
71
-        self.main_light_zigbee = tradfri_light(mqtt_client, config.TOPIC_GFW_DIRK_MAIN_LIGHT_ZIGBEE, True, True, True)
72
-        self.main_light.add_callback(shelly.KEY_OUTPUT_0, self.main_light_zigbee.power_on, True)
73
-        self.main_light.add_callback(shelly.KEY_OUTPUT_0, self.main_light_zigbee.power_off, False)
74
-
75
-        self.amplifier = my_powerplug(mqtt_client, config.TOPIC_GFW_DIRK_POWERPLUG, 0)
76
-        self.amplifier.add_channel_name(my_powerplug.KEY_OUTPUT_0, "Amplifier")
77
-        self.desk_light = my_powerplug(mqtt_client, config.TOPIC_GFW_DIRK_POWERPLUG, 1)
78
-        self.desk_light.add_channel_name(my_powerplug.KEY_OUTPUT_0, "Desk Light")
79
-        self.cd_player = my_powerplug(mqtt_client, config.TOPIC_GFW_DIRK_POWERPLUG, 2)
80
-        self.cd_player.add_channel_name(my_powerplug.KEY_OUTPUT_0, "CD_Player")
81
-        self.pc_dock = my_powerplug(mqtt_client, config.TOPIC_GFW_DIRK_POWERPLUG, 3)
82
-        self.pc_dock.add_channel_name(my_powerplug.KEY_OUTPUT_0, "PC_Dock")
83
-        self.desk_light_zigbee = tradfri_light(mqtt_client, config.TOPIC_GFW_DIRK_DESK_LIGHT_ZIGBEE, True, True, True)
84
-        self.desk_light.add_callback(my_powerplug.KEY_OUTPUT_0, self.desk_light_zigbee.power_on, True)
85
-        self.desk_light.add_callback(my_powerplug.KEY_OUTPUT_0, self.desk_light_zigbee.power_off, False)
86
-
87
-        self.heating_valve = brennenstuhl_heating_valve(mqtt_client, config.TOPIC_GFW_DIRK_HEATING_VALVE_ZIGBEE)
88
-
89
-        #
90
-        self.videv_main_light = videv_light(mqtt_client, config.TOPIC_GFW_DIRK_MAIN_LIGHT_VIDEV, True, True, True)
91
-        self.videv_amplifier = videv_light(mqtt_client, config.TOPIC_GFW_DIRK_AMPLIFIER_VIDEV, True, False, False)
92
-        self.videv_desk_light = videv_light(mqtt_client, config.TOPIC_GFW_DIRK_DESK_LIGHT_VIDEV, True, True, True)
93
-        self.videv_cd_player = videv_light(mqtt_client, config.TOPIC_GFW_DIRK_CD_PLAYER_VIDEV, True, False, False)
94
-        self.videv_pc_dock = videv_light(mqtt_client, config.TOPIC_GFW_DIRK_PC_DOCK_VIDEV, True, False, False)
95
-
96
-
97
-class gfw(base):
98
-    def __init__(self, mqtt_client):
99
-        self.floor = gfw_floor(mqtt_client)
100
-        self.marion = gfw_marion(mqtt_client)
101
-        self.dirk = gfw_dirk(mqtt_client)
102
-
103
-
104
-class ffw_julian(base):
105
-    def __init__(self, mqtt_client):
106
-        self.main_light = shelly(mqtt_client, config.TOPIC_FFW_JULIAN_MAIN_LIGHT_SHELLY, input_0_func=shelly.INPUT_FUNC_OUT1_TRIGGER)
107
-        self.main_light.add_channel_name(shelly.KEY_OUTPUT_0, "Main Light")
108
-        self.main_light_zigbee = tradfri_light(mqtt_client, config.TOPIC_FFW_JULIAN_MAIN_LIGHT_ZIGBEE, True, True, True)
109
-        self.main_light.add_callback(shelly.KEY_OUTPUT_0, self.main_light_zigbee.power_on, True)
110
-        self.main_light.add_callback(shelly.KEY_OUTPUT_0, self.main_light_zigbee.power_off, False)
111
-
112
-        #
113
-        self.videv_main_light = videv_light(mqtt_client, config.TOPIC_FFW_JULIAN_MAIN_LIGHT_VIDEV, True, True, True)
114
-
115
-
116
-class ffw_livingroom(base):
117
-    def __init__(self, mqtt_client):
118
-        self.main_light = shelly(mqtt_client, config.TOPIC_FFW_LIVINGROOM_MAIN_LIGHT_SHELLY, input_0_func=shelly.INPUT_FUNC_OUT1_TRIGGER)
119
-        self.main_light.add_channel_name(shelly.KEY_OUTPUT_0, "Main Light")
120
-        self.main_light_zigbee = tradfri_light(mqtt_client, config.TOPIC_FFW_LIVINGROOM_MAIN_LIGHT_ZIGBEE, True, True, True)
121
-        self.main_light.add_callback(shelly.KEY_OUTPUT_0, self.main_light_zigbee.power_on, True)
122
-        self.main_light.add_callback(shelly.KEY_OUTPUT_0, self.main_light_zigbee.power_off, False)
123
-
124
-        #
125
-        self.videv_main_light = videv_light(mqtt_client, config.TOPIC_FFW_LIVINGROOM_MAIN_LIGHT_VIDEV, True, True, True)
126
-
127
-
128
-class ffw_sleep(base):
129
-    def __init__(self, mqtt_client):
130
-        self.main_light = shelly(mqtt_client, config.TOPIC_FFW_SLEEP_MAIN_LIGHT_SHELLY, input_0_func=shelly.INPUT_FUNC_OUT1_TRIGGER)
131
-        self.main_light.add_channel_name(shelly.KEY_OUTPUT_0, "Main Light")
132
-        self.main_light_zigbee = tradfri_light(mqtt_client, config.TOPIC_FFW_SLEEP_MAIN_LIGHT_ZIGBEE, True, True, True)
133
-        self.main_light.add_callback(shelly.KEY_OUTPUT_0, self.main_light_zigbee.power_on, True)
134
-        self.main_light.add_callback(shelly.KEY_OUTPUT_0, self.main_light_zigbee.power_off, False)
135
-
136
-        #
137
-        self.videv_main_light = videv_light(mqtt_client, config.TOPIC_FFW_SLEEP_MAIN_LIGHT_VIDEV, True, True, False)
138
-
139
-
140
-class ffw_bath(base):
141
-    def __init__(self, mqtt_client):
142
-        self.heating_valve = brennenstuhl_heating_valve(mqtt_client, config.TOPIC_FFW_BATH_HEATING_VALVE_ZIGBEE)
143
-
144
-
145
-class ffw(base):
146
-    def __init__(self, mqtt_client):
147
-        self.julian = ffw_julian(mqtt_client)
148
-        self.livingroom = ffw_livingroom(mqtt_client)
149
-        self.sleep = ffw_sleep(mqtt_client)
150
-        self.bath = ffw_bath(mqtt_client)
151
-
152
-
153
-class ffe_floor(base):
154
-    def __init__(self, mqtt_client):
155
-        self.main_light = shelly(mqtt_client, config.TOPIC_FFE_FLOOR_MAIN_LIGHT_SHELLY, input_0_func=shelly.INPUT_FUNC_OUT1_TRIGGER)
156
-        self.main_light.add_channel_name(shelly.KEY_OUTPUT_0, "Main Light")
157
-
158
-        #
159
-        self.videv_main_light = videv_light(mqtt_client, config.TOPIC_FFE_FLOOR_MAIN_LIGHT_VIDEV, True, False, False)
160
-
161
-
162
-class ffe_kitchen(base):
163
-    def __init__(self, mqtt_client):
164
-        self.main_light = shelly(mqtt_client, config.TOPIC_FFE_KITCHEN_MAIN_LIGHT_SHELLY, input_0_func=shelly.INPUT_FUNC_OUT1_TRIGGER)
165
-        self.main_light.add_channel_name(shelly.KEY_OUTPUT_0, "Main Light")
166
-
167
-        self.circulation_pump = shelly(mqtt_client, config.TOPIC_FFE_KITCHEN_CIRCULATION_PUMP_SHELLY,
168
-                                       input_0_func=shelly.INPUT_FUNC_OUT1_TRIGGER, output_0_auto_off=10*60)
169
-        self.circulation_pump.add_channel_name(shelly.KEY_OUTPUT_0, "Circulation Pump")
170
-
171
-        #
172
-        self.videv_main_light = videv_light(mqtt_client, config.TOPIC_FFE_KITCHEN_MAIN_LIGHT_VIDEV, True, False, False)
173
-        self.videv_circulation_pump = videv_light(mqtt_client, config.TOPIC_FFE_KITCHEN_CIRCULATION_PUMP_VIDEV, True, False, False, True)
174
-
175
-
176
-class ffe_diningroom(base):
177
-    def __init__(self, mqtt_client):
178
-        self.main_light = shelly(mqtt_client, config.TOPIC_FFE_DININGROOM_MAIN_LIGHT_SHELLY, input_0_func=shelly.INPUT_FUNC_OUT1_TRIGGER)
179
-        self.main_light.add_channel_name(shelly.KEY_OUTPUT_0, "Main Light")
180
-
181
-        self.floor_lamp = silvercrest_powerplug(mqtt_client, config.TOPIC_FFE_DININGROOM_FLOOR_LAMP_POWERPLUG)
182
-        self.floor_lamp.add_channel_name(silvercrest_powerplug.KEY_OUTPUT_0, "Floor Lamp")
183
-
184
-        if config.CHRISTMAS:
185
-            self.garland = silvercrest_powerplug(mqtt_client, config.TOPIC_FFE_DININGROOM_GARLAND_POWERPLUG)
186
-            self.garland.add_channel_name(silvercrest_powerplug, "Garland")
187
-
188
-        #
189
-        self.videv_main_light = videv_light(mqtt_client, config.TOPIC_FFE_DININGROOM_MAIN_LIGHT_VIDEV, True, False, False)
190
-        self.videv_floor_lamp = videv_light(mqtt_client, config.TOPIC_FFE_DININGROOM_FLOOR_LAMP_VIDEV, True, False, False)
191
-        if config.CHRISTMAS:
192
-            self.videv_garland = videv_light(mqtt_client, config.TOPIC_FFE_DININGROOM_GARLAND_VIDEV, True, False, False)
193
-
194
-
195
-class ffe_sleep(base):
196
-    def __init__(self, mqtt_client):
197
-        self.main_light = shelly(mqtt_client, config.TOPIC_FFE_SLEEP_MAIN_LIGHT_SHELLY, input_0_func=shelly.INPUT_FUNC_OUT1_TRIGGER)
198
-        self.main_light.add_channel_name(shelly.KEY_OUTPUT_0, "Main Light")
199
-        self.main_light_zigbee = tradfri_light(mqtt_client, config.TOPIC_FFE_SLEEP_MAIN_LIGHT_ZIGBEE, True, True, True)
200
-        self.main_light.add_callback(shelly.KEY_OUTPUT_0, self.main_light_zigbee.power_on, True)
201
-        self.main_light.add_callback(shelly.KEY_OUTPUT_0, self.main_light_zigbee.power_off, False)
202
-
203
-        self.bed_light_di_zigbee = tradfri_light(mqtt_client, config.TOPIC_FFE_SLEEP_BED_LIGHT_DI_ZIGBEE, True, True, False)
204
-        self.bed_light_ma = silvercrest_powerplug(mqtt_client, config.TOPIC_FFE_SLEEP_BED_LIGHT_MA_POWERPLUG)
205
-
206
-        self.heating_valve = brennenstuhl_heating_valve(mqtt_client, config.TOPIC_FFE_SLEEP_HEATING_VALVE_ZIGBEE)
207
-
208
-        #
209
-        self.videv_bed_light_ma = videv_light(mqtt_client, config.TOPIC_FFE_SLEEP_BED_LIGHT_MA_VIDEV, True, False, False)
210
-        self.videv_main_light = videv_light(mqtt_client, config.TOPIC_FFE_SLEEP_MAIN_LIGHT_VIDEV, True, True, True)
211
-        self.videv_bed_light_di = videv_light(mqtt_client, config.TOPIC_FFE_SLEEP_BED_LIGHT_DI_VIDEV, True, True, False)
212
-        self.videv_bed_light_ma = videv_light(mqtt_client, config.TOPIC_FFE_SLEEP_BED_LIGHT_MA_VIDEV, True, False, False)
213
-
214
-
215
-class ffe_livingroom(base):
216
-    def __init__(self, mqtt_client):
217
-        self.main_light = shelly(mqtt_client, config.TOPIC_FFE_LIVINGROOM_MAIN_LIGHT_SHELLY, input_0_func=shelly.INPUT_FUNC_OUT1_TRIGGER)
218
-        self.main_light.add_channel_name(shelly.KEY_OUTPUT_0, "Main Light")
219
-        self.main_light_zigbee = tradfri_light(mqtt_client, config.TOPIC_FFE_LIVINGROOM_MAIN_LIGHT_ZIGBEE, True, True, True)
220
-        self.main_light.add_callback(shelly.KEY_OUTPUT_0, self.main_light_zigbee.power_on, True)
221
-        self.main_light.add_callback(shelly.KEY_OUTPUT_0, self.main_light_zigbee.power_off, False)
222
-
223
-        self.floor_lamp_zigbee = tradfri_light(mqtt_client, config.TOPIC_FFE_LIVINGROOM_FLOOR_LAMP_ZIGBEE % 1, True, True, True)
224
-        for i in range(2, 7):
225
-            setattr(self, "floor_lamp_zigbee_%d" % i, tradfri_light(mqtt_client, config.TOPIC_FFE_LIVINGROOM_FLOOR_LAMP_ZIGBEE % i, True, True, True))
226
-
227
-        if config.CHRISTMAS:
228
-            self.xmas_tree = silvercrest_powerplug(mqtt_client, config.TOPIC_FFE_LIVINGROOM_XMAS_TREE_POWERPLUG)
229
-            self.xmas_tree.add_channel_name(silvercrest_powerplug, "Xmas-Tree")
230
-            self.xmas_star = silvercrest_powerplug(mqtt_client, config.TOPIC_FFE_LIVINGROOM_XMAS_STAR_POWERPLUG)
231
-            self.xmas_star.add_channel_name(silvercrest_powerplug, "Xmas-Star")
232
-
233
-        #
234
-        self.videv_main_light = videv_light(mqtt_client, config.TOPIC_FFE_LIVINGROOM_MAIN_LIGHT_VIDEV, True, True, True)
235
-        self.videv_floor_lamp = videv_light(mqtt_client, config.TOPIC_FFE_LIVINGROOM_FLOOR_LAMP_VIDEV, True, True, True)
236
-        if config.CHRISTMAS:
237
-            self.videv_xmas_tree = videv_light(mqtt_client, config.TOPIC_FFE_LIVINGROOM_XMAS_TREE_VIDEV)
238
-
239
-
240
-class ffe(base):
241
-    def __init__(self, mqtt_client):
242
-        self.floor = ffe_floor(mqtt_client)
243
-        self.kitchen = ffe_kitchen(mqtt_client)
244
-        self.diningroom = ffe_diningroom(mqtt_client)
245
-        self.sleep = ffe_sleep(mqtt_client)
246
-        self.livingroom = ffe_livingroom(mqtt_client)
247
-
248
-
249
-class stairway(base):
250
-    def __init__(self, mqtt_client):
251
-        self.main_light = shelly(mqtt_client, config.TOPIC_STW_STAIRWAY_MAIN_LIGHT_SHELLY, input_0_func=shelly.INPUT_FUNC_OUT1_TRIGGER)
252
-        self.main_light.add_channel_name(shelly.KEY_OUTPUT_0, "Main Light")
253
-
254
-        #
255
-        self.videv_main_light = videv_light(mqtt_client, config.TOPIC_STW_STAIRWAY_MAIN_LIGHT_VIDEV, True, False, False, True)
256
-
257
-
258
-class house(base):
259
-    def __init__(self, mqtt_client):
260
-        self.gfw = gfw(mqtt_client)
261
-        self.ffw = ffw(mqtt_client)
262
-        self.ffe = ffe(mqtt_client)
263
-        self.stairway = stairway(mqtt_client)

+ 0
- 249
__simulation__/test.py Переглянути файл

@@ -1,249 +0,0 @@
1
-import colored
2
-import inspect
3
-from __simulation__ import devices
4
-import time
5
-
6
-
7
-DT_TOGGLE = 0.3
8
-
9
-
10
-TEST_FULL = 'full'
11
-TEST_SMOKE = 'smoke'
12
-#
13
-COLOR_SUCCESS = colored.fg("light_green")
14
-COLOR_FAIL = colored.fg("light_red")
15
-
16
-
17
-class test_smarthome(object):
18
-    def __init__(self, rooms):
19
-        # add testcases by room objects
20
-        for name in rooms.getmembers():
21
-            obj = rooms.getobjbyname(name)
22
-            if obj.__class__.__name__ == "videv_light":
23
-                common_name = '.'.join(name.split('.')[:-1]) + '.' + name.split('.')[-1][6:]
24
-                li_device = rooms.getobjbyname(common_name + '_zigbee') if obj.enable_brightness or obj.enable_color_temp else None
25
-                try:
26
-                    sw_device = rooms.getobjbyname(common_name) if obj.enable_state else None
27
-                except AttributeError:
28
-                    # must be a device without switching device
29
-                    sw_device = li_device
30
-                setattr(self, common_name.replace('.', '_'), testcase_light(obj, sw_device, li_device))
31
-        # add test collection
32
-        self.all = test_collection(self)
33
-
34
-    def getmembers(self, prefix=''):
35
-        rv = []
36
-        for name, obj in inspect.getmembers(self):
37
-            if prefix:
38
-                full_name = prefix + '.' + name
39
-            else:
40
-                full_name = name
41
-            if not name.startswith('_'):
42
-                try:
43
-                    if obj.__class__.__bases__[0].__name__ == "testcase" or obj.__class__.__name__ == "test_collection":
44
-                        rv.append(full_name)
45
-                    else:
46
-                        rv.extend(obj.getmembers(full_name))
47
-                except AttributeError:
48
-                    pass
49
-        return rv
50
-
51
-    def getobjbyname(self, name):
52
-        if name.startswith("test."):
53
-            name = name[5:]
54
-        obj = self
55
-        for subname in name.split('.'):
56
-            obj = getattr(obj, subname)
57
-        return obj
58
-
59
-    def command(self, full_command):
60
-        try:
61
-            parameter = " " + full_command.split(' ')[1]
62
-        except IndexError:
63
-            parameter = ""
64
-        command = full_command.split(' ')[0].split('.')[-1] + parameter
65
-        device_name = '.'.join(full_command.split(' ')[0].split('.')[:-1])
66
-        self.getobjbyname(device_name).command(command)
67
-
68
-
69
-class test_result_base(object):
70
-    def __init__(self):
71
-        self.__init_test_counters__()
72
-
73
-    def __init_test_counters__(self):
74
-        self.test_counter = 0
75
-        self.success_tests = 0
76
-        self.failed_tests = 0
77
-
78
-    def statistic(self):
79
-        return (self.test_counter, self.success_tests, self.failed_tests)
80
-
81
-    def print_statistic(self):
82
-        color = COLOR_SUCCESS if self.test_counter == self.success_tests else COLOR_FAIL
83
-        print(color + "*** SUCCESS: (%4d/%4d)   FAIL: (%4d/%4d) ***\n" % (self.success_tests,
84
-              self.test_counter, self.failed_tests, self.test_counter) + colored.attr("reset"))
85
-
86
-
87
-class test_collection(test_result_base):
88
-    def __init__(self, test_instance):
89
-        super().__init__()
90
-        self.test_instance = test_instance
91
-
92
-    def capabilities(self):
93
-        return [TEST_FULL, TEST_SMOKE]
94
-
95
-    def command(self, command):
96
-        self.__init_test_counters__()
97
-        for member in self.test_instance.getmembers():
98
-            obj = self.test_instance.getobjbyname(member)
99
-            if id(obj) != id(self):
100
-                obj.test_all(command)
101
-                num, suc, fail = obj.statistic()
102
-                self.test_counter += num
103
-                self.success_tests += suc
104
-                self.failed_tests += fail
105
-        self.print_statistic()
106
-
107
-
108
-class testcase(test_result_base):
109
-    def __init__(self):
110
-        super().__init__()
111
-        self.__test_list__ = []
112
-
113
-    def capabilities(self):
114
-        if len(self.__test_list__) > 0 and not 'test_all' in self.__test_list__:
115
-            self.__test_list__.append('test_all')
116
-        self.__test_list__.sort()
117
-        return self.__test_list__
118
-
119
-    def test_all(self, test=TEST_FULL):
120
-        test_counter = 0
121
-        success_tests = 0
122
-        failed_tests = 0
123
-        for tc_name in self.capabilities():
124
-            if tc_name != "test_all":
125
-                self.command(tc_name, test)
126
-                test_counter += self.test_counter
127
-                success_tests += self.success_tests
128
-                failed_tests += self.failed_tests
129
-        self.test_counter = test_counter
130
-        self.success_tests = success_tests
131
-        self.failed_tests = failed_tests
132
-
133
-    def command(self, command, test=TEST_FULL):
134
-        self.__init_test_counters__()
135
-        tc = getattr(self, command)
136
-        self.__init_test_counters__()
137
-        rv = tc(test)
138
-        self.print_statistic()
139
-
140
-    def heading(self, desciption):
141
-        print(desciption)
142
-
143
-    def sub_heading(self, desciption):
144
-        print(2 * " " + desciption)
145
-
146
-    def result(self, desciption, success):
147
-        self.test_counter += 1
148
-        if success:
149
-            self.success_tests += 1
150
-        else:
151
-            self.failed_tests += 1
152
-        print(4 * " " + ("SUCCESS - " if success else "FAIL    - ") + desciption)
153
-
154
-
155
-class testcase_light(testcase):
156
-    def __init__(self, videv, sw_device, li_device):
157
-        self.videv = videv
158
-        self.sw_device = sw_device
159
-        self.li_device = li_device
160
-        self.__test_list__ = []
161
-        if self.videv.enable_state:
162
-            self.__test_list__.append('test_power_on_off')
163
-        if self.videv.enable_brightness:
164
-            self.__test_list__.append('test_brightness')
165
-        if self.videv.enable_color_temp:
166
-            self.__test_list__.append('test_color_temp')
167
-
168
-    def test_power_on_off(self, test=TEST_FULL):
169
-        self.heading("Power On/ Off test (%s)" % self.videv.topic)
170
-        #
171
-        sw_state = self.sw_device.get_data(self.sw_device.KEY_OUTPUT_0)
172
-        #
173
-        for i in range(0, 2):
174
-            self.sub_heading("State change of switching device")
175
-            #
176
-            self.sw_device.store_data(**{self.sw_device.KEY_OUTPUT_0: not self.sw_device.data.get(self.sw_device.KEY_OUTPUT_0)})
177
-            time.sleep(DT_TOGGLE)
178
-            self.result("Virtual device state after Switch on by switching device", sw_state != self.videv.get_data(self.videv.KEY_STATE))
179
-            self.result("Switching device state after Switch on by switching device",
180
-                        sw_state != self.sw_device.get_data(self.sw_device.KEY_OUTPUT_0))
181
-
182
-            self.sub_heading("State change of virtual device")
183
-            #
184
-            self.videv.send(self.videv.KEY_STATE, not self.videv.data.get(self.videv.KEY_STATE))
185
-            time.sleep(DT_TOGGLE)
186
-            self.result("Virtual device state after Switch off by virtual device", sw_state == self.videv.get_data(self.videv.KEY_STATE))
187
-            self.result("Switching device state after Switch on by switching device",
188
-                        sw_state == self.sw_device.get_data(self.sw_device.KEY_OUTPUT_0))
189
-
190
-    def test_brightness(self, test=TEST_FULL):
191
-        self.heading("Brightness test (%s)" % self.videv.topic)
192
-        #
193
-        br_state = self.li_device.get_data(self.li_device.KEY_BRIGHTNESS)
194
-        delta = -15 if br_state > 50 else 15
195
-
196
-        self.sw_device.store_data(**{self.sw_device.KEY_OUTPUT_0: True})
197
-        time.sleep(DT_TOGGLE)
198
-
199
-        for i in range(0, 2):
200
-            self.sub_heading("Brightness change by light device")
201
-            #
202
-            self.li_device.store_data(**{self.li_device.KEY_BRIGHTNESS: br_state + delta})
203
-            time.sleep(DT_TOGGLE)
204
-            self.result("Virtual device state after setting brightness by light device",
205
-                        br_state + delta == self.videv.get_data(self.videv.KEY_BRIGHTNESS))
206
-            self.result("Light device state after setting brightness by light device", br_state +
207
-                        delta == self.li_device.get_data(self.li_device.KEY_BRIGHTNESS))
208
-
209
-            self.sub_heading("Brightness change by virtual device")
210
-            #
211
-            self.videv.send(self.videv.KEY_BRIGHTNESS, br_state)
212
-            time.sleep(DT_TOGGLE)
213
-            self.result("Virtual device state after setting brightness by light device", br_state == self.videv.get_data(self.videv.KEY_BRIGHTNESS))
214
-            self.result("Light device state after setting brightness by light device",
215
-                        br_state == self.li_device.get_data(self.li_device.KEY_BRIGHTNESS))
216
-
217
-        self.sw_device.store_data(**{self.sw_device.KEY_OUTPUT_0: False})
218
-        time.sleep(DT_TOGGLE)
219
-
220
-    def test_color_temp(self, test=TEST_FULL):
221
-        self.heading("Color temperature test (%s)" % self.videv.topic)
222
-        #
223
-        ct_state = self.li_device.get_data(self.li_device.KEY_COLOR_TEMP)
224
-        delta = -3 if ct_state > 5 else 3
225
-
226
-        self.sw_device.store_data(**{self.sw_device.KEY_OUTPUT_0: True})
227
-        time.sleep(DT_TOGGLE)
228
-
229
-        for i in range(0, 2):
230
-            self.sub_heading("Color temperature change by light device")
231
-            #
232
-            self.li_device.store_data(**{self.li_device.KEY_COLOR_TEMP: ct_state + delta})
233
-            time.sleep(DT_TOGGLE)
234
-            self.result("Virtual device state after setting color temperature by light device",
235
-                        ct_state + delta == self.videv.get_data(self.videv.KEY_COLOR_TEMP))
236
-            self.result("Light device state after setting color temperature by light device", ct_state +
237
-                        delta == self.li_device.get_data(self.li_device.KEY_COLOR_TEMP))
238
-
239
-            self.sub_heading("Color temperature change by virtual device")
240
-            #
241
-            self.videv.send(self.videv.KEY_COLOR_TEMP, ct_state)
242
-            time.sleep(DT_TOGGLE)
243
-            self.result("Virtual device state after setting color temperature by light device",
244
-                        ct_state == self.videv.get_data(self.videv.KEY_COLOR_TEMP))
245
-            self.result("Light device state after setting color temperature by light device",
246
-                        ct_state == self.li_device.get_data(self.li_device.KEY_COLOR_TEMP))
247
-
248
-        self.sw_device.store_data(**{self.sw_device.KEY_OUTPUT_0: False})
249
-        time.sleep(DT_TOGGLE)

+ 0
- 84
house_n_gui_sim.py Переглянути файл

@@ -1,84 +0,0 @@
1
-import config
2
-import logging
3
-import mqtt
4
-import readline
5
-import report
6
-from __simulation__.rooms import house
7
-from __simulation__.test import test_smarthome
8
-import time
9
-
10
-if __name__ == "__main__":
11
-    report.stdoutLoggingConfigure(((config.APP_NAME, logging.WARNING), ), report.SHORT_FMT)
12
-    #
13
-    mc = mqtt.mqtt_client(host=config.MQTT_SERVER, port=config.MQTT_PORT, username=config.MQTT_USER,
14
-                          password=config.MQTT_PASSWORD, name=config.APP_NAME + '_simulation')
15
-    #
16
-    COMMANDS = ['quit', 'help']
17
-    #
18
-    h = house(mc)
19
-    for name in h.getmembers():
20
-        d = h.getobjbyname(name)
21
-        for c in d.capabilities():
22
-            COMMANDS.append(name + '.' + c)
23
-    #
24
-    ts = test_smarthome(h)
25
-    for name in ts.getmembers():
26
-        d = ts.getobjbyname(name)
27
-        for c in d.capabilities():
28
-            COMMANDS.append('test.' + name + '.' + c)
29
-
30
-    def reduced_list(text):
31
-        """
32
-        Create reduced completation list
33
-        """
34
-        reduced_list = {}
35
-        for cmd in COMMANDS:
36
-            next_dot = cmd[len(text):].find('.')
37
-            if next_dot >= 0:
38
-                reduced_list[cmd[:len(text) + next_dot + 1]] = None
39
-            else:
40
-                reduced_list[cmd] = None
41
-        return reduced_list.keys()
42
-
43
-    def completer(text, state):
44
-        """
45
-        Our custom completer function
46
-        """
47
-        options = [x for x in reduced_list(text) if x.startswith(text)]
48
-        return options[state]
49
-
50
-    def complete(text, state):
51
-        for cmd in COMMANDS:
52
-            if cmd.startswith(text):
53
-                if not state:
54
-                    hit = ""
55
-                    index = 0
56
-                    sub_list = cmd.split('.')
57
-                    while len(text) >= len(hit):
58
-                        hit += sub_list[index] + '.'
59
-                    return hit  # cmd
60
-                else:
61
-                    state -= 1
62
-
63
-    readline.parse_and_bind("tab: complete")
64
-    readline.set_completer(completer)
65
-    time.sleep(0.3)
66
-    print("\nEnter command: ")
67
-
68
-    while True:
69
-        userfeedback = input('')
70
-        command = userfeedback.split(' ')[0]
71
-        if userfeedback == 'quit':
72
-            break
73
-        elif userfeedback == 'help':
74
-            print("Help is not yet implemented!")
75
-        elif userfeedback.startswith("test"):
76
-            ts.command(userfeedback)
77
-        elif userfeedback == 'test.smoke':
78
-            ts.smoke()
79
-        elif command in COMMANDS[2:]:
80
-            h.command(userfeedback)
81
-        elif userfeedback != "":
82
-            print("Unknown command!")
83
-        else:
84
-            print()

Завантаження…
Відмінити
Зберегти