GrovePi icon indicating copy to clipboard operation
GrovePi copied to clipboard

API of grovepi.read_i2c_block is unsafe and chashes grovepi.ultrasonicRead

Open Wuestenschiff opened this issue 9 years ago • 0 comments

read_i2c_block normally returns a list but in case of an IOError it returns -1 (int). This is extremely difficult to handle as one would had to test the return value of read_i2c_block.

One would have to use something like this:

number = read_i2c_block(address)
if type(number) is list:
     do something_usefull()
else:
  handle_error()

which is the same thing as catching the exception. ultrasonicRead and all the other function I saw in grovepi.py use the function in unsafe manor:

def ultrasonicRead(pin):
        write_i2c_block(address, uRead_cmd + [pin, unused, unused])
        time.sleep(.2)
        read_i2c_byte(address)
        number = read_i2c_block(address)
        return (number[1] * 256 + number[2])

Which leads to an TypeError and the program to crash as one is not expecting an TypeError.

This also happens in the wild: http://www.dexterindustries.com/forum/?topic=ultrasonic-ranger-1-0-broken/

It would be much clearer to just raise the IOError as this is what is happening as to convert it in an TypeError.

I have not checked all the other i2c routines maybe there are more problems like this.

Edit: Typo

Wuestenschiff avatar Aug 28 '15 08:08 Wuestenschiff