ROS2: Template to program a Server

Aus HSHL Mechatronik
Version vom 29. Januar 2026, 17:00 Uhr von Mirekgoebel (Diskussion | Beiträge)
(Unterschied) ← Nächstältere Version | Aktuelle Version (Unterschied) | Nächstjüngere Version → (Unterschied)
Zur Navigation springen Zur Suche springen


zurück zum Hauptartikel

#!/usr/bin/env python # this specifies the interpreter of this script

# ros-core-library for standard ros2-functionality (this is the one for python)
import rclpy
# use ROS-nodes
from rclpy.node import Node
# For the Service-Server: Using Trigger for simple status checking
from std_srvs.srv import Trigger 

# create a Node "MyNode", that inherits all functionality from "Node"
class MyNode(Node):
    def __init__(self):
        # call super() in the constructor to initialize the Node object
        # the parameter we pass is the node name
        super().__init__('MyNodeName')

        # Create a service that will handle status queries
        name_service = '/user_def_service'
        self.srv = self.create_service(Trigger, name_service, self.my_service_callback)
        # Send log-message
        self.get_logger().info(name_service+" Service Server Ready...")

    def my_service_callback(self, request, response):
        # set some response
        response.success = True
        
        # Construct response message
        response.message = ('some text')

        return response