CK-InoDrive-API 1.0.0__py3-none-any.whl → 1.0.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: CK-InoDrive-API
3
- Version: 1.0.0
3
+ Version: 1.0.1
4
4
  Summary: InoDrive API Library
5
5
  Home-page: https://cardinalkinetic.com
6
6
  Author: Cardinal Kinetic
@@ -20,7 +20,7 @@ License-File: LICENSE.txt
20
20
  License-File: README.txt
21
21
  Requires-Dist: websocket-client ==1.8.0
22
22
  Requires-Dist: ifaddr ==0.2.0
23
- Requires-Dist: msgpack ==1.0.8
23
+ Requires-Dist: msgpack ==1.1.0
24
24
 
25
25
  #### **Installation**
26
26
 
@@ -19,10 +19,10 @@ of the license associated with each component.
19
19
  SECTION 1: Apache License, V2.0
20
20
 
21
21
  >>> bleach-5.0.1
22
- >>> importlib-metadata-8.4.0
23
- >>> msgpack-1.0.8
22
+ >>> importlib-metadata-8.6.1
23
+ >>> msgpack-1.1.0
24
24
  >>> readme-renderer-44.0
25
- >>> requests-2.31.0
25
+ >>> requests-2.32.3
26
26
  >>> requests-toolbelt-1.0.0
27
27
  >>> rfc3986-2.0.0
28
28
  >>> twine-5.1.1
@@ -49,20 +49,20 @@ SECTION 2: BSD-STYLE, MIT-STYLE, OR SIMILAR STYLE LICENSES
49
49
  >>> markdown-it-py-3.0.0
50
50
  >>> markupsafe-2.1.3
51
51
  >>> mdurl-0.1.2
52
- >>> more-itertools-10.5.0
53
- >>> nh3-0.2.18
54
- >>> pkginfo-1.9.6
52
+ >>> more-itertools-10.6.0
53
+ >>> nh3-0.2.21
54
+ >>> pkginfo-1.10.0
55
55
  >>> pygments-2.18.0
56
56
  >>> pycryptodome-3.19.0
57
57
  >>> pywin32-ctypes-0.2.3
58
- >>> rich-13.7.0
58
+ >>> rich-13.9.4
59
59
  >>> setuptools-74.1.2
60
60
  >>> six-1.16.0
61
61
  >>> sqlalchemy-2.0.23
62
- >>> urllib3-2.1.0
62
+ >>> urllib3-2.3.0
63
63
  >>> webencodings-0.5.1
64
64
  >>> werkzeug-3.0.1
65
- >>> zipp-3.20.1
65
+ >>> zipp-3.21.0
66
66
 
67
67
  SECTION 3: GNU General Public License, V2.0
68
68
 
@@ -78,6 +78,7 @@ SECTION 5: Python License, V2.0
78
78
  >>> json-2.0.9
79
79
  >>> logging-0.5.1.2
80
80
  >>> os
81
+ >>> pathlib
81
82
  >>> select
82
83
  >>> socket
83
84
  >>> ssl
@@ -86,7 +87,7 @@ SECTION 5: Python License, V2.0
86
87
  >>> re-2.2.1
87
88
  >>> threading
88
89
  >>> time
89
- >>> typing-extensions-4.8.0
90
+ >>> typing-extensions-4.12.2
90
91
  >>> uuid
91
92
  >>> weakref
92
93
 
@@ -110,7 +111,7 @@ Copyright (c) 2014-2017, Mozilla Foundation
110
111
  See the License for the specific language governing permissions and
111
112
  limitations under the License.
112
113
 
113
- >>> msgpack-1.0.8
114
+ >>> msgpack-1.1.0
114
115
 
115
116
  Found in: msgpack-python/COPYING
116
117
 
@@ -160,7 +161,7 @@ Copyright 2014 Ian Cordasco, Rackspace
160
161
  See the License for the specific language governing permissions and
161
162
  limitations under the License.
162
163
 
163
- >>> importlib-metadata-8.4.0
164
+ >>> importlib-metadata-8.6.1
164
165
  >>> readme-renderer-44.0
165
166
  >>> requests-2.32.3
166
167
  >>> twine-5.1.1
@@ -345,7 +346,7 @@ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
345
346
  =============== SECTION 2. BSD-STYLE, MIT-STYLE, OR SIMILAR STYLE LICENSES ===============
346
347
 
347
348
 
348
- >>> blinker-1.0.0
349
+ >>> blinker-1.7.0
349
350
 
350
351
  Copyright 2010 Jason Kirtland
351
352
 
@@ -368,7 +369,7 @@ CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
368
369
  TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
369
370
  SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
370
371
 
371
- >>> charset-normalizer-3.3.2
372
+ >>> charset-normalizer-3.4.1
372
373
 
373
374
  MIT License
374
375
 
@@ -714,7 +715,7 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
714
715
  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
715
716
  THE SOFTWARE.
716
717
 
717
- >>> idna-3.8
718
+ >>> idna-3.10
718
719
 
719
720
  BSD 3-Clause License
720
721
 
@@ -938,7 +939,7 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
938
939
  FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
939
940
  IN THE SOFTWARE.
940
941
 
941
- >>> more-itertools-10.5.0
942
+ >>> more-itertools-10.6.0
942
943
 
943
944
  Copyright (c) 2012 Erik Rose
944
945
 
@@ -960,7 +961,7 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
960
961
  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
961
962
  SOFTWARE.
962
963
 
963
- >>> nh3-0.2.18
964
+ >>> nh3-0.2.21
964
965
 
965
966
  The MIT License (MIT)
966
967
 
@@ -984,7 +985,7 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
984
985
  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
985
986
  SOFTWARE.
986
987
 
987
- >>> pkginfo-1.9.6
988
+ >>> pkginfo-1.10.0
988
989
 
989
990
  MIT License
990
991
 
@@ -1131,7 +1132,7 @@ ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
1131
1132
  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
1132
1133
  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
1133
1134
 
1134
- >>> rich-13.7.0
1135
+ >>> rich-13.9.4
1135
1136
 
1136
1137
  Copyright (c) 2020 Will McGugan
1137
1138
 
@@ -1196,7 +1197,7 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
1196
1197
  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
1197
1198
  SOFTWARE.
1198
1199
 
1199
- >>> urllib3-2.1.0
1200
+ >>> urllib3-2.3.0
1200
1201
 
1201
1202
  MIT License
1202
1203
 
@@ -1288,9 +1289,9 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
1288
1289
  >>> jaraco.classes-3.4.0
1289
1290
  >>> jaraco.context-6.0.1
1290
1291
  >>> jaraco.functools-4.0.2
1291
- >>> keyring-25.3.0
1292
+ >>> keyring-25.6.0
1292
1293
  >>> setuptools-74.1.2
1293
- >>> zipp-3.20.1
1294
+ >>> zipp-3.21.0
1294
1295
 
1295
1296
  Permission is hereby granted, free of charge, to any person obtaining a copy
1296
1297
  of this software and associated documentation files (the "Software"), to
@@ -1686,11 +1687,11 @@ one at http://mozilla.org/MPL/2.0/.
1686
1687
 
1687
1688
  =============== SECTION 5. Python License, V2.0 ===============
1688
1689
 
1689
-
1690
1690
  >>> ipaddress-1.0
1691
1691
  >>> json-2.0.9
1692
1692
  >>> logging-0.5.1.2
1693
1693
  >>> os
1694
+ >>> pathlib
1694
1695
  >>> select
1695
1696
  >>> socket
1696
1697
  >>> ssl
@@ -1699,7 +1700,7 @@ one at http://mozilla.org/MPL/2.0/.
1699
1700
  >>> re-2.2.1
1700
1701
  >>> threading
1701
1702
  >>> time
1702
- >>> typing-extensions-4.8.0
1703
+ >>> typing-extensions-4.12.2
1703
1704
  >>> uuid
1704
1705
  >>> weakref
1705
1706
 
@@ -0,0 +1,20 @@
1
+ CkInoDriveAPI/IO.py,sha256=NFWkNzsI08y46yCkunuRq2Ejuodl9GM_FGA3WKIO1_Q,10534
2
+ CkInoDriveAPI/__init__.py,sha256=V5-YDL556lySvBnT9rq4x0joH6rTKyBWZwFY-52pq_s,150
3
+ CkInoDriveAPI/_version.py,sha256=GUGIXjDASp9ptQMPrIhgmvX329wtZPhLXRjv_wUEJ1A,399
4
+ CkInoDriveAPI/callback.py,sha256=c0kjor6n-3VKsO_Kc3zRPV4d1GnNfvQl2as38A1f46g,2962
5
+ CkInoDriveAPI/ck_ca.crt,sha256=uopTpSLmrazZpYhrJ-79bMTFYIjiAMxhHhMo07hYsy4,878
6
+ CkInoDriveAPI/defines.py,sha256=ZbgVXIF9Ax-cKU3bXl7tsT6rVPUpr6p2rlVqmGvh1wc,12903
7
+ CkInoDriveAPI/discoverLan.py,sha256=BWjol34X2iZJCtwa5z6TqTSsEbZSjuIZg40jeFnxQ5M,11029
8
+ CkInoDriveAPI/discoverWs.py,sha256=Mf4n0x-5xOBLJgANHTcEnPH0_WIbb-WQHKNI12h4ZMY,1152
9
+ CkInoDriveAPI/file.py,sha256=Eo1he5tY5wnb10MviXZu4Tswc_N70w7jf9LmHmihi3w,6582
10
+ CkInoDriveAPI/inoDrive.py,sha256=ZFGsOlejk5Pxk0nlkoP7mnBggeaxB2Xh-g72f6PKZN8,6080
11
+ CkInoDriveAPI/sysControl.py,sha256=i41dW8DNrpE8afRdciNOFfc7bGvbzPGVdZxq46PK7No,3480
12
+ CkInoDriveAPI/userApp.py,sha256=0E87QhG1gdKzI_sysrRWxJcPepmCnhw7p3W3uccWhTo,24366
13
+ CkInoDriveAPI/utils.py,sha256=dJVIPxW2tLohBEn1w8KTBPx4YfkNbGyqn3aE4vHPROA,16003
14
+ CkInoDriveAPI/wsHandle.py,sha256=alHU-v8M_GRWzQht65r6ye85vESY5NcZMpeGhxQZqXU,19626
15
+ CK_InoDrive_API-1.0.1.dist-info/LICENSE.txt,sha256=Htz8K82ehzm2lkK44nZ_hU0M5I4W8YHipiiRYyRdH5o,1077
16
+ CK_InoDrive_API-1.0.1.dist-info/METADATA,sha256=lTd7V0IJm1bna4n1k8szKQMxw17lcqsWkdVH7abb8Qg,3127
17
+ CK_InoDrive_API-1.0.1.dist-info/README.txt,sha256=RFQtWK6ncVBblsph8W0C1i-GViHEBw5PkdPRrT80CbY,94553
18
+ CK_InoDrive_API-1.0.1.dist-info/WHEEL,sha256=cVxcB9AmuTcXqmwrtPhNK88dr7IR_b6qagTj0UvIEbY,91
19
+ CK_InoDrive_API-1.0.1.dist-info/top_level.txt,sha256=HQb3X73ZpaiGH2dSziFYqzUFtsf1oG6A5_qUtF03xyQ,14
20
+ CK_InoDrive_API-1.0.1.dist-info/RECORD,,
CkInoDriveAPI/IO.py CHANGED
@@ -6,7 +6,7 @@ from .defines import OP_STATE
6
6
 
7
7
  class IO(object):
8
8
  def __init__(self, **kwargs):
9
- self._get_connection_handle = kwargs.get('get_connection_handle')
9
+ self._get_connection_handle = kwargs.get('getConnectionHandle')
10
10
 
11
11
  @property
12
12
  def _connection_handle(self):
@@ -20,7 +20,7 @@ class IO(object):
20
20
  response = self._connection_handle.msg_pack_request([CK.MSG_PACK.GET_METRICS])
21
21
 
22
22
  if response.get('error'):
23
- return {'success': False, 'Error': f'InoDrive GetMetrics Error: {str(response.get("error"))}'}
23
+ return {'success': False, 'Error': f"InoDrive GetMetrics Error: {str(response.get('error'))}"}
24
24
 
25
25
  data = response['data'][0]
26
26
 
@@ -105,7 +105,7 @@ class IO(object):
105
105
  response = self._connection_handle.msg_pack_request([CK.MSG_PACK.GET_INPUTS])
106
106
 
107
107
  if response.get('error'):
108
- return {'success': False, 'Error': f'InoDrive GetInputData Error: {str(response.get("error"))}'}
108
+ return {'success': False, 'Error': f"InoDrive GetInputData Error: {str(response.get('error'))}"}
109
109
 
110
110
  data = response['data'][0]
111
111
  data.update({'success': True})
@@ -188,13 +188,13 @@ class IO(object):
188
188
  else:
189
189
  state = 0x1 if state else 0x0
190
190
  else:
191
- logging.error(f'InoDrive SetInputPolarity Error: target or state not supported...')
191
+ logging.error(f"InoDrive SetInputPolarity Error: target or state not supported...")
192
192
  return None
193
193
 
194
194
  response = self._connection_handle.msg_pack_request([CK.MSG_PACK.SET_INPUT_POLARITY, target, state])
195
195
 
196
196
  if response.get('error'):
197
- logging.error(f'InoDrive SetInputPolarity Error: {str(response)}')
197
+ logging.error(f"InoDrive SetInputPolarity Error: {str(response)}")
198
198
  return None
199
199
 
200
200
  return True
@@ -224,7 +224,7 @@ class IO(object):
224
224
  response = self._connection_handle.msg_pack_request([CK.MSG_PACK.GET_OUTPUTS])
225
225
 
226
226
  if response.get('error'):
227
- return {'success': False, 'Error': f'InoDrive GetOutputData Error: {str(response.get("error"))}'}
227
+ return {'success': False, 'Error': f"InoDrive GetOutputData Error: {str(response.get('error'))}"}
228
228
 
229
229
  data = response['data'][0]
230
230
  data.update({'success': True})
@@ -243,14 +243,14 @@ class IO(object):
243
243
  elif type(target) is int and 0 <= target <= 2 and state is not None:
244
244
  state = 0x1 if state else 0x0
245
245
  else:
246
- logging.error(f'InoDrive SetOutput Error: target os state not supported...')
246
+ logging.error(f"InoDrive SetOutput Error: target os state not supported...")
247
247
  return None
248
248
 
249
249
  response = self._connection_handle.msg_pack_request([CK.MSG_PACK.SET_OUTPUTS, target, state])
250
250
 
251
251
  if response.get('error'):
252
- logging.error(f'InoDrive SetOutput Error: {str(response)}')
253
- return None
252
+ logging.error(f"InoDrive SetOutput Error: {str(response)}")
253
+ return False
254
254
 
255
255
  return True
256
256
  except Exception as ex:
@@ -300,8 +300,8 @@ class IO(object):
300
300
  response = self._connection_handle.msg_pack_request([CK.MSG_PACK.SET_HOLDING_BRAKE, True if state else False])
301
301
 
302
302
  if response.get('error'):
303
- logging.error(f'InoDrive GetOutputFault Error: {str(response)}')
304
- return None
303
+ logging.error(f"InoDrive SetHoldingBrake Error: {str(response)}")
304
+ return False
305
305
 
306
306
  return True
307
307
  except Exception as ex:
CkInoDriveAPI/__init__.py CHANGED
@@ -2,3 +2,5 @@ from .inoDrive import InoDrive
2
2
  from .discoverLan import id_discover_lan
3
3
 
4
4
  discover = id_discover_lan
5
+ __version__ = '1.0.1'
6
+ __version__ = '1.0.1'
@@ -0,0 +1,17 @@
1
+ from pathlib import Path
2
+ import sys
3
+ import os
4
+
5
+
6
+ def get_version_number():
7
+ try:
8
+ dir_path = str(Path(os.path.dirname(__file__)).parent)
9
+ sys.path.append(dir_path)
10
+
11
+ from versions import get_latest_number
12
+ version = get_latest_number()
13
+ except ImportError:
14
+ from .__init__ import __version__
15
+ version = __version__
16
+
17
+ return version
@@ -0,0 +1,87 @@
1
+ import logging
2
+
3
+
4
+ class Callback(object):
5
+ _context = None
6
+ _callbacks = {}
7
+
8
+ def __init__(self, **kwargs):
9
+ self._context = kwargs.get('context', self)
10
+
11
+ def on(self, name=None, func=None):
12
+ try:
13
+ callbacks = {}
14
+
15
+ if type(name) is dict:
16
+ callbacks = name
17
+ elif type(name) is str and callable(func):
18
+ callbacks[name] = func
19
+ else:
20
+ return
21
+
22
+ for callback_name, callback_function in callbacks.items():
23
+ if type(callback_name) is not str:
24
+ continue
25
+
26
+ if not callable(callback_function):
27
+ continue
28
+
29
+ if callback_name not in self._callbacks:
30
+ # Callback does not exist
31
+ self._callbacks[callback_name] = [callback_function]
32
+ continue
33
+
34
+ if callback_function not in self._callbacks[callback_name]:
35
+ # Function is not in callback group
36
+ self._callbacks[callback_name].append(callback_function)
37
+ continue
38
+
39
+ except Exception as ex:
40
+ logging.exception(ex)
41
+
42
+ def remove(self, name=None, func=None):
43
+ try:
44
+ if type(name) is not str:
45
+ return
46
+
47
+ if not callable(func):
48
+ return
49
+
50
+ if self._callbacks[name] and func in self._callbacks[name]:
51
+ # Function exist so we need to remove it - removing callback.
52
+ self._callbacks[name].pop(self._callbacks[name].index(func))
53
+
54
+ if len(self._callbacks[name]) == 0:
55
+ # There are no more functions in the group - remove the group
56
+ del self._callbacks[name]
57
+
58
+ except Exception as ex:
59
+ logging.exception(ex)
60
+
61
+ def dispatch(self, callback_name=None, *args):
62
+ try:
63
+ # Get call back group
64
+ if callback_name in self._callbacks:
65
+ callbacks = self._callbacks[callback_name]
66
+ if callbacks is not None:
67
+ for callback in callbacks:
68
+ # Call each callback
69
+ if callable(callback):
70
+ callback(*args)
71
+
72
+ except Exception as ex:
73
+ logging.exception(ex)
74
+
75
+ def dispatch_with_context(self, context=None, callback_name=None, *args):
76
+ try:
77
+ # Get call back group
78
+ if callback_name in self._callbacks:
79
+ callbacks = self._callbacks[callback_name]
80
+ if callbacks is not None:
81
+ for callback in callbacks:
82
+ # Call each callback
83
+ if callable(callback):
84
+ callback(context, *args)
85
+
86
+ except Exception as ex:
87
+ logging.exception(ex)
@@ -228,5 +228,5 @@ def id_discover_lan(net_adapter_ip=None, num_attempts=2):
228
228
 
229
229
  # Return a stripped down version of the dictionary because the serial number key is no longer needed.
230
230
  results = list(all_modules_on_all_ifs.values())
231
- logging.info(f'Total modules found: {len(results)}')
231
+ logging.info(f"Total modules found: {len(results)}")
232
232
  return results
@@ -6,7 +6,7 @@ from .utils import Utils
6
6
 
7
7
  class DiscoverWs(object):
8
8
  def __init__(self, **kwargs):
9
- self._get_connection_handle = kwargs.get('get_connection_handle')
9
+ self._get_connection_handle = kwargs.get('getConnectionHandle')
10
10
 
11
11
  @property
12
12
  def _connection_handle(self):
@@ -21,7 +21,7 @@ class DiscoverWs(object):
21
21
  resp = self._connection_handle.request(Utils.get_tlv(CK.SPECIAL.GET_DISCOVER_INFO))
22
22
 
23
23
  if resp.get('error'):
24
- logging.error(f'Retrieving discover info failed...')
24
+ logging.error(f"Retrieving discover info failed...")
25
25
  return None
26
26
 
27
27
  result = None
CkInoDriveAPI/file.py CHANGED
@@ -7,7 +7,7 @@ from .utils import Utils
7
7
 
8
8
  class File(object):
9
9
  def __init__(self, **kwargs):
10
- self._get_connection_handle = kwargs.get('get_connection_handle')
10
+ self._get_connection_handle = kwargs.get('getConnectionHandle')
11
11
 
12
12
  @property
13
13
  def _connection_handle(self):
@@ -19,7 +19,7 @@ class File(object):
19
19
  def read(self, files=None, transfer_type=None):
20
20
  try:
21
21
  if files is None:
22
- logging.error(f'Files is None...')
22
+ logging.error(f"Files is None...")
23
23
  return None
24
24
 
25
25
  if type(files) is not list:
@@ -32,14 +32,14 @@ class File(object):
32
32
 
33
33
  for file in files:
34
34
  if type(file) is not dict:
35
- logging.error(f'File is not a dict...')
35
+ logging.error(f"File is not a dict...")
36
36
  return None
37
37
 
38
38
  file_path = file.get('path')
39
39
  content = file.get('content', 'bytes')
40
40
 
41
41
  if type(file_path) is not str:
42
- logging.error(f'File path is not a string...')
42
+ logging.error(f"File path is not a string...")
43
43
  return None
44
44
 
45
45
  file_path = file_path.replace('\\', '/')
@@ -48,7 +48,7 @@ class File(object):
48
48
  file_path = file_path[1:]
49
49
 
50
50
  if file_path[0] != '/':
51
- file_path = f'/{file_path}'
51
+ file_path = f"/{file_path}"
52
52
 
53
53
  file_path = file_path.replace('\\', '/')
54
54
 
@@ -83,7 +83,7 @@ class File(object):
83
83
  def write(self, files=None, transfer_type=None):
84
84
  try:
85
85
  if files is None:
86
- logging.error(f'Files not provided...')
86
+ logging.error(f"Files not provided...")
87
87
  return False
88
88
 
89
89
  if type(files) is not list:
@@ -94,7 +94,7 @@ class File(object):
94
94
 
95
95
  for file in files:
96
96
  if type(file) is not dict:
97
- logging.error(f'File is not a dict...')
97
+ logging.error(f"File is not a dict...")
98
98
  return False
99
99
 
100
100
  file_path = file.get('path')
@@ -105,7 +105,7 @@ class File(object):
105
105
  file_path = file_path[1:]
106
106
 
107
107
  if file_path[0] != '/':
108
- file_path = f'/{file_path}'
108
+ file_path = f"/{file_path}"
109
109
 
110
110
  file_path = file_path.replace('\\', '/')
111
111
 
@@ -118,7 +118,7 @@ class File(object):
118
118
  file_content = bytes(file_content, 'utf-8')
119
119
 
120
120
  if file_content is None or type(file_content) is not bytes:
121
- logging.error(f'File content is not bytes...')
121
+ logging.error(f"File content is not bytes...")
122
122
  return False
123
123
 
124
124
  msg = b''
@@ -133,7 +133,7 @@ class File(object):
133
133
  resp = self._connection_handle.request(msg)
134
134
 
135
135
  if resp.get('error'):
136
- logging.error(f'File [{file_path}] write error: {resp.get("error")}')
136
+ logging.error(f"File [{file_path}] write error: {resp.get('error')}")
137
137
  return False
138
138
 
139
139
  return True
@@ -148,7 +148,7 @@ class File(object):
148
148
  resp = self._connection_handle.request(Utils.get_tlv(CK.SPECIAL.DELETE_UAPP))
149
149
 
150
150
  if resp.get('error'):
151
- logging.error(f'Deleting User Application failed...')
151
+ logging.error(f"Deleting User Application failed...")
152
152
  return False
153
153
 
154
154
  return True
CkInoDriveAPI/inoDrive.py CHANGED
@@ -1,5 +1,7 @@
1
1
  import logging
2
2
  import weakref
3
+ from ._version import get_version_number
4
+ from .callback import Callback
3
5
 
4
6
  from .wsHandle import InoDriveWS
5
7
  from .file import File
@@ -10,23 +12,36 @@ from .sysControl import SysControl
10
12
 
11
13
 
12
14
  class InoDrive(object):
15
+ version = None
13
16
  _kwargs = None
14
- _callbacks = {}
15
17
  _connection_handle_instance = None
16
18
 
17
19
  def __init__(self, **kwargs):
20
+ self.version = get_version_number()
18
21
  self._kwargs = kwargs
19
22
  logging.debug('Create InoDrive instance...')
20
23
  self._auto_connect = kwargs.get('autoConnect', False)
21
24
 
25
+ # Callbacks
26
+ self._callback = Callback()
27
+
28
+ if 'callbacks' in self._kwargs:
29
+ if type(self._kwargs['callbacks']) is dict:
30
+ for name, functions in self._kwargs['callbacks'].items():
31
+ if type(functions) is not list:
32
+ functions = [functions]
33
+ for func in functions:
34
+ if callable(func):
35
+ self._callback.on(name, func)
36
+
22
37
  # ==============================================================================================================
23
38
  # MODULES BEGIN
24
39
  # ==============================================================================================================
25
- self.File = File(**kwargs, get_connection_handle=self._get_connection_handle)
26
- self.Discover = DiscoverWs(**kwargs, get_connection_handle=self._get_connection_handle)
27
- self.IO = IO(**kwargs, get_connection_handle=self._get_connection_handle)
28
- self.UserApp = UserApp(**kwargs, get_connection_handle=self._get_connection_handle)
29
- self.SysControl = SysControl(**kwargs, get_connection_handle=self._get_connection_handle)
40
+ self.File = File(**kwargs, getConnectionHandle=self._get_connection_handle, callback=self._callback)
41
+ self.Discover = DiscoverWs(**kwargs, getConnectionHandle=self._get_connection_handle, callback=self._callback)
42
+ self.IO = IO(**kwargs, getConnectionHandle=self._get_connection_handle, callback=self._callback)
43
+ self.UserApp = UserApp(**kwargs, getConnectionHandle=self._get_connection_handle, callback=self._callback)
44
+ self.SysControl = SysControl(**kwargs, getConnectionHandle=self._get_connection_handle, callback=self._callback)
30
45
  # ==============================================================================================================
31
46
  # MODULES END
32
47
  # ==============================================================================================================
@@ -40,9 +55,9 @@ class InoDrive(object):
40
55
  self._use_fallback = True
41
56
 
42
57
  if "secureConnection" in self._kwargs:
43
- False if self._kwargs["secureConnection"] == False else True
58
+ self._secure_connection = False if self._kwargs["secureConnection"] == False else True
44
59
  else:
45
- self._kwargs["secureConnection"] = True
60
+ self._secure_connection = True
46
61
 
47
62
  if self._auto_connect:
48
63
  self.connect()
@@ -56,6 +71,14 @@ class InoDrive(object):
56
71
  def __del__(self):
57
72
  self._finalizer()
58
73
 
74
+ @property
75
+ def callback(self):
76
+ return self._callback
77
+
78
+ @property
79
+ def on(self):
80
+ return self._callback.on
81
+
59
82
  def dispose(self):
60
83
  try:
61
84
  if self.UserApp:
@@ -70,11 +93,16 @@ class InoDrive(object):
70
93
  try:
71
94
  if self._connection_handle_instance is None:
72
95
  # Connection handle is not created yet
73
- if self._kwargs["secureConnection"]:
96
+ connection_handle = None
97
+ if self._secure_connection:
74
98
  try:
75
- connection_handle = InoDriveWS(**self._kwargs, callbacks=self._callbacks, secure=True)
76
- connection_handle.connect()
99
+ connection_handle = InoDriveWS(
100
+ **self._kwargs,
101
+ callback=self._callback,
102
+ secure=True
103
+ )
77
104
  self._connection_handle_instance = connection_handle
105
+ connection_handle.connect()
78
106
  except Exception as ex:
79
107
  logging.exception(ex)
80
108
  if connection_handle:
@@ -83,9 +111,9 @@ class InoDrive(object):
83
111
  if not self._use_fallback:
84
112
  return
85
113
  else:
86
- connection_handle = InoDriveWS(**self._kwargs, callbacks=self._callbacks, secure=False)
87
- connection_handle.connect()
114
+ connection_handle = InoDriveWS(**self._kwargs, callback=self._callback, secure=False)
88
115
  self._connection_handle_instance = connection_handle
116
+ connection_handle.connect()
89
117
  else:
90
118
  self._connection_handle_instance.connect()
91
119
  except Exception as ex:
@@ -98,7 +126,7 @@ class InoDrive(object):
98
126
  except Exception as ex:
99
127
  logging.exception(ex)
100
128
 
101
- def set_target(self, target):
129
+ def set_target(self, target=None):
102
130
  if type(target) is not str:
103
131
  return
104
132
 
@@ -107,20 +135,6 @@ class InoDrive(object):
107
135
 
108
136
  self._kwargs.host = target
109
137
 
110
- def on(self, evt, func):
111
- try:
112
- match evt:
113
- case "connect":
114
- self._callbacks['onConnect'] = func if callable(func) else None
115
- case "disconnect":
116
- self._callbacks['onDisconnect'] = func if callable(func) else None
117
- case "error":
118
- self._callbacks['onError'] = func if callable(func) else None
119
- case "message":
120
- self._callbacks['onMessage'] = func if callable(func) else None
121
- except Exception as ex:
122
- logging.exception(ex)
123
-
124
138
  @property
125
139
  def connected(self):
126
140
  if self._connection_handle_instance is not None:
@@ -6,7 +6,7 @@ from .utils import Utils
6
6
 
7
7
  class SysControl(object):
8
8
  def __init__(self, **kwargs):
9
- self._get_connection_handle = kwargs.get('get_connection_handle')
9
+ self._get_connection_handle = kwargs.get('getConnectionHandle')
10
10
 
11
11
  @property
12
12
  def _connection_handle(self):
@@ -20,7 +20,7 @@ class SysControl(object):
20
20
  response = self._connection_handle.msg_pack_request([CK.MSG_PACK.CONSOLE_ENABLE, True if state else False])
21
21
 
22
22
  if response.get('error'):
23
- logging.error(f'InoDrive ConsoleEnable Error: {str(response)}')
23
+ logging.error(f"InoDrive ConsoleEnable Error: {str(response)}")
24
24
  return None
25
25
 
26
26
  return True
@@ -32,7 +32,7 @@ class SysControl(object):
32
32
  response = self._connection_handle.msg_pack_request([CK.MSG_PACK.TAKE_CONTROL, True if state else False])
33
33
 
34
34
  if response.get('error'):
35
- logging.error(f'InoDrive TakeControl Error: {str(response)}')
35
+ logging.error(f"InoDrive TakeControl Error: {str(response)}")
36
36
  return None
37
37
 
38
38
  return True
@@ -44,7 +44,7 @@ class SysControl(object):
44
44
  response = self._connection_handle.msg_pack_request([CK.MSG_PACK.MODULE_INFO])
45
45
 
46
46
  if response.get('error'):
47
- logging.error(f'InoDrive GetModuleInfo Error: {str(response)}')
47
+ logging.error(f"InoDrive GetModuleInfo Error: {str(response)}")
48
48
  return None
49
49
 
50
50
  data = response['data'][0]
CkInoDriveAPI/userApp.py CHANGED
@@ -11,41 +11,55 @@ PROTOCOL_JSON_API = 'json'
11
11
 
12
12
 
13
13
  class UserApp(object):
14
- def __init__(self, **kwargs):
15
- self._get_connection_handle = kwargs.get('get_connection_handle')
14
+ _guard_thread = None
15
+ _guard_timeout = 0.01
16
+ _last_poll_time = None
17
+ _connected = False
18
+ _poll_active = False
19
+ _initialized = False
20
+ _data_available = False
16
21
 
17
- self._poll_callback = kwargs.get('pollCallback', None)
18
- self._poll_callback = self._poll_callback if callable(self._poll_callback) else None
22
+ def __init__(self, **kwargs):
23
+ self._callback = kwargs.get('callback')
24
+ self._get_connection_handle = kwargs.get('getConnectionHandle')
25
+ self._guard_multiplier = kwargs.get('disconnectOnMissedPolls', 3)
19
26
 
20
27
  self._protocol = PROTOCOL_MSG_PACK
21
28
 
22
- self._variables_update_required = True
23
-
24
29
  self._variable_values = {}
25
30
  self._awaiting_response = False
26
31
 
27
32
  self._program_id = None
28
33
  self._ntp_poll_time = 0
29
34
 
30
- self._poll_time = kwargs.get("pollTime", 1)
35
+ self._poll_time = kwargs.get('pollTime', 1)
31
36
  self._poll_running = False
32
37
 
33
38
  self._thread = None
34
39
  self._thread_running = False
35
40
 
41
+ self._guard_thread = None
42
+ self._guard_running = False
43
+
44
+ self._callback.on('connect', self._on_connect)
45
+ self._callback.on('disconnect', self._on_disconnect)
46
+ self._callback.on('error', self._on_error)
47
+
36
48
  @property
37
49
  def _connection_handle(self):
38
50
  return self._get_connection_handle()
39
51
 
52
+ @property
53
+ def callback(self):
54
+ return self._callback
55
+
56
+ @property
57
+ def on(self):
58
+ return self._callback.on
59
+
40
60
  def dispose(self):
41
61
  self.stop_poll()
42
62
 
43
- def set_poll_callback(self, callback):
44
- if not callable(callback):
45
- return
46
- # todo need implementation
47
- self._poll_callback = callback
48
-
49
63
  def get_variable(self, id=None):
50
64
  try:
51
65
  for var_name, var_props in self._variable_values.items():
@@ -69,10 +83,19 @@ class UserApp(object):
69
83
  if timeout:
70
84
  self._poll_time = timeout
71
85
 
86
+ self._last_poll_time = int(time.time())
87
+
88
+ # Retrieve the data from the module first
89
+ self._poll()
90
+
72
91
  self._thread = threading.Thread(target=self._thread_loop, daemon=True)
73
92
  self._thread_running = True
74
93
  self._thread.start()
75
94
 
95
+ self._guard_thread = threading.Thread(target=self._poll_guard_loop, daemon=True)
96
+ self._guard_running = True
97
+ self._guard_thread.start()
98
+
76
99
  def stop_poll(self):
77
100
  if not self._thread:
78
101
  return
@@ -81,6 +104,21 @@ class UserApp(object):
81
104
  self._thread.join()
82
105
  self._thread = None
83
106
 
107
+ self._guard_running = False
108
+ self._guard_thread.join()
109
+ self._guard_thread = None
110
+
111
+ def wait_for_data_available(self, timeout=None):
112
+ timeout = timeout or 5
113
+
114
+ logging.debug(f"Timeout: {timeout}")
115
+
116
+ begin = int(time.time())
117
+ while (int(time.time()) - begin) < timeout:
118
+ if len(self._variable_values) > 0:
119
+ break
120
+ time.sleep(0.1)
121
+
84
122
  def get_variables_list(self, access=None):
85
123
  try:
86
124
  var_list = []
@@ -104,6 +142,7 @@ class UserApp(object):
104
142
  def get_all_variables(self):
105
143
  result = {
106
144
  'timestamp': self._ntp_poll_time,
145
+ 'programId': self._program_id,
107
146
  'items': {},
108
147
  }
109
148
 
@@ -132,7 +171,7 @@ class UserApp(object):
132
171
  # Target device is using old firmware switch to JSON_API
133
172
  self._protocol = PROTOCOL_JSON_API
134
173
  else:
135
- logging.error(f'Retrieving variables list failed. Error: {str(error)}')
174
+ logging.error(f"Retrieving variables list failed. Error: {str(error)}")
136
175
  return False
137
176
  else:
138
177
  program_id = resp['data'][0]
@@ -145,15 +184,15 @@ class UserApp(object):
145
184
  resp = self._connection_handle.request(msg)
146
185
 
147
186
  if resp.get('error'):
148
- logging.error(f'Retrieving variables list failed...')
187
+ logging.error(f"Retrieving variables list failed...")
149
188
  return False
150
189
 
151
190
  if len(resp['items']) == 0:
152
- logging.error(f'Missing data.')
191
+ logging.error(f"Missing data.")
153
192
  return False
154
193
 
155
194
  if resp['items'][0]['ctpType'] != CK.TYPE.STRING:
