python 3.x – Sending Hex data Over Mqtt in modbus protocol
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??
`
Read more here: Source link
