해당 실습 자료는 한양대학교 Road Balance - ROS 2 for G Camp와 ROS 2 Documentation: Foxy, 표윤석, 임태훈 <ROS 2로 시작하는 로봇 프로그래밍> 루피페이퍼(2022) 를 참고하여 작성하였습니다.
앞선 장에서 Service에 대해 배워보았습니다. 간단하게 정리하자면 node가 Service를 사용하여 통신할 때 데이터 요청(
request
)을 보내는 node를 Client Node라고 하고 요청에 응답(response
)하는 Server Node라고 합니다. 요청과 응답의 구조는.srv
파일에 의해 결정됩니다.
request
하고, Server Node에서는 연산 결과를 response
합니다.ros2_ws/src
디렉토리에 이동하신 다음 새로운 패키지를 생성합니다.$ ros2 pkg create py_srvcli --build-type ament_python --dependencies rclpy example_interfaces
새로운 패키지 이름은 py_srvcli
으로 동명의 디렉토리에 패키지 기본 구성이 생성된 것을 확인 할 수 있을 겁니다.
추가로 --dependencies
인수를 통해 패키지 환경 설정 파일 package.xml
에 필요한 종속성 패키지인 rclpy
, example_interfaces
가 자동으로 추가됩니다.
example_interfaces
는 request
와 response
을 구성하는 데에 필요한 .srv
파일이 포함된 패키지 입니다.
int64 a
int64 b
---
int64 sum
ros2_ws/src/py_srvcli/py_srvcli
경로에 새로운 파이썬 스크립트 service_member_function.py
생성하여 아래의 코드를 작성해주세요from example_interfaces.srv import AddTwoInts
import rclpy
from rclpy.node import Node
class MinimalService(Node):
def __init__(self):
super().__init__('minimal_service')
### ============= 서버 설정 =============
self.srv = self.create_service(
AddTwoInts, ## srv 타입: 해당 클래스의 인터페이스로 서비스 요청에 해당되는 request
'add_two_ints', ## 서비스 서버 명
self.add_two_ints_callback) ## 콜백 함수
### ===========================================
def add_two_ints_callback(self, request, response): ## Client Node로부터 클래스로 생성된 인터페이스로 서비스 요청에 해당되는 request 부분과 응답에 해당되는 response으로 구분
response.sum = request.a + request.b ## 위의 AddTwoInts 인터페이스 정보 확인
self.get_logger().info('Incoming request\\na: %d b: %d' % (request.a, request.b)) # cmd 창 출력
return response ## 응답값 반환
def main(args=None):
rclpy.init(args=args) # 초기화
node = MinimalService() # MinimalService를 node라는 이름으로 생성
try:
rclpy.spin(node) # 생성한 노드를 spin하여 지정된 콜백 함수 실행
except KeyboardInterrupt:
node.get_logger().info('Keyboard Interrupt (SIGINT)')
finally:# 종료시 (ex `Ctrl + c`)
node.destroy_node() # 노드 소멸
rclpy.shutdown() # rclpy.shutdown 함수로 노드 종료
if __name__ == '__main__':
main()