Main Content

ros2genmsg

ROS 2 定義からのカスタム メッセージの生成

R2019b 以降

説明

ros2genmsg(folderpath) は、指定されたフォルダー パスで ROS 2 カスタム メッセージおよびサービス定義を読み取ることにより、ROS 2 カスタム メッセージを生成します。この関数のフォルダーには、1 つ以上の ROS 2 パッケージが含まれている必要があります。これらのパッケージでは、メッセージ定義が .msg ファイルに、サービス定義が .srv ファイルに、アクション定義が .action ファイルに含まれています。

生成したカスタム メッセージは、サポートされている他のすべてのメッセージと同様に、MATLAB® で送受信できます。これらのメッセージは ros2message を使用して作成するか、MATLAB コマンド ウィンドウで「ros2 msg list」と入力してメッセージのリストを表示することもできます。

メモ

  • ROS 2 用のカスタム メッセージを生成するには、ROS 2 パッケージを作成しなければなりません。このプロセスには、ご使用のプラットフォームに対応した C++ コンパイラが必要です。詳細については、ROS Toolbox システム要件を参照してください。

  • ROS 2 定義からのカスタム メッセージは、MATLAB の新しいリリースごとに再生成する必要があります。

  • MATLAB で生成したカスタム メッセージで eProsima Fast DDS および Eclipse Cyclone DDS ミドルウェアがサポートされるようになりました。ROS ミドルウェア実装の詳細については、Switching Between ROS Middleware Implementationsを参照してください。

ros2genmsg(folderpath,Name=Value) は、1 つ以上の名前と値の引数を使用して追加のオプションを指定します。

すべて折りたたむ

カスタム メッセージを使用して、ROS 2 で現在サポートされているメッセージ タイプのセットを拡張します。カスタム メッセージはユーザー定義のメッセージです。サポートされているメッセージ タイプを送受信する場合は、カスタム メッセージを使用する必要はありません。サポートされているメッセージ タイプのリストを表示するには、MATLAB® コマンド ウィンドウで「ros2 msg list」と入力します。サポートされている ROS 2 メッセージの詳細については、基本的な ROS 2 メッセージの操作を参照してください。

ROS 2 カスタム メッセージをはじめて取り扱う場合は、ROS Toolbox システム要件を参照してください。

ROS 2 カスタム メッセージは、msg という名前のフォルダーを含む ROS 2 パッケージ フォルダー内に指定されます。msg フォルダーには、すべてのカスタム メッセージ タイプ定義が含まれています。たとえば、custom フォルダーにある example_b_msgs パッケージのフォルダーとファイルの構造は次のとおりです。

このパッケージにはカスタム メッセージ タイプ Standalone.msg が含まれています。MATLAB はこれらのファイルを使用して、パッケージに含まれるカスタム メッセージを使用するために必要なファイルを生成します。

この例では、MATLAB で ROS 2 カスタム メッセージを作成します。必要な msg ファイルが含まれる ROS 2 パッケージがなければなりません。

カスタム メッセージ パッケージが正しいことを確認したら、親フォルダーへのパスを指定し、指定したパスで ros2genmsg を呼び出します。次の例では、依存関係にある example_package_a,example_package_b、および example_package_c という 3 つのメッセージが指定されています。また、この例は、複数のメッセージが含まれるフォルダーを使用して、すべてのメッセージを同時に生成できることも示しています。

新しい MATLAB セッションを開き、カスタム メッセージ フォルダーをローカル フォルダーに作成します。

folderPath = fullfile(pwd,"custom");
copyfile("example_*_msgs",folderPath);

カスタム メッセージ ファイルのフォルダー パスを指定し、ros2genmsg を使用してカスタム メッセージを作成します。

ros2genmsg(folderPath)
Identifying message files in folder 'C:/Work/custom'.Done.
Removing previous version of Python virtual environment.Done.
Creating a Python virtual environment.Done.
Adding required Python packages to virtual environment.Done.
Copying include folders.Done.
Copying libraries.Done.
Validating message files in folder 'C:/Work/custom'.Done.
[3/3] Generating MATLAB interfaces for custom message packages... Done.
Running colcon build in folder 'C:/Work/custom/matlab_msg_gen/win64'.
Build in progress. This may take several minutes...
Build succeeded.build log

