Skip to content

Commit b60d80b

Browse files
authored
fix #272 (#360)
* fix #272 * fix wrong Errortype
1 parent 6a56345 commit b60d80b

File tree

7 files changed

+40
-48
lines changed

7 files changed

+40
-48
lines changed

snap7/client.py

Lines changed: 12 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,6 @@
1010

1111
import snap7
1212
from snap7.common import check_error, ipv4, load_library
13-
from snap7.exceptions import Snap7Exception
1413
from snap7.types import S7SZL, Areas, BlocksList, S7CpInfo, S7CpuInfo, S7DataItem
1514
from snap7.types import S7OrderCode, S7Protection, S7SZLList, TS7BlockInfo, WordLen
1615
from snap7.types import S7Object, buffer_size, buffer_type, cpu_statuses, param_types
@@ -125,7 +124,7 @@ def get_cpu_state(self) -> str:
125124
Description of the cpu state.
126125
127126
Raises:
128-
:obj:`Snap7Exception`: if the cpu state is invalid.
127+
:obj:`ValueError`: if the cpu state is invalid.
129128
130129
Examples:
131130
>>> client.get_cpu_statE()
@@ -136,7 +135,7 @@ def get_cpu_state(self) -> str:
136135
try:
137136
status_string = cpu_statuses[state.value]
138137
except KeyError:
139-
raise Snap7Exception(f"The cpu state ({state.value}) is invalid")
138+
raise ValueError(f"The cpu state ({state.value}) is invalid")
140139

141140
logger.debug(f"CPU state is {status_string}")
142141
return status_string
@@ -481,12 +480,12 @@ def list_blocks_of_type(self, blocktype: str, size: int) -> Union[int, Array]:
481480
If size is 0, it returns a 0, otherwise an `Array` of specified block type.
482481
483482
Raises:
484-
:obj:`Snap7Exception`: if the `blocktype` is not valid.
483+
:obj:`ValueError`: if the `blocktype` is not valid.
485484
"""
486485

487486
_blocktype = snap7.types.block_types.get(blocktype)
488487
if not _blocktype:
489-
raise Snap7Exception("The blocktype parameter was invalid")
488+
raise ValueError("The blocktype parameter was invalid")
490489

491490
logger.debug(f"listing blocks of type: {_blocktype} size: {size}")
492491

@@ -516,7 +515,7 @@ def get_block_info(self, blocktype: str, db_number: int) -> TS7BlockInfo:
516515
Structure of information from block.
517516
518517
Raises:
519-
:obj:`Snap7Exception`: if the `blocktype` is not valid.
518+
:obj:`ValueError`: if the `blocktype` is not valid.
520519
521520
Examples:
522521
>>> block_info = client.get_block_info("DB", 1)
@@ -540,7 +539,7 @@ def get_block_info(self, blocktype: str, db_number: int) -> TS7BlockInfo:
540539
blocktype_ = snap7.types.block_types.get(blocktype)
541540

542541
if not blocktype_:
543-
raise Snap7Exception("The blocktype parameter was invalid")
542+
raise ValueError("The blocktype parameter was invalid")
544543
logger.debug(f"retrieving block info for block {db_number} of type {blocktype_}")
545544

546545
data = TS7BlockInfo()
@@ -589,7 +588,7 @@ def set_connection_params(self, address: str, local_tsap: int, remote_tsap: int)
589588
590589
Raises:
591590
:obj:`ValueError`: if the `address` is not a valid IPV4.
592-
:obj:`Snap7Exception`: if the result of setting the connection params is
591+
:obj:`ValueError`: if the result of setting the connection params is
593592
different than 0.
594593
"""
595594
if not re.match(ipv4, address):
@@ -598,7 +597,7 @@ def set_connection_params(self, address: str, local_tsap: int, remote_tsap: int)
598597
c_uint16(local_tsap),
599598
c_uint16(remote_tsap))
600599
if result != 0:
601-
raise Snap7Exception("The parameter was invalid")
600+
raise ValueError("The parameter was invalid")
602601

603602
def set_connection_type(self, connection_type: int):
604603
""" Sets the connection resource type, i.e the way in which the Clients connects to a PLC.
@@ -607,13 +606,13 @@ def set_connection_type(self, connection_type: int):
607606
connection_type: 1 for PG, 2 for OP, 3 to 10 for S7 Basic
608607
609608
Raises:
610-
:obj:`Snap7Exception`: if the result of setting the connection type is
609+
:obj:`ValueError`: if the result of setting the connection type is
611610
different than 0.
612611
"""
613612
result = self._library.Cli_SetConnectionType(self._pointer,
614613
c_uint16(connection_type))
615614
if result != 0:
616-
raise Snap7Exception("The parameter was invalid")
615+
raise ValueError("The parameter was invalid")
617616

618617
def get_connected(self) -> bool:
619618
"""Returns the connection status
@@ -1122,11 +1121,11 @@ def as_list_blocks_of_type(self, blocktype: str, data, count) -> int:
11221121
Snap7 code.
11231122
11241123
Raises:
1125-
:obj:`Snap7Exception`: if the `blocktype` is invalid
1124+
:obj:`ValueError`: if the `blocktype` is invalid
11261125
"""
11271126
_blocktype = snap7.types.block_types.get(blocktype)
11281127
if not _blocktype:
1129-
raise Snap7Exception("The blocktype parameter was invalid")
1128+
raise ValueError("The blocktype parameter was invalid")
11301129
result = self._library.Cli_AsListBlocksOfType(self._pointer, _blocktype, byref(data), byref(count))
11311130
check_error(result, context="client")
11321131
return result

snap7/common.py

Lines changed: 4 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,6 @@
77
from typing import Optional
88
from ctypes.util import find_library
99

10-
from snap7.exceptions import Snap7Exception
11-
1210
if platform.system() == 'Windows':
1311
from ctypes import windll as cdll # type: ignore
1412
else:
@@ -52,7 +50,7 @@ def __init__(self, lib_location: Optional[str] = None):
5250
lib_location: full path to the `snap7.dll` file. Optional.
5351
5452
Raises:
55-
Snap7Exception: if `lib_location` is not found.
53+
RuntimeError: if `lib_location` is not found.
5654
"""
5755
if self.cdll: # type: ignore
5856
return
@@ -62,8 +60,7 @@ def __init__(self, lib_location: Optional[str] = None):
6260
or find_library('snap7')
6361
or find_locally('snap7'))
6462
if not self.lib_location:
65-
msg = "can't find snap7 library. If installed, try running ldconfig"
66-
raise Snap7Exception(msg)
63+
raise RuntimeError("can't find snap7 library. If installed, try running ldconfig")
6764
self.cdll = cdll.LoadLibrary(self.lib_location)
6865

6966

@@ -84,12 +81,12 @@ def check_error(code: int, context: str = "client") -> None:
8481
context: context in which is called.
8582
8683
Raises:
87-
Snap7Exception: if the code exists and is diferent from 1.
84+
RuntimeError: if the code exists and is different from 1.
8885
"""
8986
if code and code != 1:
9087
error = error_text(code, context)
9188
logger.error(error)
92-
raise Snap7Exception(error)
89+
raise RuntimeError(error)
9390

9491

9592
def error_text(error, context: str = "client") -> bytes:

snap7/logo.py

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,6 @@
1010
from snap7 import types
1111
from snap7.types import WordLen, S7Object, param_types
1212
from snap7.common import ipv4, check_error, load_library
13-
from snap7.exceptions import Snap7Exception
1413

1514
logger = logging.getLogger(__name__)
1615

@@ -268,15 +267,15 @@ def set_connection_params(self, ip_address: str, tsap_snap7: int, tsap_logo: int
268267
269268
Raises:
270269
:obj:`ValueError`: if the `ip_address` is not an IPV4.
271-
:obj:`Snap7Exception`: if the snap7 error code is diferent from 0.
270+
:obj:`ValueError`: if the snap7 error code is diferent from 0.
272271
"""
273272
if not re.match(ipv4, ip_address):
274273
raise ValueError(f"{ip_address} is invalid ipv4")
275274
result = self.library.Cli_SetConnectionParams(self.pointer, ip_address.encode(),
276275
c_uint16(tsap_snap7),
277276
c_uint16(tsap_logo))
278277
if result != 0:
279-
raise Snap7Exception("The parameter was invalid")
278+
raise ValueError("The parameter was invalid")
280279

281280
def set_connection_type(self, connection_type: int):
282281
"""Sets the connection resource type, i.e the way in which the Clients
@@ -286,12 +285,12 @@ def set_connection_type(self, connection_type: int):
286285
connection_type: 1 for PG, 2 for OP, 3 to 10 for S7 Basic
287286
288287
Raises:
289-
:obj:`Snap7Exception`: if the snap7 error code is diferent from 0.
288+
:obj:`ValueError`: if the snap7 error code is diferent from 0.
290289
"""
291290
result = self.library.Cli_SetConnectionType(self.pointer,
292291
c_uint16(connection_type))
293292
if result != 0:
294-
raise Snap7Exception("The parameter was invalid")
293+
raise ValueError("The parameter was invalid")
295294

296295
def get_connected(self) -> bool:
297296
"""Returns the connection status

snap7/partner.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,6 @@
1414

1515
import snap7.types
1616
from snap7.common import ipv4, check_error, load_library
17-
from snap7.exceptions import Snap7Exception
1817

1918
logger = logging.getLogger(__name__)
2019

@@ -86,7 +85,7 @@ def check_as_b_send_completion(self) -> Tuple[str, c_int32]:
8685
}
8786

8887
if result == -2:
89-
raise Snap7Exception("The Client parameter was invalid")
88+
raise ValueError("The Client parameter was invalid")
9089

9190
return return_values[result], op_result
9291

snap7/util.py

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -92,7 +92,6 @@
9292

9393
from snap7.types import Areas
9494
from snap7.client import Client
95-
from snap7.exceptions import Snap7Exception
9695

9796
logger = logging.getLogger(__name__)
9897

@@ -1167,7 +1166,7 @@ def get_value(self, byte_index: Union[str, int], type_: str) -> Union[ValueError
11671166
type_: type of data to read.
11681167
11691168
Raises:
1170-
:obj:`Snap7Exception`: if reading a `string` when checking the lenght of the string.
1169+
:obj:`ValueError`: if reading a `string` when checking the lenght of the string.
11711170
:obj:`ValueError`: if the `type_` is not handled.
11721171
11731172
Returns:
@@ -1190,7 +1189,7 @@ def get_value(self, byte_index: Union[str, int], type_: str) -> Union[ValueError
11901189
if type_.startswith('STRING'):
11911190
max_size = re.search(r'\d+', type_)
11921191
if max_size is None:
1193-
raise Snap7Exception("Max size could not be determinate. re.search() returned None")
1192+
raise ValueError("Max size could not be determinate. re.search() returned None")
11941193
max_size_grouped = max_size.group(0)
11951194
max_size_int = int(max_size_grouped)
11961195
return get_string(bytearray_, byte_index, max_size_int)
@@ -1226,7 +1225,7 @@ def set_value(self, byte_index: Union[str, int], type: str, value: Union[bool, s
12261225
value: value to write.
12271226
12281227
Raises:
1229-
:obj:`Snap7Exception`: if reading a `string` when checking the length of the string.
1228+
:obj:`ValueError`: if reading a `string` when checking the length of the string.
12301229
:obj:`ValueError`: if the `type_` is not handled.
12311230
12321231
Returns:
@@ -1245,7 +1244,7 @@ def set_value(self, byte_index: Union[str, int], type: str, value: Union[bool, s
12451244
if type.startswith('STRING') and isinstance(value, str):
12461245
max_size = re.search(r'\d+', type)
12471246
if max_size is None:
1248-
raise Snap7Exception("Max size could not be determinate. re.search() returned None")
1247+
raise ValueError("Max size could not be determinate. re.search() returned None")
12491248
max_size_grouped = max_size.group(0)
12501249
max_size_int = int(max_size_grouped)
12511250
return set_string(bytearray_, byte_index, value, max_size_int)

test/test_client.py

Lines changed: 14 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,6 @@
1212

1313
import snap7
1414
from snap7 import util
15-
from snap7.exceptions import Snap7Exception
1615
from snap7.common import check_error
1716
from snap7.server import mainloop
1817
from snap7.types import S7AreaDB, S7DataItem, S7SZL, S7SZLList, buffer_type, buffer_size, S7Object, Areas, WordLen
@@ -61,7 +60,7 @@ def _as_check_loop(self, check_times=20) -> int:
6160
break
6261
time.sleep(0.5)
6362
else:
64-
raise Snap7Exception(f"Async Request not finished after {check_times} times - Fail")
63+
raise TimeoutError(f"Async Request not finished after {check_times} times - Fail")
6564
return check_status.value
6665

6766
def test_db_read(self):
@@ -156,13 +155,13 @@ def test_upload(self):
156155
this raises an exception due to missing authorization? maybe not
157156
implemented in server emulator
158157
"""
159-
self.assertRaises(Snap7Exception, self.client.upload, db_number)
158+
self.assertRaises(RuntimeError, self.client.upload, db_number)
160159

161160
def test_as_upload(self):
162161
_buffer = buffer_type()
163162
size = ctypes.c_int(ctypes.sizeof(_buffer))
164163
self.client.as_upload(1, _buffer, size)
165-
self.assertRaises(Snap7Exception, self.client.wait_as_completion, 500)
164+
self.assertRaises(RuntimeError, self.client.wait_as_completion, 500)
166165

167166
@unittest.skip("TODO: invalid block size")
168167
def test_download(self):
@@ -229,7 +228,7 @@ def test_list_blocks(self):
229228
def test_list_blocks_of_type(self):
230229
self.client.list_blocks_of_type('DB', 10)
231230

232-
self.assertRaises(Snap7Exception, self.client.list_blocks_of_type, 'NOblocktype', 10)
231+
self.assertRaises(ValueError, self.client.list_blocks_of_type, 'NOblocktype', 10)
233232

234233
def test_get_block_info(self):
235234
"""test Cli_GetAgBlockInfo"""
@@ -592,7 +591,7 @@ def test_wait_as_completion_timeouted(self, timeout=0, tries=500):
592591
try:
593592
res = self.client.wait_as_completion(timeout)
594593
check_error(res)
595-
except Snap7Exception as s7_err:
594+
except RuntimeError as s7_err:
596595
if not s7_err.args[0] == b'CLI : Job Timeout':
597596
self.fail(f"While waiting another error appeared: {s7_err}")
598597
# Wait for a thread to finish
@@ -712,24 +711,24 @@ def test_as_eb_read(self):
712711
buffer = (type_ * 1)()
713712
response = self.client.as_eb_read(0, 1, buffer)
714713
self.assertEqual(0, response)
715-
self.assertRaises(Snap7Exception, self.client.wait_as_completion, 500)
714+
self.assertRaises(RuntimeError, self.client.wait_as_completion, 500)
716715

717716
def test_as_eb_write(self):
718717
# Cli_AsEBWrite
719718
response = self.client.as_eb_write(0, 1, bytearray(b'\x00'))
720719
self.assertEqual(0, response)
721-
self.assertRaises(Snap7Exception, self.client.wait_as_completion, 500)
720+
self.assertRaises(RuntimeError, self.client.wait_as_completion, 500)
722721

723722
def test_as_full_upload(self):
724723
# Cli_AsFullUpload
725724
self.client.as_full_upload('DB', 1)
726-
self.assertRaises(Snap7Exception, self.client.wait_as_completion, 500)
725+
self.assertRaises(RuntimeError, self.client.wait_as_completion, 500)
727726

728727
def test_as_list_blocks_of_type(self):
729728
data = (ctypes.c_uint16 * 10)()
730729
count = ctypes.c_int()
731730
self.client.as_list_blocks_of_type('DB', data, count)
732-
self.assertRaises(Snap7Exception, self.client.wait_as_completion, 500)
731+
self.assertRaises(RuntimeError, self.client.wait_as_completion, 500)
733732

734733
def test_as_mb_read(self):
735734
# Cli_AsMBRead
@@ -738,13 +737,13 @@ def test_as_mb_read(self):
738737
data = (type_ * 1)()
739738
self.client.as_mb_read(0, 1, data)
740739
bytearray(data)
741-
self.assertRaises(Snap7Exception, self.client.wait_as_completion, 500)
740+
self.assertRaises(RuntimeError, self.client.wait_as_completion, 500)
742741

743742
def test_as_mb_write(self):
744743
# Cli_AsMBWrite
745744
response = self.client.as_mb_write(0, 1, bytearray(b'\x00'))
746745
self.assertEqual(0, response)
747-
self.assertRaises(Snap7Exception, self.client.wait_as_completion, 500)
746+
self.assertRaises(RuntimeError, self.client.wait_as_completion, 500)
748747

749748
def test_as_read_szl(self):
750749
# Cli_AsReadSZL
@@ -927,8 +926,8 @@ def test_read_szl(self):
927926
# read_szl_invalid_id
928927
ssl_id = 0xffff
929928
index = 0xffff
930-
self.assertRaises(Snap7Exception, self.client.read_szl, ssl_id)
931-
self.assertRaises(Snap7Exception, self.client.read_szl, ssl_id, index)
929+
self.assertRaises(RuntimeError, self.client.read_szl, ssl_id)
930+
self.assertRaises(RuntimeError, self.client.read_szl, ssl_id, index)
932931

933932
def test_read_szl_list(self):
934933
# Cli_ReadSZLList
@@ -952,7 +951,7 @@ def test_tm_write(self):
952951
data = b'\x10\x01'
953952
self.assertEqual(0, self.client.tm_write(0, 1, bytearray(data)))
954953
self.assertEqual(data, self.client.tm_read(0, 1))
955-
self.assertRaises(Snap7Exception, self.client.tm_write, 0, 100, bytes(200))
954+
self.assertRaises(RuntimeError, self.client.tm_write, 0, 100, bytes(200))
956955
self.assertRaises(ValueError, self.client.tm_write, 0, 2, bytes(2))
957956

958957
def test_write_multi_vars(self):

test/test_partner.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -113,7 +113,7 @@ def test_stop(self):
113113
self.partner.stop()
114114

115115
def test_wait_as_b_send_completion(self):
116-
self.assertRaises(Snap7Exception, self.partner.wait_as_b_send_completion)
116+
self.assertRaises(RuntimeError, self.partner.wait_as_b_send_completion)
117117

118118

119119
class TestLibraryIntegration(unittest.TestCase):

0 commit comments

Comments
 (0)