Encoding/decoding dictionaries to byte arrays for LoRa/serial #16533
Replies: 4 comments 2 replies
-
answer to question 2, first: yes, printing a bytearray does print anything which is a printable, 7-bit ASCII character as such. Non-printable characters below 0x7f and all characters above 0x7f are printed as \x codes. (Note: I believe all printables are 0x20-0x3f (space through ?), 0x40-0x5f (@ through _) and 0x60-0x7e(` through ~)) question 1: don't trust |
Beta Was this translation helpful? Give feedback.
-
You might find the micropython-lib cbor2 library useful: https://github.com/micropython/micropython-lib/tree/master/python-ecosys/cbor2 CBOR is a standard binary encoding format, and the I think A CBOR encoded dict will be bigger than your encoding, because IIUC your encoding doesn't include the dict keys in the messages. However you could make a list of values and encode this as cbor2, and it would probably be a similar size. |
Beta Was this translation helpful? Give feedback.
-
This document describes options for serialisation in MicroPython. There are some interesting tradeoffs between various methods. |
Beta Was this translation helpful? Give feedback.
-
Thanks for the feedback all. The document on serialisation has some good info and the suggested cbor2 library might interesting in case I need to transmit other datatypes. I did a quick test on cbor2 and it look like it's around 30% reduction in bytes, but that's just a first limited test. In my current project transmission speed is priority. My homebrew solution transmits only 2 bytes for each key/value pair, with the limitation that the values can only be 0-255 and TX/RX both need to have the list of all variables. It's all about tradeoffs... |
Beta Was this translation helpful? Give feedback.
-
Hi all,
I'm working with LoRa and currently I use dictionaries/JSON to transmit messages. It keeps everything clear and readable but if I understand correctly each character in the JSON strings (including { " " : }) is transmitted as one byte, right? Since I have a fixed set of variables and my values are 0-255 I thought I'd explore the option to encode my dictionaries to byte arrays.
I wrote the class below and it seems to work fine but I'm hoping for some feedback and answers to my questions about the returned byte array. Below is the code and screenshots with comment (because tabbed comments are totally messed up when posting code)
General question are:
Question 1, size:
I would assume that a byte array of 8 bytes has a size of, well 8 bytes, so why is the size reported as 48?
Question 2, characters:
When encoding {'var1':60, 'var2':75, 'var3':88}
The result is printed as : bytearray(b'\x00<\x01K\x02X')
I read that this is just the way a byte array is printed, if it 'sees' an ASCII code it prints the character, is this correct?
Thanks for reading!
The class:
Example code:
Beta Was this translation helpful? Give feedback.
All reactions