Main Content

Connect to ROS 2 Network and Establish Communication

R2026b

ROS 2 Nodes

Nodes are the basic building blocks of ROS applications, which takes care of the computation. A ROS 2 network can have multiple nodes running on a single computer or across multiple computers. Nodes are independent processes that communicate with each other by sending and receiving messages. In a robot system, nodes include sensors (camera), motion controllers (motors), and algorithm components (route planner).

Initialize ROS 2 Network

To connect with a ROS 2 network, you can create a ROS 2 node. A ROS 2 network is identified with a ROS Domain ID. To create a ROS 2 node in the default domain (with domain ID of 0), use ros2node command.

defaultNode = ros2node("/default_node")
defaultNode = 
  ros2node with properties:

    Name: '/default_node'
      ID: 0

View ROS 2 Network Information

Use ros2 node list to view the network information on the default domain.

ros2 node list
/default_node
/node_1

Create ROS 2 Node on Different Domain

Pass the domain ID as a parameter to create a node in a domain other than the default one.

newDomainNode = ros2node("/new_domain_node",25)
newDomainNode = 
  ros2node with properties:

    Name: '/new_domain_node'
      ID: 25

This will create a node and connect to the network with domain ID of 25.

Provide the domain ID as shown below for non-default domains.

ros2("node","list","DomainID",25)
/new_domain_node

Shutdown ROS 2 Network

Use clear to remove the reference to the node and remove the node from the network.

clear defaultNode
clear newDomainNode

You can create multiple such nodes and establish communication between them by sending and receiving messages of different interface types.

Communication in ROS 2 Network

To connect to an existing ROS 2 network, create a node in the desired domain. The ROS 2 network automatically detects any new nodes created in the same domain which you studied in Discovery.

ROS 2 Communication Outside Subnet

A subnet is a logical partition of an IP network into multiple, smaller network segments. ROS 2 nodes can communicate with other nodes within the same subnet.

To detect nodes present outside the subnet, configure the DDS middleware used by MATLAB® by creating a DEFAULT_FASTRTPS_PROFILE.xml file. Add the IP addresses of systems outside the subnet with which to communicate inside the <address> elements. Note that for both systems to communicate, they each must specify the other system's address in their respective DEFAULT_FASTRTPS_PROFILE.xml files. Set the domain ID element to the appropriate value for the network that is used for communication.

Note

The required configuration depends on the DDS middleware implementation in use. MATLAB uses Fast DDS by default.

Keep this file in the MATLAB current working directory. Systems using ROS 2 outside MATLAB must place this file in the same directory from which the ROS 2 application is launched.

The code snippet below is an example of DEFAULT_FASTRTPS_PROFILE.xml file.

<?xml version="1.0" encoding="UTF-8" ?>
<profiles>
    <participant profile_name="participant_win" is_default_profile="true">
        <rtps>
            <builtin>
                <metatrafficUnicastLocatorList>
                     <locator/>
                </metatrafficUnicastLocatorList>
                 <initialPeersList>
                     <locator>
                         <udpv4>
                         <address>192.34.17.36</address>
                         </udpv4>
                     </locator>
                     <locator>
                         <udpv4>
                         <address>182.30.45.12</address>
                         </udpv4>
                     </locator>
                     <locator>
                         <udpv4>
                         <address>194.158.78.29</address>
                         </udpv4>
                     </locator>
                 </initialPeersList>
             </builtin>
         </rtps>
     </participant>
</profiles> 

ROS 2 advertises information to the nodes present in the systems with IP addresses listed inside the DEFAULT_FASTRTPS_PROFILE.xml. If this file is not present or does not contain the correct IP addresses, ROS 2 does not receive information from nodes outside the subnet.

Troubleshoot ROS 2 Communication Across Remote Networks

Use these troubleshooting steps when MATLAB is unable to discover or communicate with ROS 2 nodes running on a remote machine or outside the local subnet.

The network configuration of the external ROS 2 environment can affect DDS discovery and message exchange. Ensure that the environment uses one of the recommended network adapter modes.

