Skip to content

Instantly share code, notes, and snippets.

@HWiese1980
Created October 14, 2019 11:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save HWiese1980/659b0488b11744be19d05b29cdcc5a6d to your computer and use it in GitHub Desktop.
Save HWiese1980/659b0488b11744be19d05b29cdcc5a6d to your computer and use it in GitHub Desktop.
A very, **very** basic ROS MQTT Bridge using `rosbridge_library` and `paho.mqtt`
import json
import paho.mqtt.client as mqtt
import rospy
from loguru import logger
from paho.mqtt.subscribe import simple
from rosbridge_library.rosbridge_protocol import RosbridgeProtocol
# The following parameters are passed on to RosbridgeProtocol
# defragmentation.py:
fragment_timeout = 600 # seconds
# protocol.py:
delay_between_messages = 0 # seconds
max_message_size = None # bytes
unregister_timeout = 10.0 # seconds
mqtt_publisher = mqtt.Client("rosbridge_mqtt")
mqtt_publisher.connect("localhost")
def process_message(message=None):
obj = json.loads(message)
topic = obj["topic"]
msg = obj["msg"]
payload = json.dumps(msg)
try:
mqtt_publisher.publish(topic, payload)
except Exception as e:
logger.error(f"Error publishing message to MQTT: {str(e)}")
if __name__ == "__main__":
rospy.init_node("mqtt_bridge")
parameters = {
"fragment_timeout": fragment_timeout,
"delay_between_messages": delay_between_messages,
"max_message_size": max_message_size,
"unregister_timeout": unregister_timeout
}
rb_prot = RosbridgeProtocol(0, parameters=parameters)
rb_prot.outgoing = process_message
while not rospy.is_shutdown():
msg = simple("rosbridge")
logger.info(f"Message {msg.payload.decode()}")
rb_prot.incoming(msg.payload.decode())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment