Skip to content

Add optional word_len parameter to read_area/write_area#584

Open
gijzelaerr wants to merge 2 commits intomasterfrom
fix/559-write-area-word-len
Open

Add optional word_len parameter to read_area/write_area#584
gijzelaerr wants to merge 2 commits intomasterfrom
fix/559-write-area-word-len

Conversation

@gijzelaerr
Copy link
Owner

Summary

Fixes #559

write_area() and read_area() previously hardcoded WordLen.Byte for all non-timer/counter areas, making it impossible to perform bit-level operations through the standard API.

Root cause analysis

The S7 protocol supports multiple word lengths for area access (S7WLBit, S7WLByte, S7WLWord, etc.), and the original Snap7 C library exposes this parameter in Cli_WriteArea() / Cli_ReadArea(). However, the python-snap7 wrapper hardcoded the word length selection based solely on the area type:

if area == Area.TM:
    word_len = S7WordLen.TIMER
elif area == Area.CT:
    word_len = S7WordLen.COUNTER
else:
    word_len = S7WordLen.BYTE  # <-- always Byte, no way to override

This meant users could not write individual bits using WordLen.Bit with the byte_index*8 + bit_index addressing scheme described in the Snap7 documentation.

Fix

Added an optional word_len: Optional[WordLen] = None parameter to both read_area() and write_area():

  • When word_len is None (the default), the existing area-based logic is preserved — fully backwards compatible
  • When word_len is provided, it is used directly after mapping from the public WordLen enum to the internal S7WordLen enum (they share identical integer values)

This enables bit-level writes like:

client.write_area(Area.DB, 1, byte_index * 8 + bit_index, data, word_len=WordLen.Bit)

Test plan

  • Existing tests pass (326 passed)
  • Verify bit-level write with a real PLC using WordLen.Bit
  • Verify backwards compatibility — calls without word_len parameter behave identically

🤖 Generated with Claude Code

gijzelaerr and others added 2 commits February 27, 2026 10:27
The read_area() and write_area() methods hardcoded WordLen.Byte for
non-timer/counter areas, preventing users from performing bit-level
reads and writes. Add an optional word_len parameter that allows
callers to override the default area-based word length selection.

When word_len is None (the default), the existing area-based logic
is preserved. When provided, the WordLen enum value is mapped to
the corresponding S7WordLen value.

Fixes #559

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

WriteArea() function

1 participant