forked from OpenZWave/python-openzwave
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnetwork.py
More file actions
executable file
·1674 lines (1356 loc) · 61.9 KB
/
Copy pathnetwork.py
File metadata and controls
executable file
·1674 lines (1356 loc) · 61.9 KB
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
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
"""
.. module:: openzwave.network
This file is part of **python-openzwave** project https://github.com/OpenZWave/python-openzwave.
:platform: Unix, Windows, MacOS X
:sinopsis: openzwave API
.. moduleauthor: bibi21000 aka Sébastien GALLET <[email protected]>
License : GPL(v3)
**python-openzwave** is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
**python-openzwave** is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with python-openzwave. If not, see http://www.gnu.org/licenses.
"""
import os
#from collections import namedtuple
import time
import sys
import six
if six.PY3:
from pydispatch import dispatcher
import _thread as thread
else:
from louie import dispatcher
import thread
import threading
import libopenzwave
import openzwave
from openzwave.object import ZWaveException, ZWaveTypeException, ZWaveObject
from openzwave.controller import ZWaveController
from openzwave.node import ZWaveNode
from openzwave.option import ZWaveOption
from openzwave.scene import ZWaveScene
from openzwave.singleton import Singleton
import json
# Set default logging handler to avoid "No handler found" warnings.
import logging
try: # Python 2.7+
from logging import NullHandler
except ImportError:
class NullHandler(logging.Handler):
"""NullHandler logger for python 2.6"""
def emit(self, record):
pass
logger = logging.getLogger('openzwave')
logger.addHandler(NullHandler())
try:
import sqlite3 as lite
except ImportError:
logger.warning('pysqlite is not installed')
class ZWaveNetwork(ZWaveObject):
"""
The network objet = homeid.
It contains a reference to the manager and the controller.
It dispatch the following louie signals :
* SIGNAL_NETWORK_FAILED = 'NetworkFailed'
* SIGNAL_NETWORK_STARTED = 'NetworkStarted'
* SIGNAL_NETWORK_READY = 'NetworkReady'
* SIGNAL_NETWORK_STOPPED = 'NetworkStopped'
* SIGNAL_NETWORK_RESETTED = 'DriverResetted'
* SIGNAL_NETWORK_AWAKED = 'DriverAwaked'
* SIGNAL_DRIVER_FAILED = 'DriverFailed'
* SIGNAL_DRIVER_READY = 'DriverReady'
* SIGNAL_DRIVER_RESET = 'DriverReset'
* SIGNAL_DRIVER_REMOVED = 'DriverRemoved'
* SIGNAL_NODE_ADDED = 'NodeAdded'
* SIGNAL_NODE_EVENT = 'NodeEvent'
* SIGNAL_NODE_NAMING = 'NodeNaming'
* SIGNAL_NODE_NEW = 'NodeNew'
* SIGNAL_NODE_PROTOCOL_INFO = 'NodeProtocolInfo'
* SIGNAL_NODE_READY = 'NodeReady'
* SIGNAL_NODE_REMOVED = 'NodeRemoved'
* SIGNAL_SCENE_EVENT = 'SceneEvent'
* SIGNAL_VALUE_ADDED = 'ValueAdded'
* SIGNAL_VALUE_CHANGED = 'ValueChanged'
* SIGNAL_VALUE_REFRESHED = 'ValueRefreshed'
* SIGNAL_VALUE_REMOVED = 'ValueRemoved'
* SIGNAL_POLLING_ENABLED = 'PollingEnabled'
* SIGNAL_POLLING_DISABLED = 'PollingDisabled'
* SIGNAL_CREATE_BUTTON = 'CreateButton'
* SIGNAL_DELETE_BUTTON = 'DeleteButton'
* SIGNAL_BUTTON_ON = 'ButtonOn'
* SIGNAL_BUTTON_OFF = 'ButtonOff'
* SIGNAL_ESSENTIAL_NODE_QUERIES_COMPLETE = 'EssentialNodeQueriesComplete'
* SIGNAL_NODE_QUERIES_COMPLETE = 'NodeQueriesComplete'
* SIGNAL_AWAKE_NODES_QUERIED = 'AwakeNodesQueried'
* SIGNAL_ALL_NODES_QUERIED = 'AllNodesQueried'
* SIGNAL_MSG_COMPLETE = 'MsgComplete'
* SIGNAL_ERROR = 'Error'
The table presented below sets notifications in the order they might typically be received,
and grouped into a few logically related categories. Of course, given the variety
of ZWave controllers, devices and network configurations the actual sequence will vary (somewhat).
The descriptions below the notification name (in square brackets) identify whether the
notification is always sent (unless there’s a significant error in the network or software)
or potentially sent during the execution sequence.
Driver Initialization Notification
The notification below is sent when OpenZWave has successfully connected
to a physical ZWave controller.
* DriverReady
[always sent] Sent when the driver (representing a connection between OpenZWave
and a Z-Wave controller attached to the specified serial (or HID) port) has been initialized.
At the time this notification is sent, only certain information about the controller itself is known:
* Controller Z-Wave version
* Network HomeID
* Controller capabilities
* Controller Application Version & Manufacturer/Product ID
* Nodes included in the network
* DriverRemoved
[always sent (either due to Error or by request)] The Driver is being removed.
Do Not Call Any Driver Related Methods after receiving this
Node Initialization Notifications
As OpenZWave starts, it identifies and reads information about each node in the network.
The following notifications may be sent during the initialization process.
* NodeNew
[potentially sent] Sent when a new node has been identified as part of the Z-Wave network.
It is not sent if the node was identified in a prior execution of the OpenZWave library
and stored in the zwcfg*.xml file.
At the time this notification is sent, very little is known about the node itself...
only that it is new to OpenZWave. This message is sent once for each new node identified.
* NodeAdded
[always sent (for each node associated with the controller)]
Sent when a node has been added to OpenZWave’s set of nodes. It can be
triggered either as the zwcfg*.xml file is being read, when a new node
is found on startup (see NodeNew notification above), or if a new node
is included in the network while OpenZWave is running.
As with NodeNew, very little is known about the node at the time the
notification is sent…just the fact that a new node has been identified
and its assigned NodeID.
* NodeProtocolInfo
[potentially sent] Sent after a node’s protocol information has been
successfully read from the controller.
At the time this notification is sent, only certain information about the node is known:
* Whether it is a “listening” or “sleeping” device
* Whether the node is capable of routing messages
* Maximum baud rate for communication
* Version number
* Security byte
NodeNaming
[potentially sent] Sent when a node’s name has been set or changed
(although it may be “set” to “” or NULL).
* ValueAdded
[potentially sent] Sent when a new value has been associated with the node.
At the time this notification is sent, the new value may or may not
have “live” data associated with it. It may be populated, but it may
alternatively just be a placeholder for a value that has not been read
at the time the notification is sent.
* NodeQueriesComplete
[always sent (for each node associated with the controller that has been successfully queried)] Sent when a node’s values and attributes have been fully queried. At the time this notification is sent, the node’s information has been fully read at least once. So this notification might trigger “full” display of the node’s information, values, etc. If this notification is not sent, it indicates that there has been a problem initializing the device. The most common issue is that the node is a “sleeping” device. The NodeQueriesComplete notification will be sent when the node wakes up and the query process completes.
Initialization Complete Notifications
As indicated above, when OpenZWave starts it reads certain information
from a file, from the controller and from the network. The following
notifications identify when this initialization/querying process is complete.
* AwakeNodesQueried
[always sent] Sent when all “listening” -always-on-devices have been
queried successfully. It also indicates, by implication, that there
are some “sleeping” nodes that will not complete their queries until
they wake up. This notification should be sent relatively quickly
after start-up. (Of course, it depends on the number of devices on
the ZWave network and whether there are any messages that “time out”
without a proper response.)
* AllNodesQueried
[potentially sent] Sent when all nodes have been successfully queried.
This notification should be sent relatively quickly if there are
no “sleeping” nodes. But it might be sent quite a while after start-up
if there are sleeping nodes and at least one of these nodes has a long “wake-up” interval.
Other Notifications
In addition to the notifications described above, which are primarily
“initialization” notifications that are sent during program start-up,
the following notifications may be sent as a result of user actions,
external program control, etc.
* ValueChanged : Sent when a value associated with a node has changed. Receipt of this notification indicates that it may be a good time to read the new value and display or otherwise process it accordingly.
* ValueRemoved : Sent when a value associated with a node has been removed.
* Group : Sent when a node’s group association has changed.
* NodeRemoved : Sent when a node has been removed from the ZWave network.
* NodeEvent : Sent when a node sends a Basic_Set command to the controller. This notification can be generated by certain sensors, for example, motion detectors, to indicate that an event has been sensed.
* PollingEnabled : Sent when node/value polling has been enabled.
* PollingDisabled : Sent when node/value polling has been disabled.
* DriverReset : Sent to indicate when a controller has been reset. This notification is intended to replace the potentially hundreds of notifications representing each value and node removed from the network.
About the use of louie signals :
For network, python-openzwave send the following louie signal :
SIGNAL_NETWORK_FAILED : the driver has failed to start.
SIGNAL_NETWORK_STARTED : the driver is ready, but network is not available.
SIGNAL_NETWORK_AWAKED : all awake nodes are queried. Some sleeping nodes may be missing.
SIGNAL_NETWORK_READY : all nodes are queried. Network is fully functionnal.
SIGNAL_NETWORK_RESETTED : the network has been resetted. It will start again.
SIGNAL_NETWORK_STOPPED : the network has been stopped.
Deprecated : SIGNAL_DRIVER_* shouldn't be used anymore.
"""
SIGNAL_NETWORK_FAILED = 'NetworkFailed'
SIGNAL_NETWORK_STARTED = 'NetworkStarted'
SIGNAL_NETWORK_READY = 'NetworkReady'
SIGNAL_NETWORK_STOPPED = 'NetworkStopped'
SIGNAL_NETWORK_RESETTED = 'DriverResetted'
SIGNAL_NETWORK_AWAKED = 'DriverAwaked'
SIGNAL_DRIVER_FAILED = 'DriverFailed'
SIGNAL_DRIVER_READY = 'DriverReady'
SIGNAL_DRIVER_RESET = 'DriverReset'
SIGNAL_DRIVER_REMOVED = 'DriverRemoved'
SIGNAL_GROUP = 'Group'
SIGNAL_NODE = 'Node'
SIGNAL_NODE_ADDED = 'NodeAdded'
SIGNAL_NODE_EVENT = 'NodeEvent'
SIGNAL_NODE_NAMING = 'NodeNaming'
SIGNAL_NODE_NEW = 'NodeNew'
SIGNAL_NODE_PROTOCOL_INFO = 'NodeProtocolInfo'
SIGNAL_NODE_READY = 'NodeReady'
SIGNAL_NODE_REMOVED = 'NodeRemoved'
SIGNAL_SCENE_EVENT = 'SceneEvent'
SIGNAL_VALUE = 'Value'
SIGNAL_VALUE_ADDED = 'ValueAdded'
SIGNAL_VALUE_CHANGED = 'ValueChanged'
SIGNAL_VALUE_REFRESHED = 'ValueRefreshed'
SIGNAL_VALUE_REMOVED = 'ValueRemoved'
SIGNAL_POLLING_ENABLED = 'PollingEnabled'
SIGNAL_POLLING_DISABLED = 'PollingDisabled'
SIGNAL_CREATE_BUTTON = 'CreateButton'
SIGNAL_DELETE_BUTTON = 'DeleteButton'
SIGNAL_BUTTON_ON = 'ButtonOn'
SIGNAL_BUTTON_OFF = 'ButtonOff'
SIGNAL_ESSENTIAL_NODE_QUERIES_COMPLETE = 'EssentialNodeQueriesComplete'
SIGNAL_NODE_QUERIES_COMPLETE = 'NodeQueriesComplete'
SIGNAL_AWAKE_NODES_QUERIED = 'AwakeNodesQueried'
SIGNAL_ALL_NODES_QUERIED = 'AllNodesQueried'
SIGNAL_ALL_NODES_QUERIED_SOME_DEAD = 'AllNodesQueriedSomeDead'
SIGNAL_MSG_COMPLETE = 'MsgComplete'
SIGNAL_NOTIFICATION = 'Notification'
SIGNAL_CONTROLLER_COMMAND = 'ControllerCommand'
SIGNAL_CONTROLLER_WAITING = 'ControllerWaiting'
STATE_STOPPED = 0
STATE_FAILED = 1
STATE_RESETTED = 3
STATE_STARTED = 5
STATE_AWAKED = 7
STATE_READY = 10
ignoreSubsequent = True
def __init__(self, options, log=None, autostart=True, kvals=True):
"""
Initialize zwave network
:param options: Options to use with manager
:type options: ZWaveOption
:param log: A log file (not used. Deprecated
:type log:
:param autostart: should we start the network.
:type autostart: bool
:param autostart: Enable kvals (use pysqlite)
:type autostart: bool
"""
logger.debug("Create network object.")
self.log = log
self._options = options
ZWaveObject.__init__(self, None, self)
self._controller = ZWaveController(1, self, options)
self._manager = libopenzwave.PyManager()
self._manager.create()
self._state = self.STATE_STOPPED
self.nodes = None
self._semaphore_nodes = threading.Semaphore()
self._id_separator = '.'
self.network_event = threading.Event()
self.dbcon = None
if kvals == True:
try:
self.dbcon = lite.connect(os.path.join(self._options.user_path, 'pyozw.sqlite'), check_same_thread=False)
cur = self.dbcon.cursor()
version = cur.execute('SELECT SQLITE_VERSION()').fetchone()
logger.debug("Use sqlite version : %s", version)
self._check_db_tables()
except lite.Error as e:
logger.warning("Can't connect to sqlite database : kvals are disabled - %s", e.args[0])
self._started = False
if autostart:
self.start()
def __str__(self):
"""
The string representation of the node.
:rtype: str
"""
return 'home_id: [%s] controller: [%s]' % \
(self.home_id_str, self.controller)
def _check_db_tables(self):
"""
Check that the tables for "classes" are in database.
:returns: True if operation succeed. False oterwise
:rtype: boolean
"""
if self.dbcon is None:
return False
cur = self.dbcon.cursor()
for mycls in ['ZWaveOption', 'ZWaveOptionSingleton', 'ZWaveNetwork', 'ZWaveNetworkSingleton', 'ZWaveNode', 'ZWaveController', 'ZWaveValue']:
cur.execute("SELECT name FROM sqlite_master WHERE type='table' AND name=?", (mycls,))
data = cur.fetchone()
if data is None:
cur.execute("CREATE TABLE %s(object_id INT, key TEXT, value TEXT)" % mycls)
return True
def start(self):
"""
Start the network object :
- add a watcher
- add a driver
"""
if self._started == True:
return
logger.info("Start Openzwave network.")
self._manager.addWatcher(self.zwcallback)
self._manager.addDriver(self._options.device)
self._started = True
def stop(self, fire=True):
"""
Stop the network object.
- remove the watcher
- remove the driver
- clear the nodes
.. code-block:: python
dispatcher.send(self.SIGNAL_NETWORK_STOPPED, **{'network': self})
"""
if self._started == False:
return
logger.info("Stop Openzwave network.")
if self.controller is not None:
self.controller.stop()
self.write_config()
try:
self._semaphore_nodes.acquire()
self._manager.removeWatcher(self.zwcallback)
try:
self.network_event.wait(1.0)
except AssertionError:
#For gevent AssertionError: Impossible to call blocking function in the event loop callback
pass
self._manager.removeDriver(self._options.device)
try:
self.network_event.wait(1.0)
except AssertionError:
#For gevent AssertionError: Impossible to call blocking function in the event loop callback
pass
for i in range(0, 60):
if self.controller.send_queue_count <= 0:
break
else:
try:
self.network_event.wait(1.0)
except AssertionError:
#For gevent AssertionError: Impossible to call blocking function in the event loop callback
pass
self.nodes = None
except:
import sys, traceback
logger.error('Stop network : %s', traceback.format_exception(*sys.exc_info()))
finally:
self._semaphore_nodes.release()
self._started = False
self._state = self.STATE_STOPPED
try:
self.network_event.wait(1.0)
except AssertionError:
#For gevent AssertionError: Impossible to call blocking function in the event loop callback
pass
if fire:
dispatcher.send(self.SIGNAL_NETWORK_STOPPED, **{'network': self})
def destroy(self):
"""
Destroy the netwok and all related stuff.
"""
if self.dbcon is not None:
self.dbcon.commit()
self.dbcon.close()
self._manager.destroy()
self._options.destroy()
self._manager = None
self._options = None
@property
def home_id(self):
"""
The home_id of the network.
:rtype: int
"""
if self._object_id is None:
return 0
return self._object_id
@home_id.setter
def home_id(self, value):
"""
The home_id of the network.
:param value: new home_id
:type value: int
"""
self._object_id = value
@property
def home_id_str(self):
"""
The home_id of the network as string.
:rtype: str
"""
return "0x%0.8x" % self.home_id
@property
def is_ready(self):
"""
Says if the network is ready for operations.
:rtype: bool
"""
return self._state >= self.STATE_READY
@property
def state(self):
"""
The state of the network. Values may be changed in the future,
only order is important.
You can safely ask node information when state >= STATE_READY
* STATE_STOPPED = 0
* STATE_FAILED = 1
* STATE_RESETTED = 3
* STATE_STARTED = 5
* STATE_AWAKED = 7
* STATE_READY = 10
:rtype: int
"""
return self._state
@state.setter
def state(self, value):
"""
The state of the network. Values may be changed in the future,
only order is important.
* STATE_STOPPED = 0
* STATE_FAILED = 1
* STATE_RESETTED = 3
* STATE_STARTED = 5
* STATE_AWAKED = 7
* STATE_READY = 10
:param value: new state
:type value: int
"""
self._state = value
@property
def state_str(self):
"""
The state of the network. Values may be changed in the future,
only order is important.
You can safely ask node informations when state >= STATE_AWAKED
:rtype: int
"""
if self._state == self.STATE_STOPPED:
return "Network is stopped"
elif self._state == self.STATE_FAILED:
return "Driver failed"
elif self._state == self.STATE_STARTED:
return "Driver initialised"
elif self._state == self.STATE_RESETTED:
return "Driver is reset"
elif self._state == self.STATE_AWAKED:
return "Topology loaded"
elif self._state == self.STATE_READY:
return "Network ready"
else:
return "Unknown state"
@property
def manager(self):
"""
The manager to use to communicate with the lib c++.
:rtype: ZWaveManager
"""
if self._manager is not None:
return self._manager
else:
raise ZWaveException("Manager not initialised")
@property
def controller(self):
"""
The controller of the network.
:return: The controller of the network
:rtype: ZWaveController
"""
if self._controller is not None:
return self._controller
else:
raise ZWaveException("Controller not initialised")
@property
def nodes(self):
"""
The nodes of the network.
:rtype: dict()
"""
return self._nodes
def nodes_to_dict(self, extras=['all']):
"""
Return a dict representation of the network.
:param extras: The extra inforamtions to add
:type extras: []
:returns: A dict
:rtype: dict()
"""
ret = {}
for ndid in self._nodes.keys():
ret[ndid]=self._nodes[ndid].to_dict(extras=extras)
return ret
def to_dict(self, extras=['kvals']):
"""
Return a dict representation of the network.
:param extras: The extra inforamtions to add
:type extras: []
:returns: A dict
:rtype: dict()
"""
ret = {}
ret['state'] = self.state,
ret['state_str'] = self.state_str,
ret['home_id'] = self.home_id_str,
ret['nodes_count'] = self.nodes_count,
if 'kvals' in extras and self.network.dbcon is not None:
vals = self.kvals
for key in vals.keys():
ret[key]=vals[key]
return ret
@nodes.setter
def nodes(self, value):
"""
The nodes of the network.
:param value: The new value
:type value: dict() or None
"""
if type(value) == type(dict()):
self._nodes = value
else:
self._nodes = dict()
def switch_all(self, state):
"""
Method for switching all devices on or off together. The devices must support
the SwitchAll command class. The command is first broadcast to all nodes, and
then followed up with individual commands to each node (because broadcasts are
not routed, the message might not otherwise reach all the nodes).
:param state: True to turn on the switches, False to turn them off
:type state: bool
"""
if state:
self.manager.switchAllOn(self.home_id)
else:
self.manager.switchAllOff(self.home_id)
def test(self, count=1):
"""
Send a number of test messages to every node and record results.
:param count: The number of test messages to send.
:type count: int
"""
self.manager.testNetwork(self.home_id, count)
def heal(self, upNodeRoute=False):
"""
Heal network by requesting nodes rediscover their neighbors.
Sends a ControllerCommand_RequestNodeNeighborUpdate to every node.
Can take a while on larger networks.
:param upNodeRoute: Optional Whether to perform return routes initialization. (default = false).
:type upNodeRoute: bool
:return: True is the ControllerCommand ins sent. False otherwise
:rtype: bool
"""
if self.network.state < self.network.STATE_AWAKED:
logger.warning('Network state must a minimum set to awake')
return False
self.manager.healNetwork(self.home_id, upNodeRoute)
return True
def get_value(self, value_id):
"""
Retrieve a value on the network.
Check every nodes to see if it holds the value
:param value_id: The id of the value to find
:type value_id: int
:return: The value or None
:rtype: ZWaveValue
"""
for node in self.nodes:
if value_id in self.nodes[node].values:
return self.nodes[node].values[value_id]
return None
@property
def id_separator(self):
"""
The separator in id representation.
:rtype: char
"""
return self._id_separator
@id_separator.setter
def id_separator(self, value):
"""
The nodes of the network.
:param value: The new separator
:type value: char
"""
self._id_separator = value
def get_value_from_id_on_network(self, id_on_network):
"""
Retrieve a value on the network from it's id_on_network.
Check every nodes to see if it holds the value
:param id_on_network: The id_on_network of the value to find
:type id_on_network: str
:return: The value or None
:rtype: ZWaveValue
"""
for node in self.nodes.itervalues():
for val in node.values.itervalues():
if val.id_on_network == id_on_network:
return val
return None
def get_scenes(self):
"""
The scenes of the network.
Scenes are generated directly from the lib. There is no notification
support to keep them up to date. So for a batch job, consider
storing them in a local variable.
:return: return a dict() (that can be empty) of scene object. Return None if betwork is not ready
:rtype: dict() or None
"""
if self.state < self.STATE_AWAKED:
return None
else:
return self._load_scenes()
def scenes_to_dict(self, extras=['all']):
"""
Return a JSONifiable dict representation of the scenes.
:param extras: The extra inforamtions to add
:type extras: []
:returns: A dict
:rtype: dict()
"""
ret={}
scenes = self.get_scenes()
for scnid in scenes.keys():
ret[scnid] = scenes[scnid].to_dict(extras=extras)
return ret
def _load_scenes(self):
"""
Load the scenes of the network.
:return: return a dict() (that can be empty) of scene object.
:rtype: dict()
"""
ret = {}
set_scenes = self._manager.getAllScenes()
logger.debug('Load Scenes: %s', set_scenes)
for scene_id in set_scenes:
scene = ZWaveScene(scene_id, network=self)
ret[scene_id] = scene
return ret
def create_scene(self, label=None):
"""
Create a new scene on the network.
If label is set, also change the label of the scene
If you store your scenes on a local variable, get a new one
to get the scene id
:param label: The new label
:type label: str or None
:return: return the id of scene on the network. Return 0 if fails
:rtype: int
"""
scene = ZWaveScene(None, network=self)
return scene.create(label)
def scene_exists(self, scene_id):
"""
Check that the scene exists
:param scene_id: The id of the scene to check
:type scene_id: int
:return: True if the scene exist. False in other cases
:rtype: bool
"""
return self._network.manager.sceneExists(scene_id)
@property
def scenes_count(self):
"""
Return the number of scenes
:return: The number of scenes
:rtype: int
"""
return self._network.manager.getNumScenes()
def remove_scene(self, scene_id):
"""
Delete the scene on the network.
:param scene_id: The id of the scene to check
:type scene_id: int
:return: True if the scene was removed. False in other cases
:rtype: bool
"""
return self._network.manager.removeScene(scene_id)
@property
def nodes_count(self):
"""
The nodes count of the network.
:rtype: int
"""
return len(self.nodes)
@property
def sleeping_nodes_count(self):
"""
The count of sleeping nodes on the network.
:rtype: int
"""
result = 0
for node in self.nodes:
if node.is_sleeping:
result += 1
return result
def get_poll_interval(self):
"""
Get the time period between polls of a nodes state
:return: The number of milliseconds between polls
:rtype: int
"""
return self.manager.getPollInterval()
def set_poll_interval(self, milliseconds=500, bIntervalBetweenPolls=True):
"""
Set the time period between polls of a nodes state.
Due to patent concerns, some devices do not report state changes automatically
to the controller. These devices need to have their state polled at regular
intervals. The length of the interval is the same for all devices. To even
out the Z-Wave network traffic generated by polling, OpenZWave divides the
polling interval by the number of devices that have polling enabled, and polls
each in turn. It is recommended that if possible, the interval should not be
set shorter than the number of polled devices in seconds (so that the network
does not have to cope with more than one poll per second).
:param milliseconds: The length of the polling interval in milliseconds.
:type milliseconds: int
:param bIntervalBetweenPolls: If set to true (via SetPollInterval), the pollInterval will be interspersed between each poll (so a much smaller m_pollInterval like 100, 500, or 1,000 may be appropriate). If false, the library attempts to complete all polls within m_pollInterval.
:type bIntervalBetweenPolls: bool
"""
self.manager.setPollInterval(milliseconds, bIntervalBetweenPolls)
def zwcallback(self, args):
"""
The Callback Handler used with the libopenzwave.
n['valueId'] = {
* 'home_id' : v.GetHomeId(),
* 'node_id' : v.GetNodeId(),
* 'commandClass' : PyManager.COMMAND_CLASS_DESC[v.GetCommandClassId()],
* 'instance' : v.GetInstance(),
* 'index' : v.GetIndex(),
* 'id' : v.GetId(),
* 'genre' : PyGenres[v.GetGenre()],
* 'type' : PyValueTypes[v.GetType()],
* #'value' : value.c_str(),
* 'value' : getValueFromType(manager,v.GetId()),
* 'label' : label.c_str(),
* 'units' : units.c_str(),
* 'readOnly': manager.IsValueReadOnly(v)
}
:param args: A dict containing informations about the state of the controller
:type args: dict()
"""
logger.debug('zwcallback args=[%s]', args)
try:
notify_type = args['notificationType']
if notify_type == self.SIGNAL_DRIVER_FAILED:
self._handle_driver_failed(args)
elif notify_type == self.SIGNAL_DRIVER_READY:
self._handle_driver_ready(args)
elif notify_type == self.SIGNAL_DRIVER_RESET:
self._handle_driver_reset(args)
elif notify_type == self.SIGNAL_NODE_ADDED:
self._handle_node_added(args)
elif notify_type == self.SIGNAL_NODE_EVENT:
self._handle_node_event(args)
elif notify_type == self.SIGNAL_NODE_NAMING:
self._handle_node_naming(args)
elif notify_type == self.SIGNAL_NODE_NEW:
self._handle_node_new(args)
elif notify_type == self.SIGNAL_NODE_PROTOCOL_INFO:
self._handle_node_protocol_info(args)
elif notify_type == self.SIGNAL_NODE_READY:
self._handleNodeReady(args)
elif notify_type == self.SIGNAL_NODE_REMOVED:
self._handle_node_removed(args)
elif notify_type == self.SIGNAL_GROUP:
self._handle_group(args)
elif notify_type == self.SIGNAL_SCENE_EVENT:
self._handle_scene_event(args)
elif notify_type == self.SIGNAL_VALUE_ADDED:
self._handle_value_added(args)
elif notify_type == self.SIGNAL_VALUE_CHANGED:
self._handle_value_changed(args)
elif notify_type == self.SIGNAL_VALUE_REFRESHED:
self._handle_value_refreshed(args)
elif notify_type == self.SIGNAL_VALUE_REMOVED:
self._handle_value_removed(args)
elif notify_type == self.SIGNAL_POLLING_DISABLED:
self._handle_polling_disabled(args)
elif notify_type == self.SIGNAL_POLLING_ENABLED:
self._handle_polling_enabled(args)
elif notify_type == self.SIGNAL_CREATE_BUTTON:
self._handle_create_button(args)
elif notify_type == self.SIGNAL_DELETE_BUTTON:
self._handle_delete_button(args)
elif notify_type == self.SIGNAL_BUTTON_ON:
self._handle_button_on(args)
elif notify_type == self.SIGNAL_BUTTON_OFF:
self._handle_button_off(args)
elif notify_type == self.SIGNAL_ALL_NODES_QUERIED:
self._handle_all_nodes_queried(args)
elif notify_type == self.SIGNAL_ALL_NODES_QUERIED_SOME_DEAD:
self._handle_all_nodes_queried_some_dead(args)
elif notify_type == self.SIGNAL_AWAKE_NODES_QUERIED:
self._handle_awake_nodes_queried(args)
elif notify_type == self.SIGNAL_ESSENTIAL_NODE_QUERIES_COMPLETE:
self._handle_essential_node_queries_complete(args)
elif notify_type == self.SIGNAL_NODE_QUERIES_COMPLETE:
self._handle_node_queries_complete(args)
elif notify_type == self.SIGNAL_MSG_COMPLETE:
self._handle_msg_complete(args)
elif notify_type == self.SIGNAL_NOTIFICATION:
self._handle_notification(args)
elif notify_type == self.SIGNAL_DRIVER_REMOVED:
self._handle_driver_removed(args)
elif notify_type == self.SIGNAL_CONTROLLER_COMMAND:
self._handle_controller_command(args)
else:
logger.warning('Skipping unhandled notification [%s]', args)
except:
import sys, traceback
logger.error('Error in manager callback : %s', traceback.format_exception(*sys.exc_info()))
def _handle_driver_failed(self, args):
"""
Driver failed to load.
:param args: data sent by the notification
:type args: dict()
dispatcher.send(self.SIGNAL_NETWORK_FAILED, **{'network': self})
"""