156
- logging.error(f'Unsupported response type: {resp['items'][0]['ctpType']}')
195
+ logging.error(f"Unsupported response type: {resp['items'][0]['ctpType']}")
157
196
  return False
158
197
 
159
198
  json_response = json.loads(resp['items'][0]['data'])
@@ -162,18 +201,17 @@ class UserApp(object):
162
201
  data = json_response['data']
163
202
 
164
203
  if not program_id:
165
- logging.error('Program ID is missing...')
204
+ logging.error("Program ID is missing...")
166
205
  return False
167
206
 
168
207
  if not data:
169
- logging.error('Variable list data is missing...')
208
+ logging.error("Variable list data is missing...")
170
209
  return False
171
210
 
172
211
  self._program_id = program_id
173
212
  self._update_variables_list(data)
174
- self._variables_update_required = False
175
213
 
176
- return True
214
+ return self._variable_values
177
215
  except Exception as ex:
178
216
  logging.exception(ex)
179
217
 
@@ -181,8 +219,8 @@ class UserApp(object):
181
219
 
182
220
  def read_var(self, argv=None, **kwargs):
183
221
  try:
184
- if self._connection_handle.connected() and self._variables_update_required:
185
- self.update_variables_list()
222
+ if self._connection_handle.connected() and not self._initialized:
223
+ self._poll()
186
224
 
187
225
  request_data = []
188
226
  var_list = []
@@ -206,7 +244,7 @@ class UserApp(object):
206
244
  elif self._protocol == PROTOCOL_JSON_API:
207
245
  request_data.append({'id': variable['id']})
208
246
  else:
209
- logging.error('Unsupported protocol...')
247
+ logging.error("Unsupported protocol...")
210
248
  return None
211
249
 
212
250
  if len(request_data) == 0:
@@ -248,8 +286,8 @@ class UserApp(object):
248
286
 
249
287
  def write_var(self, argv=None, value=None, **kwarg):
250
288
  try:
251
- if self._connection_handle.connected() and self._variables_update_required:
252
- self.update_variables_list()
289
+ if self._connection_handle.connected() and not self._initialized:
290
+ self._poll()
253
291
 
254
292
  var_dict = {}
255
293
  request_data = []
@@ -282,7 +320,7 @@ class UserApp(object):
282
320
  elif self._protocol == PROTOCOL_JSON_API:
283
321
  request_data.append({'id': variable['id'], 'val': var_value})
284
322
  else:
285
- logging.error('Unsupported protocol...')
323
+ logging.error("Unsupported protocol...")
286
324
  return False
287
325
  else:
288
326
  logging.error(f"Variable < {var_name} > not found...")
@@ -377,6 +415,30 @@ class UserApp(object):
377
415
 
378
416
  return False
379
417
 
418
+ def _on_connect(self, wsapp):
419
+ try:
420
+ if not self._connected:
421
+ self._callback.dispatch("appStatus", {'state': "connected"})
422
+ self._connected = True
423
+ except Exception as ex:
424
+ logging.exception(ex)
425
+
426
+ def _on_disconnect(self, wsapp, close_status_code, close_msg):
427
+ try:
428
+ if self._connected:
429
+ self._callback.dispatch("appStatus", {'state': "disconnected"})
430
+ self._connected = False
431
+ except Exception as ex:
432
+ logging.exception(ex)
433
+
434
+ def _on_error(self, wsapp, evt):
435
+ try:
436
+ if self._connected:
437
+ self._callback.dispatch("appStatus", {'state': "disconnected"})
438
+ self._connected = False
439
+ except Exception as ex:
440
+ logging.exception(ex)
441
+
380
442
  def _thread_loop(self):
381
443
  while self._thread_running:
382
444
  if self._thread is None:
@@ -413,6 +475,8 @@ class UserApp(object):
413
475
  try:
414
476
  if variable_list is None:
415
477
  return
478
+ # See if we need to reset all variables or keep some of them
479
+ # self._variable_values = {}
416
480
 
417
481
  # Remove all old variables which are no longer in the user application
418
482
  items_to_remove = []
@@ -448,6 +512,9 @@ class UserApp(object):
448
512
  'value': variable['value'],
449
513
  })
450
514
 
515
+ self._initialized = True
516
+ self._callback.dispatch("appStatus", {'state': "varUpdated"})
517
+
451
518
  except Exception as ex:
452
519
  logging.exception(ex)
453
520
 
@@ -463,8 +530,8 @@ class UserApp(object):
463
530
  'success': True,
464
531
  'token': resp['token'],
465
532
  'program_id': resp['data'][0],
466
- 'data': resp['data'][1],
467
533
  'ntpTime': resp['ntpTime'],
534
+ 'data': resp['data'][1],
468
535
  }
469
536
  elif self._protocol == PROTOCOL_JSON_API:
470
537
  msg = Utils.get_tlv(CK.SPECIAL.JSON_API)
@@ -477,10 +544,10 @@ class UserApp(object):
477
544
  return {'success': False, 'error': resp['error']}
478
545
 
479
546
  if len(resp['items']) == 0:
480
- return {'success': False, 'error': 'Missing data.'}
547
+ return {'success': False, 'error': "Missing data."}
481
548
 
482
549
  if resp['items'][0]['ctpType'] != CK.TYPE.STRING:
483
- return {'success': False, 'error': 'Unsupported response type...'}
550
+ return {'success': False, 'error': "Unsupported response type..."}
484
551
 
485
552
  json_response = json.loads(resp['items'][0]['data'])
486
553
 
@@ -501,7 +568,7 @@ class UserApp(object):
501
568
  }
502
569
  else:
503
570
  # Unknown protocol
504
- return {'success': False, 'error': 'Unknown protocol.'}
571
+ return {'success': False, 'error': "Unknown protocol."}
505
572
 
506
573
  except Exception as ex:
507
574
  return {'success': False, 'error': str(ex)}
@@ -509,11 +576,11 @@ class UserApp(object):
509
576
  def _poll(self):
510
577
  try:
511
578
  if not self._connection_handle.connected():
512
- self._variables_update_required = True
513
579
  return
514
580
 
515
- if self._variables_update_required or len(self._variable_values) == 0:
581
+ if not self._initialized:
516
582
  self.update_variables_list()
583
+ return
517
584
 
518
585
  data = []
519
586
  write_list = []
@@ -552,22 +619,25 @@ class UserApp(object):
552
619
  resp = self._var_access_request(data)
553
620
  # ===========================================================================================
554
621
 
555
- # Variables are successfully written, so now we can remove the write flag
556
- # todo: Maybe we should place clearing the write flag after checking for error and program ID.
557
- for variable in write_list:
558
- variable['write'] = False
622
+ # Set new poll time
623
+ self._last_poll_time = int(time.time())
559
624
 
560
625
  # Error
561
626
  if resp.get('error'):
562
- logging.error(resp['error'])
563
- self._variables_update_required = True
627
+ logging.error(f"Poll request error: {resp['error']}")
628
+ self._initialized = False
564
629
  return
565
630
 
566
631
  # Check if this is new program
567
632
  if self._program_id != resp.get('program_id'):
568
- self._variables_update_required = True
633
+ self._callback.dispatch("appStatus", {'state': "newProgram"})
634
+ self._initialized = False
569
635
  return
570
636
 
637
+ # Variables are successfully written, so now we can remove the write flag
638
+ for variable in write_list:
639
+ variable['write'] = False
640
+
571
641
  # Current module time
572
642
  if resp.get('ntpTime'):
