-1

I've been trying to pub and sub a image using mosquitto in R-pi.

This is pub.py

    import paho.mqtt.client as mqtt

    def on_publish(mosq, userdata, mid):
     mosq.disconnect()

    client = mqtt.Client()

    client.connect("test.mosquitto.org", 1883, 60) #error?

    f = open("1.jpg", "rb")
    fileContent = f.read()
    byteArr = bytes(fileContent)
    client.publish("image", byteArr, 0)

    client.loop(5)

However, there is a error which is "UnicodeDecodeError:'ascii' code can't decode byte oxff in psition" when I run it.

I've thought this error is caused by "test.mosquitto.org" Line 8.

So, I was trying to change it other ways but It didn't work.

The most wired thing is that it worked when I'd tried open a text file and extract some char and pub/sub like this source.

    #It does work
    import paho.mqtt.client as mqtt

    def on_public(mosq, userdata, mid):
        mosq.disconnect()

    client = mqtt.Client()

    client.connect("test.mosquitto.org", 1883, 60)

    f=open("text.txt")
    con=f.read(3)
    client.publish("image",con)

    client.loop(5)

I can't find any difference and solve.

ralight
  • 11,033
  • 3
  • 49
  • 59
ahnstar
  • 55
  • 1
  • 3
  • 7

1 Answers1

1

It looks like you're running Python 2.7.

Try replacing

byteArr = bytes(fileContent)

with

byteArr = bytearray(fileContent)

The former still looks like a string, which is then passed through upayload = payload.encode('utf-8') by the library. If you've got binary data that won't work.


Other things you should do are to replace client.loop(5) with client.loop_forever(), otherwise the file may not get sent.

You don't assign your callback function either.

ralight
  • 11,033
  • 3
  • 49
  • 59