Last active
August 31, 2022 08:12
-
-
Save tandv592082/50b6a426b82ad6eb7937321b8c733a88 to your computer and use it in GitHub Desktop.
Auto connect/reconnect to ROS Bridge Websocket with roslibjs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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