573
643
  self._ntp_poll_time = resp['ntpTime']
@@ -579,8 +649,28 @@ class UserApp(object):
579
649
  if variable:
580
650
  variable.update({'value': item[1]})
581
651
 
582
- if self._poll_callback:
583
- self._poll_callback(self.get_all_variables())
652
+ self._data_available = True
653
+ self._callback.dispatch("appPoll", self.get_all_variables())
584
654
 
585
655
  except Exception as ex:
586
656
  logging.exception(ex)
657
+
658
+ def _poll_guard_loop(self):
659
+ while self._guard_running:
660
+ try:
661
+ timeout = self._poll_time * self._guard_multiplier
662
+
663
+ if (int(time.time()) - self._last_poll_time) > timeout:
664
+ # Lost connection
665
+ if self._poll_active:
666
+ self._callback.dispatch("appStatus", {'state': "lostPoll"})
667
+ self._poll_active = False
668
+ else:
669
+ # Resume connection
670
+ if not self._poll_active:
671
+ self._callback.dispatch("appStatus", {'state': "resumePoll"})
672
+ self._poll_active = True
673
+ time.sleep(self._guard_timeout)
674
+
675
+ except Exception as ex:
676
+ logging.exception(ex)
CkInoDriveAPI/utils.py CHANGED
@@ -35,7 +35,7 @@ class CkUtils(object):
35
35
  port_number = None
36
36
 
37
37
  if port_number is not None:
38
- port = f':{port_number}'
38
+ port = f":{port_number}"
39
39
 
40
40
  if path is not None:
41
41
  path = path.replace('\\', '/')
@@ -50,15 +50,15 @@ class CkUtils(object):
50
50
  logging.error("Target has an octet out of the range from 0 to 255.")
51
51
  break
52
52
 
53
- url = f'{protocol}://{target}'
53
+ url = f"{protocol}://{target}"
54
54
  if not is_ipv4:
55
55
  if timestamp and secure == False:
56
- url += f'{cmd_delimiter}T{int(time.time())}'
56
+ url += f"{cmd_delimiter}T{int(time.time())}"
57
57
 
58
58
  if has_dot_local or dot_local:
59
59
  url += '.local'
60
60
 
61
- url += f'{port if port is not None else ""}/{path if path is not None else ""}'
61
+ url += f"{port if port is not None else ''}/{path if path is not None else ''}"
62
62
 
63
63
  return url
64
64
  except Exception as ex:
@@ -157,7 +157,7 @@ class CkUtils(object):
157
157
  if data_type not in types:
158
158
  return None
159
159
 
160
- value = struct.pack(f'{types.get(data_type)}', data)
160
+ value = struct.pack(f"{types.get(data_type)}", data)
161
161
 
162
162
  return True
163
163
 
@@ -208,7 +208,7 @@ class CkUtils(object):
208
208
  if data_type == 'macAddress':
209
209
  items = []
210
210
  for item in data:
211
- items.append(f'{item:0>2X}')
211
+ items.append(f"{item:0>2X}")
212
212
 
213
213
  return ':'.join(items)
214
214
 
@@ -219,7 +219,7 @@ class CkUtils(object):
219
219
 
220
220
  return '.'.join(items)
221
221
 
222
- value = struct.unpack(f'{endian_opt}{types.get(data_type)}', data)[0]
222
+ value = struct.unpack(f"{endian_opt}{types.get(data_type)}", data)[0]
223
223
  return value
224
224
 
225
225
  except Exception as ex:
CkInoDriveAPI/wsHandle.py CHANGED
@@ -26,7 +26,7 @@ class InoDriveWS(object):
26
26
  self._target = ""
27
27
 
28
28
  if type(self._target) is not str or self._target == "":
29
- raise Exception(f'Target device not provided...')
29
+ raise Exception(f"Target device not provided...")
30
30
 
31
31
  self._port = kwargs.get('port')
32
32
  self._path = kwargs.get('path', 'cmd')
@@ -47,7 +47,7 @@ class InoDriveWS(object):
47
47
  self._keep_alive_timeout = kwargs.get('keepAliveTimeout', 5)
48
48
  self._reconnect_timeout = (self._connect_timeout / 3) - 0.5
49
49
  if self._reconnect_timeout <= 0:
50
- raise Exception(f'Connect timeout too small. Has to be at least: 5')
50
+ raise Exception(f"Connect timeout too small. Has to be at least: 5")
51
51
  self._reconnect_timeout = 1
52
52
 
53
53
  self._ws_input_buff_size = kwargs.get('wsInputBuffer', None)
@@ -58,9 +58,6 @@ class InoDriveWS(object):
58
58
  self._keep_alive = kwargs.get('keepAlive', True)
59
59
  self._binary = kwargs.get('binary', True)
60
60
 
61
- # Callbacks
62
- self._callbacks = kwargs.get("callbacks")
63
-
64
61
  if self._keep_alive_timeout < 1:
65
62
  self._keep_alive_timeout = 1
66
63
 
@@ -85,9 +82,20 @@ class InoDriveWS(object):
85
82
  self._connection_guard_timeout = 0.1
86
83
  self._connection_guard_timer = None
87
84
 
85
+ # Callbacks
86
+ self._callback = kwargs.get("callback")
87
+
88
+ @property
89
+ def callback(self):
90
+ return self._callback
91
+
92
+ @property
93
+ def on(self):
94
+ return self._callback.on
95
+
88
96
  def dispose(self):
89
97
  try:
90
- logging.debug(f'Dispose connection -> host [{self._target}]...')
98
+ logging.debug(f"Dispose connection -> host [{self._target}]...")
91
99
  self._cmd_state = "dispose"
92
100
 
93
101
  self.disconnect()
@@ -102,7 +110,7 @@ class InoDriveWS(object):
102
110
  kwargs = {}
103
111
  url = Utils.get_target_url(self._target, {'port': self._port, 'path': self._path, 'secure': self._secure, **kwargs})
104
112
  if self._ws_input_buff_size is not None:
105
- url = f'{url}?ibs={self._ws_input_buff_size}'
113
+ url = f"{url}?ibs={self._ws_input_buff_size}"
106
114
  return url
107
115
 
108
116
  def set_target(self, target=None):
@@ -139,7 +147,7 @@ class InoDriveWS(object):
139
147
  if not getattr(self, "_wsapp", None):
140
148
  logging.warning(f"Connect to: ---> {self._target_url}")
141
149
  timestamp = True if attempt == self._reconnect_attempts else False
142
- url = self.get_target(timestamp=timestamp)
150
+ url = self.get_target(timestamp=timestamp, secure=self._secure)
143
151
  # WebSocket instance
144
152
  self._wsapp = websocket.WebSocketApp(
145
153
  url,
@@ -149,12 +157,16 @@ class InoDriveWS(object):
149
157
  on_message=self.on_message
150
158
  )
151
159
 
152
- ca = f"{os.path.join(os.path.dirname(__file__))}\\ck_ca.crt"
160
+ # Secure Socket Options
161
+ sslopt = None
162
+ if self._secure:
163
+ ca = f"{os.path.join(os.path.dirname(__file__))}\\ck_ca.crt"
164
+
165
+ sslopt = {
166
+ "ca_certs": ca,
167
+ "cert_reqs": ssl.CERT_REQUIRED
168
+ }
153
169
 
154
- sslopt = {
155
- "ca_certs": ca,
156
- "cert_reqs": ssl.CERT_REQUIRED
157
- }
158
170
  websocket.setdefaulttimeout(self._connect_timeout)
159
171
  self._ws_thread = threading.Thread(
160
172
  target=self._wsapp.run_forever,
@@ -216,7 +228,7 @@ class InoDriveWS(object):
216
228
  self._dispose_ws()
217
229
  return
218
230
 
219
- self._disconnecting = False
231
+ self._disconnecting = True
220
232
 
221
233
  self._state = 'disconnecting'
222
234
  self._cmd_state = 'disconnect'
@@ -392,36 +404,41 @@ class InoDriveWS(object):
392
404
 
393
405
  self._msg_queue_pull(msg_token)
394
406
 
395
- if self._callbacks.get('onMessage'):
396
- self._callbacks['onMessage'](msg)
407
+ self._callback.dispatch("message", msg)
397
408
  except Exception as ex:
398
409
  logging.exception(str(ex))
399
410
 
400
411
  def on_connect(self, wsapp):
401
- logging.debug(f'Connection connected: {self._target_url}')
412
+ logging.debug(f"Connection connected: {self._target_url}")
402
413
 
403
414
  self._state = "connected"
404
415
  self._connecting = False
405
416
 
406
- if self._callbacks.get('onConnect'):
407
- self._callbacks['onConnect'](wsapp)
417
+ self._callback.dispatch("connect", wsapp)
408
418
 
409
419
  def on_disconnect(self, wsapp, close_status_code, close_msg):
410
- logging.debug(f'Connection disconnected: {self._target_url}')
420
+ logging.debug(f"Connection disconnected: {self._target_url}")
421
+
422
+ self._disconnecting = False
411
423
 
412
- self._disconnecting = True
413
424
  self._state = "disconnected"
414
425
 
415
- if self._callbacks.get('onDisconnect'):
416
- self._callbacks['onDisconnect'](wsapp, close_status_code, close_msg)
426
+ self._callback.dispatch("disconnect", wsapp, close_status_code, close_msg)
417
427
 
418
428
  def on_error(self, wsapp, evt):
419
- logging.exception(f'Connection error: {self._target_url}')
429
+ logging.exception(f"Connection error: {self._target_url}")
430
+
431
+ if "errno" in evt:
432
+ errno = evt.errno
433
+ if errno == 10061:
434
+ if self._secure:
435
+ # Tried secure websocket connection and got active connection refusal, try unsecure websocket connection
436
+ self._secure = False
437
+ self._target_url = self.get_target()
420
438
 
421
439
  self._state = "error"
422
440
 
423
- if self._callbacks.get('onError'):
424
- self._callbacks['onError'](wsapp, evt)
441
+ self._callback.dispatch("error", wsapp, evt)
425
442
 
426
443
  def _connect(self):
427
444
  logging.exception("Method not implemented...")
@@ -439,8 +456,8 @@ class InoDriveWS(object):
439
456
  def _msg_queue_put(self, token, props):
440
457
  if token in self._msg_queue:
441
458
  # Should never happen
442
- logging.warning(f'Message with token [ {token} ] already exist...')
443
- logging.warning(f'Connection message queue [ {token} ] -> Duplicated token...')
459
+ logging.warning(f"Message with token [ {token} ] already exist...")
460
+ logging.warning(f"Connection message queue [ {token} ] -> Duplicated token...")
444
461
  return
445
462
  self._msg_queue.update({token: props})
446
463
 
@@ -478,13 +495,13 @@ class InoDriveWS(object):
478
495
 
479
496
  def _guard_start(self):
480
497
  if not self._connection_guard_timer:
481
- logging.warning(f'Start guard [ {self._target_url} ]')
498
+ logging.warning(f"Start guard [ {self._target_url} ]")
482
499
  self._connection_guard_timer = threading.Thread(target=self._connection_guard_loop, daemon=True)
483
500
  self._connection_guard_running = True
484
501
  self._connection_guard_timer.start()
485
502
 
486
503
  def _guard_stop(self):
487
- logging.warning(f'Stop guard [ {self._target_url} ]')
504
+ logging.warning(f"Stop guard [ {self._target_url} ]")
488
505
  self._connection_guard_running = False
489
506
  self._connection_guard_timer.join()
490
507
  self._connection_guard_timer = None
@@ -1,18 +0,0 @@
1
- CkInoDriveAPI/IO.py,sha256=vaCoHNPF5-qYzA2vjtykYKHjtJicqAexL_tyGj9Vspk,10533
2
- CkInoDriveAPI/__init__.py,sha256=ejsWVPPET1Yvp3iHCYVdxGNw0rKtk814M8xEL4Lo2zM,104
3
- CkInoDriveAPI/ck_ca.crt,sha256=uopTpSLmrazZpYhrJ-79bMTFYIjiAMxhHhMo07hYsy4,878
4
- CkInoDriveAPI/defines.py,sha256=ZbgVXIF9Ax-cKU3bXl7tsT6rVPUpr6p2rlVqmGvh1wc,12903
5
- CkInoDriveAPI/discoverLan.py,sha256=cMUfD5MDxPxPOu2K-1oOoUIMdDJtplh3-ff3hxeTFc8,11029
6
- CkInoDriveAPI/discoverWs.py,sha256=hdqKz0IAS9NBO90r3TFzsyKKl152XpfVZX5eUemk4fg,1154
7
- CkInoDriveAPI/file.py,sha256=amUdZOKKr9EXDEjYNmkNrRtYqGro93BjdtvhsiwhjLQ,6584
8
- CkInoDriveAPI/inoDrive.py,sha256=g3IWnKt-PZD9j43nCj7cgSAX8uTI9BYSUeRHPIEjhGY,5667
9
- CkInoDriveAPI/sysControl.py,sha256=SLsi6JKG1jRkLDtSS0YW8Jqmcrl3UV4xC5Li9N-rvvw,3482
10
- CkInoDriveAPI/userApp.py,sha256=3i9zrml8JAheOzId-6KSks_1grWwXQc6UHMitwJV5jc,21465
11
- CkInoDriveAPI/utils.py,sha256=CwAVqkWMfbGcY2xq8jply8qgXs3Ff6EnD0UUkJs8Fi8,16003
12
- CkInoDriveAPI/wsHandle.py,sha256=WVn_yDVHyuSQOxnvY1GC0AUaXyOC-lXSFJ5eA2qnYeI,19150
13
- CK_InoDrive_API-1.0.0.dist-info/LICENSE.txt,sha256=Htz8K82ehzm2lkK44nZ_hU0M5I4W8YHipiiRYyRdH5o,1077
14
- CK_InoDrive_API-1.0.0.dist-info/METADATA,sha256=KHx5mUSHBM73xd5tcf5N1fn7eYuHTvMa4hDuEoo0eWE,3127
15
- CK_InoDrive_API-1.0.0.dist-info/README.txt,sha256=AmRZf0ukNgLBwr5t_xfghCUOF4UIsmrNtSJtUeWL6ms,94524
16
- CK_InoDrive_API-1.0.0.dist-info/WHEEL,sha256=cVxcB9AmuTcXqmwrtPhNK88dr7IR_b6qagTj0UvIEbY,91
17
- CK_InoDrive_API-1.0.0.dist-info/top_level.txt,sha256=HQb3X73ZpaiGH2dSziFYqzUFtsf1oG6A5_qUtF03xyQ,14
18
- CK_InoDrive_API-1.0.0.dist-info/RECORD,,