How to access instance of class in ROS2 subscriber callback?

조회 수: 4 (최근 30일)
Kyösti Alkio
Kyösti Alkio 2022년 8월 8일
답변: Josh Chen 2022년 8월 10일
I have the following code
classdef MTMSApiSimple
%MTMSAPI Summary of this class goes here
% Detailed explanation goes here
properties
data
node
status_subscriber
end
methods
function obj = MTMSApiSimple()
obj.node = ros2node("mtms_matlab_api");
obj.status_subscriber = ros2subscriber(obj.node, "/fpga/status_monitor_state", "fpga_interfaces/SystemState", @obj.subscriber_callback);
end
function subscriber_callback(message)
% access and set obj.data
end
end
end
I create a class with a subscriber that subscribes to a topic. My problem is that I would like to access obj.data inside the subscriber_callback method, but since the callback is called when a new message is received, I don't know how to give obj as a parameter for it. subscriber_callback receives only the message as an argument.

답변 (1개)

Josh Chen
Josh Chen 2022년 8월 10일
Hello Kyösti,
Using a single object to manage both data and callback for subscriber is feasible. In this case, subscriber callback can have one additional argument, i.e., obj. This will be considered as a member function of the MTMSApiSimple class:
classdef MTMSApiSimple < handle
%MTMSAPI Summary of this class goes here
% Detailed explanation goes here
properties
data
node
status_subscriber
end
methods
function obj = MTMSApiSimple()
obj.node = ros2node("mtms_matlab_api");
obj.status_subscriber = ros2subscriber(obj.node, "/fpga/status_monitor_state", "std_msgs/Int32", @obj.subscriber_callback);
end
function subscriber_callback(obj,message)
% access and set obj.data
fprintf('data received is: %d\n', message.data);
obj.data = message.data;
end
end
end
>> nd = ros2node('aaa');
>> [pub, pubmsg] = ros2publisher(nd,"/fpga/status_monitor_state", "std_msgs/Int32");
>> msa = MTMSApiSimple();
>> pubmsg.data = int32(5);
>> send(pub,pubmsg)
data received is: 5
>> msa.data
ans =
int32
5
I am using "std_msgs/Int32" as the message type since I do not have the custom message on my end, but the original message type should also work.
Hope this helps,
Josh

카테고리

Help CenterFile Exchange에서 Network Connection and Exploration에 대해 자세히 알아보기

제품


릴리스

R2022a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by