ROS 2 EnvironmentRecommended Networking ModeReferences to Change Networking Mode
WSL 2NATConfigure WSL Settings
Docker (operating in WSL 2)Host NetworkConfigure Docker Settings
VirtualBox/VMWareBridged (recommended)/NATConfigure Virtual Machine Settings
  1. Stop all ROS 2 nodes within and outside MATLAB.

    • In the MATLAB command window, run this command to clear all node objects.

      clear all;

    • On Windows®, manually stop all applications that are failing to communicate. To achieve this, stop any remaining libmwros2server.exe from Task Manager.

    • Stop all ROS 2 nodes running outside MATLAB.

  2. Verify outgoing messages from MATLAB.

    • Run the following commands in the MATLAB command window to create a ROS 2 node and publisher. Send messages on the /hello_world topic and verify that they appear in the external environment.

      node = ros2node("my_node");
      pub  = ros2publisher(node,"/hello_world","std_msgs/String");
      msg  = ros2message(pub);
      
      for ii=1:100
        send(pub,msg);
        pause(1);
      end
    • On the remote system, open the terminal and run the following command to subscribe to the published topic.

      # For Unix
      source /opt/ros/<distro>/setup.bash
      ros2 daemon stop
      ros2 topic echo /hello_world
      
      If you see messages printed in the terminal, MATLAB successfully communicates with the external ROS 2 environment.

  3. Verify incoming messages to MATLAB.

    • On the remote system, open the terminal and create a publisher to publish from the external ROS 2 environment on the /hello_world topic.

      # For Unix
      source /opt/ros/<distro>/setup.bash
      ros2 topic pub -r 10 /hello_world std_msgs/msgs/String "{data: 'hello world'}"

    • In the system running MATLAB, create a ROS 2 node and subscribe to the published message using the following command.

      node = ros2node('my_node');
      sub = ros2subscriber(node, '/hello_world', 'std_msgs/String');
      sub.LatestMessage

If MATLAB displays the incoming message, it confirms two-way communication. You can now relaunch your application to check that the communication issue is resolved. If the issue persists, continue with the next troubleshooting steps to verify that ROS 2 configurations such as middleware and domain ID are consistent across environments.

  • ROS 2 distribution compatibility — Ensure that the ROS 2 distribution running in your virtual environment outside MATLAB is supported by ROS Toolbox. ROS 2 does not generally support cross-distribution communication.

    Additionally, ensure that all the system requirements align with MATLAB requirements. For a complete list of supported ROS 2 distributions, see ROS Toolbox System Requirements.

  • ROS middleware implementation — Ensure that both environments use the same RMW implementation. In MATLAB, open Settings from the toolstrip and select ROS Toolbox from the list of products on the left pane to verify the registered RMW implementation.

    In the external environment, verify the RMW_IMPLEMENTATION variable to find the registered middleware by running the following command.

    # For Unix, or Mac
    echo $RMW_IMPLEMENTATION  # Displays middleware (blank = default FastDDS/FastRTPS)

    If the values do not match, set the variables explicitly to ensure that the MATLAB and ROS 2 environment align with each other.

  • ROS domain ID — Ensure that the ROS 2 nodes created in both MATLAB and external ROS 2 environment use the same ROS_DOMAIN_ID.

    To check the domain ID in MATLAB, run the following command in the command window.

    getenv('ROS_DOMAIN_ID')

    To check the domain ID in remote target machine, use the following command.

    # For Unix, or Mac
    echo $ROS_DOMAIN_ID       # Blank = default 0

    Ensure that ROS_DOMAIN_ID is 0-101 or 215-232 on Linux® and 0-166 on Windows. Follow the platform specific range mentioned in the ROS 2 documentation.

    Now verify if the issue is resolved, by performing a publisher/subscriber test again. If the issue still persists, proceed with the next steps.

