Util
Data type conversion helpers for reading and writing S7 data types (BOOL, INT, REAL, STRING, etc.):
from s7 import util
data = client.db_read(1, 0, 4)
value = util.get_real(data, 0)
- snap7.util.get_bool(bytearray_: bytearray | memoryview, byte_index: int, bool_index: int) bool[source]
Get the boolean value from location in bytearray
- Parameters:
bytearray – buffer data.
byte_index – byte index to read from.
bool_index – bit index to read from.
- Returns:
True if the bit is 1, else 0.
Examples
>>> buffer = bytearray([0b00000001]) # Only one byte length >>> get_bool(buffer, 0, 0) # The bit 0 starts at the right. True
- snap7.util.get_byte(bytearray_: bytearray | memoryview, byte_index: int) int[source]
Get byte value from bytearray.
Notes
WORD 8bit 1bytes Decimal number unsigned B#(0) to B#(255) => 0 to 255
- Parameters:
bytearray – buffer to be read from.
byte_index – byte index to be read.
- Returns:
value get from the byte index.
- snap7.util.get_char(bytearray_: bytearray | memoryview, byte_index: int) str[source]
Get char value from bytearray.
Notes
Datatype char in the PLC is represented in 1 byte. It has to be in ASCII-format.
- Parameters:
bytearray – buffer to read from.
byte_index – byte index to start reading from.
- Returns:
Value read.
Examples
Read 1 Byte raw from DB1.10, where a char value is stored. Return Python compatible value. >>> from snap7 import Client >>> data = Client().db_read(db_number=1, start=10, size=1) >>> get_char(data, 0) ‘C’
- snap7.util.get_date_time_object(bytearray_: bytearray | memoryview, byte_index: int) datetime[source]
Get DATE_AND_TIME Value from bytearray as python datetime object .. rubric:: Notes
Datatype DATE_AND_TIME consists in 8 bytes in the PLC.
- Parameters:
bytearray – buffer to read.
byte_index – byte index from where to start writing.
Examples
>>> data = bytearray(8) >>> data[:] = [32, 7, 18, 23, 50, 2, 133, 65] #date '2020-07-12 17:32:02.854' >>> get_date_time_object(data,0) datetime.datetime(2020, 7, 12, 17, 32, 2, 854000)
- snap7.util.get_dint(bytearray_: bytearray | memoryview, byte_index: int) int[source]
Get dint value from bytearray.
Notes
Datatype dint consists in 4 bytes in the PLC. Maximum possible value is 2147483647. Lower posible value is -2147483648.
- Parameters:
bytearray – buffer to read.
byte_index – byte index from where to start reading.
- Returns:
Value read.
Examples
>>> import struct >>> data = bytearray(4) >>> data[:] = struct.pack(">i", 2147483647) >>> get_dint(data, 0) 2147483647
- snap7.util.get_dt(bytearray_: bytearray | memoryview, byte_index: int) str[source]
Get DATE_AND_TIME Value from bytearray as ISO 8601 formatted Date String .. rubric:: Notes
Datatype DATE_AND_TIME consists in 8 bytes in the PLC.
- Parameters:
bytearray – buffer to read.
byte_index – byte index from where to start writing.
Examples
>>> data = bytearray(8) >>> data[:] = [32, 7, 18, 23, 50, 2, 133, 65] #'2020-07-12T17:32:02.854000' >>> get_dt(data,0) '2020-07-12T17:32:02.854000'
- snap7.util.get_dtl(bytearray_: bytearray | memoryview, byte_index: int) datetime[source]
Get DTL (Date and Time Long) value from bytearray.
Notes
Datatype
DTLconsists of 12 bytes in the PLC: - Bytes 0-1: Year (uint16, big-endian) - Byte 2: Month (1-12) - Byte 3: Day (1-31) - Byte 4: Weekday (1=Sunday, 7=Saturday) - Byte 5: Hour (0-23) - Byte 6: Minute (0-59) - Byte 7: Second (0-59) - Bytes 8-11: Nanoseconds (uint32, big-endian)- Parameters:
bytearray – buffer to read from.
byte_index – byte index from where to start reading.
- Returns:
datetime value (microsecond precision; sub-microsecond nanoseconds are truncated).
- snap7.util.get_dword(bytearray_: bytearray | memoryview, byte_index: int) int[source]
Gets the dword from the buffer.
Notes
Datatype dword consists in 8 bytes in the PLC. The maximum value posible is 4294967295
- Parameters:
bytearray – buffer to read.
byte_index – byte index from where to start reading.
- Returns:
Value read.
Examples
>>> data = bytearray(8) >>> data[:] = b"\x12\x34\xAB\xCD" >>> get_dword(data, 0) 4294967295
- snap7.util.get_fstring(bytearray_: bytearray | memoryview, byte_index: int, max_length: int, remove_padding: bool = True, encoding: str = 'latin-1') str[source]
Parse space-padded fixed-length string from bytearray
Notes
This function supports fixed-length strings, right-padded with spaces. Use the
encodingparameter to decode multi-byte strings (e.g."gbk"for Chinese PLCs or"utf-8").- Parameters:
bytearray – buffer from where to get the string.
byte_index – byte index from where to start reading.
max_length – the maximum length of the string in bytes.
remove_padding – whether to remove the right-padding.
encoding – character encoding used to decode the raw bytes (default
"latin-1").
- Returns:
String value.
Examples
>>> data = [ord(letter) for letter in "hello world "] >>> get_fstring(data, 0, 15) 'hello world' >>> get_fstring(data, 0, 15, remove_padding=False) 'hello world '
- snap7.util.get_int(bytearray_: bytearray | memoryview, byte_index: int) int[source]
Get int value from bytearray.
Notes
Datatype int in the PLC is represented in two bytes
- Parameters:
bytearray – buffer to read from.
byte_index – byte index to start reading from.
- Returns:
Value read.
Examples
>>> get_int(bytearray([0, 255]), 0) 255
- snap7.util.get_ldt(bytearray_: bytearray | memoryview, byte_index: int) datetime[source]
Get LDT (Long Date and Time) value from bytearray.
Notes
Datatype LDT consists of 8 bytes (64-bit unsigned integer) representing nanoseconds since 1970-01-01 00:00:00 UTC. Used in S7-1500 PLCs.
- Parameters:
bytearray – buffer to read from.
byte_index – byte index from where to start reading.
- Returns:
datetime value.
- snap7.util.get_lint(bytearray_: bytearray | memoryview, byte_index: int) int[source]
Get the long int
THIS VALUE IS NEITHER TESTED NOR VERIFIED BY A REAL PLC AT THE MOMENT
Notes
Datatype lint (long int) consists in 8 bytes in the PLC. Maximum value posible is +9223372036854775807 Lowest value posible is -9223372036854775808
- Parameters:
bytearray – buffer to read from.
byte_index – byte index from where to start reading.
- Returns:
Value read.
Examples
read lint value (here as example 12345) from DB1.10 of a PLC >>> from snap7 import Client >>> data = Client().db_read(db_number=1, start=10, size=8) >>> get_lint(data, 0) 12345
- snap7.util.get_lreal(bytearray_: bytearray | memoryview, byte_index: int) float[source]
Get the long real
Datatype lreal (long real) consists in 8 bytes in the PLC. Negative Range: -1.7976931348623158e+308 to -2.2250738585072014e-308 Positive Range: +2.2250738585072014e-308 to +1.7976931348623158e+308 Zero: ±0
- Parameters:
bytearray – buffer to read from.
byte_index – byte index from where to start reading.
- Returns:
The real value.
Examples
read lreal value (here as example 12345.12345) from DB1.10 of a PLC >>> from snap7 import Client >>> data = Client().db_read(db_number=1, start=10, size=8) >>> get_lreal(data, 0) 12345.12345
- snap7.util.get_ltime(bytearray_: bytearray | memoryview, byte_index: int) timedelta[source]
Get LTIME value from bytearray.
Notes
Datatype LTIME consists of 8 bytes (64-bit signed integer) representing nanoseconds. Used in S7-1500 PLCs.
- Parameters:
bytearray – buffer to read from.
byte_index – byte index from where to start reading.
- Returns:
timedelta value.
Examples
>>> data = bytearray(8) >>> data[:] = b'\x00\x00\x00\x00\x3b\x9a\xca\x00' # 1 second in nanoseconds >>> get_ltime(data, 0) datetime.timedelta(seconds=1)
- snap7.util.get_ltod(bytearray_: bytearray | memoryview, byte_index: int) timedelta[source]
Get LTOD (Long Time of Day) value from bytearray.
Notes
Datatype LTOD consists of 8 bytes (64-bit unsigned integer) representing nanoseconds since midnight. Used in S7-1500 PLCs. Range: 0 to 86399999999999 ns.
- Parameters:
bytearray – buffer to read from.
byte_index – byte index from where to start reading.
- Returns:
timedelta value representing time of day.
- snap7.util.get_lword(bytearray_: bytearray | memoryview, byte_index: int) int[source]
Get the long word
Notes
Datatype lword (long word) consists in 8 bytes in the PLC. Maximum value is 18446744073709551615 (0xFFFFFFFFFFFFFFFF). Minimum value is 0.
- Parameters:
bytearray – buffer to read from.
byte_index – byte index from where to start reading.
- Returns:
Value read.
Examples
>>> data = bytearray(b"\x00\x00\x00\x00\x00\x00\xAB\xCD") >>> get_lword(data, 0) 43981
- snap7.util.get_real(bytearray_: bytearray | memoryview, byte_index: int) float[source]
Get real value.
Notes
Datatype real is represented in 4 bytes in the PLC. The packed representation uses the IEEE 754 binary32.
- Parameters:
bytearray – buffer to read from.
byte_index – byte index to reading from.
- Returns:
Real value.
Examples
>>> data = bytearray(b'B\xf6\xa4Z') >>> get_real(data, 0) 123.32099914550781
- snap7.util.get_sint(bytearray_: bytearray | memoryview, byte_index: int) int[source]
Get the small int
Notes
Datatype sint (Small int) consists in 1 byte in the PLC. Maximum value posible is 127. Lowest value posible is -128.
- Parameters:
bytearray – buffer to read from.
byte_index – byte index from where to start reading.
- Returns:
Value read.
Examples
>>> data = bytearray([127]) >>> get_sint(data, 0) 127
- snap7.util.get_string(bytearray_: bytearray | memoryview, byte_index: int, encoding: str = 'latin-1') str[source]
Parse string from bytearray
Notes
The first byte of the buffer will contain the max size posible for a string. The second byte contains the length of the string that contains. Use the
encodingparameter to decode multi-byte strings (e.g."gbk"for Chinese PLCs or"utf-8").- Parameters:
bytearray – buffer from where to get the string.
byte_index – byte index from where to start reading.
encoding – character encoding used to decode the raw bytes (default
"latin-1").
- Returns:
String value.
Examples
>>> data = bytearray([254, len("hello world")] + [ord(l) for letter in "hello world"]) >>> get_string(data, 0) 'hello world'
- snap7.util.get_time(bytearray_: bytearray | memoryview, byte_index: int) str[source]
Get time value from bytearray.
Notes
Datatype time consists in 4 bytes in the PLC. Maximum possible value is T#24D_20H_31M_23S_647MS(2147483647). Lower posible value is T#-24D_20H_31M_23S_648MS(-2147483648).
- Parameters:
bytearray – buffer to read.
byte_index – byte index from where to start reading.
- Returns:
Value read.
Examples
>>> import struct >>> data = bytearray(4) >>> data[:] = struct.pack(">i", 2147483647) >>> get_time(data, 0) '24:20:31:23.647'
- snap7.util.get_udint(bytearray_: bytearray | memoryview, byte_index: int) int[source]
Get unsigned dint value from bytearray.
Notes
Datatype udint consists in 4 bytes in the PLC. Maximum possible value is 4294967295. Minimum posible value is 0.
- Parameters:
bytearray – buffer to read.
byte_index – byte index from where to start reading.
- Returns:
Value read.
Examples
>>> import struct >>> data = bytearray(4) >>> data[:] = struct.pack(">I", 4294967295) >>> get_udint(data, 0) 4294967295
- snap7.util.get_uint(bytearray_: bytearray | memoryview, byte_index: int) int[source]
Get unsigned int value from bytearray.
Notes
Datatype uint in the PLC is represented in two bytes Maximum posible value is 65535. Lower posible value is 0.
- Parameters:
bytearray – buffer to read from.
byte_index – byte index to start reading from.
- Returns:
Value read.
Examples
>>> data = bytearray([255, 255]) >>> get_uint(data, 0) 65535
- snap7.util.get_ulint(bytearray_: bytearray | memoryview, byte_index: int) int[source]
Get ulint value from bytearray.
Notes
Datatype int in the PLC is represented in 8 bytes
- Parameters:
bytearray – buffer to read from.
byte_index – byte index to start reading from.
- Returns:
Value read.
Examples
Read 8 Bytes raw from DB1.10, where an ulint value is stored. Return Python compatible value. >>> from snap7 import Client >>> data = Client().db_read(db_number=1, start=10, size=8) >>> get_ulint(data, 0) 12345
- snap7.util.get_usint(bytearray_: bytearray | memoryview, byte_index: int) int[source]
Get the unsigned small int from the bytearray
Notes
Datatype usint (Unsigned small int) consists on 1 byte in the PLC. Maximum posible value is 255. Lower posible value is 0.
- Parameters:
bytearray – buffer to read from.
byte_index – byte index from where to start reading.
- Returns:
Value read.
Examples
>>> data = bytearray([255]) >>> get_usint(data, 0) 255
- snap7.util.get_wchar(bytearray_: bytearray | memoryview, byte_index: int) str[source]
Get wchar value from bytearray.
Datatype wchar in the PLC is represented in 2 bytes. It has to be in utf-16-be format.
- Parameters:
bytearray – buffer to read from.
byte_index – byte index to start reading from.
- Returns:
Value read.
Examples
Read 2 Bytes raw from DB1.10, where a wchar value is stored. Return Python compatible value. >>> from snap7 import Client >>> data = Client().db_read(db_number=1, start=10, size=2) >>> get_wchar(data, 0) ‘C’
- snap7.util.get_word(bytearray_: bytearray | memoryview, byte_index: int) int[source]
Get word value from bytearray.
Notes
WORD 16bit 2bytes Decimal number unsigned B#(0,0) to B#(255,255) => 0 to 65535
- Parameters:
bytearray – buffer to get the word from.
byte_index – byte index from where start reading from.
- Returns:
Word value.
Examples
>>> get_word(bytearray([0, 100]), 0) 100
- snap7.util.get_wstring(bytearray_: bytearray | memoryview, byte_index: int) str[source]
Parse wstring from bytearray
Notes
Byte 0 and 1 contains the max size posible for a string (2 Byte value). byte 2 and 3 contains the length of the string that contains (2 Byte value). The other bytes contain WCHARs (2Byte) in utf-16-be style.
- Parameters:
bytearray – buffer from where to get the string.
byte_index – byte index from where to start reading.
- Returns:
String value.
Examples
Read from DB1.10 22, where the WSTRING is stored, the raw 22 Bytes and convert them to a python string >>> from snap7 import Client >>> data = Client().db_read(db_number=1, start=10, size=22) >>> get_wstring(data, 0) ‘hello world’
- snap7.util.set_bool(bytearray_: bytearray | memoryview, byte_index: int, bool_index: int, value: bool) bytearray | memoryview[source]
Set boolean value on location in bytearray.
- Parameters:
bytearray – buffer to write to.
byte_index – byte index to write to.
bool_index – bit index to write to.
value – value to write.
Examples
>>> buffer = bytearray([0b00000000]) >>> set_bool(buffer, 0, 0, True) >>> buffer bytearray(b"\x01")
- snap7.util.set_byte(bytearray_: bytearray | memoryview, byte_index: int, _int: int) bytearray | memoryview[source]
Set value in bytearray to byte
- Parameters:
bytearray – buffer to write to.
byte_index – byte index to write.
_int – value to write.
- Returns:
buffer with the written value.
Examples
>>> buffer = bytearray([0b00000000]) >>> set_byte(buffer, 0, 255) bytearray(b"\xFF")
- snap7.util.set_char(bytearray_: bytearray | memoryview, byte_index: int, chr_: str) bytearray | memoryview[source]
Set char value in a bytearray.
Notes
Datatype char in the PLC is represented in 1 byte. It has to be in ASCII-format
- Parameters:
bytearray – buffer to write to.
byte_index – byte index from where to start writing.
chr – char to write.
- Returns:
Buffer with the written value.
Examples
write char (here as example ‘C’) to DB1.10 of a PLC >>> data = bytearray(1) >>> set_char(data, 0, ‘C’) >>> data bytearray(‘0x43’)
- snap7.util.set_date(bytearray_: bytearray | memoryview, byte_index: int, date_: date) bytearray | memoryview[source]
Set value in bytearray to date .. rubric:: Notes
Datatype date consists in the number of days elapsed from 1990-01-01. It is stored as an int (2 bytes) in the PLC.
- Parameters:
bytearray – buffer to write.
byte_index – byte index from where to start writing.
date – date object
Examples
>>> data = bytearray(2) >>> set_date(data, 0, date(2024, 3, 27)) >>> data bytearray(b'0Ø')
- snap7.util.set_dint(bytearray_: bytearray | memoryview, byte_index: int, dint: int) bytearray | memoryview[source]
Set value in bytearray to dint
Notes
Datatype dint consists in 4 bytes in the PLC. Maximum possible value is 2147483647. Lower posible value is -2147483648.
- Parameters:
bytearray – buffer to write.
byte_index – byte index from where to start writing.
dint – double integer value
Examples
>>> data = bytearray(4) >>> set_dint(data, 0, 2147483647) >>> data bytearray(b'\x7f\xff\xff\xff')
- snap7.util.set_dt(bytearray_: bytearray | memoryview, byte_index: int, dt_: datetime) bytearray | memoryview[source]
Set DATE_AND_TIME value in bytearray.
Notes
Datatype DATE_AND_TIME consists of 8 bytes in BCD encoding: - Byte 0: Year (BCD, 0-99, 90-99 = 1990-1999, 0-89 = 2000-2089) - Byte 1: Month (BCD) - Byte 2: Day (BCD) - Byte 3: Hour (BCD) - Byte 4: Minute (BCD) - Byte 5: Second (BCD) - Byte 6-7: Milliseconds (BCD) + weekday
- Parameters:
bytearray – buffer to write to.
byte_index – byte index from where to start writing.
dt – datetime object to write.
- Returns:
Buffer with the written value.
Examples
>>> from datetime import datetime >>> data = bytearray(8) >>> set_dt(data, 0, datetime(2020, 7, 12, 17, 32, 2, 854000))
- snap7.util.set_dtl(bytearray_: bytearray | memoryview, byte_index: int, dt_: datetime) bytearray | memoryview[source]
Set DTL (Date and Time Long) value in bytearray.
Notes
Datatype DTL consists of 12 bytes in the PLC: - Bytes 0-1: Year (uint16, big-endian) - Byte 2: Month (1-12) - Byte 3: Day (1-31) - Byte 4: Weekday (1=Sunday, 7=Saturday) - Byte 5: Hour (0-23) - Byte 6: Minute (0-59) - Byte 7: Second (0-59) - Bytes 8-11: Nanoseconds (uint32, big-endian)
- Parameters:
bytearray – buffer to write to.
byte_index – byte index from where to start writing.
dt – datetime object to write.
- Returns:
Buffer with the written value.
Examples
>>> from datetime import datetime >>> data = bytearray(12) >>> set_dtl(data, 0, datetime(2024, 3, 27, 14, 30, 0))
- snap7.util.set_dword(bytearray_: bytearray | memoryview, byte_index: int, dword: int) bytearray | memoryview[source]
Set a DWORD to the buffer.
Notes
Datatype dword consists in 8 bytes in the PLC. The maximum value posible is 4294967295
- Parameters:
bytearray – buffer to write to.
byte_index – byte index from where to write.
dword – value to write.
Examples
>>> data = bytearray(4) >>> set_dword(data,0, 4294967295) >>> data bytearray(b'\xff\xff\xff\xff')
- snap7.util.set_fstring(bytearray_: bytearray | memoryview, byte_index: int, value: str, max_length: int, encoding: str = 'latin-1') bytearray | memoryview[source]
Set space-padded fixed-length string value
- Parameters:
bytearray – buffer to write to.
byte_index – byte index to start writing from.
value – string to write.
max_length – maximum string length in bytes, i.e. the fixed size of the string.
encoding – character encoding used to encode the string (default
"latin-1").
- Raises:
ValueError – if the encoded byte length of the value is larger than
max_length.
Examples
>>> data = bytearray(20) >>> set_fstring(data, 0, "hello world", 15) >>> data bytearray(b'hello world ')
- snap7.util.set_int(bytearray_: bytearray | memoryview, byte_index: int, _int: int) bytearray | memoryview[source]
Set value in bytearray to int
Notes
An datatype int in the PLC consists of two bytes.
- Parameters:
bytearray – buffer to write on.
byte_index – byte index to start writing from.
_int – int value to write.
- Returns:
Buffer with the written value.
Examples
>>> data = bytearray(2) >>> set_int(data, 0, 255) bytearray(b'\x00\xff')
- snap7.util.set_ldt(bytearray_: bytearray | memoryview, byte_index: int, value: datetime) bytearray | memoryview[source]
Set an LDT (Long Date and Time) value in bytearray.
Notes
Datatype
LDTconsists of 8 bytes (64-bit unsigned integer) representing nanoseconds since 1970-01-01 00:00:00 UTC. Used in S7-1500 PLCs.- Parameters:
bytearray – buffer to write to.
byte_index – byte index from where to start writing.
value – datetime value to write.
- Returns:
Buffer with the written value.
Examples
>>> from datetime import datetime >>> data = bytearray(8) >>> set_ldt(data, 0, datetime(2024, 1, 15, 10, 30, 0))
- snap7.util.set_lint(bytearray_: bytearray | memoryview, byte_index: int, value: int) bytearray | memoryview[source]
Set a long int value in bytearray.
Notes
Datatype
lintconsists of 8 bytes (64-bit signed integer). Range: -9223372036854775808 to +9223372036854775807.- Parameters:
bytearray – buffer to write to.
byte_index – byte index from where to start writing.
value – value to write.
- Returns:
Buffer with the written value.
Examples
>>> data = bytearray(8) >>> set_lint(data, 0, 12345)
- snap7.util.set_lreal(bytearray_: bytearray | memoryview, byte_index: int, lreal: float) bytearray | memoryview[source]
Set the long real
Notes
Datatype lreal (long real) consists in 8 bytes in the PLC. Negative Range: -1.7976931348623158e+308 to -2.2250738585072014e-308 Positive Range: +2.2250738585072014e-308 to +1.7976931348623158e+308 Zero: ±0
- Parameters:
bytearray – buffer to read from.
byte_index – byte index from where to start reading.
lreal – float value to set
- Returns:
Value to write.
Examples
write lreal value (here as example 12345.12345) to DB1.10 of a PLC >>> data = set_lreal(data, 12345.12345) >>> from snap7 import Client >>> Client().db_write(db_number=1, start=10, data=data)
- snap7.util.set_ltime(bytearray_: bytearray | memoryview, byte_index: int, value: timedelta) bytearray | memoryview[source]
Set an LTIME value in bytearray.
Notes
Datatype
LTIMEconsists of 8 bytes (64-bit signed integer) representing nanoseconds. Used in S7-1500 PLCs.- Parameters:
bytearray – buffer to write to.
byte_index – byte index from where to start writing.
value – timedelta value to write.
- Returns:
Buffer with the written value.
Examples
>>> from datetime import timedelta >>> data = bytearray(8) >>> set_ltime(data, 0, timedelta(seconds=1))
- snap7.util.set_ltod(bytearray_: bytearray | memoryview, byte_index: int, value: timedelta) bytearray | memoryview[source]
Set an LTOD (Long Time of Day) value in bytearray.
Notes
Datatype
LTODconsists of 8 bytes (64-bit unsigned integer) representing nanoseconds since midnight. Used in S7-1500 PLCs.- Parameters:
bytearray – buffer to write to.
byte_index – byte index from where to start writing.
value – timedelta representing time of day.
- Returns:
Buffer with the written value.
Examples
>>> from datetime import timedelta >>> data = bytearray(8) >>> set_ltod(data, 0, timedelta(hours=12, minutes=30))
- snap7.util.set_lword(bytearray_: bytearray | memoryview, byte_index: int, lword: int) bytearray | memoryview[source]
Set the long word
Notes
Datatype lword (long word) consists in 8 bytes in the PLC. Maximum value is 18446744073709551615 (0xFFFFFFFFFFFFFFFF). Minimum value is 0.
- Parameters:
bytearray – buffer to write to.
byte_index – byte index from where to start writing.
lword – unsigned 64-bit value to write.
- Returns:
Buffer with the written value.
Examples
>>> data = bytearray(8) >>> set_lword(data, 0, 0xABCD) >>> data bytearray(b'\x00\x00\x00\x00\x00\x00\xab\xcd')
- snap7.util.set_real(bytearray_: bytearray | memoryview, byte_index: int, real: bool | str | float | int) bytearray | memoryview[source]
Set Real value
Notes
Datatype real is represented in 4 bytes in the PLC. The packed representation uses the IEEE 754 binary32.
- Parameters:
bytearray – buffer to write to.
byte_index – byte index to start writing from.
real – value to be written.
- Returns:
Buffer with the value written.
Examples
>>> data = bytearray(4) >>> set_real(data, 0, 123.321) bytearray(b'B\xf6\xa4Z')
- snap7.util.set_sint(bytearray_: bytearray | memoryview, byte_index: int, _int: int) bytearray | memoryview[source]
Set small int to the buffer.
Notes
Datatype sint (Small int) consists in 1 byte in the PLC. Maximum value posible is 127. Lowest value posible is -128.
- Parameters:
bytearray –
buffer to write to.
byte_index: byte index from where to start writing. _int: value to write.
- Returns:
Buffer with the written value.
Examples
>>> data = bytearray(1) >>> set_sint(data, 0, 127) bytearray(b'\x7f')
- snap7.util.set_string(bytearray_: bytearray | memoryview, byte_index: int, value: str, max_size: int = 254, encoding: str = 'latin-1') bytearray | memoryview[source]
Set string value
- Parameters:
bytearray – buffer to write to.
byte_index – byte index to start writing from.
value – string to write.
max_size – maximum possible string size in bytes, max. 254 as default.
encoding – character encoding used to encode the string (default
"latin-1").
- Raises:
ValueError – if the encoded byte length of the value is larger than the
max_size, ormax_sizeis greater than 254.
Examples
>>> from snap7.util import set_string >>> data = bytearray(20) >>> set_string(data, 0, "hello world", 254) >>> data bytearray(b'\xff\x0bhello world\x00\x00\x00\x00\x00\x00\x00')
- snap7.util.set_time(bytearray_: bytearray | memoryview, byte_index: int, time_string: str) bytearray | memoryview[source]
Set value in bytearray to time
Notes
Datatype time consists in 4 bytes in the PLC. Maximum possible value is T#24D_20H_31M_23S_647MS(2147483647). Lower posible value is T#-24D_20H_31M_23S_648MS(-2147483648).
- Parameters:
bytearray – buffer to write.
byte_index – byte index from where to start writing.
time_string – time value in string
Examples
>>> data = bytearray(4)
>>> set_time(data, 0, '-22:3:57:28.192')
>>> data bytearray(b'Ú¯')
- snap7.util.set_tod(bytearray_: bytearray | memoryview, byte_index: int, tod: timedelta) bytearray | memoryview[source]
Set TIME_OF_DAY value in bytearray.
Notes
Datatype TIME_OF_DAY is stored as milliseconds since midnight in 4 bytes. Range: 0 to 86399999 ms (00:00:00.000 to 23:59:59.999).
- Parameters:
bytearray – buffer to write to.
byte_index – byte index from where to start writing.
tod – timedelta representing the time of day.
- Returns:
Buffer with the written value.
Examples
>>> from datetime import timedelta >>> data = bytearray(4) >>> set_tod(data, 0, timedelta(hours=12, minutes=30, seconds=15, milliseconds=500))
- snap7.util.set_udint(bytearray_: bytearray | memoryview, byte_index: int, udint: int) bytearray | memoryview[source]
Set value in bytearray to unsigned dint
Notes
Datatype dint consists in 4 bytes in the PLC. Maximum possible value is 4294967295. Minimum posible value is 0.
- Parameters:
bytearray – buffer to write.
byte_index – byte index from where to start writing.
udint – unsigned double integer value
Examples
>>> data = bytearray(4) >>> set_udint(data, 0, 4294967295) >>> data bytearray(b'\xff\xff\xff\xff')
- snap7.util.set_uint(bytearray_: bytearray | memoryview, byte_index: int, _int: int) bytearray | memoryview[source]
Set value in bytearray to unsigned int
Notes
An datatype uint in the PLC consists of two bytes.
- Parameters:
bytearray – buffer to write on.
byte_index – byte index to start writing from.
_int – int value to write.
- Returns:
Buffer with the written value.
Examples
>>> from snap7.util import set_uint >>> data = bytearray(2) >>> set_uint(data, 0, 65535) bytearray(b'\xff\xff')
- snap7.util.set_ulint(bytearray_: bytearray | memoryview, byte_index: int, value: int) bytearray | memoryview[source]
Set an unsigned long int value in bytearray.
Notes
Datatype
ulintconsists of 8 bytes (64-bit unsigned integer). Range: 0 to 18446744073709551615.- Parameters:
bytearray – buffer to write to.
byte_index – byte index from where to start writing.
value – value to write.
- Returns:
Buffer with the written value.
Examples
>>> data = bytearray(8) >>> set_ulint(data, 0, 12345)
- snap7.util.set_usint(bytearray_: bytearray | memoryview, byte_index: int, _int: int) bytearray | memoryview[source]
Set unsigned small int
Notes
Datatype usint (Unsigned small int) consists on 1 byte in the PLC. Maximum posible value is 255. Lower posible value is 0.
- Parameters:
bytearray –
buffer to write.
byte_index: byte index from where to start writing. _int: value to write.
- Returns:
Buffer with the written value.
Examples
>>> data = bytearray(1) >>> set_usint(data, 0, 255) bytearray(b'\xff')
- snap7.util.set_wchar(bytearray_: bytearray | memoryview, byte_index: int, chr_: str) bytearray | memoryview[source]
Set wchar value in a bytearray.
Notes
Datatype wchar in the PLC is represented in 2 bytes as UTF-16-BE.
- Parameters:
bytearray – buffer to write to.
byte_index – byte index from where to start writing.
chr – single character to write.
- Returns:
Buffer with the written value.
Examples
>>> data = bytearray(2) >>> set_wchar(data, 0, 'C') >>> data bytearray(b'\x00C')
- snap7.util.set_word(bytearray_: bytearray | memoryview, byte_index: int, _int: int) bytearray | memoryview[source]
Set value in bytearray to word
Notes
Word datatype is 2 bytes long.
- Parameters:
bytearray – buffer to be written.
byte_index – byte index to start write from.
_int – value to write.
- Returns:
buffer with the written value
- snap7.util.set_wstring(bytearray_: bytearray | memoryview, byte_index: int, value: str, max_size: int = 16382) None[source]
Set wstring value
Notes
Byte 0-1: max size (number of characters, 2-byte big-endian). Byte 2-3: current length (number of characters, 2-byte big-endian). Byte 4+: UTF-16-BE encoded characters (2 bytes each).
- Parameters:
bytearray – buffer to write to.
byte_index – byte index to start writing from.
value – string to write.
max_size – maximum number of characters allowed (default 16382).
- Raises:
TypeError – if the value is not a string.
ValueError – if the string is too long or max_size exceeds 16382.
Examples
>>> data = bytearray(26) >>> set_wstring(data, 0, "hello", 10)
DB layout helpers
DB and Row map a textual DB layout specification onto a byte buffer.
They are also exported directly from s7 and snap7.
This module contains utility functions for working with PLC DB objects. There are functions to work with the raw bytearray data snap7 functions return In order to work with this data you need to make python able to work with the PLC bytearray data.
For example code see test_util.py and example.py in the example folder.
example:
spec/DB layout
# Byte index Variable name Datatype
layout="""
4 ID INT
6 NAME STRING[6]
12.0 test_bool1 BOOL
12.1 test_bool2 BOOL
12.2 test_bool3 BOOL
12.3 test_bool4 BOOL
12.4 test_bool5 BOOL
12.5 test_bool6 BOOL
12.6 test_bool7 BOOL
12.7 test_bool8 BOOL
13 testReal REAL
17 testDword DWORD
"""
client = snap7.client.Client()
client.connect('192.168.200.24', 0, 3)
# this looks confusing but this means uploading from the PLC to YOU
# so downloading in the PC world :)
all_data = client.upload(db_number)
simple:
from snap7 import DB
db1 = DB(
db_number, # the db we use
all_data, # bytearray from the plc
layout, # layout specification DB variable data
# A DB specification is the specification of a
# DB object in the PLC you can find it using
# the dataview option on a DB object in PCS7
17+2, # size of the specification 17 is start
# of last value
# which is a DWORD which is 2 bytes,
1, # number of row's / specifications
id_field='ID', # field we can use to identify a row.
# default index is used
layout_offset=4, # sometimes specification does not start a 0
# like in our example
db_offset=0 # At which point in 'all_data' should we start
# reading. This could be that the specification
# does not start at 0
)
Now we can use db1 in python as a dict. if 'ID' contains
the 'test' we can identify the 'test' row in the all_data bytearray
To test of you layout matches the data from the plc you can
just print db1[0] or db['test'] in the example
db1['test']['test_bool1'] = 0
If we do not specify an id_field this should work to read out the
same data.
db1[0]['test_bool1']
to read and write a single Row from the plc. takes like 5ms!
db1['test'].write()
db1['test'].read(client)
- class snap7.util.db.DB(db_number: int, bytearray_: bytearray, specification: str, row_size: int, size: int, id_field: str | None = None, db_offset: int = 0, layout_offset: int = 0, row_offset: int = 0, area: Area = Area.DB)[source]
Manage a DB bytearray block given a specification of the Layout.
It is possible to have many repetitive instances of a specification this is called a “row”.
Probably most usecases there is just one row
Note
This class has some of the semantics of a dict. In particular, the membership operators (
in,not it), the access operator ([]), as well as thekeys()anditems()methods work as usual. Iteration, on the other hand, happens on items instead of keys (much likeitems()method).Examples
>>> db = DB() >>> db[0]['test_bool1'] = "test" >>> db.write(Client()) # puts data in plc
- __getitem__(key: str, default: None = None) None | Row[source]
Access a row of the table through its index.
Rows (values) are of type
DB_Row.Notes
This method has the same semantics as
dictaccess.
- __init__(db_number: int, bytearray_: bytearray, specification: str, row_size: int, size: int, id_field: str | None = None, db_offset: int = 0, layout_offset: int = 0, row_offset: int = 0, area: Area = Area.DB)[source]
Creates a new instance of the Row class.
- Parameters:
db_number – number of the DB to read from. This value should be 0 if area!=Areas.DB.
bytearray – initial buffer read from the PLC.
specification – layout of the PLC memory.
row_size – bytes size of a db row.
size – length of the memory area.
id_field – name to reference the row. Optional.
db_offset – at which byte in the db starts reading.
layout_offset – at which byte in the row specification we start reading the data.
row_offset – offset between rows.
area – which memory area this row is representing.
- __iter__() Iterator[Tuple[str, Any]][source]
Iterate over the items contained in the table, in the physical order they are contained in memory.
Notes
This method does not have the same semantics as
dictiteration. Instead, it has the same semantics as theitems()method, yielding(index, row)tuples.
- __len__() int[source]
Return the number of rows contained in the DB.
Notes
If more than one row has the same index value, it is only counted once.
- export() Dict[str, Any][source]
Export the object to a dict, where each item in the dictionary has an index as the key, and the value of the DB row associated with that index as a value, represented itself as a
dict(as returned byDB_Row.export()).The outer dictionary contains the rows in the physical order they are contained in memory.
Notes
This function effectively returns a snapshot of the DB.
- items() Iterator[Tuple[str, Any]][source]
Return a view object of the items (
(index, row)pairs) that are used as indices for the rows in the DB.
- keys() Iterator[str][source]
Return a view object of the keys that are used as indices for the rows in the DB.
- read(client: Client) None[source]
Reads all the rows from the PLC to the
bytearrayof this instance.- Parameters:
client –
Clientsnap7 instance.- Raises:
ValueError – if the row_size is less than 0.
- set_data(bytearray_: bytearray) None[source]
Set the new buffer data from the PLC to the current instance.
- write(client: Client) None[source]
Writes all the rows from the
bytearrayof this instance to the PLCNotes
When the row_offset property has been set to something other than None while constructing this object, this operation is not guaranteed to be atomic.
- Parameters:
client –
Clientsnap7 instance.- Raises:
ValueError – if the row_size is less than 0.
- class snap7.util.db.Row(bytearray_: bytearray | DB, _specification: str, row_size: int = 0, db_offset: int = 0, layout_offset: int = 0, row_offset: int | None = 0, area: Area = Area.DB)[source]
Provide ROW API for DB bytearray
- __init__(bytearray_: bytearray | DB, _specification: str, row_size: int = 0, db_offset: int = 0, layout_offset: int = 0, row_offset: int | None = 0, area: Area = Area.DB)[source]
Creates a new instance of the DB_Row class.
- Parameters:
bytearray – reference to the data of the parent DB.
_specification – row specification layout.
row_size – Amount of bytes of the row.
db_offset – at which byte in the db starts reading.
layout_offset – at which byte in the row specification we start reading the data.
row_offset – offset between rows.
area – which memory area this row is representing.
- Raises:
TypeError – if bytearray_ is not an instance of
bytearrayorDB.
- export() Dict[str, str | int | float | bool | datetime][source]
Export dictionary with values
- Returns:
dictionary containing the values of each value of the row.
- get_bytearray() bytearray[source]
Gets bytearray from self or DB parent
- Returns:
Buffer data corresponding to the row.
- get_offset(byte_index: str | int) int[source]
- Calculate correct beginning position for a row
the db_offset = row_size * index
- Parameters:
byte_index – byte index from where to start reading from.
- Returns:
Amount of bytes to ignore.
- get_value(byte_index: str | int, type_: str) int | float | str | datetime | bytearray | bytes | date | timedelta[source]
Gets the value for a specific type.
- Parameters:
byte_index – byte index from where start reading.
type – type of data to read.
- Raises:
ValueError – if reading a string when checking the length of the string.
ValueError – if the type_ is not handled.
- Returns:
Value read according to the type_
- read(client: Client) None[source]
Read current data of db row from plc.
- Parameters:
client –
Clientsnap7 instance.- Raises:
TypeError – if the _bytearray is not an instance of
DBclass.ValueError – if the row_size is less than 0.
- set_value(byte_index: str | int, type_: str, value: bool | str | float | date | datetime | timedelta) bytearray | memoryview | None[source]
Sets the value for a specific type in the specified byte index.
- Parameters:
byte_index – byte index to start writing to.
type – type of value to write.
value – value to write.
- Raises:
ValueError – if reading a string when checking the length of the string.
ValueError – if the type_ is not handled.
- Returns:
Buffer data with the value written. Optional.
- snap7.util.db.parse_specification(db_specification: str) Dict[str, Any][source]
- Create a db specification derived from a
dataview of a db in which the byte layout is specified
- Parameters:
db_specification – string formatted table with the indexes, aliases and types.
- Returns:
Parsed DB specification.