Reputation: 1
I am trying to send a file through the MQTT protocol using the Paho MQTT as client and the Mosquitto MQTT broker.
Client code to send the message:
import paho.mqtt.client as mqtt
# Define the broker details
broker_address = "127.0.0.1"
port = 1883
topic = "test"
keep_alive_time = 18 * 60 * 60
# Read the file contents in binary mode
file_path = "D:/FSP/OTA//ftpserverpython/public/u2a16_startup.mot"
with open(file_path, 'rb') as file:
message = file.read()
# Create an MQTT client instance
client = mqtt.Client()
# Connect to the broker
client.connect(broker_address, port, keep_alive_time)
# Publish the message as binary data
client.publish(topic, message, retain=True)
# Disconnect from the broker
client.disconnect()
print("Binary file published successfully.")
Client code to receive the message:
import paho.mqtt.client as mqtt
# Define the broker details
broker_address = "127.0.0.1"
port = 1883
topic = "test"
keep_alive_time = 18 * 60 * 60
# Read the file contents in binary mode
output_file_path = "D:/FSP/OTA/mqttclient//file/b.mot"
def on_message(client, userdata, message):
# Write the received message payload to a file
with open(output_file_path, 'wb') as file:
file.write(message.payload)
print(f"File saved to {output_file_path}")
# Create an MQTT client instance
client = mqtt.Client()
# Connect to the broker
client.connect(broker_address, port, keep_alive_time)
# Publish the message as binary data
client.publish(topic, message, retain=True)
# Set the on_message callback
client.on_message = on_message
# Subscribe to the topic
client.subscribe(topic)
# Start the MQTT loop to process network traffic and dispatch callbacks
client.loop_forever()
First I run the code from receive side and the log from broker:
However, when running publish code the broker does not respond. The log is below:
Therefore, the file is not transmitted successfully.
I use mosquitto -v
to run Mosquitto.
I expect the file to be transmitted successfully
Upvotes: 0
Views: 89
Reputation: 59826
You message is bigger than will fit in one network packet (MTU), so you must run the MQTT client loop in the publisher.
You have 2 choices.
import paho.mqtt.publish as publish
publish.single(topic, message, hostname=broker, port=port)
def publish_callback(client, userdata, mid):
client.disconnect()
print("Binary file published successfully.")
# Create an MQTT client instance
client = mqtt.Client()
# Connect to the broker
client.connect(broker_address, port, keep_alive_time)
client.on_publish = publish_callback
client.loop_start()
# Publish the message as binary data
client.publish(topic, message, retain=True)
Upvotes: 1