eProsima Fast DDS

  1. Create a DEFAULT_FASTRTPS_PROFILE.xml file, as described in the ROS 2 Communication Outside Subnet section.

  2. Remove existing <locator> entries and add the list of IP addresses of systems outside the subnet in the <address> elements, with which you wish to establish communication.

  3. For both systems to communicate, they each must specify the other system's address in their respective DEFAULT_FASTRTPS_PROFILE.xml files.

  4. Set the environment variable on both the systems.

    In the system running MATLAB, run the following command in the command window.

    setenv("DEFAULT_FASTRTPS_PROFILE","<path-to-DEFAULT_FASTRTPS_PROFILE>")
    

    In the remote target that will run the ROS 2 nodes, run either of the following commands, based on the operating system.

    # For Unix, and Mac
    export DEFAULT_FASTRTPS_PROFILE="<path-to-DEFAULT_FASTRTPS_PROFILE>"
    # For Windows
    set DEFAULT_FASTRTPS_PROFILE="<path-to-DEFAULT_FASTRTPS_PROFILE>"

Eclipse Cyclone DDS

  1. Create a CYCLONEDDS.xml file to configure this specific DDS implementation in MATLAB and use the by using the following XML.

    <?xml version="1.0" encoding="UTF-8" ?>
    <CycloneDDS xmlns="https://www.eclipse.org/cyclonedds" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="https://www.eclipse.org/cyclonedds https://www.eclipse.org/cyclonedds/schema/CycloneDDS.xsd">
        <Domain>
            <Discovery>
                <Peers>
                    <Peer address="192.168.1.100"/>
                    <Peer address="192.168.1.101:7401"/> <!-- Specify port if needed -->
                    <Peer address="hostname_of_peer"/>
                </Peers>
            </Discovery>
        </Domain>
    </CycloneDDS>
  2. Remove existing <Peer> entries and add the list of IP address of systems outside the subnet in the <address> elements, with which you wish to establish communication.

  3. For both systems to communicate, they each must specify the other system's address in their respective CYCLONEDDS.xml files.

  4. Set the environment variable on both the systems. In the system running MATLAB, run the following command in the command window.

    setenv('CYCLONEDDS_URI', '<path-to-cyclonedds.xml>');
    
  5. In the remote target that will run the ROS 2 nodes, run either of the following commands, based on the operating system.

    # For Unix, and Mac
    export CYCLONEDDS_URI="<path-to-cyclonedds.xml>"
    
    # For Windows
    set CYCLONEDDS_URI="<path-to-cyclonedds.xml>"
    
  • Ensure that all nodes use QoS settings compatible with each other. For more information on compatible QoS policies, see Manage Quality of Service Policies in ROS 2.

  • Ensure that the message, service, and action definitions are identical between MATLAB and the external ROS 2 environment. Differences in type definitions or missing custom messages can prevent communication.

  • If MATLAB is still unable to communicate with external ROS 2 nodes after verifying network settings, Domain ID, middleware, and QoS settings, the Windows firewall may be blocking the multicast traffic that ROS 2 uses for node discovery. This commonly occurs on public network profiles.

    To resolve this, allow the MATLAB ROS 2 background process through the firewall. You can find the process in this location:

    <matlabroot>\toolbox\ros\bin\win64\libmwros2server.exe
    

  • Create inbound and outbound rules in Windows Defender Firewall with Advanced Security:

    1. Open Windows Defender Firewall with Advanced Security.

    2. Under Inbound Rules, create New Rule and apply the following settings:

      • Rule Type: Program

      • Program Path: Paste the path to libmwros2server.exe

      • Action: Allow the connection

      • Profile: Select Domain, Private, and Public

      • Name: e.g., MATLAB ROS2 Server

    3. Repeat the step again under Outbound Rules to allow outgoing traffic.

After you configure the firewall, test communication again using the steps from the Verify ROS 2 Communication Between MATLAB and External Environment section or launch your application to verify that MATLAB connects to ROS 2 nodes.

ROS 2 Communication Interfaces

You can communicate between ROS 2 nodes using different interface types: