Bye Bye Moore

PoCソルジャーな零細事業主が作業メモを残すブログ

rclpyでROS2 paramsを使ってみる

以前つくったcpu温度をtopicで配信するcpu_tempの応用として、
nodeの挙動にパラメータを与える「ROS2 params」の実験をしてみます
適切に使えばビミョーな値の変更で毎回ビルドを変更しなくてよくなります

実際のところ

前提

shuzo-kino.hateblo.jp
をベースにします

paramsファイルの用意

$ cd ~/dev_ws/src
$ mkdir rpi_cpu_temp/params
$ touch rpi_cpu_temp/params/params.yaml

で、params.yamlを以下の様に設定します

cpu_temp_publisher:
    ros__parameters:
        timer_period: 2.0

これをsetup.py

    data_files=[
        #...
        ('share/' + package_name + '/params', ['params/params.yaml']),
    ],

スクリプトの更新

元プロジェクトでは1秒の固定値だったところ、秒数を変更できるようになりました

import rclpy
from rclpy.node import Node
from std_msgs.msg import Float64

class CpuTempPublisher(Node):

    def __init__(self):
        super().__init__('cpu_temp_publisher')
        self.publisher_ = self.create_publisher(Float64, 'cpu_temperature', 10)

        # timer_periodの使用を宣言 空なら1.0を
        self.declare_parameter("timer_period", 1.0)
        
        # Parameter Serverから"timer_period"を取得し、float型への変換を試みる
        try:
            new_timer_period = float(self.get_parameter("timer_period").value)
        except (TypeError, ValueError):  # 値が存在しないか、floatにキャストできない場合
            new_timer_period = False

        if isinstance(new_timer_period, float):
            timer_period = new_timer_period
        else:
            timer_period = 1.0

        self.timer = self.create_timer(timer_period, self.timer_callback)

    def timer_callback(self):
        temp = self.get_cpu_temperature()
        msg = Float64()
        msg.data = temp
        self.publisher_.publish(msg)
        self.get_logger().info(f"Published CPU Temp: {msg.data}")

    @staticmethod
    def get_cpu_temperature():
        with open("/sys/class/thermal/thermal_zone0/temp", "r") as f:
            temp = float(f.read()) / 1000.0
        return temp

def main(args=None):
    rclpy.init(args=args)
    cpu_temp_node = CpuTempPublisher()
    rclpy.spin(cpu_temp_node)
    cpu_temp_node.destroy_node()
    rclpy.shutdown()

if __name__ == '__main__':
    main()

ビルド

$ cd ~/dev_ws/
$ colcon build --packages-select rpi_cpu_temp
$ source install/setup.bash

コマンド

$ ros2 run rpi_cpu_temp cpu_temp_publisher --ros-args --params-file install/rpi_cpu_temp/share/rpi_cpu_temp/params/params.yaml

このパラメータファイルは適宜変更可能です
状態や時間帯に応じてアルゴリズムの挙動を微妙に変えたい場合などで使えるかもしれません

参考もと

Using the ros2 param command-line tool — ROS 2 Documentation: Humble documentation

launch時の初期値を変更したいだけの場合、LaunchConfigurationが使えるかもしれない

今回のようなケースで、単に初期値を設定したいだけの場合、Launchファイル用のパッケージLaunchConfigurationが有効なケースもあるかもしれません
shuzo-kino.hateblo.jp