0

I am using the lib presented in https://github.com/cmcqueen/cobs-python to make sure i can send data over a serial line. However, this lib requires a string as input, which can be about anything (text files, images, etc...). Since I'm using serial line without any special features on, there is no need to worry about special characters triggering some events.

If I could, I would send for example the image in raw mode, since it does not matter how the data is passed to the other end, but I need to encode it with this lib.

I have tried the following:

data = open('img.jpg', 'wb')
cobs_packet = cobs.encode(''.join(data).encode('utf-8'))

This gives me the following error:

>>> UnicodeDecodeError: 'ascii' codec can't decode byte 0xff in position 0: ordinal not in range(128)

The problem is, if I use different encoding types, the data length is changed, and that can't happen for what I'm trying to do.

Isn't there any way to simply convert the input to string as-is?

EDIT: I'm using python version 2.7

Helder Esteves
  • 451
  • 4
  • 13
  • 1
    Which Python version do you use? – Michael Butscher Jan 04 '18 at 00:33
  • I'm using python 2.7 – Helder Esteves Jan 04 '18 at 00:39
  • 1
    Does this change the data length? `import base64 with open("img.jpg", "rb") as imageFile: str = base64.b64encode(imageFile.read()) print str` https://www.programcreek.com/2013/09/convert-image-to-string-in-python/ – chickity china chinese chicken Jan 04 '18 at 01:09
  • Yes, I've tested it by comparing with os.stat and printing the length of the encoding, b64 increases data length. – Helder Esteves Jan 04 '18 at 01:12
  • this returns the same data length as os.stat: `with open('img.jpg', "rb") as f: str_output = io.BytesIO(bytearray(f.read())).getvalue()`, taken from this answer https://stackoverflow.com/questions/41850407/image-from-bytes-python – chickity china chinese chicken Jan 04 '18 at 02:35
  • Please clarify 'serial line'. It just means that data are sent a bit at a time. The port could be any of RS232, USB, Firewire, Ethernet, or ... . Also important is the number of bits per 'character'. Base64 allows transmission of 8 bit bytes over a 7-bit line. I suspect that this is not your situation. Reading the cobs link, I suspect that you should *not* encode your image with *any* text encoding before passing it to `cobs.encode`. – Terry Jan Reedy Jan 04 '18 at 03:08
  • I have found a solution. It seems rather simple, I don't know how viable it was, but it worked, by using bytes() function. But to answer you Terry, the port I'm using is UART, so literally only 2 wires being used. The transmission is done with 8N1, all normal. – Helder Esteves Jan 04 '18 at 04:00

1 Answers1

0

I didn't test how far this is valid, but I have found a simple solution which seems to be working. By using bytes() function, it works somehow as strings. I can pass it to the lib in question like this.

Thanks for the help everyone. Cheers.

Helder Esteves
  • 451
  • 4
  • 13