Recently I wanted to enter the Alexa / LEGO MINDSTORMS challenge:
My idea required being able to send EV3 Mailbox messages via Bluetooth between ev3dev and a stock EV3 running the EV3g language – from Python. I’m new to Python, I’m a Perl programmer at heart, so this was somewhat of a learning curve moment. I had to get to grips with Bluetooth (not that difficult as I’m used the IP networking) and Python at the same time.
I figured that one of the major selling points of Python was its extensive library of support functions, so set to looking for something providing EV3 Mailbox handling. My research wasn’t as fruitful as I’d hoped for. I could find various chunks of code but either they were flawed in their behaviour, or much more heavyweight than I wanted. So I decided to jump in feet first and write my own library.
I’d written a library for App Inventor 2      that would encode & decode EV3 Mailbox payloads before, so this wasn’t too daunting a task. One aspect of Mailbox messages is that there isn’t an identifier within the payload that identifies the content: String, Float (IEE754 32 bit), Boolean. Normally this is handled in EV3g by expecting a specific type relating to the message name – i.e. a message called “status” would be defined to always be a Boolean, but “command” would always be a String – the code forces the type to remain constant. However, the type of the payload can be deduced to some extent, so I decide that I’d implement that within the Python class:
- Payload length = 1 byte => Boolean
- Payload length = 4 bytes
- Last byte != NULL or NULL in the other bytes => Float
- Otherwise => String
- All other payloads => String
The only issue with the logic above is that really, really, small numbers may get decoded as strings, e.g. “@@@\x00” would get seen as a string, not 5.90052e-39 which is also a valid decode of it. As such I also implemented a .force_float() method which will re-decode the payload.
The git repo for this library can be found at:
To use it do something like:
from ev3mailbox import EV3Mailbox as Mailbox message = EV3Mailbox.encode("Name", "Message value", Mailbox.Type.TEXT) print(message) # Data from Bluetooth mailbox = EV3Mailbox.decode(payload) print(mailbox)
Hopefully this will prove useful to others. The code has been released under the GPLv3: https://www.gnu.org/licenses/gpl-3.0.txt