Skip to content

Commit 38b9248

Browse files
authored
add support for read/write byte from bytearray with tests (#268)
1 parent 3279ea1 commit 38b9248

File tree

2 files changed

+42
-1
lines changed

2 files changed

+42
-1
lines changed

snap7/util.py

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -135,6 +135,28 @@ def set_bool(bytearray_: bytearray, byte_index: int, bool_index: int, value: boo
135135
bytearray_[byte_index] -= index_value
136136

137137

138+
def set_byte(bytearray_: bytearray, byte_index: int, _int: int) -> bytearray:
139+
"""
140+
Set value in bytearray to byte
141+
"""
142+
_int = int(_int)
143+
_bytes = struct.pack('B', _int)
144+
bytearray_[byte_index:byte_index + 1] = _bytes
145+
return bytearray_
146+
147+
148+
def get_byte(bytearray_: bytearray, byte_index: int) -> int:
149+
"""
150+
Get byte value from bytearray.
151+
WORD 8bit 1bytes Decimal number unsigned B#(0) to B#(255) => 0 to 255
152+
"""
153+
data = bytearray_[byte_index:byte_index + 1]
154+
data[0] = data[0] & 0xff
155+
packed = struct.pack('B', *data)
156+
value = struct.unpack('B', packed)[0]
157+
return value
158+
159+
138160
def set_word(bytearray_: bytearray, byte_index: int, _int: int):
139161
"""
140162
Set value in bytearray to word

test/test_util.py

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import re
22
import unittest
3+
import struct
34

45
from snap7 import util, types
56

@@ -67,12 +68,30 @@
6768
32, 7, 18, 23, 50, 2, 133, 65, # these 8 values build the date and time 12 byte total
6869
# data typ together, for details under this link
6970
# https://support.industry.siemens.com/cs/document/36479/date_and_time-format-bei-s7-?dti=0&lc=de-DE
70-
254, 254, 254, 254, 254, 127 # test small int
71+
254, 254, 254, 254, 254, 127, # test small int
72+
128, # test set byte
7173
])
7274

75+
_new_bytearray = bytearray(100)
76+
_new_bytearray[41:41 + 1] = struct.pack("B", 128) # byte_index=41, value=128, bytes=1
77+
_new_bytearray[42:42 + 1] = struct.pack("B", 255) # byte_index=41, value=255, bytes=1
78+
7379

7480
class TestS7util(unittest.TestCase):
7581

82+
def test_get_byte(self):
83+
test_array = bytearray(_new_bytearray)
84+
byte_ = util.get_byte(test_array, 41)
85+
self.assertEqual(byte_, 128)
86+
byte_ = util.get_byte(test_array, 42)
87+
self.assertEqual(byte_, 255)
88+
89+
def test_set_byte(self):
90+
test_array = bytearray(_new_bytearray)
91+
util.set_byte(test_array, 41, 127)
92+
byte_ = util.get_byte(test_array, 41)
93+
self.assertEqual(byte_, 127)
94+
7695
def test_get_s5time(self):
7796
"""
7897
S5TIME extraction from bytearray

0 commit comments

Comments
 (0)