How to access instance of class in ROS2 subscriber callback?

3 次查看(过去 30 天)
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 中查找有关 ROS Network Access in MATLAB 的更多信息

产品


版本

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by