vrogg
vrogg

Reputation: 101

Can't send bytearray via paho-mqtt client.publish(). Socket error

I'm trying to send an image over paho-mqtt. I can send a simple string via client.publish() or when not using the paho.client -> client.publish(), but publish.single() my bytearray.

When trying to send the bytearray with client.publish() I get a socket error on my broker and it doesnt send my message (No on_publish call). What am I missing?

client = paho.Client()
client.on_connect = on_connect
client.on_publish = on_publish
client.connect(MQTT_BROKER, MQTT_PORT)

f = open("foo.jpg", "rb")
fileContent = f.read()
f.close()
byteArr = bytearray(fileContent)

client.publish("/data", byteArr)   # only works with strings. socket error on broker when using bytearray
# publish.single("/data", byteArr, hostname=MQTT_BROKER) # works with string and bytearray

Upvotes: 2

Views: 1579

Answers (1)

hardillb
hardillb

Reputation: 59648

As hashed out in the comments

def on_publish(client, userdata, mid):
  client.disconnect()
  client.stop_loop()

client = paho.Client()
client.on_connect = on_connect
client.on_publish = on_publish
client.connect(MQTT_BROKER, MQTT_PORT)
client.loop_start()

f = open("foo.jpg", "rb")
fileContent = f.read()
f.close()
byteArr = bytearray(fileContent)

client.publish("/data", byteArr) 

The reason client.loop_forever() didn't work is because this is a blocking call that never returns, so assuming you inserted it before the call to client.publish() you will never get there.

Upvotes: 1

Related Questions