-
Notifications
You must be signed in to change notification settings - Fork 137
Expand file tree
/
Copy pathlibopenzwave.pyx
More file actions
executable file
·5001 lines (4110 loc) · 184 KB
/
libopenzwave.pyx
File metadata and controls
executable file
·5001 lines (4110 loc) · 184 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 -*-
#cython: c_string_type=unicode, c_string_encoding=utf8
"""
.. module:: libopenzwave
This file is part of **python-openzwave** project https://github.com/OpenZWave/python-openzwave.
:platform: Unix, Windows, MacOS X
:sinopsis: openzwave C++
.. moduleauthor: bibi21000 aka Sebastien GALLET <bibi21000@gmail.com>
.. moduleauthor: Maarten Damen <m.damen@gmail.com>
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.
"""
from cython.operator cimport dereference as deref
from libcpp.map cimport map, pair
from libcpp cimport bool
#from libc.stdint cimport bint
from libcpp.vector cimport vector
from libc.stdint cimport uint16_t, uint32_t, uint64_t, int32_t, int16_t, uint8_t, int8_t
from libc.stdlib cimport malloc, free
#from libcpp.string cimport string
from mylibc cimport string
#from vers cimport ozw_vers_major, ozw_vers_minor, ozw_vers_revision, ozw_version_string
from mylibc cimport PyEval_InitThreads, Py_Initialize
from group cimport InstanceAssociation_t, InstanceAssociation
from node cimport NodeData_t, NodeData
from node cimport SecurityFlag
from driver cimport DriverData_t, DriverData
from driver cimport ControllerCommand, ControllerState, ControllerError, pfnControllerCallback_t
from notification cimport Notification, NotificationType, NotificationCode
from notification cimport Type_Notification, Type_Group, Type_NodeEvent, Type_SceneEvent, Type_DriverReset, Type_DriverRemoved
from notification cimport Type_CreateButton, Type_DeleteButton, Type_ButtonOn, Type_ButtonOff
from notification cimport Type_ValueAdded, Type_ValueRemoved, Type_ValueChanged, Type_ValueRefreshed
from notification cimport Type_ControllerCommand, Type_LevelChangeStart, Type_LevelChangeStop
from notification cimport const_notification, pfnOnNotification_t
from values cimport ValueGenre, ValueType, ValueID
from options cimport Options, Create as CreateOptions, OptionType, OptionType_Invalid, OptionType_Bool, OptionType_Int, OptionType_String
from manager cimport Manager, Create as CreateManager, Get as GetManager
from manager cimport struct_associations, int_associations
from log cimport LogLevel
import os
import sys
import warnings
import six
from shutil import copyfile
# 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('libopenzwave')
logger.addHandler(NullHandler())
from pkg_resources import get_distribution, DistributionNotFound
cdef extern from 'pyversion.h':
string PY_LIB_VERSION_STRING
string PY_LIB_FLAVOR_STRING
string PY_LIB_BACKEND_STRING
string PY_LIB_DATE_STRING
string PY_LIB_TIME_STRING
__version__ = PY_LIB_VERSION_STRING
#For historical ways of working
libopenzwave_location = 'not_installed'
libopenzwave_file = 'not_installed'
try:
_dist = get_distribution('libopenzwave')
except DistributionNotFound:
pass
else:
libopenzwave_location = _dist.location
if libopenzwave_location == 'not_installed' :
try:
_dist = get_distribution('libopenzwave')
libopenzwave_file = _dist.__file__
except AttributeError:
libopenzwave_file = 'not_installed'
except DistributionNotFound:
libopenzwave_file = 'not_installed'
cdef string str_to_cppstr(str s):
if isinstance(s, unicode):
b = s.encode('utf-8')
else:
b = s
return string(b)
cdef cstr_to_str(s):
if six.PY3 and not isinstance(s, str):
return s.decode('utf-8')
elif six.PY3:
return s
else:
try:
return s.encode('utf-8')
except:
try:
return s.decode('utf-8')
except:
return s
class LibZWaveException(Exception):
"""
Exception class for LibOpenZWave
"""
def __init__(self, value):
Exception.__init__(self)
self.msg = "LibOpenZwave Generic Exception"
self.value = value
def __str__(self):
return repr(self.msg+' : '+self.value)
# See http://www.electricmonk.nl/log/2011/08/14/redirect-stdout-and-stderr-to-a-logger-in-python/ for capturing console output of the c++ library
# http://stackoverflow.com/questions/616645/how-do-i-duplicate-sys-stdout-to-a-log-file-in-python
# https://github.com/nose-devs/nose/blob/master/nose/plugins/capture.py
#~ class StdOutToLogger(object):
#~ """
#~ Capture stdout and send it to logging.debug
#~ """
#~ def __init__(self):
#~ self.stdout = sys.stdout
#~ sys.stdout = self
#~
#~ def __del__(self):
#~ sys.stdout = self.stdout
#~ self.file.close()
#~
#~ def write(self, data):
#~ pass
#~ logger.debug(data)
PYLIBRARY = __version__
PY_OZWAVE_CONFIG_DIRECTORY = "config"
OZWAVE_CONFIG_DIRECTORY = "share/openzwave/config"
CWD_CONFIG_DIRECTORY = "openzwave/config"
class EnumWithDoc(str):
"""Enum helper"""
def setDoc(self, doc):
self.doc = doc
return self
PyNotifications = [
EnumWithDoc('ValueAdded').setDoc("A new node value has been added to OpenZWave's set. These notifications occur after a node has been discovered, and details of its command classes have been received. Each command class may generate one or more values depending on the complexity of the item being represented."),
EnumWithDoc('ValueRemoved').setDoc("A node value has been removed from OpenZWave's set. This only occurs when a node is removed."),
EnumWithDoc('ValueChanged').setDoc("A node value has been updated from the Z-Wave network and it is different from the previous value."),
EnumWithDoc('ValueRefreshed').setDoc("A node value has been updated from the Z-Wave network."),
EnumWithDoc('Group').setDoc("The associations for the node have changed. The application should rebuild any group information it holds about the node."),
EnumWithDoc('NodeNew').setDoc("A new node has been found (not already stored in zwcfg*.xml file)."),
EnumWithDoc('NodeAdded').setDoc("A new node has been added to OpenZWave's set. This may be due to a device being added to the Z-Wave network, or because the application is initializing itself."),
EnumWithDoc('NodeRemoved').setDoc("A node has been removed from OpenZWave's set. This may be due to a device being removed from the Z-Wave network, or because the application is closing."),
EnumWithDoc('NodeProtocolInfo').setDoc("Basic node information has been receievd, such as whether the node is a setening device, a routing device and its baud rate and basic, generic and specific types. It is after this notification that you can call Manager::GetNodeType to obtain a label containing the device description."),
EnumWithDoc('NodeNaming').setDoc("One of the node names has changed (name, manufacturer, product)."),
EnumWithDoc('NodeEvent').setDoc("A node has triggered an event. This is commonly caused when a node sends a Basic_Set command to the controller. The event value is stored in the notification."),
EnumWithDoc('PollingDisabled').setDoc("Polling of a node has been successfully turned off by a call to Manager::DisablePoll."),
EnumWithDoc('PollingEnabled').setDoc("Polling of a node has been successfully turned on by a call to Manager::EnablePoll."),
EnumWithDoc('SceneEvent').setDoc("Scene Activation Set received."),
EnumWithDoc('CreateButton').setDoc("Handheld controller button event created."),
EnumWithDoc('DeleteButton').setDoc("Handheld controller button event deleted."),
EnumWithDoc('ButtonOn').setDoc("Handheld controller button on pressed event."),
EnumWithDoc('ButtonOff').setDoc("Handheld controller button off pressed event."),
EnumWithDoc('DriverReady').setDoc("A driver for a PC Z-Wave controller has been added and is ready to use. The notification will contain the controller's Home ID, which is needed to call most of the Manager methods."),
EnumWithDoc('DriverFailed').setDoc("Driver failed to load."),
EnumWithDoc('DriverReset').setDoc("All nodes and values for this driver have been removed. This is sent instead of potentially hundreds of individual node and value notifications."),
EnumWithDoc('EssentialNodeQueriesComplete').setDoc("The queries on a node that are essential to its operation have been completed. The node can now handle incoming messages."),
EnumWithDoc('NodeQueriesComplete').setDoc("All the initialisation queries on a node have been completed."),
EnumWithDoc('AwakeNodesQueried').setDoc("All awake nodes have been queried, so client application can expected complete data for these nodes."),
EnumWithDoc('AllNodesQueriedSomeDead').setDoc("All nodes have been queried but some dead nodes found."),
EnumWithDoc('AllNodesQueried').setDoc("All nodes have been queried, so client application can expected complete data."),
EnumWithDoc('Notification').setDoc("A manager notification report."),
EnumWithDoc('DriverRemoved').setDoc("The Driver is being removed."),
EnumWithDoc('ControllerCommand').setDoc("When Controller Commands are executed, Notifications of Success/Failure etc are communicated via this Notification."),
EnumWithDoc('NodeReset').setDoc("A node has been reset from OpenZWave's set. The Device has been reset and thus removed from the NodeList in OZW."),
EnumWithDoc('UserAlerts').setDoc("Warnings and Notifications Generated by the library that should be displayed to the user (eg, out of date config files)"),
EnumWithDoc('ManufacturerSpecificDBReady').setDoc("The ManufacturerSpecific Database Is Ready"),
EnumWithDoc('LevelChangeStart').setDoc("Start for a multilevel switch or color change transition"),
EnumWithDoc('LevelChangeStop').setDoc("End of a multilevel switch or color change transition")
]
PyNotificationCodes = [
EnumWithDoc('MsgComplete').setDoc("Completed messages."),
EnumWithDoc('Timeout').setDoc("Messages that timeout will send a Notification with this code."),
EnumWithDoc('NoOperation').setDoc("Report on NoOperation message sent completion."),
EnumWithDoc('Awake').setDoc("Report when a sleeping node wakes."),
EnumWithDoc('Sleep').setDoc("Report when a node goes to sleep."),
EnumWithDoc('Dead').setDoc("Report when a node is presumed dead."),
EnumWithDoc('Alive').setDoc("Report when a node is revived."),
]
PyGenres = [
EnumWithDoc('Basic').setDoc("The 'level' as controlled by basic commands. Usually duplicated by another command class."),
EnumWithDoc('User').setDoc("Basic values an ordinary user would be interested in."),
EnumWithDoc('Config').setDoc("Device-specific configuration parameters. These cannot be automatically discovered via Z-Wave, and are usually described in the user manual instead."),
EnumWithDoc('System').setDoc("Values of significance only to users who understand the Z-Wave protocol"),
]
PyValueTypes = [
EnumWithDoc('Bool').setDoc("Boolean, true or false"),
EnumWithDoc('Byte').setDoc("8-bit unsigned value"),
EnumWithDoc('Decimal').setDoc("Represents a non-integer value as a string, to avoid floating point accuracy issues."),
EnumWithDoc('Int').setDoc("32-bit signed value"),
EnumWithDoc('List').setDoc("List from which one item can be selected"),
EnumWithDoc('Schedule').setDoc("Complex type used with the Climate Control Schedule command class"),
EnumWithDoc('Short').setDoc("16-bit signed value"),
EnumWithDoc('String').setDoc("Text string"),
EnumWithDoc('Button').setDoc("A write-only value that is the equivalent of pressing a button to send a command to a device"),
EnumWithDoc('Raw').setDoc("Raw byte values"),
]
PyControllerState = [
EnumWithDoc('Normal').setDoc("No command in progress."),
EnumWithDoc('Starting').setDoc("The command is starting."),
EnumWithDoc('Cancel').setDoc("The command was cancelled."),
EnumWithDoc('Error').setDoc("Command invocation had error(s) and was aborted."),
EnumWithDoc('Waiting').setDoc("Controller is waiting for a user action."),
EnumWithDoc('Sleeping').setDoc("Controller command is on a sleep queue wait for device."),
EnumWithDoc('InProgress').setDoc("The controller is communicating with the other device to carry out the command."),
EnumWithDoc('Completed').setDoc("The command has completed successfully."),
EnumWithDoc('Failed').setDoc("The command has failed."),
EnumWithDoc('NodeOK').setDoc("Used only with ControllerCommand_HasNodeFailed to indicate that the controller thinks the node is OK."),
EnumWithDoc('NodeFailed').setDoc("Used only with ControllerCommand_HasNodeFailed to indicate that the controller thinks the node has failed."),
]
PyControllerCommand = [
EnumWithDoc('None').setDoc("No command."),
EnumWithDoc('AddDevice').setDoc("Add a new device (but not a controller) to the Z-Wave network."),
EnumWithDoc('CreateNewPrimary').setDoc("Add a new controller to the Z-Wave network. The new controller will be the primary, and the current primary will become a secondary controller."),
EnumWithDoc('ReceiveConfiguration').setDoc("Receive Z-Wave network configuration information from another controller."),
EnumWithDoc('RemoveDevice').setDoc("Remove a new device (but not a controller) from the Z-Wave network."),
EnumWithDoc('RemoveFailedNode').setDoc("Move a node to the controller's failed nodes list. This command will only work if the node cannot respond."),
EnumWithDoc('HasNodeFailed').setDoc("Check whether a node is in the controller's failed nodes list."),
EnumWithDoc('ReplaceFailedNode').setDoc("Replace a non-responding node with another. The node must be in the controller's list of failed nodes for this command to succeed."),
EnumWithDoc('TransferPrimaryRole').setDoc("Make a different controller the primary."),
EnumWithDoc('RequestNetworkUpdate').setDoc("Request network information from the SUC/SIS."),
EnumWithDoc('RequestNodeNeighborUpdate').setDoc("Get a node to rebuild its neighbour list. This method also does ControllerCommand_RequestNodeNeighbors."),
EnumWithDoc('AssignReturnRoute').setDoc("Assign a network return routes to a device."),
EnumWithDoc('DeleteAllReturnRoutes').setDoc("Delete all return routes from a device."),
EnumWithDoc('SendNodeInformation').setDoc("Send a node information frame."),
EnumWithDoc('ReplicationSend').setDoc("Send information from primary to secondary."),
EnumWithDoc('CreateButton').setDoc("Create an id that tracks handheld button presses."),
EnumWithDoc('DeleteButton').setDoc("Delete id that tracks handheld button presses."),
]
PyControllerError = [
EnumWithDoc('None').setDoc("None."),
EnumWithDoc('ButtonNotFound').setDoc("Button."),
EnumWithDoc('NodeNotFound').setDoc("Button."),
EnumWithDoc('NotBridge').setDoc("Button."),
EnumWithDoc('NotSUC').setDoc("CreateNewPrimary."),
EnumWithDoc('NotSecondary').setDoc("CreateNewPrimary."),
EnumWithDoc('NotPrimary').setDoc("RemoveFailedNode, AddNodeToNetwork."),
EnumWithDoc('IsPrimary').setDoc("ReceiveConfiguration."),
EnumWithDoc('NotFound').setDoc("RemoveFailedNode."),
EnumWithDoc('Busy').setDoc("RemoveFailedNode, RequestNetworkUpdate."),
EnumWithDoc('Failed').setDoc("RemoveFailedNode, RequestNetworkUpdate."),
EnumWithDoc('Disabled').setDoc("RequestNetworkUpdate error."),
EnumWithDoc('Overflow').setDoc("RequestNetworkUpdate error."),
]
PyControllerInterface = [
EnumWithDoc('Unknown').setDoc("Controller interface use unknown protocol."),
EnumWithDoc('Serial').setDoc("Controller interface use serial protocol."),
EnumWithDoc('Hid').setDoc("Controller interface use human interface device protocol."),
]
PyOptionType = [
EnumWithDoc('Invalid').setDoc("Invalid type."),
EnumWithDoc('Bool').setDoc("Boolean."),
EnumWithDoc('Int').setDoc("Integer."),
EnumWithDoc('String').setDoc("String."),
]
PyUserAlerts = [
EnumWithDoc('Alert_None').setDoc("No Alert Currently Present"),
EnumWithDoc('Alert_ConfigOutOfDate').setDoc("One of the Config Files is out of date. Use GetNodeId to determine which node is effected."),
EnumWithDoc('Alert_MFSOutOfDate').setDoc("the manufacturer_specific.xml file is out of date."),
EnumWithDoc('Alert_ConfigFileDownloadFailed').setDoc("A Config File failed to download "),
EnumWithDoc('Alert_DNSError').setDoc("A error occurred performing a DNS Lookup"),
EnumWithDoc('Alert_NodeReloadRequired').setDoc("A new Config file has been discovered for this node, and its pending a Reload to Take affect"),
EnumWithDoc('Alert_UnsupportedController').setDoc("The Controller is not running a Firmware Library we support"),
EnumWithDoc('Alert_ApplicationStatus_Retry').setDoc("Application Status CC returned a Retry Later Message"),
EnumWithDoc('Alert_ApplicationStatus_Queued').setDoc("Command Has been Queued for later execution"),
EnumWithDoc('Alert_ApplicationStatus_Rejected').setDoc("Command has been rejected"),
]
PyLevelChangeType = [
EnumWithDoc('LevelChange_Switch').setDoc("Multilevel Switch"),
EnumWithDoc('LevelChange_Color').setDoc("Color Switch start/stop level change")
]
PyLevelChangeDirection = [
EnumWithDoc('LevelChangeDirection_Up').setDoc("When the change is started, increment."),
EnumWithDoc('LevelChangeDirection_Down').setDoc("When the change is started, decrement."),
EnumWithDoc('LevelChangeDirection_None').setDoc("Do not increment or decrement. Used for multilevel switch with 2 switches.")
]
class EnumWithDocType(str):
"""Enum helper"""
def setDocType(self, doc, stype):
self.doc = doc
self.type = stype
return self
PyOptionList = {
'ConfigPath' : {'doc' : "Path to the OpenZWave config folder.", 'type' : "String"},
'UserPath' : {'doc' : "Path to the user's data folder.", 'type' : "String"},
'Logging' : {'doc' : "Enable logging of library activity.", 'type' : "Bool"},
'LogFileName' : {'doc' : "Name of the log file (can be changed via Log::SetLogFileName).", 'type' : "String"},
'AppendLogFile' : {'doc' : "Append new session logs to existing log file (false = overwrite).", 'type' : "Bool"},
'ConsoleOutput' : {'doc' : "Display log information on console (as well as save to disk).", 'type' : "Bool"},
'SaveLogLevel' : {'doc' : "Save (to file) log messages equal to or above LogLevel_Detail.", 'type' : "Int"},
'QueueLogLevel' : {'doc' : "Save (in RAM) log messages equal to or above LogLevel_Debug.", 'type' : "Int"},
'DumpTriggerLevel' : {'doc' : "Default is to never dump RAM-stored log messages.", 'type' : "Int"},
'Associate' : {'doc' : "Enable automatic association of the controller with group one of every device.", 'type' : "Bool"},
'Exclude' : {'doc' : "Remove support for the listed command classes.", 'type' : "String"},
'Include' : {'doc' : "Only handle the specified command classes. The Exclude option is ignored if anything is listed here.", 'type' : "String"},
'NotifyTransactions' : {'doc' : "Notifications when transaction complete is reported.", 'type' : "Bool"},
'Interface' : {'doc' : "Identify the serial port to be accessed (TODO: change the code so more than one serial port can be specified and HID).", 'type' : "String"},
'SaveConfiguration' : {'doc' : "Save the XML configuration upon driver close.", 'type' : "Bool"},
'DriverMaxAttempts' : {'doc' : ".", 'type' : "Int"},
'PollInterval' : {'doc' : "30 seconds (can easily poll 30 values in this time; ~120 values is the effective limit for 30 seconds).", 'type' : "Int"},
'IntervalBetweenPolls' : {'doc' : "If false, try to execute the entire poll list within the PollInterval time frame. If true, wait for PollInterval milliseconds between polls.", 'type' : "Bool"},
'SuppressValueRefresh' : {'doc' : "If true, notifications for refreshed (but unchanged) values will not be sent.", 'type' : "Bool"},
'PerformReturnRoutes' : {'doc' : "If true, return routes will be updated.", 'type' : "Bool"},
'NetworkKey' : {'doc' : "Key used to negotiate and communicate with devices that support Security Command Class", 'type' : "String"},
'RefreshAllUserCodes' : {'doc' : "If true, during startup, we refresh all the UserCodes the device reports it supports. If False, we stop after we get the first 'Available' slot (Some devices have 250+ usercode slots! - That makes our Session Stage Very Long ).", 'type' : "Bool"},
'RetryTimeout' : {'doc' : "How long do we wait to timeout messages sent.", 'type' : "Int"},
'EnableSIS' : {'doc' : "Automatically become a SUC if there is no SUC on the network.", 'type' : "Bool"},
'AssumeAwake' : {'doc' : "Assume Devices that Support the Wakeup CC are awake when we first query them ...", 'type' : "Bool"},
'NotifyOnDriverUnload' : {'doc' : "Should we send the Node/Value Notifications on Driver Unloading - Read comments in Driver::~Driver() method about possible race conditions.", 'type' : "Bool"},
'SecurityStrategy' : {'doc' : "Should we encrypt CC's that are available via both clear text and Security CC?.", 'type' : "String", 'value' : 'SUPPORTED'},
'CustomSecuredCC' : {'doc' : "What List of Custom CC should we always encrypt if SecurityStrategy is CUSTOM.", 'type' : "String", 'value' : '0x62,0x4c,0x63'},
'EnforceSecureReception' : {'doc' : "If we recieve a clear text message for a CC that is Secured, should we drop the message", 'type' : "Bool"},
}
PyStatDriver = {
'SOFCnt' : "Number of SOF bytes received",
'ACKWaiting' : "Number of unsolicited messages while waiting for an ACK",
'readAborts' : "Number of times read were aborted due to timeouts",
'badChecksum' : "Number of bad checksums",
'readCnt' : "Number of messages successfully read",
'writeCnt' : "Number of messages successfully sent",
'CANCnt' : "Number of CAN bytes received",
'NAKCnt' : "Number of NAK bytes received",
'ACKCnt' : "Number of ACK bytes received",
'OOFCnt' : "Number of bytes out of framing",
'dropped' : "Number of messages dropped & not delivered",
'retries' : "Number of messages retransmitted",
'callbacks' : "Number of unexpected callbacks",
'badroutes' : "Number of failed messages due to bad route response",
'noack' : "Number of no ACK returned errors",
'netbusy' : "Number of network busy/failure messages",
'nondelivery' : "Number of messages not delivered to network",
'routedbusy' : "Number of messages received with routed busy status",
'broadcastReadCnt' : "Number of broadcasts read",
'broadcastWriteCnt' : "Number of broadcasts sent",
}
PyStatNode = {
'sentCnt' : "Number of messages sent from this node",
'sentFailed' : "Number of sent messages failed",
'retries' : "Number of message retries",
'receivedCnt' : "Number of messages received from this node",
'receivedDups' : "Number of duplicated messages received",
'receivedUnsolicited' : "Number of messages received unsolicited",
'lastRequestRTT' : "Last message request RTT",
'lastResponseRTT' : "Last message response RTT",
'sentTS' : "Last message sent time",
'receivedTS' : "Last message received time",
'averageRequestRTT' : "Average Request round trip time",
'averageResponseRTT' : "Average Response round trip time",
'quality' : "Node quality measure",
'lastReceivedMessage' : "Place to hold last received message",
'errors' : "Count errors for dead node detection",
}
PyLogLevels = {
'Invalid' : {'doc':'Invalid Log Status', 'value':0},
'None' : {'doc':'Disable all logging', 'value':1},
'Always' : {'doc':'These messages should always be shown', 'value':2},
'Fatal' : {'doc':'A likely fatal issue in the library', 'value':3},
'Error' : {'doc':'A serious issue with the library or the network', 'value':4},
'Warning' : {'doc':'A minor issue from which the library should be able to recover', 'value':5},
'Alert' : {'doc':'Something unexpected by the library about which the controlling application should be aware', 'value':6},
'Info' : {'doc':"Everything's working fine...these messages provide streamlined feedback on each message", 'value':7},
'Detail' : {'doc':'Detailed information on the progress of each message', 'value':8},
'Debug' : {'doc':'Very detailed information on progress that will create a huge log file quickly but this level (as others) can be queued and sent to the log only on an error or warning', 'value':9},
'StreamDetail' : {'doc':'Will include low-level byte transfers from controller to buffer to application and back', 'value':10},
'Internal' : {'doc':'Used only within the log class (uses existing timestamp, etc', 'value':11},
}
cdef map[uint64_t, ValueID] values_map
cdef getValueFromType(Manager *manager, valueId):
"""
Translate a value in the right type
"""
cdef float type_float
cdef bool type_bool
cdef uint8_t type_byte
cdef int32_t type_int
cdef int16_t type_short
cdef string type_string
cdef vector[string] vect
cdef uint8_t* vectraw = NULL
cdef uint8_t size
cdef string s
c = ""
ret = None
if values_map.find(valueId) != values_map.end():
datatype = PyValueTypes[values_map.at(valueId).GetType()]
if datatype == "Bool":
cret = manager.GetValueAsBool(values_map.at(valueId), &type_bool)
ret = type_bool if cret else None
return ret
elif datatype == "Byte":
cret = manager.GetValueAsByte(values_map.at(valueId), &type_byte)
ret = type_byte if cret else None
return ret
elif datatype == "Raw":
cret = manager.GetValueAsRaw(values_map.at(valueId), &vectraw, &size)
if cret:
for x in range (0, size):
c += chr(vectraw[x])
ret = c if cret else None
free(vectraw)
return ret
elif datatype == "Decimal":
cret = manager.GetValueAsFloat(values_map.at(valueId), &type_float)
ret = type_float if cret else None
return ret
elif datatype == "Int":
cret = manager.GetValueAsInt(values_map.at(valueId), &type_int)
ret = type_int if cret else None
return ret
elif datatype == "Short":
cret = manager.GetValueAsShort(values_map.at(valueId), &type_short)
ret = type_short if cret else None
return ret
elif datatype == "String":
cret = manager.GetValueAsString(values_map.at(valueId), &type_string)
ret = type_string.c_str() if cret else None
return ret
elif datatype == "Button":
cret = manager.GetValueAsBool(values_map.at(valueId), &type_bool)
ret = type_bool if cret else None
return ret
elif datatype == "List":
cret = manager.GetValueListSelection(values_map.at(valueId), &type_string)
ret = type_string.c_str() if cret else None
return ret
else :
cret = manager.GetValueAsString(values_map.at(valueId), &type_string)
ret = type_string.c_str() if cret else None
logger.debug("getValueFromType return %s", ret)
return ret
cdef delValueId(ValueID v, n):
logger.debug("delValueId : ValueID : %s", v.GetId())
if values_map.find(v.GetId()) != values_map.end():
values_map.erase(values_map.find(v.GetId()))
cdef addValueId(ValueID v, n):
logger.debug("addValueId : ValueID : %s", v.GetId())
#check is a valid value
if v.GetInstance() == 0:
return
logger.debug("addValueId : GetCommandClassId : %s, GetType : %s", v.GetCommandClassId(), v.GetType())
cdef Manager *manager = GetManager()
item = new pair[uint64_t, ValueID](v.GetId(), v)
values_map.insert(deref(item))
del item
genre = PyGenres[v.GetGenre()]
#handle basic value in different way
if genre =="Basic":
n['valueId'] = {'homeId' : v.GetHomeId(),
'nodeId' : v.GetNodeId(),
'commandClass' : PyManager.COMMAND_CLASS_DESC[v.GetCommandClassId()],
'instance' : v.GetInstance(),
'index' : v.GetIndex(),
'id' : v.GetId(),
'genre' : '',
'type' : PyValueTypes[v.GetType()],
'value' : None,
'label' : None,
'units' : None,
'readOnly': False,
}
else:
n['valueId'] = {'homeId' : v.GetHomeId(),
'nodeId' : v.GetNodeId(),
'commandClass' : PyManager.COMMAND_CLASS_DESC[v.GetCommandClassId()],
'instance' : v.GetInstance(),
'index' : v.GetIndex(),
'id' : v.GetId(),
'genre' : genre,
'type' : PyValueTypes[v.GetType()],
'value' : getValueFromType(manager,v.GetId()),
'label' : manager.GetValueLabel(v).c_str(),
'units' : manager.GetValueUnits(v).c_str(),
'readOnly': manager.IsValueReadOnly(v),
}
logger.debug("addValueId : Notification : %s", n)
cdef void notif_callback(const_notification _notification, void* _context) with gil:
"""
Notification callback to the C++ library
"""
logger.debug("notif_callback : new notification")
cdef Notification* notification = <Notification*>_notification
logger.debug("notif_callback : Notification type : %s, nodeId : %s", notification.GetType(), notification.GetNodeId())
try:
n = {'notificationType' : PyNotifications[notification.GetType()],
'homeId' : notification.GetHomeId(),
'nodeId' : notification.GetNodeId(),
'instance' : notification.GetInstance(),
'userAlert' : PyUserAlerts[ notification.GetUserAlertType() ]
}
except:
logger.exception("notif_callback exception - type %s", notification.GetType())
if notification.GetType() == Type_Group:
try:
n['groupIdx'] = notification.GetGroupIdx()
except:
logger.exception("notif_callback exception Type_Group")
elif notification.GetType() == Type_NodeEvent:
try:
n['event'] = notification.GetEvent()
except:
logger.exception("notif_callback exception Type_NodeEvent")
raise
elif notification.GetType() == Type_Notification:
try:
n['notificationCode'] = notification.GetNotification()
except:
logger.exception("notif_callback exception Type_Notification")
raise
elif notification.GetType() == Type_ControllerCommand:
try:
state = notification.GetEvent()
n['controllerStateInt'] = state
n['controllerState'] = PyControllerState[state]
n['controllerStateDoc'] = PyControllerState[state].doc
#Notification is filled with error
error = notification.GetNotification()
n['controllerErrorInt'] = error
n['controllerError'] = PyControllerError[error]
n['controllerErrorDoc'] = PyControllerError[error].doc
except:
logger.exception("notif_callback exception Type_ControllerCommand")
raise
elif notification.GetType() in (Type_CreateButton, Type_DeleteButton, Type_ButtonOn, Type_ButtonOff):
try:
n['buttonId'] = notification.GetButtonId()
except:
logger.exception("notif_callback exception Type_CreateButton, Type_DeleteButton, Type_ButtonOn, Type_ButtonOff")
raise
elif notification.GetType() == Type_DriverRemoved:
try:
logger.debug("Notification : Type_DriverRemoved received : clean all valueids")
values_map.empty()
except:
logger.exception("notif_callback exception Type_DriverRemoved")
raise
elif notification.GetType() == Type_DriverReset:
try:
logger.debug("Notification : Type_DriverReset received : clean all valueids")
values_map.empty()
except:
logger.exception("notif_callback exception Type_DriverReset")
raise
elif notification.GetType() == Type_SceneEvent:
try:
n['sceneId'] = notification.GetSceneId()
except:
logger.exception("notif_callback exception Type_SceneEvent")
raise
elif notification.GetType() in (Type_ValueAdded, Type_ValueChanged, Type_ValueRefreshed):
try:
addValueId(notification.GetValueID(), n)
except:
logger.exception("notif_callback exception Type_ValueAdded, Type_ValueChanged, Type_ValueRefreshed")
raise
elif notification.GetType() == Type_ValueRemoved:
try:
n['valueId'] = {'id' : notification.GetValueID().GetId()}
except:
logger.exception("notif_callback exception Type_ValueRemoved")
raise
#elif notification.GetType() in (Type_PollingEnabled, Type_PollingDisabled):
# #Maybe we should enable/disable this
# addValueId(notification.GetValueID(), n)
elif notification.GetType() == Type_LevelChangeStart:
try:
n['type'] = PyLevelChangeType[notification.GetLevelChangeParameters().m_type]
n['primaryDirection'] = PyLevelChangeDirection[notification.GetLevelChangeParameters().m_primaryDirection]
n['secondaryDirection'] = PyLevelChangeDirection[notification.GetLevelChangeParameters().m_secondaryDirection]
n['ignoreStartLevel'] = notification.GetLevelChangeParameters().m_ignoreStartLevel
n['primaryStartLevel'] = notification.GetLevelChangeParameters().m_primaryStartLevel
n['durationSeconds'] = notification.GetLevelChangeParameters().m_durationSeconds
n['secondaryStepSize'] = notification.GetLevelChangeParameters().m_secondaryStepSize
n['colorTarget'] = notification.GetLevelChangeParameters().m_colorTarget
except:
logger.exception("notif_callback exception Type_MultilevelSwitchStart")
raise
elif notification.GetType() == Type_LevelChangeStop:
try:
n['type'] = PyLevelChangeType[notification.GetLevelChangeParameters().m_type]
except:
logger.exception("notif_callback exception Type_LevelChangeStop")
raise
logger.debug("notif_callback : call callback context")
(<object>_context)(n)
if notification.GetType() == Type_ValueRemoved:
try:
delValueId(notification.GetValueID(), n)
except:
logger.exception("notif_callback exception Type_ValueRemoved delete")
raise
logger.debug("notif_callback : end")
cdef void ctrl_callback(ControllerState _state, ControllerError _error, void* _context) with gil:
"""
Controller callback to the C++ library
"""
c = {'state' : PyControllerState[_state],
'message' : PyControllerState[_state].doc,
'error' : _error,
'error_msg' : PyControllerError[_error].doc,
}
logger.debug("ctrl_callback : Message: %s", c)
(<object>_context)(c)
cpdef object driverData():
cdef DriverData data
def configPath():
'''
Retrieve the config path. This directory hold the xml files.
:return: A string containing the library config path or None.
:rtype: str
'''
if os.path.isfile(os.path.join("/etc/openzwave/",'device_classes.xml')):
#At first, check in /etc/openzwave
return "/etc/openzwave/"
elif os.path.isfile(os.path.join("/usr/local/etc/openzwave/",'device_classes.xml')):
#Next, check in /usr/local/etc/openzwave
return "/usr/local/etc/openzwave/"
else :
#Check in python_openzwave.resources
dirn = None
try:
from pkg_resources import resource_filename
dirn = resource_filename('python_openzwave.ozw_config', '__init__.py')
dirn = os.path.dirname(dirn)
except ImportError:
dirn = None
if dirn is not None and os.path.isfile(os.path.join(dirn,'device_classes.xml')):
#At first, check in /etc/openzwave
return dirn
elif os.path.isfile(os.path.join("openzwave/config",'device_classes.xml')):
return os.path.abspath('openzwave/config')
#For historical reasons.
elif os.path.isdir(os.path.join("/usr",PY_OZWAVE_CONFIG_DIRECTORY)):
return os.path.join("/usr",PY_OZWAVE_CONFIG_DIRECTORY)
elif os.path.isdir(os.path.join("/usr/local",PY_OZWAVE_CONFIG_DIRECTORY)):
return os.path.join("/usr/local",PY_OZWAVE_CONFIG_DIRECTORY)
elif os.path.isdir(os.path.join("/usr",OZWAVE_CONFIG_DIRECTORY)):
return os.path.join("/usr",OZWAVE_CONFIG_DIRECTORY)
elif os.path.isdir(os.path.join("/usr/local",OZWAVE_CONFIG_DIRECTORY)):
return os.path.join("/usr/local",OZWAVE_CONFIG_DIRECTORY)
else:
if os.path.isdir(os.path.join(os.path.dirname(libopenzwave_file),PY_OZWAVE_CONFIG_DIRECTORY)):
return os.path.join(os.path.dirname(libopenzwave_file), PY_OZWAVE_CONFIG_DIRECTORY)
if os.path.isdir(os.path.join(os.getcwd(),CWD_CONFIG_DIRECTORY)):
return os.path.join(os.getcwd(),CWD_CONFIG_DIRECTORY)
if os.path.isdir(os.path.join(libopenzwave_location,PY_OZWAVE_CONFIG_DIRECTORY)):
return os.path.join(libopenzwave_location, PY_OZWAVE_CONFIG_DIRECTORY)
return None
cdef class PyOptions:
"""
Manage options manager
"""
cdef readonly str _config_path
cdef readonly str _user_path
cdef readonly str _cmd_line
cdef Options *options
def __init__(self, config_path=None, user_path=None, cmd_line=None):
"""
Create an option object and check that parameters are valid.
:param device: The device to use
:type device: str
:param config_path: The openzwave config directory. If None, try to configure automatically.
:type config_path: str
:param user_path: The user directory
:type user_path: str
:param cmd_line: The "command line" options of the openzwave library
:type cmd_line: str
"""
if config_path is None:
config_path = self.getConfigPath()
if config_path is None:
raise LibZWaveException("Can't autoconfigure path to config")
if os.path.exists(config_path):
if not os.path.exists(os.path.join(config_path, "zwcfg.xsd")):
raise LibZWaveException("Can't retrieve zwcfg.xsd from %s" % config_path)
self._config_path = config_path
else:
raise LibZWaveException("Can't find config directory %s" % config_path)
if user_path is None:
user_path = "."
if os.path.exists(user_path):
if os.access(user_path, os.W_OK)==True and os.access(user_path, os.R_OK)==True:
self._user_path = user_path
else:
raise LibZWaveException("Can't write in user directory %s" % user_path)
else:
raise LibZWaveException("Can't find user directory %s" % user_path)
if cmd_line is None:
cmd_line=""
self._cmd_line = cmd_line
self.create(self._config_path, self._user_path, self._cmd_line)
def create(self, str a, str b, str c):
"""
.. _createoptions:
Create an option object used to start the manager
:param a: The path of the config directory
:type a: str
:param b: The path of the user directory
:type b: str
:param c: The "command line" options of the openzwave library
:type c: str
:see: destroyoptions_
"""
self.options = CreateOptions(
str_to_cppstr(a), str_to_cppstr(b), str_to_cppstr(c))
return True
def destroy(self):
"""
.. _destroyoptions:
Deletes the Options and cleans up any associated objects.
The application is responsible for destroying the Options object,
but this must not be done until after the Manager object has been
destroyed.
:return: The result of the operation.
:rtype: bool
:see: createoptions_
"""
return self.options.Destroy()
def lock(self):
"""
.. _lock:
Lock the options. Needed to start the manager
:return: The result of the operation.
:rtype: bool
:see: areLocked_
"""
if not os.path.isfile(os.path.join(self._user_path,'options.xml')):
if os.path.isfile(os.path.join(self._config_path,'options.xml')):
copyfile(os.path.join(self._config_path,'options.xml'), os.path.join(self._user_path,'options.xml'))
else:
logger.warning("Can't find options.xml in %s"%self._config_path)
return self.options.Lock()
def areLocked(self):
'''
.. _areLocked:
Test whether the options have been locked.
:return: true if the options have been locked.
:rtype: boolean
:see: lock_
'''
return self.options.AreLocked()
def addOptionBool(self, str name, value):
"""
.. _addOptionBool:
Add a boolean option.
:param name: The name of the option.
:type name: str
:param value: The value of the option.
:type value: boolean
:return: The result of the operation.
:rtype: bool
:see: addOption_, addOptionInt_, addOptionString_
"""
return self.options.AddOptionBool(str_to_cppstr(name), value)
def addOptionInt(self, str name, value):
"""
.. _addOptionInt:
Add an integer option.
:param name: The name of the option.
:type name: str
:param value: The value of the option.
:type value: boolean
:return: The result of the operation.
:rtype: bool
:see: addOption_, addOptionBool_, addOptionString_
"""
return self.options.AddOptionInt(str_to_cppstr(name), value)
def addOptionString(self, str name, str value, append=False):
"""
.. _addOptionString:
Add a string option.
:param name: The name of the option. Option names are case insensitive and must be unique.
:type name: str
:param value: The value of the option.
:type value: str
:param append: Setting append to true will cause values read from the command line
or XML file to be concatenated into a comma delimited set. If _append is false,
newer values will overwrite older ones.
:type append: boolean
:return: The result of the operation.
:rtype: bool
:see: addOption_, addOptionBool_, addOptionInt_
"""
return self.options.AddOptionString(
str_to_cppstr(name), str_to_cppstr(value), append)
def addOption(self, name, value):
"""
.. _addOption:
Add an option.
:param name: The name of the option.
:type name: string
:param value: The value of the option.
:type value: boolean, integer, string
:return: The result of the operation.
:rtype: bool
:see: addOptionBool_, addOptionInt_, addOptionString_
"""
if name not in PyOptionList:
return False
if PyOptionList[name]['type'] == "String":
return self.addOptionString(name, value)
elif PyOptionList[name]['type'] == "Bool":
return self.addOptionBool(name, value)
elif PyOptionList[name]['type'] == "Int":
return self.addOptionInt(name, value)
return False
def getOption(self, name):
"""
.. _getOption:
Retrieve option of a value.
:param name: The name of the option.
:type name: string
:return: The value
:rtype: boolean, integer, string or None
:see: getOptionAsBool_, getOptionAsInt_, getOptionAsString_
"""
if name not in PyOptionList:
return None
if PyOptionList[name]['type'] == "String":
return self.getOptionAsString(name)
elif PyOptionList[name]['type'] == "Bool":
return self.getOptionAsBool(name)
elif PyOptionList[name]['type'] == "Int":
return self.getOptionAsInt(name)
return False
def getOptionAsBool(self, name):
"""
.. _getOptionAsBool:
Retrieve boolean value of an option.
:param name: The name of the option.
:type name: string
:return: The value or None
:rtype: boolean or None
:see: getOption_, getOptionAsInt_, getOptionAsString_
"""
cdef bool type_bool
cret = self.options.GetOptionAsBool(str_to_cppstr(name), &type_bool)
ret = type_bool if cret==True else None
return ret
def getOptionAsInt(self, name):
"""
.. _getOptionAsInt:
Retrieve integer value of an option.
:param name: The name of the option.
:type name: string
:return: The value or None
:rtype: Integer or None
:see: getOption_, getOptionAsBool_, getOptionAsString_
"""
cdef int32_t type_int
cret = self.options.GetOptionAsInt(str_to_cppstr(name), &type_int)
ret = type_int if cret==True else None
return ret
def getOptionAsString(self, name):
"""
.. _getOptionAsString:
Retrieve string value of an option.
:param name: The name of the option.
:type name: string
:return: The value or None
:rtype: String or None
:see: getOption_, getOptionAsBool_, getOptionAsInt_
"""
cdef string type_string
cret = self.options.GetOptionAsString(str_to_cppstr(name), &type_string)
ret = cstr_to_str(type_string.c_str()) if cret==True else None
return ret
def getConfigPath(self):
'''
.. _getConfigPath: