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

Multiple bits in single byte get squished #104

Closed
jwdfki opened this issue Aug 15, 2018 · 1 comment
Closed

Multiple bits in single byte get squished #104

jwdfki opened this issue Aug 15, 2018 · 1 comment
Assignees
Milestone

Comments

@jwdfki
Copy link

jwdfki commented Aug 15, 2018

I have a PDO which has 2 bit in one byte. Say bit 0 and bit 1.
If I set or reset bit 0 and read it back, all behaves as expected. But if I do set and reset bit 1 I actually only change bit 0 again.

I got to the bottom of this and the problem is in file pdo.py in the functions set_data and get_data.
In function set_data this line destroys all the correctly done bitshifting and masking to one bool that gets written at one byte location

data = od_struct.pack_into(self.msg.data, byte_offset, data)

using this line instead 'fixes' it. I don't quite know what other sideeffects this might have.

self.msg.data[byte_offset] = data

Although this just fixes the writing part. If your try to read bit 1 it still does not work. But bit 0 would report as set if bit 1 was set.

This happens because in the function get_data this line

data = od_struct.unpack_from(self.msg.data, byte_offset)[0]

squishes everything from one byte into one boolean which sits at bit 0. The shifting and masking will then zero out any bit above 0 that we try to read.
I could 'fix' this with this:

if self.od.data_type is 1: #is of type boolean
  data = self.msg.data[byte_offset]
  data = (data >> bit_offset) & ((1 << self.length) - 1)
  data = bool(data)
else:
  data = od_struct.unpack_from(self.msg.data, byte_offset)[0]
  data = (data >> bit_offset) & ((1 << self.length) - 1)
#now comes the sign check and sign fixup

The magic number 1 here checks if the type is bool and then does not use unpack but rather shifts first and then converts to type bool later. If the type is not bool everything stays as before.

@christiansandberg
Copy link
Owner

Thanks for the detailed report! You are right of course, we haven't considered boolean types.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants