Skip to content

Instantly share code, notes, and snippets.

@tandv592082
Last active August 31, 2022 08:12
Show Gist options
  • Select an option

  • Save tandv592082/50b6a426b82ad6eb7937321b8c733a88 to your computer and use it in GitHub Desktop.

Select an option

Save tandv592082/50b6a426b82ad6eb7937321b8c733a88 to your computer and use it in GitHub Desktop.
Auto connect/reconnect to ROS Bridge Websocket with roslibjs
import ROSLIB from "roslib";
const connectToRosBridgeWs = (rosBridgeWSUrl = undefined, cb) => {
if (rosBridgeWSUrl) {
const ros = new ROSLIB.Ros();
try {
ros.connect(rosBridgeWSUrl);
if(typeof cb === 'function') {
cb(ros)
}
} catch (error) {
console.log('Invalid ws url!');
}
return ros;
} else {
console.log(
"Connecting to ROS bridge ws need a valid url, but got: " +
rosBridgeWSUrl
);
}
};
const handleRosConnection = (ros) => {
ros
.on('connection', function () {
console.log('Connected to ROS!')
clearTimeout(window.autoConnectTimeOut)
delete window.autoConnectTimeOut;
})
.on('error', function () {
console.log('Error connection!')
})
.on('close', function() {
console.log('Close connection, auto reconnect after 3 seconds!')
window.autoConnectTimeOut = setTimeout(() => {
connectToRosBridgeWs(rosBridgeWSUrl, handleRosConnection)
}, 3000)
})
}
const rosBridgeWSUrl = 'ws://localhost:9090'
connectToRosBridgeWs(rosBridgeWSUrl, handleRosConnection)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment