Python mmp protocol

image
In the Python opto MMP protocol code in the init.py the range function at line 254 expects an int, dividing my hex values length at the moment gives a float of 2.5 which causes an error. Also, the “hexvals” operation at line 256 requires an int but it is fed “i + (4 - len(value) / 2)” which may be a float. I am still trying to understand what this code needed to accomplish but if any knows what should be done to fix this code please share your knowledge. I am using python 3.

Which function and what input are you using that is causing the error? Just trying to understand what is breaking exactly.

I am calling “self.grv_epic.SetScratchPadIntegerArea(<my_index>, <my_value>)” which works until I send a value greater than 255 which appears to cause the first if statement in the code above to execute.

Here is the error message:

for the sake of the delta between the package that loaded and what shows on the gethub master branch here is what is running on my machine:


What happens if you just cast the range result to an int on line 260?

for i in int(range(len(value) / 2 )):

Wouldn’t using a library make this simpler:

import struct
def PackInteger(self, value):
    return struct.pack('>I', value)

It’s been a while (5ish years) but if I recall correctly it started misbehaving with values over 256 because of the byte Endian order.

After much dabbling I ended up with this:


which yields:
image
is there some corner cases this code could cause problems with?

Looks complicated. Without using a library, couldn’t this function be reduced to this:

def PackInteger(self, value):
  hexvals = [0,0,0,0] #init a byte array
  for i in range(3, -1, -1): #loop through 3, 2, 1, 0
    hexvals[i] = value & 0x0FF; #bitand to get the least significant byte
    value = value >> 8; #shift the value over by a byte
  return hexvals

jdoodle: Online Compiler and Editor/IDE for Java, C/C++, PHP, Python, Perl, etc

2 Likes

That is beautiful… and it works.

3 Likes

If you’re a python purist, you can be more pythonic with a list comprehension and turn this into a one-liner:

def PackInteger(self, value):
  return [(value >> 8 * i) & 0x0FF for i in range(3, -1, -1)]
2 Likes