harmsm / PyCmdMessenger

Python interface for CmdMessenger arduino serial communication library
MIT License
80 stars 32 forks source link

New datatype "byte" #12

Closed sphh closed 7 years ago

sphh commented 7 years ago

Hi Mike,

I noticed that I cannot exchange "bytes" as integers between 0 and 255. They are handy to save a bit of dynamic memory on the Genuino. Here are the changes (sorry, no diff...):

        self._send_methods = {"c":self._send_char,
                              "b":self._send_byte,
                              "i":self._send_int,
        self._recv_methods = {"c":self._recv_char,
                              "b":self._recv_byte,
                              "i":self._recv_int,
    def _send_byte(self,value):
        """
        Convert a numerical value into an integer, then to a byte object. Check
        bounds for byte.
        """

        # Coerce to int. This will throw a ValueError if the value can't
        # actually be converted.
        if type(value) != int:
            new_value = int(value)

            if self.give_warnings:
                w = "Coercing {} into int ({})".format(value,new_value)
                warnings.warn(w,Warning)
                value = new_value

        # Range check
        if value > 255 or value < 0:
            err = "Value {} exceeds the size of the board's byte.".format(value)
            raise OverflowError(err)

        return struct.pack("b",value)
    def _recv_byte(self,value):
        """
        Recieve a byte in binary format, returning as python int.
        """

        return struct.unpack("b",value)[0]

Maybe you want to include it in your code...

Cheers, Stephan

harmsm commented 7 years ago

Hi Stephan,

Good idea. I've implemented this on a new branch: https://github.com/harmsm/PyCmdMessenger/tree/add-byte.

I added the byte type to the test suite and README. Would you be willing to test new code in your application to make sure it works? If so, I'll merge the branch into master.

Thanks for the suggestion. Mike

sphh commented 7 years ago

Hi Mike,

It worked for me before I sent you the changes. Since you only changed the type from "b" to "B" in struct.pack() and struck.unpack(), I don't see any reason, why it should not work!

Stephan

harmsm commented 7 years ago

Great, thanks. (Had to switch to "B" or it would choke for values above 127). Will merge into master.