Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add missing set_date function #494

Closed
wants to merge 5 commits into from
Closed
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions snap7/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -1175,6 +1175,35 @@ def get_date(bytearray_: bytearray, byte_index: int = 0) -> date:
raise ValueError("date_val is higher than specification allows.")
return date_val

def set_date(bytearray_: bytearray, byte_index: int, date: date) -> bytearray:
"""Set value in bytearray to date

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.

Args:
bytearray_: buffer to write.
byte_index: byte index from where to start writing.
date: date object

Examples:
>>> data = bytearray(2)

>>> snap7.util.set_date(data, 0, date(2024, 3, 27))

>>> data
bytearray(b'\x30\xd8')
"""
if date < date(1990, 1, 1):
edo2313 marked this conversation as resolved.
Show resolved Hide resolved
raise ValueError("date is lower than specification allows.")
elif date > date(2168, 12, 31):
raise ValueError("date is higher than specification allows.")
_days = (date - date(1990, 1, 1)).days
_bytes = struct.unpack('2B', struct.pack('>h', _days))
bytearray_[byte_index:byte_index + 2] = _bytes
edo2313 marked this conversation as resolved.
Show resolved Hide resolved
return bytearray_


def get_ltime(bytearray_: bytearray, byte_index: int) -> str:
raise NotImplementedError
Expand Down