Skip to content

str_to_data() incorrectly adds length to point_data #54

Open

Description

@jmmgenerac

The following function in sunspec/core/util.py is intended to convert a text string to bytes for writing to a device (i.e. via Modbus).

def str_to_data(s, slen=None):
    if slen is None:
        slen = len(s)
    if sys.version_info > (3,):
        s = bytes(s, 'latin-1')
    if slen < 16:
        s += b'\x00'
        slen += 1
    return struct.pack(str(slen) + 's', s)

The part I don't understand is:

    if slen < 16:
        s += b'\x00'
        slen += 1

if slen < 16:

Why is this here? It seems like all it does is add a null character if the string length is less than 16 bytes (or 8 Modbus registers). If you are unlucky enough to be writing an 8-register string, this causes an erroneous write of zero to the register immediately following the string. Indeed, this is how I discovered the bug.

Before I submit a pull request to delete these three lines of code, I'd like to understand what the intended purpose for adding the null byte is.

It seems like the only time you'd want to add a null byte would be to fill in the last word if the string had an odd number of characters. For this case, perhaps the check should be if slen % 2 == 1 instead of if slen < 16.

As far as I can tell, these to_data functions are only called with slen as an even number (i.e., point_len * 2), as in sunspec/core/client.py (on the last line in the code block below):

for block in self.blocks:
    for point in block.points_list:
        if point.dirty:
            point_addr = int(point.addr)
            point_len = int(point.point_type.len)
            point_data = point.point_type.to_data(point.value_base, (point_len * 2))

Activity

  1. changed the title [-]str_to_data adds extra null byte[/-] [+]str_to_data() incorrectly adds length to point_data[/+] on Mar 28, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions