LoginSignup
8
7

More than 5 years have passed since last update.

ROSでNode.jsを使う

Posted at

やっと、rosnodejsの環境が整ったのでその時のメモです。
環境は以下の通り。

  • Ubuntu18.04
  • ROS Melodic

準備

まずはいつもどおり、パッケージを作ります。
パッケージ名は好きに変更してください。今回はサンプルなのでstd_msgsを使います。

$ cd ~/catkin_ws/src
$ catkin_create_pkg rosnodejs_sample std_msgs

次にパッケージに移動しrosnodejsをインストール

$ cd ~/catkin_ws/src/rosnodejs_sample/
$ npm init
$ npm install rosnodejs

サンプルコード

サンプルはtalkerとlistenerを作ります。以下のファイルをrosnodejs_sample/scripts/に置きます。

talker.js
#!/usr/bin/env node
'use strict';

const rosnodejs = require('rosnodejs');
const std_msgs = rosnodejs.require('std_msgs').msg;

function talker() {
  rosnodejs.initNode('/talker_node')
    .then((rosNode) => {
      let pub = rosNode.advertise('/chatter', std_msgs.String);
      let count = 0;
      const msg = new std_msgs.String();
      setInterval(() => {
        msg.data = 'hello world ' + count;
        pub.publish(msg);
        rosnodejs.log.info('I said: [' + msg.data + ']');
        ++count;
      }, 100);
    });
}

if (require.main === module) {
  talker();
}
listener.js
#!/usr/bin/env node
'use strict';

const rosnodejs = require('rosnodejs');
const std_msgs = rosnodejs.require('std_msgs').msg;

function listener() {
  rosnodejs.initNode('/listener_node')
    .then((rosNode) => {
      let sub = rosNode.subscribe('/chatter', std_msgs.String,
        (data) => {
          rosnodejs.log.info('I heard: [' + data.data + ']');
        }
      );
    });
}

if (require.main === module) {
  listener();
}

その後、package.jsonに以下のように書きます。

package.json
{
  "name": "rosnodejs_sample",
  "version": "1.0.0",
  "description": "",
  "dependencies": {
    "rosnodejs": "^3.0.0"
  },
  "scripts": {
    "talker": "node scripts/talker.js",
    "listener": "node scripts/listener.js"
  },
  "author": "",
  "license": "ISC"
}

ビルドと実行

上記までできたらビルドします。rosrunで起動するためにscriptに実行権限をつけておきましょう。

cd ~/catkin_ws/src/rosnodejs_sample/scripts/
chmod +x *.js

ビルドはいつもどおりcatkin_makeで行います。

cd ~/catkin_ws/ && catkin_make

実行方法も特に変わりはありません。
端末を3つ開いて、それぞれで以下を実行します。

#terminal A
$ roscore

#terminal B
$ rosrun rosnodejs_sample talker.js

#terminal C
$ rosrun rosnodejs_sample listener.js 

 参考

8
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
7