forked from cyberjunky/python-plugwise
/
stick.py
883 lines (837 loc) · 38.8 KB
/
stick.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
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
"""
Use of this source code is governed by the MIT license found in the LICENSE file.
Main stick object to control associated plugwise plugs
"""
import logging
import time
import serial
import sys
import threading
from datetime import datetime, timedelta
from plugwise.constants import (
ACK_ERROR,
ACK_TIMEOUT,
CB_NEW_NODE,
MAX_TIME_DRIFT,
MESSAGE_TIME_OUT,
MESSAGE_RETRY,
NODE_TYPE_STICK,
NODE_TYPE_CIRCLE_PLUS,
NODE_TYPE_CIRCLE,
NODE_TYPE_SWITCH,
NODE_TYPE_SENSE,
NODE_TYPE_SCAN,
NODE_TYPE_STEALTH,
SLEEP_TIME,
WATCHDOG_DEAMON,
)
from plugwise.connections.socket import SocketConnection
from plugwise.connections.serial import PlugwiseUSBConnection
from plugwise.exceptions import (
CirclePlusError,
NetworkDown,
PortError,
StickInitError,
TimeoutException,
)
from plugwise.message import PlugwiseMessage
from plugwise.messages.requests import (
CirclePlusScanRequest,
CircleCalibrationRequest,
CirclePlusRealTimeClockGetRequest,
CirclePlusRealTimeClockSetRequest,
CirclePowerUsageRequest,
CircleSwitchRequest,
NodeClockGetRequest,
NodeClockSetRequest,
NodeInfoRequest,
NodePingRequest,
NodeRequest,
StickInitRequest,
)
from plugwise.messages.responses import (
CircleScanResponse,
CircleCalibrationResponse,
CirclePlusRealTimeClockResponse,
CirclePowerUsageResponse,
CircleSwitchResponse,
NodeClockResponse,
NodeInfoResponse,
NodePingResponse,
NodeResponse,
StickInitResponse,
)
from plugwise.parser import PlugwiseParser
from plugwise.node import PlugwiseNode
from plugwise.nodes.circle import PlugwiseCircle
from plugwise.nodes.circle_plus import PlugwiseCirclePlus
from plugwise.nodes.stealth import PlugwiseStealth
from plugwise.util import inc_seq_id, validate_mac
from queue import Queue
class stick(object):
"""
Plugwise connection stick
"""
def __init__(self, port, callback=None, print_progress=False):
self.logger = logging.getLogger("python-plugwise")
self._mac_stick = None
self.port = port
self.network_online = False
self.circle_plus_mac = None
self._circle_plus_discovered = False
self._circle_plus_retries = 0
self.network_id = None
self.parser = PlugwiseParser(self)
self._plugwise_nodes = {}
self._nodes_registered = 0
self._nodes_to_discover = {}
self._nodes_not_discovered = {}
self._stick_initialized = False
self._stick_callbacks = {}
self.last_ack_seq_id = None
self.expected_responses = {}
self.print_progress = print_progress
self.timezone_delta = datetime.now().replace(
minute=0, second=0, microsecond=0
) - datetime.utcnow().replace(minute=0, second=0, microsecond=0)
self._run_receive_timeout_thread = False
self._run_send_message_thread = False
self._run_update_thread = False
if callback:
self.auto_initialize(callback)
def auto_initialize(self, callback=None):
""" automatic initialization """
def init_finished():
if not self.network_online:
self.logger.Error("plugwise Zigbee network down")
else:
if self.print_progress:
print("Scan Plugwise network")
self.scan(callback)
try:
if self.print_progress:
print("Open port")
self.connect()
if self.print_progress:
print("Initialize Plugwise USBstick")
self.initialize_stick(init_finished)
except PortError as e:
self.logger.error("Failed to connect: '%s'", e)
except StickInitError as e:
self.logger.error("Failed to initialize USBstick: '%s'", e)
except NetworkDown as e:
self.logger.error("Failed to communicated: Plugwise Zigbee network")
except TimeoutException as e:
self.logger.error("Timeout exception while initializing USBstick")
except Exception as e:
self.logger.error("Unknown error : %s", e)
def connect(self, callback=None):
""" Connect to stick and raise error if it fails"""
self.init_callback = callback
# Open connection to USB Stick
if ":" in self.port:
self.logger.debug("Open socket connection to Plugwise Zigbee stick")
self.connection = SocketConnection(self.port, self)
else:
self.logger.debug("Open USB serial connection to Plugwise Zigbee stick")
self.connection = PlugwiseUSBConnection(self.port, self)
self.connection.connect()
self.logger.debug("Starting threads...")
# receive timeout deamon
self._run_receive_timeout_thread = True
self._receive_timeout_thread = threading.Thread(
None, self._receive_timeout_loop, "receive_timeout_thread", (), {}
)
self._receive_timeout_thread.daemon = True
self._receive_timeout_thread.start()
# send deamon
self._send_message_queue = Queue()
self._run_send_message_thread = True
self._send_message_thread = threading.Thread(
None, self._send_message_loop, "send_messages_thread", (), {}
)
self._send_message_thread.daemon = True
self._send_message_thread.start()
# update deamon
self._run_update_thread = False
self._auto_update_timer = None
self._update_thread = threading.Thread(
None, self._update_loop, "update_thread", (), {}
)
self._update_thread.daemon = True
self.logger.debug("All threads started")
def initialize_stick(self, callback=None, timeout=MESSAGE_TIME_OUT):
# Initialize USBstick
if not self.connection.is_connected():
raise StickInitError
def cb_stick_initialized():
""" Callback when initialization of Plugwise USBstick is finished """
self._stick_initialized = True
# Start watchdog deamon
self._run_watchdog = True
self._watchdog_thread = threading.Thread(
None, self._watchdog_loop, "watchdog_thread", (), {}
)
self._watchdog_thread.daemon = True
self._watchdog_thread.start()
# Try to discover Circle+
if self.circle_plus_mac:
self.discover_node(self.circle_plus_mac)
if callback:
callback()
self.logger.debug("Send init request to Plugwise Zigbee stick")
self.send(StickInitRequest(), cb_stick_initialized)
time_counter = 0
while not self._stick_initialized and (time_counter < timeout):
time_counter += 0.1
time.sleep(0.1)
if not self._stick_initialized:
raise StickInitError
if not self.network_online:
raise NetworkDown
def initialize_circle_plus(self, callback=None, timeout=MESSAGE_TIME_OUT):
# Initialize Circle+
if (
not self.connection.is_connected()
or not self._stick_initialized
or not self.circle_plus_mac
):
raise StickInitError
# discover circle+ node
self.discover_node(self.circle_plus_mac)
time_counter = 0
while not self._circle_plus_discovered and (time_counter < timeout):
time_counter += 0.1
time.sleep(0.1)
if not self._circle_plus_discovered:
raise CirclePlusError
def disconnect(self):
""" Disconnect from stick and raise error if it fails"""
self._run_watchdog = False
self._run_update_thread = False
self._auto_update_timer = None
self._run_send_message_thread = False
self._run_receive_timeout_thread = False
self.connection.disconnect()
def subscribe_stick_callback(self, callback, callback_type):
""" Subscribe callback to execute """
if callback_type not in self._stick_callbacks:
self._stick_callbacks[callback_type] = []
self._stick_callbacks[callback_type].append(callback)
def unsubscribe_stick_callback(self, callback, callback_type):
""" Register callback to execute """
if callback_type in self._stick_callbacks:
self._stick_callbacks[callback_type].remove(callback)
def do_callback(self, callback_type, callback_arg=None):
""" Execute callbacks registered for specified callback type """
if callback_type in self._stick_callbacks:
for callback in self._stick_callbacks[callback_type]:
try:
if callback_arg is None:
callback()
else:
callback(callback_arg)
except Exception as e:
self.logger.error("Error while executing callback : %s", e)
def _discover_after_scan(self):
""" Helper to do callback for new node """
node_discovered = None
for mac in self._nodes_not_discovered.keys():
if self._plugwise_nodes.get(mac, None):
node_discovered = mac
break
if node_discovered:
del self._nodes_not_discovered[node_discovered]
self.do_callback(CB_NEW_NODE, node_discovered)
def registered_nodes(self) -> int:
""" Return number of nodes registered in Circle+ """
# Include Circle+ too
return self._nodes_registered + 1
def nodes(self) -> list:
""" Return list of mac addresses of discovered and supported plugwise nodes """
return list(dict(filter(lambda item: item[1] is not None, self._plugwise_nodes.items())).keys())
def node(self, mac : str) -> PlugwiseNode:
""" Return specific Plugwise node object"""
return self._plugwise_nodes.get(mac, None)
def discover_node(self, mac: str, callback=None) -> bool:
""" Discovery of plugwise node """
if validate_mac(mac) == True:
if mac not in self._plugwise_nodes.keys():
if mac not in self._nodes_not_discovered.keys():
self._nodes_not_discovered[mac] = (
None,
None,
)
self.send(
NodeInfoRequest(bytes(mac, "ascii")), callback,
)
return True
else:
return False
else:
return False
def scan(self, callback=None):
""" scan for connected plugwise nodes """
def scan_finished(nodes_to_discover):
""" Callback when scan is finished """
time.sleep(1)
self.logger.debug("Scan plugwise network finished")
self._nodes_discovered = 0
self._nodes_to_discover = nodes_to_discover
self._nodes_registered = len(nodes_to_discover)
self._discovery_finished = False
def node_discovered():
self._nodes_discovered += 1
self.logger.debug(
"Discovered Plugwise node %s of %s",
str(len(self._plugwise_nodes)),
str(len(self._nodes_to_discover)),
)
if (len(self._plugwise_nodes) - 1) >= len(self._nodes_to_discover):
self._discovery_finished = True
self._nodes_to_discover = {}
self._nodes_not_discovered = {}
if callback:
callback()
def timeout_expired():
if not self._discovery_finished:
for mac in self._nodes_to_discover:
if mac not in self._plugwise_nodes.keys():
self.logger.warning(
"Failed to discover registered Plugwise node with MAC '%s' before timeout expired.",
str(mac),
)
else:
if mac in self._nodes_not_discovered:
del self._nodes_not_discovered[mac]
if callback:
callback()
# setup timeout for loading nodes
discover_timeout = (
10 + (len(nodes_to_discover) * 2) + (MESSAGE_TIME_OUT * MESSAGE_RETRY)
)
self.discover_timeout = threading.Timer(
discover_timeout, timeout_expired
).start()
self.logger.debug("Start discovery of linked node types...")
for mac in nodes_to_discover:
self.discover_node(mac, node_discovered)
def scan_circle_plus():
"""Callback when Circle+ is discovered"""
if self._plugwise_nodes.get(self.circle_plus_mac):
if self.print_progress:
print("Scan Circle+ for linked nodes")
self.logger.debug("Scan Circle+ for linked nodes...")
self._plugwise_nodes[self.circle_plus_mac].scan_for_nodes(scan_finished)
else:
self.logger.error(
"Circle+ is not discovered in %s", self._plugwise_nodes
)
# Discover Circle+
if self.circle_plus_mac:
if self._plugwise_nodes.get(self.circle_plus_mac):
scan_circle_plus()
else:
if self.print_progress:
print("Discover Circle+")
self.logger.debug("Discover Circle+ at %s", self.circle_plus_mac)
self.discover_node(self.circle_plus_mac, scan_circle_plus)
else:
self.logger.error(
"Plugwise stick not properly initialized, Circle+ MAC is missing."
)
def _append_node(self, mac, address, node_type):
""" Add Plugwise node to be controlled """
self.logger.debug(
"Add new node type (%s) with mac %s", str(node_type), mac,
)
if node_type == NODE_TYPE_CIRCLE:
if self.print_progress:
print("Circle node found using mac " + mac)
self._plugwise_nodes[mac] = PlugwiseCircle(mac, address, self)
elif node_type == NODE_TYPE_CIRCLE_PLUS:
if self.print_progress:
print("Circle+ node found using mac " + mac)
self._plugwise_nodes[mac] = PlugwiseCirclePlus(mac, address, self)
elif node_type == NODE_TYPE_STEALTH:
if self.print_progress:
print("Stealth node found using mac " + mac)
self._plugwise_nodes[mac] = PlugwiseStealth(mac, address, self)
else:
self.logger.warning("Unsupported node type '%s'", str(node_type))
self._plugwise_nodes[mac] = None
def _remove_node(self, mac):
"""
remove circle from stick
:return: None
"""
if mac in self._plugwise_nodes:
del self._plugwise_nodes[mac]
def feed_parser(self, data):
""" Feed parser with new data """
assert isinstance(data, bytes)
self.parser.feed(data)
def send(self, request, callback=None, retry_counter=0):
"""
Submit request message into Plugwise Zigbee network and queue expected response
"""
assert isinstance(request, NodeRequest)
if isinstance(request, CirclePowerUsageRequest):
response_message = CirclePowerUsageResponse()
elif isinstance(request, NodeInfoRequest):
response_message = NodeInfoResponse()
elif isinstance(request, NodePingRequest):
response_message = NodePingResponse()
elif isinstance(request, CircleSwitchRequest):
response_message = CircleSwitchResponse()
elif isinstance(request, CircleCalibrationRequest):
response_message = CircleCalibrationResponse()
elif isinstance(request, CirclePlusScanRequest):
response_message = CircleScanResponse()
elif isinstance(request, CirclePlusRealTimeClockGetRequest):
response_message = CirclePlusRealTimeClockResponse()
elif isinstance(request, NodeClockGetRequest):
response_message = NodeClockResponse()
elif isinstance(request, StickInitRequest):
response_message = StickInitResponse()
else:
response_message = None
self._send_message_queue.put(
[response_message, request, callback, retry_counter, None,]
)
def _send_message_loop(self):
""" deamon to send messages in queue """
while self._run_send_message_thread:
request_set = self._send_message_queue.get(block=True)
if self.last_ack_seq_id:
# Calc new seq_id based last received ack messsage
seq_id = inc_seq_id(self.last_ack_seq_id)
else:
# first message, so use a fake seq_id
seq_id = b"0000"
self.expected_responses[seq_id] = request_set
if not isinstance(request_set[1], StickInitRequest):
mac = request_set[1].mac.decode("ascii")
self.logger.debug(
"send %s to %s using seq_id %s",
request_set[1].__class__.__name__,
mac,
str(seq_id),
)
if self._plugwise_nodes.get(mac):
self._plugwise_nodes[mac].last_request = datetime.now()
if self.expected_responses[seq_id][3] > 0:
self.logger.debug(
"Retry %s for message %s to %s",
str(self.expected_responses[seq_id][3]),
str(self.expected_responses[seq_id][1].__class__.__name__),
self.expected_responses[seq_id][1].mac.decode("ascii"),
)
else:
self.logger.debug(
"send StickInitRequest using seq_id %s", str(seq_id),
)
self.expected_responses[seq_id][4] = datetime.now()
self.connection.send(request_set[1])
time.sleep(SLEEP_TIME)
timeout_counter = 0
# Wait max 1 second for acknowledge response
while (
self.last_ack_seq_id != seq_id
and timeout_counter <= 10
and seq_id != b"0000"
and self.last_ack_seq_id != None
):
time.sleep(0.1)
timeout_counter += 1
if timeout_counter > 10 and self._run_send_message_thread:
if seq_id in self.expected_responses:
if self.expected_responses[seq_id][3] <= MESSAGE_RETRY:
self.logger.info(
"Resend %s for %s because stick did not acknowledge request (%s)",
str(self.expected_responses[seq_id][1].__class__.__name__),
self.expected_responses[seq_id][1].mac.decode("ascii"),
str(seq_id),
)
self.send(
self.expected_responses[seq_id][1],
self.expected_responses[seq_id][2],
self.expected_responses[seq_id][3] + 1,
)
else:
self.logger.info(
"Drop %s request for mac %s because max (%s) retries reached",
self.expected_responses[seq_id][1].__class__.__name__,
self.expected_responses[seq_id][1].mac.decode("ascii"),
str(MESSAGE_RETRY),
)
del self.expected_responses[seq_id]
def _receive_timeout_loop(self):
""" deamon to time out receive messages """
while self._run_receive_timeout_thread:
for seq_id in list(self.expected_responses.keys()):
if isinstance(self.expected_responses[seq_id][1], StickInitRequest):
if self._cb_stick_initialized:
self._cb_stick_initialized()
del self.expected_responses[seq_id]
elif isinstance(
self.expected_responses[seq_id][1], NodeClockSetRequest
):
del self.expected_responses[seq_id]
elif isinstance(
self.expected_responses[seq_id][1],
CirclePlusRealTimeClockSetRequest,
):
del self.expected_responses[seq_id]
else:
if self.expected_responses[seq_id][4] != None:
if self.expected_responses[seq_id][4] < (
datetime.now() - timedelta(seconds=MESSAGE_TIME_OUT)
):
self.logger.debug(
"Timeout expired for message with sequence ID %s",
str(seq_id),
)
if self.expected_responses[seq_id][3] <= MESSAGE_RETRY:
self.logger.debug(
"Resend request %s",
str(
self.expected_responses[seq_id][
1
].__class__.__name__
),
)
self.send(
self.expected_responses[seq_id][1],
self.expected_responses[seq_id][2],
self.expected_responses[seq_id][3] + 1,
)
else:
self.logger.info(
"Drop %s request for mac %s because max (%s) retries reached",
self.expected_responses[seq_id][
1
].__class__.__name__,
self.expected_responses[seq_id][1].mac.decode(
"ascii"
),
str(MESSAGE_RETRY),
)
del self.expected_responses[seq_id]
time.sleep(MESSAGE_TIME_OUT)
def new_message(self, message):
""" Received message from Plugwise Zigbee network """
assert isinstance(message, NodeResponse)
self.logger.debug(
"New %s message with seq id %s for %s",
message.__class__.__name__,
str(message.seq_id),
message.mac.decode("ascii"),
)
mac = message.mac.decode("ascii")
if isinstance(message, StickInitResponse):
self._mac_stick = message.mac
if message.network_is_online.value == 1:
self.network_online = True
else:
self.network_online = False
# Replace first 2 charactors by 00 for mac of circle+ node
self.circle_plus_mac = "00" + message.circle_plus_mac.value[2:].decode(
"ascii"
)
self.network_id = message.network_id.value
# The first StickInitResponse gives the actual sequence ID
if b"0000" in self.expected_responses:
seq_id = b"0000"
else:
seq_id = message.seq_id
self.message_processed(seq_id)
elif isinstance(message, NodeInfoResponse):
if not mac in self._plugwise_nodes:
if message.node_type.value == NODE_TYPE_CIRCLE_PLUS:
self._circle_plus_discovered = True
self._append_node(mac, 0, message.node_type.value)
if mac in self._nodes_not_discovered:
del self._nodes_not_discovered[mac]
else:
for mac_to_discover in self._nodes_to_discover:
if mac == mac_to_discover:
self._append_node(mac, self._nodes_to_discover[mac_to_discover], message.node_type.value)
if self._plugwise_nodes.get(mac):
self._plugwise_nodes[mac].on_message(message)
else:
if self._plugwise_nodes.get(mac):
self._plugwise_nodes[mac].on_message(message)
def message_processed(self, seq_id, ack_response=None):
""" Execute callback of received messages """
if seq_id in self.expected_responses:
# excute callback at response of message
self.logger.debug(
"%s request with seq id %s processed",
self.expected_responses[seq_id][0].__class__.__name__,
str(seq_id),
)
if isinstance(self.expected_responses[seq_id][1], StickInitRequest):
if self.expected_responses[seq_id][2]:
self.expected_responses[seq_id][2]()
else:
if ack_response == ACK_TIMEOUT:
if self.expected_responses[seq_id][3] <= MESSAGE_RETRY:
mac = self.expected_responses[seq_id][1].mac.decode("ascii")
self.logger.debug(
"Network time out received for (%s of %s) of %s to %s, resend request",
str(self.expected_responses[seq_id][3] + 1),
str(MESSAGE_RETRY + 1),
str(self.expected_responses[seq_id][1].__class__.__name__),
mac,
)
if self._plugwise_nodes.get(mac):
if self._plugwise_nodes[mac].get_available():
self.send(
self.expected_responses[seq_id][1],
self.expected_responses[seq_id][2],
self.expected_responses[seq_id][3] + 1,
)
else:
self.logger.debug(
"Max (%s) network time out messages received for %s to %s, drop request",
str(self.expected_responses[seq_id][3] + 1),
str(self.expected_responses[seq_id][1].__class__.__name__),
self.expected_responses[seq_id][1].mac.decode("ascii"),
)
# Mark node as unavailable
mac = self.expected_responses[seq_id][1].mac.decode("ascii")
if self._plugwise_nodes.get(mac):
if self._plugwise_nodes[mac].get_available():
self.logger.info(
"Mark %s as unavailabe because %s time out responses reached",
mac,
str(MESSAGE_RETRY + 1),
)
self._plugwise_nodes[mac].set_available(False)
elif ack_response == ACK_ERROR:
mac = self.expected_responses[seq_id][1].mac.decode("ascii")
if self.expected_responses[seq_id][3] <= MESSAGE_RETRY:
self.logger.debug(
"Error response received for (%s of %s) of %s to %s, resend request",
str(self.expected_responses[seq_id][3] + 1),
str(MESSAGE_RETRY + 1),
str(self.expected_responses[seq_id][1].__class__.__name__),
mac,
)
if self._plugwise_nodes.get(mac):
if self._plugwise_nodes[mac].get_available():
self.send(
self.expected_responses[seq_id][1],
self.expected_responses[seq_id][2],
self.expected_responses[seq_id][3] + 1,
)
else:
self.logger.debug(
"Error response received for (%s of %s) of %s to %s, drop request",
str(self.expected_responses[seq_id][3] + 1),
str(MESSAGE_RETRY + 1),
str(self.expected_responses[seq_id][1].__class__.__name__),
mac,
)
elif ack_response == None:
if self.expected_responses[seq_id][2]:
try:
self.expected_responses[seq_id][2]()
except Exception as e:
self.logger.error(
"Error while executing callback after processing message : %s",
e,
)
del self.expected_responses[seq_id]
def _watchdog_loop(self):
"""
Main worker loop to watch all other worker threads
"""
time.sleep(5)
circle_plus_retry_counter = 0
while self._run_watchdog:
# Connection
if self.connection.is_connected():
# Connection reader daemon
if not self.connection.read_thread_alive():
self.logger.warning("Unexpected halt of connection reader thread")
# Connection writer daemon
if not self.connection.write_thread_alive():
self.logger.warning("Unexpected halt of connection writer thread")
# receive timeout daemon
if self._run_receive_timeout_thread:
if not self._receive_timeout_thread.isAlive():
self.logger.warning(
"Unexpected halt of receive thread, restart thread",
)
self._receive_timeout_thread = threading.Thread(
None,
self._receive_timeout_loop,
"receive_timeout_thread",
(),
{},
)
self._receive_timeout_thread.daemon = True
self._receive_timeout_thread.start()
# send message deamon
if self._run_send_message_thread:
if not self._send_message_thread.isAlive():
self.logger.warning(
"Unexpected halt of send thread, restart thread",
)
self._send_message_thread = threading.Thread(
None, self._send_message_loop, "send_messages_thread", (), {}
)
self._send_message_thread.daemon = True
self._send_message_thread.start()
# Update daemon
if self._run_update_thread:
if not self._update_thread.isAlive():
self.logger.warning(
"Unexpected halt of update thread, restart thread",
)
self._run_update_thread = True
self._update_thread = threading.Thread(
None, self._update_loop, "update_thread", (), {}
)
self._update_thread.daemon = True
self._update_thread.start()
# Circle+ discovery
if self._circle_plus_discovered == False:
# First hour every once an hour
if self._circle_plus_retries < 60 or circle_plus_retry_counter > 60:
self.logger.info(
"Circle+ not yet discovered, resubmit discovery request",
)
self.discover_node(self.circle_plus_mac, self.scan)
self._circle_plus_retries += 1
circle_plus_retry_counter = 0
circle_plus_retry_counter += 1
time.sleep(WATCHDOG_DEAMON)
def _update_loop(self):
"""
When node has not received any message during
last 2 update polls, reset availability
"""
self._run_update_thread = True
self._auto_update_first_run = True
day_of_month = datetime.now().day
try:
while self._run_update_thread:
for mac in self._plugwise_nodes:
if self._plugwise_nodes[mac]:
# Do ping request
self.logger.debug(
"Send ping to node %s", mac,
)
self._plugwise_nodes[mac].ping()
# Only power use updates for supported nodes
if isinstance(
self._plugwise_nodes[mac], PlugwiseCircle
) or isinstance(self._plugwise_nodes[mac], PlugwiseCirclePlus):
# Don't check at first time
self.logger.debug(
"Request current power usage for node %s", mac
)
if not self._auto_update_first_run and self._run_update_thread:
# Only request update if node is available
if self._plugwise_nodes[mac].get_available():
self.logger.debug(
"Node '%s' is available for update request, last update (%s)",
mac,
str(self._plugwise_nodes[mac].get_last_update()),
)
# Skip update request if there is still an request expected to be received
open_requests_found = False
for seq_id in list(self.expected_responses.keys()):
if isinstance(
self.expected_responses[seq_id][1],
CirclePowerUsageRequest,
):
if mac == self.expected_responses[seq_id][
1
].mac.decode("ascii"):
open_requests_found = True
break
if not open_requests_found:
self._plugwise_nodes[mac].update_power_usage()
# Refresh node info once per hour and request power use afterwards
if self._plugwise_nodes[mac]._last_info_message != None:
if self._plugwise_nodes[mac]._last_info_message < (
datetime.now().replace(
minute=1,
second=MAX_TIME_DRIFT,
microsecond=0,
)
):
self._plugwise_nodes[mac]._request_info(
self._plugwise_nodes[
mac
]._request_power_buffer
)
if not self._plugwise_nodes[mac]._last_log_collected:
self._plugwise_nodes[mac]._request_power_buffer()
else:
if self._run_update_thread:
self.logger.debug(
"First request for current power usage for node %s",
mac,
)
self._plugwise_nodes[mac].update_power_usage()
self._auto_update_first_run = False
# Try to rediscover node(s) which where not available at initial scan
# Do this the first hour at every update, there after only once an hour
for mac in self._nodes_not_discovered:
(firstrequest, lastrequest) = self._nodes_not_discovered[mac]
if firstrequest and lastrequest:
if (firstrequest + timedelta(hours=1)) > datetime.now():
# first hour, so do every update a request
self.discover_node(mac, self._discover_after_scan)
self._nodes_not_discovered[mac] = (
firstrequest,
datetime.now(),
)
else:
if (lastrequest + timedelta(hours=1)) < datetime.now():
self.discover_node(mac, self._discover_after_scan)
self._nodes_not_discovered[mac] = (
firstrequest,
datetime.now(),
)
else:
self.discover_node(mac, self._discover_after_scan)
self._nodes_not_discovered[mac] = (
datetime.now(),
datetime.now(),
)
# Sync internal clock of all available nodes once a day
if datetime.now().day != day_of_month:
day_of_month = datetime.now().day
for mac in self._plugwise_nodes:
if self._plugwise_nodes[mac]:
if self._plugwise_nodes[mac].get_available():
self._plugwise_nodes[mac].sync_clock()
if self._auto_update_timer:
time.sleep(self._auto_update_timer)
except Exception as e:
exc_type, exc_obj, exc_tb = sys.exc_info()
self.logger.error(
"Error at line %s of _update_loop : %s", exc_tb.tb_lineno, e
)
def auto_update(self, timer=None):
"""
setup auto update polling for power usage.
"""
if timer == 0:
self._run_update_thread = False
self._auto_update_timer = None
else:
self._auto_update_timer = 5
if timer == None:
# Timer based on number of nodes and 3 seconds per node
self._auto_update_timer = len(self._plugwise_nodes) * 3
elif timer > 5:
self._auto_update_timer = timer
if not self._run_update_thread:
self._update_thread.start()