ros2 msg list を呼び出して、新しいカスタム メッセージの作成を確認します。

ros2 msg list
action_msgs/CancelGoalRequest
action_msgs/CancelGoalResponse
action_msgs/GoalInfo
action_msgs/GoalStatus
action_msgs/GoalStatusArray
actionlib_msgs/GoalID
actionlib_msgs/GoalStatus
actionlib_msgs/GoalStatusArray
builtin_interfaces/Duration
builtin_interfaces/Time
composition_interfaces/ListNodesRequest
composition_interfaces/ListNodesResponse
composition_interfaces/LoadNodeRequest
composition_interfaces/LoadNodeResponse
composition_interfaces/UnloadNodeRequest
composition_interfaces/UnloadNodeResponse
diagnostic_msgs/AddDiagnosticsRequest
diagnostic_msgs/AddDiagnosticsResponse
diagnostic_msgs/DiagnosticArray
diagnostic_msgs/DiagnosticStatus
diagnostic_msgs/KeyValue
diagnostic_msgs/SelfTestRequest
diagnostic_msgs/SelfTestResponse
example_a_msgs/DependsOnB
example_b_msgs/Standalone
example_c_msgs/DependsOnB
example_interfaces/AddTwoIntsRequest
example_interfaces/AddTwoIntsResponse
example_interfaces/Bool
example_interfaces/Byte
example_interfaces/ByteMultiArray
example_interfaces/Char
example_interfaces/Empty
example_interfaces/Float32
example_interfaces/Float32MultiArray
example_interfaces/Float64
example_interfaces/Float64MultiArray
example_interfaces/Int16
example_interfaces/Int16MultiArray
example_interfaces/Int32
example_interfaces/Int32MultiArray
example_interfaces/Int64
example_interfaces/Int64MultiArray
example_interfaces/Int8
example_interfaces/Int8MultiArray
example_interfaces/MultiArrayDimension
example_interfaces/MultiArrayLayout
example_interfaces/SetBoolRequest
example_interfaces/SetBoolResponse
example_interfaces/String
example_interfaces/TriggerRequest
example_interfaces/TriggerResponse
example_interfaces/UInt16
example_interfaces/UInt16MultiArray
example_interfaces/UInt32
example_interfaces/UInt32MultiArray
example_interfaces/UInt64
example_interfaces/UInt64MultiArray
example_interfaces/UInt8
example_interfaces/UInt8MultiArray
example_interfaces/WString
geometry_msgs/Accel
geometry_msgs/AccelStamped
geometry_msgs/AccelWithCovariance
geometry_msgs/AccelWithCovarianceStamped
geometry_msgs/Inertia
geometry_msgs/InertiaStamped
geometry_msgs/Point
geometry_msgs/Point32
geometry_msgs/PointStamped
geometry_msgs/Polygon
geometry_msgs/PolygonStamped
geometry_msgs/Pose
geometry_msgs/Pose2D
geometry_msgs/PoseArray
geometry_msgs/PoseStamped
geometry_msgs/PoseWithCovariance
geometry_msgs/PoseWithCovarianceStamped
geometry_msgs/Quaternion
geometry_msgs/QuaternionStamped
geometry_msgs/Transform
geometry_msgs/TransformStamped
geometry_msgs/Twist
geometry_msgs/TwistStamped
geometry_msgs/TwistWithCovariance
geometry_msgs/TwistWithCovarianceStamped
geometry_msgs/Vector3
geometry_msgs/Vector3Stamped
geometry_msgs/Wrench
geometry_msgs/WrenchStamped
lifecycle_msgs/ChangeStateRequest
lifecycle_msgs/ChangeStateResponse
lifecycle_msgs/GetAvailableStatesRequest
lifecycle_msgs/GetAvailableStatesResponse
lifecycle_msgs/GetAvailableTransitionsRequest
lifecycle_msgs/GetAvailableTransitionsResponse
lifecycle_msgs/GetStateRequest
lifecycle_msgs/GetStateResponse
lifecycle_msgs/State
lifecycle_msgs/Transition
lifecycle_msgs/TransitionDescription
lifecycle_msgs/TransitionEvent
logging_demo/ConfigLoggerRequest
logging_demo/ConfigLoggerResponse
map_msgs/GetMapROIRequest
map_msgs/GetMapROIResponse
map_msgs/GetPointMapROIRequest
map_msgs/GetPointMapROIResponse
map_msgs/GetPointMapRequest
map_msgs/GetPointMapResponse
map_msgs/OccupancyGridUpdate
map_msgs/PointCloud2Update
map_msgs/ProjectedMap
map_msgs/ProjectedMapInfo
map_msgs/ProjectedMapsInfoRequest
map_msgs/ProjectedMapsInfoResponse
map_msgs/SaveMapRequest
map_msgs/SaveMapResponse
map_msgs/SetMapProjectionsRequest
map_msgs/SetMapProjectionsResponse
nav_msgs/GetMapRequest
nav_msgs/GetMapResponse
nav_msgs/GetPlanRequest
nav_msgs/GetPlanResponse
nav_msgs/GridCells
nav_msgs/MapMetaData
nav_msgs/OccupancyGrid
nav_msgs/Odometry
nav_msgs/Path
nav_msgs/SetMapRequest
nav_msgs/SetMapResponse
pendulum_msgs/JointCommand
pendulum_msgs/JointState
pendulum_msgs/RttestResults
rcl_interfaces/DescribeParametersRequest
rcl_interfaces/DescribeParametersResponse
rcl_interfaces/FloatingPointRange
rcl_interfaces/GetParameterTypesRequest
rcl_interfaces/GetParameterTypesResponse
rcl_interfaces/GetParametersRequest
rcl_interfaces/GetParametersResponse
rcl_interfaces/IntegerRange
rcl_interfaces/ListParametersRequest
rcl_interfaces/ListParametersResponse
rcl_interfaces/ListParametersResult
rcl_interfaces/Log
rcl_interfaces/Parameter
rcl_interfaces/ParameterDescriptor
rcl_interfaces/ParameterEvent
rcl_interfaces/ParameterEventDescriptors
rcl_interfaces/ParameterType
rcl_interfaces/ParameterValue
rcl_interfaces/SetParametersAtomicallyRequest
rcl_interfaces/SetParametersAtomicallyResponse
rcl_interfaces/SetParametersRequest
rcl_interfaces/SetParametersResponse
rcl_interfaces/SetParametersResult
rosgraph_msgs/Clock
sensor_msgs/BatteryState
sensor_msgs/CameraInfo
sensor_msgs/ChannelFloat32
sensor_msgs/CompressedImage
sensor_msgs/FluidPressure
sensor_msgs/Illuminance
sensor_msgs/Image
sensor_msgs/Imu
sensor_msgs/JointState
sensor_msgs/Joy
sensor_msgs/JoyFeedback
sensor_msgs/JoyFeedbackArray
sensor_msgs/LaserEcho
sensor_msgs/LaserScan
sensor_msgs/MagneticField
sensor_msgs/MultiDOFJointState
sensor_msgs/MultiEchoLaserScan
sensor_msgs/NavSatFix
sensor_msgs/NavSatStatus
sensor_msgs/PointCloud
sensor_msgs/PointCloud2
sensor_msgs/PointField
sensor_msgs/Range
sensor_msgs/RegionOfInterest
sensor_msgs/RelativeHumidity
sensor_msgs/SetCameraInfoRequest
sensor_msgs/SetCameraInfoResponse
sensor_msgs/Temperature
sensor_msgs/TimeReference
shape_msgs/Mesh
shape_msgs/MeshTriangle
shape_msgs/Plane
shape_msgs/SolidPrimitive
simple_msgs/AddTwoIntsRequest
simple_msgs/AddTwoIntsResponse
simple_msgs/Num
statistics_msgs/MetricsMessage
statistics_msgs/StatisticDataPoint
statistics_msgs/StatisticDataType
std_msgs/Bool
std_msgs/Byte
std_msgs/ByteMultiArray
std_msgs/Char
std_msgs/ColorRGBA
std_msgs/Empty
std_msgs/Float32
std_msgs/Float32MultiArray
std_msgs/Float64
std_msgs/Float64MultiArray
std_msgs/Header
std_msgs/Int16
std_msgs/Int16MultiArray
std_msgs/Int32
std_msgs/Int32MultiArray
std_msgs/Int64
std_msgs/Int64MultiArray
std_msgs/Int8
std_msgs/Int8MultiArray
std_msgs/MultiArrayDimension
std_msgs/MultiArrayLayout
std_msgs/String
std_msgs/UInt16
std_msgs/UInt16MultiArray
std_msgs/UInt32
std_msgs/UInt32MultiArray
std_msgs/UInt64
std_msgs/UInt64MultiArray
std_msgs/UInt8
std_msgs/UInt8MultiArray
std_srvs/EmptyRequest
std_srvs/EmptyResponse
std_srvs/SetBoolRequest
std_srvs/SetBoolResponse
std_srvs/TriggerRequest
std_srvs/TriggerResponse
stereo_msgs/DisparityImage
test_msgs/Arrays
test_msgs/ArraysRequest
test_msgs/ArraysResponse
test_msgs/BasicTypes
test_msgs/BasicTypesRequest
test_msgs/BasicTypesResponse
test_msgs/BoundedSequences
test_msgs/Builtins
test_msgs/Constants
test_msgs/Defaults
test_msgs/Empty
test_msgs/EmptyRequest
test_msgs/EmptyResponse
test_msgs/MultiNested
test_msgs/Nested
test_msgs/Strings
test_msgs/UnboundedSequences
test_msgs/WStrings
trajectory_msgs/JointTrajectory
trajectory_msgs/JointTrajectoryPoint
trajectory_msgs/MultiDOFJointTrajectory
trajectory_msgs/MultiDOFJointTrajectoryPoint
unique_identifier_msgs/UUID
visualization_msgs/GetInteractiveMarkersRequest
visualization_msgs/GetInteractiveMarkersResponse
visualization_msgs/ImageMarker
visualization_msgs/InteractiveMarker
visualization_msgs/InteractiveMarkerControl
visualization_msgs/InteractiveMarkerFeedback
visualization_msgs/InteractiveMarkerInit
visualization_msgs/InteractiveMarkerPose
visualization_msgs/InteractiveMarkerUpdate
visualization_msgs/Marker
visualization_msgs/MarkerArray
visualization_msgs/MenuEntry

これで、上で作成したカスタム メッセージを標準メッセージとして使用できます。メッセージ送受信の詳細については、ROS 2 のパブリッシャーとサブスクライバーとのデータ交換を参照してください。

example_b_msgs/Standalone メッセージを使用するパブリッシャーを作成します。

node = ros2node("/node_1");
pub = ros2publisher(node,"/example_topic","example_b_msgs/Standalone");

同じトピックでサブスクライバーを作成します。

sub = ros2subscriber(node,"/example_topic");

メッセージを作成し、そのメッセージを送信します。

custom_msg = ros2message("example_b_msgs/Standalone");
custom_msg.int_property = uint32(12);
custom_msg.string_property='This is ROS 2 custom message example';
send(pub,custom_msg);
pause(3) % Allow a few seconds for the message to arrive

LatestMessage フィールドを使用すると、サブスクライバーが最近受信したメッセージがわかります。

sub.LatestMessage
ans = struct with fields:
        MessageType: 'example_b_msgs/Standalone'
       int_property: 12
    string_property: 'This is ROS 2 custom message example'

作成した ROS オブジェクトを削除します。

clear node pub sub

組み込みメッセージ定義のカスタム定義との置き換え

MATLAB は、多くの組み込み ROS 2 メッセージ タイプを提供しています。これらのメッセージ タイプの定義を、上記で詳述した同じカスタム メッセージ作成ワークフローを使用して、新しい定義と置き換えることができます。組み込みのメッセージ パッケージの定義を置き換える場合は、カスタム メッセージ パッケージ フォルダーに、対応する組み込みメッセージ パッケージのすべてのメッセージ タイプに対する新しい定義 (.msg ファイル) が含まれていることを確認する必要があります。

この例では、MATLAB で共有可能な ROS 2 カスタム メッセージ パッケージを作成します。必要な msg ファイルが含まれる ROS 2 パッケージがなければなりません。この図では、適切なフォルダー構造の例を示します。

ROS 2 Custom Messages Folder

カスタム メッセージ パッケージ フォルダーを準備したら、親フォルダーへのパスを指定し、指定したパスで ros2genmsg を呼び出します。

新しい MATLAB セッションを開き、カスタム メッセージ パッケージ フォルダーをローカル フォルダーに作成します。Windows マシン上でカスタム メッセージを生成する場合は、フォルダー パスの文字数の制限を回避するために、短いフォルダー パスを選択します。次に例を示します。

genDir = fullfile('C:/test/ros2CustomMessages')

genDir = fullfile(pwd,'ros2CustomMessages');
packagePath = fullfile(genDir,'simple_msgs');
mkdir(packagePath)

カスタム メッセージ パッケージ フォルダー内に msg という名前のフォルダーを作成します。

mkdir(packagePath,'msg')

msg フォルダー内に .msg という名前のファイルを作成します。

messageDefinition = {'int64 num'};

fileID = fopen(fullfile(packagePath,'msg', ...
               'Num.msg'),'w');
fprintf(fileID,'%s\n',messageDefinition{:});
fclose(fileID);

