Skip to content
Open
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
46 changes: 42 additions & 4 deletions acd/l5x/elements.py
Original file line number Diff line number Diff line change
Expand Up @@ -2725,6 +2725,33 @@ def _program_schedule_id(record: bytes) -> int:
return parsed.comment_id


def _task_settings_attribute(record: bytes) -> Union[bytes, None]:
"""Value of attribute 0x01 of a current-layout task record, or None.

Attributes follow the 82-byte header as (u32 id, u32 length, value). The
record can lack the last four bytes of its final attribute (they lie past
the stored length); the task settings sit well before them, so a final
value up to four bytes short is returned as far as it goes.
"""
if len(record) < 82:
return None
stored_length, count = struct.unpack_from("<II", record, 74)
if stored_length not in (len(record) - 74, len(record) - 78):
return None
pos = 82
for index in range(count):
if pos + 8 > len(record):
return None
attribute_id, length = struct.unpack_from("<II", record, pos)
end = pos + 8 + length
if end > len(record) and (index != count - 1 or end - len(record) > 4):
return None
if attribute_id == 0x01:
return bytes(record[pos + 8 : end])
pos = end
return None


@dataclass
class TaskBuilder(L5xElementBuilder):
def build(self, comment_id_to_program: Dict[int, str]) -> Task:
Expand All @@ -2734,9 +2761,20 @@ def build(self, comment_id_to_program: Dict[int, str]) -> Task:
row = self._cur.fetchone()
name, record = row[0], row[1]

# All task config fields live within ext[0x01], accessed via absolute BLOB offsets.
# These offsets were reverse-engineered from CIPDemo_RevEng.ACD.
if len(record) > 0x112E:
# All task config fields live within ext[0x01]; offsets below are
# relative to that attribute's value (reverse-engineered from
# CIPDemo_RevEng.ACD, where it starts at record offset 0x5A). Other
# attributes may precede it, so it is located by id, not position.
task_attribute = _task_settings_attribute(record) if len(record) > 0x112E else None
if task_attribute is not None and len(task_attribute) > 0x10D4:
task_data = task_attribute
rate_offset = 0x1012
type_offset = 0x109C
priority_offset = 0x109E
watchdog_offset = 0x10B0
disable_update = task_attribute[0x10D4]
program_offset = 0
elif len(record) > 0x112E:
task_data = record
rate_offset = 0x106C
type_offset = 0x10F6
Expand Down Expand Up @@ -2768,7 +2806,7 @@ def build(self, comment_id_to_program: Dict[int, str]) -> Task:
task_type = _TASK_TYPE_MAP.get(type_val, "PERIODIC")
rate_str = str(rate_us // 1000) if task_type != "CONTINUOUS" else None

# Scheduled programs: ext[0x01] value starts at BLOB offset 0x5A.
# Scheduled programs: at the start of the ext[0x01] value.
# Format: u16 count followed by N u32 comment_ids.
prog_count = struct.unpack_from("<H", task_data, program_offset)[0]
max_program_count = (rate_offset - program_offset - 2) // 4
Expand Down
80 changes: 72 additions & 8 deletions test/test_rx.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import struct

import pytest
from loguru import logger as log

from acd.l5x.elements import TagBuilder, TaskBuilder, _program_schedule_id
from acd.record.rx import LegacyRxGeneric, RxGeneric
Expand Down Expand Up @@ -465,17 +466,80 @@ def test_legacy_program_schedule_id_and_task():
database.close()


def test_legacy_task_rejects_excess_program_count():
@pytest.mark.parametrize("program_count", [128, 129])
def test_legacy_task_program_count_limit(program_count):
# The program list (u16 count, then u32 ids) ends where the rate starts,
# at offset 514, so it holds at most 128 ids. A 129th id would be the rate
# itself. Every slot, and the rate, is a known program id here, so a count
# past the limit would surface as phantom programs if it were trusted.
rate_us = 10_000
programs = {1000 + i: "Program%d" % i for i in range(128)}
programs[rate_us] = "Phantom"
task_data = bytearray(806)
struct.pack_into("<H", task_data, 0, 129)
task_record = _legacy_rx(
cip_type=0x70,
attributes=[(0x01, bytes(task_data))],
)
struct.pack_into("<H", task_data, 0, program_count)
struct.pack_into("<128I", task_data, 2, *range(1000, 1128))
struct.pack_into("<I", task_data, 514, rate_us)
struct.pack_into("<H", task_data, 652, 2)
struct.pack_into("<H", task_data, 654, 5)
struct.pack_into("<I", task_data, 802, 500_000)
task_record = _legacy_rx(cip_type=0x70, attributes=[(0x01, bytes(task_data))])

warnings = []
sink = log.add(warnings.append, level="WARNING", format="{message}")
database, cursor = _database()
try:
_insert(cursor, 100, "MainTask", task_record)
with pytest.raises(ValueError, match="too many scheduled programs"):
TaskBuilder(cursor, 100).build({})
task = TaskBuilder(cursor, 100).build(programs)
finally:
database.close()
log.remove(sink)

# The task and its settings survive either way.
assert (task.name, task.type, task.rate, task.priority, task.watchdog) == (
"MainTask", "PERIODIC", "10", "5", "500",
)
scheduled = [program.name for program in task.scheduled_programs]
if program_count == 128:
assert scheduled == ["Program%d" % i for i in range(128)]
assert warnings == []
else:
assert scheduled == []
assert len(warnings) == 1
assert "MainTask" in warnings[0] and "129" in warnings[0]


def _current_task_record(task_settings_first: bool, cut_short: bool) -> bytes:
# A current-layout task record whose attribute 0x01 holds the settings:
# the program list at 0, rate at 0x1012, type and priority at 0x109C,
# watchdog at 0x10B0 and disable-update-outputs at 0x10D4.
settings = bytearray(0x1114)
struct.pack_into("<HI", settings, 0, 1, 0x2420)
struct.pack_into("<I", settings, 0x1012, 20_000)
struct.pack_into("<HH", settings, 0x109C, 2, 7)
struct.pack_into("<I", settings, 0x10B0, 300_000)
settings[0x10D4] = 1
small = [(attribute_id, struct.pack("<I", 0)) for attribute_id in (0x65, 0x66, 0x68, 0x67)]
ordered = [(0x01, bytes(settings))] + small if task_settings_first else small + [(0x01, bytes(settings))]
attributes = b"".join(struct.pack("<II", i, len(v)) + v for i, v in ordered)
head = struct.pack("<IIHHH", 0, 0, 0, 0x70, 0) + bytes(60)
# The stored length leaves out the record's last four bytes.
record = head + struct.pack("<II", len(attributes) + 4, len(ordered)) + attributes
return record[:-4] if cut_short else record


@pytest.mark.parametrize("task_settings_first", [True, False])
@pytest.mark.parametrize("cut_short", [True, False])
def test_task_settings_are_found_by_attribute_id(task_settings_first, cut_short):
database, cursor = _database()
try:
_insert(cursor, 100, "MainTask", _current_task_record(task_settings_first, cut_short))
task = TaskBuilder(cursor, 100).build({0x2420: "MainProgram"})

assert task.type == "PERIODIC"
assert task.rate == "20"
assert task.priority == "7"
assert task.watchdog == "300"
assert task.disable_update_outputs == "true"
assert [program.name for program in task.scheduled_programs] == ["MainProgram"]
finally:
database.close()