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
Show file tree
Hide file tree
Changes from all 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
32 changes: 32 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):
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 Expand Up @@ -1818,6 +1847,9 @@ def set_value(self, byte_index: Union[str, int], type_: str, value: Union[bool,

if type_ == 'TIME' and isinstance(value, str):
return set_time(bytearray_, byte_index, value)

if type_ == 'DATE' and isinstance(value, date):
return set_date(bytearray_, byte_index, value)

raise ValueError

Expand Down
6 changes: 6 additions & 0 deletions tests/test_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -531,6 +531,12 @@ def test_get_dtl(self):
val = row['testDtl']
self.assertEqual(val, datetime.datetime(year=2022, month=3, day=9, hour=12, minute=34, second=45))

def test_set_date(self):
test_array = bytearray(_bytearray)
row = util.DB_Row(test_array, test_spec_indented, layout_offset=4)
row['testDate'] = datetime.date(day=28, month=3, year=2024)
self.assertEqual(row['testDate'], datetime.date(day=28, month=3, year=2024))


def print_row(data):
"""print a single db row in chr and str
Expand Down
Loading