カスタム メッセージ パッケージ フォルダー内に srv という名前のフォルダーを作成します。

mkdir(packagePath,'srv')

srv フォルダー内に .srv という名前のファイルを作成します。

serviceDefinition = {'int64 a'
                     'int64 b'
                     '---'
                     'int64 sum'};
 
fileID = fopen(fullfile(packagePath,'srv', ...
               'AddTwoInts.srv'),'w');
fprintf(fileID,'%s\n',serviceDefinition{:});
fclose(fileID);

カスタム メッセージ パッケージ フォルダー内に action という名前のフォルダーを作成します。

mkdir(packagePath,'action')

action フォルダー内に .action という名前のファイルを作成します。

actionDefinition = {'int64 goal'
                    '---'
                    'int64 result'
                    '---'
                    'int64 feedback'};
 
fileID = fopen(fullfile(packagePath,'action', ...
               'Test.action'),'w');
fprintf(fileID,'%s\n',actionDefinition{:});
fclose(fileID);

.msg, .srv ファイルおよび .action ファイル内の ROS 2 定義からカスタム メッセージを生成します。名前と値の引数 CreateShareableFile を使用して、生成したカスタム メッセージの共有可能な ZIP アーカイブを作成します。

この ZIP アーカイブを使用してカスタム メッセージを別のマシンに登録する方法の詳細については、ros2RegisterMessagesを参照してください。

ros2genmsg(genDir,CreateShareableFile=true);
Identifying message files in folder 'C:/Users/echakrab/OneDrive - MathWorks/Documents/MATLAB/ExampleManager/echakrab.Bdoc23a.ROS2transform/ros-ex71849911/ros2CustomMessages'.Validating message files in folder 'C:/Users/echakrab/OneDrive - MathWorks/Documents/MATLAB/ExampleManager/echakrab.Bdoc23a.ROS2transform/ros-ex71849911/ros2CustomMessages'.Done.
Creating a Python virtual environment.Done.
Adding required Python packages to virtual environment.Done.
Copying include folders.Done.
Copying libraries.Done.
Done.
[1/1] Generating MATLAB interfaces for custom message packages... Done.
Running colcon build in folder 'C:/Users/echakrab/OneDrive - MathWorks/Documents/MATLAB/ExampleManager/echakrab.Bdoc23a.ROS2transform/ros-ex71849911/ros2CustomMessages/matlab_msg_gen/win64'.
Build in progress. This may take several minutes...

コマンド ウィンドウで「ros2 msg list」と入力して、新しいカスタム メッセージの作成を確認します。

入力引数

すべて折りたたむ

ROS メッセージ パッケージの親フォルダーである ROS インターフェイス フォルダーへのパス。string スカラーまたは文字ベクトルとして指定します。親フォルダーはパッケージ .xml およびパッケージ フォルダーを含む必要があります。これらのフォルダーには、メッセージ定義用の .msg ファイルがある /msg という名前のフォルダー、サービス定義用の .srv ファイルがある /srv という名前のフォルダー、アクション定義用の .action ファイルがある /action という名前のフォルダーがあります。詳細については、About ROS 2 Interfaces を参照してください。

例: 'C:/test/ros2CustomMessages'

データ型: char | string

名前と値の引数

オプションの引数のペアを Name1=Value1,...,NameN=ValueN として指定します。ここで、Name は引数名、Value は対応する値です。名前と値の引数は他の引数の後に表示されなければなりませんが、ペアの順序は重要ではありません。

R2021a より前は、名前と値をそれぞれコンマを使って区切り、Name引用符で囲みます。

例: BuildConfiguration='fasterruns'

ビルド構成。BuildConfiguration と、'fasterbuilds' または 'fasterruns' が含まれた文字ベクトルまたは string スカラーで構成されるコンマ区切りのペアとして指定します。

  • 'fasterbuilds' — ビルド時間を短縮するためにコンパイラを最適化して、メッセージ ライブラリをビルドします。

  • 'fasterruns' — 実行速度を高速化するためにコンパイラを最適化して、メッセージ ライブラリをビルドします。

例: ros2genmsg('C:/test/ros2CustomMessages',BuildConfiguration='fasterruns')

データ型: char | string

共有可能な ZIP アーカイブを生成するオプション。数値あるいは logical の 1 (true) または 0 (false) として指定します。

この引数を 1 (true) として指定した場合、この関数は、インストール フォルダーを matlab_msg_gen フォルダーに圧縮して ZIP アーカイブを作成します。このファイルは、同じプラットフォームで実行されていて同じ MATLAB バージョンを使用している別のマシンで使用できます。

この引数を 0 (false) として指定した場合、この関数は ZIP アーカイブを作成しません。

例: ros2genmsg('C:/test/ros2CustomMessages',CreateShareableFile=true)

データ型: logical

制限

ノードの再起動

  • カスタム メッセージを生成した後に、既存の ROS 2 ノードを再起動します。

カスタム メッセージを使用したコード生成:

  • カスタム メッセージ タイプおよびカスタム サービス タイプを ROS 2 機能とともに使用して、スタンドアロン ROS 2 ノード用の C++ コードを生成できます。生成された TGZ アーカイブには、カスタム メッセージの定義が含まれますが、ROS 2 カスタム メッセージ パッケージは含まれません。生成されたコードが生成先で関数によってビルドされる際には、カスタム メッセージ パッケージが colcon ワークスペースで使用可能でなければなりません。このワークスペースを現在の作業ディレクトリとして設定します。生成されたコードをビルドする前に、システムにカスタム メッセージ パッケージをインストールまたはコピーします。

MATLAB Compiler

  • MATLAB Compiler™ ソフトウェアでは、ROS カスタム メッセージと関数 ros2genmsg はサポートされません。

ヒント

  • Microsoft® Visual Studio® のインストール中に、必ず [Desktop development with C++] ワークロードを選択してください。これにより、MSVC コンパイラと、カスタム メッセージの生成に必要なすべての依存関係がインストールされます。

  • カスタム メッセージ フォルダーへのパスが 64 文字を超えていないことを確認してください。

  • Python 環境の構成が正しいことを確認します。詳細については、ROS Toolbox システム要件を参照してください。

バージョン履歴

R2019b で導入

すべて展開する