import paho.mqtt.client as mqtt
# MQTT broker details
broker = "test.mosquitto.org"
port = 1883
topic = "M66_Rx"
# Modbus RTU Frame as a list of hex values
modbus_hex = [0x11, 0x03, 0x01, 0x02, 0x01, 0x04, 0xe7, 0x59]
# Convert the list of hex values to a byte array
modbus_bytes = bytes(modbus_hex)
# MQTT client setup
client = mqtt.Client()
def on_connect(client, userdata, flags, rc):
if rc == 0:
print("Connected to MQTT broker")
else:
print(f"Failed to connect to MQTT broker, return code {rc}")
def on_publish(client, userdata, mid):
print(f"Message published with mid={mid}")
client.on_connect = on_connect
client.on_publish = on_publish
# Connect to MQTT broker
client.connect(broker, port)
# Start the MQTT client loop in a non-blocking manner``
client.loop_start()
# Send the Modbus RTU frame as a single byte array`
try:
client.publish(topic, modbus_bytes)
print("Payload being sent:", modbus_bytes.hex())
print("Modbus RTU frame sent")
except KeyboardInterrupt:
# Handle the user interrupt to stop the script gracefully
print("Interrupted by user")
# Disconnect from MQTT broker
client.disconnect()
client.loop_stop()
print("Script finished")
Above code sent the Modbus_hex
array to mqtt as a query, but whenever i put 0x00
in between query it will not sent other bytes after 0x00
and also I have to put 0x00
at the last to terminate the query so how can I use 0x00
in between query without termination?
`
Bhavik Patel is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
3