diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..684ba6a7993366b7e3ff9f1cad7043f052557131 --- /dev/null +++ b/CMakeLists.txt @@ -0,0 +1,42 @@ +cmake_minimum_required(VERSION 3.5) +project(rospy2_pkg) + +# Default to C99 +if(NOT CMAKE_C_STANDARD) + set(CMAKE_C_STANDARD 99) +endif() + +# Default to C++14 +if(NOT CMAKE_CXX_STANDARD) + set(CMAKE_CXX_STANDARD 14) +endif() + +if(CMAKE_COMPILER_IS_GNUCXX OR CMAKE_CXX_COMPILER_ID MATCHES "Clang") + add_compile_options(-Wall -Wextra -Wpedantic) +endif() + +# find dependencies +find_package(ament_cmake REQUIRED) +# uncomment the following section in order to fill in +# further dependencies manually. +# find_package(<dependency> REQUIRED) +find_package(rosidl_default_generators REQUIRED) + +rosidl_generate_interfaces(${PROJECT_NAME} + "msg/Num.msg" + "srv/Num.srv" + ) + +if(BUILD_TESTING) + find_package(ament_lint_auto REQUIRED) + # the following line skips the linter which checks for copyrights + # uncomment the line when a copyright and license is not present in all source files + #set(ament_cmake_copyright_FOUND TRUE) + # the following line skips cpplint (only works in a git repo) + # uncomment the line when this package is not in a git repo + #set(ament_cmake_cpplint_FOUND TRUE) + ament_lint_auto_find_test_dependencies() +endif() + +ament_package() + diff --git a/README.md b/README.md index cd3f017cbc9e31c4848a58f78f8efae12ba96833..06b8c7c3d9e4f61a9272219f99e0e31bbed9f316 100644 --- a/README.md +++ b/README.md @@ -1,93 +1,28 @@ -# rospy2_pkg +# ros2py +Python-Modul für vereinfachte Knotenerstellung unter Python. +# Voraussetzung +* ROS2 +* Python3 -## Getting started +# Beispiele +Aus dem /src Verzeichnis aufrufen +### Publisher + Subscriber -To make it easy for you to get started with GitLab, here's a list of recommended next steps. + python3 ros2_pub.py # Terminal 1 -Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)! + python3 ros2_sub.py # Terminal 2 -## Add your files +### Client + Server -- [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files -- [ ] [Add files using the command line](https://docs.gitlab.com/ee/gitlab-basics/add-file.html#add-a-file-using-the-command-line) or push an existing Git repository with the following command: + python3 ros2_service.py # Terminal 1 -``` -cd existing_repo -git remote add origin https://git-ce.rwth-aachen.de/thk_libs/ros_2/rospy2_pkg.git -git branch -M main -git push -uf origin main -``` + python3 ros2_client.py # Terminal 2 -## Integrate with your tools -- [ ] [Set up project integrations](https://git-ce.rwth-aachen.de/thk_libs/ros_2/rospy2_pkg/-/settings/integrations) -## Collaborate with your team +# Fehler -- [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/) -- [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html) -- [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically) -- [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/) -- [ ] [Set auto-merge](https://docs.gitlab.com/ee/user/project/merge_requests/merge_when_pipeline_succeeds.html) -## Test and Deploy - -Use the built-in continuous integration in GitLab. - -- [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/index.html) -- [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing (SAST)](https://docs.gitlab.com/ee/user/application_security/sast/) -- [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html) -- [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/) -- [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html) - -*** - -# Editing this README - -When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thanks to [makeareadme.com](https://www.makeareadme.com/) for this template. - -## Suggestions for a good README - -Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information. - -## Name -Choose a self-explaining name for your project. - -## Description -Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors. - -## Badges -On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge. - -## Visuals -Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method. - -## Installation -Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection. - -## Usage -Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README. - -## Support -Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc. - -## Roadmap -If you have ideas for releases in the future, it is a good idea to list them in the README. - -## Contributing -State if you are open to contributions and what your requirements are for accepting them. - -For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self. - -You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser. - -## Authors and acknowledgment -Show your appreciation to those who have contributed to the project. - -## License -For open source projects, say how it is licensed. - -## Project status -If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers. + noch keine \ No newline at end of file diff --git a/msg/.Num.msg.swp b/msg/.Num.msg.swp new file mode 100644 index 0000000000000000000000000000000000000000..512a1f46b0270a78b2cf83e54cee2563ef64cb9b Binary files /dev/null and b/msg/.Num.msg.swp differ diff --git a/msg/Num.msg b/msg/Num.msg new file mode 100644 index 0000000000000000000000000000000000000000..16699917b73816fc0e22958e8c60cb4b4b394557 --- /dev/null +++ b/msg/Num.msg @@ -0,0 +1,2 @@ +string txt +int64 num diff --git a/package.xml b/package.xml new file mode 100644 index 0000000000000000000000000000000000000000..ce0258227edf11babb51ffb110b80a7948e4c758 --- /dev/null +++ b/package.xml @@ -0,0 +1,24 @@ +<?xml version="1.0"?> +<?xml-model href="http://download.ros.org/schema/package_format3.xsd" schematypens="http://www.w3.org/2001/XMLSchema"?> +<package format="3"> + <name>rospy2_pkg</name> + <version>0.0.0</version> + <description>TODO: Package description</description> + <maintainer email="vladislav.vlasuk@th-koeln.de">dell</maintainer> + <license>TODO: License declaration</license> + + <buildtool_depend>ament_cmake</buildtool_depend> + + <test_depend>ament_lint_auto</test_depend> + <test_depend>ament_lint_common</test_depend> +<build_depend>rosidl_default_generators</build_depend> + +<exec_depend>rosidl_default_runtime</exec_depend> +<exec_depend>tutorial_interfaces</exec_depend> +<member_of_group>rosidl_interface_packages</member_of_group> + + <export> + <build_type>ament_cmake</build_type> + </export> + +</package> diff --git a/src/__pycache__/m_ros2py.cpython-38.pyc b/src/__pycache__/m_ros2py.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1f9491dc6212c6e17a89ee6024c72597d9978346 Binary files /dev/null and b/src/__pycache__/m_ros2py.cpython-38.pyc differ diff --git a/src/m_ros2py.py b/src/m_ros2py.py new file mode 100755 index 0000000000000000000000000000000000000000..9cfbcad1b832a8ce89003db9ff9bfb9fd9bc68c2 --- /dev/null +++ b/src/m_ros2py.py @@ -0,0 +1,41 @@ +from rclpy.node import Node +from std_msgs.msg import * +from rospy2_pkg.srv import Num + +class ros2node(Node): + def __init__(self, nodeName): + super().__init__(nodeName) + self._publishers = {} + self._subscribers = {} + self._timers = {} + self._services = {} + self._clients = {} + self.as_ClientService = False + + def create_publisher_with_timer(self, topicName, msgType, func, rate): + self._publishers[topicName] = self.create_publisher(msgType, topicName, 10) + self._timers[topicName] = self.create_timer(rate, lambda: self.timer_callback(topicName, func)) + + def create_subscriber(self, topicName, msgType, func): + self._subscribers[topicName] = self.create_subscription(msgType, topicName, func, 10) + + def create_new_service(self, topicName, msgType, func): + self._services[topicName] = self.create_service(msgType, topicName, func) + self.as_ClientService = True + + def create_new_client(self, topicName, msgType): + self._clients[topicName] = self.create_client(msgType, topicName) + self.as_ClientService = True + + def timer_callback(self, topicName, func): + if not self.as_ClientService: + publisher = self._publishers.get(topicName) + if publisher: + msg = func() # Callback-Funktion aufrufen + publisher.publish(msg) + # self.get_logger().info(f'Publishing: "{msg.data}" on topic: "{topicName}"') + else: + self.get_logger().info(f'No publisher found for topic: "{topicName}"') + + def get_client(self, topicName): + return self._clients.get(topicName) diff --git a/src/ros2_client.py b/src/ros2_client.py new file mode 100755 index 0000000000000000000000000000000000000000..a0bff066e7259602a53f554ff27c0938b1321aae --- /dev/null +++ b/src/ros2_client.py @@ -0,0 +1,53 @@ +#!/usr/bin/env python3 +""" +ROS2 Beispiel: Publisher und Subscriber +""" +# ------------------------------------------ +# inkludieren der Bibliotheken +import rclpy +from rospy2_pkg.srv import Num +from m_ros2py import ros2node +from datetime import datetime +import random + +topic_name = "addThreeInts" +# ------------------------------------------ +# Beispiel-Callback-Funktionen für Publisher + +def send_request(cli): + global future + req = Num.Request() + req.a = random.randrange(1, 10, 1) + req.b = random.randrange(1, 10, 1) + req.c = random.randrange(1, 10, 1) + future = cli.call_async(req) + print(f"Sending request {topic_name} -- data: {req.a} {req.b} {req.c} ({str(datetime.now())})") + + return future +# ------------------------------------------ + +def main(args=None): + # Initialisiere Knoten mit Knotennamen + rclpy.init(args=args) + node = ros2node("client_node") + node.create_new_client(topic_name, Num) + cli = node.get_client(topic_name) + future = send_request(cli) + + while rclpy.ok(): + rclpy.spin_once(node) + if future.done(): + try: + response = future.result() + except Exception as e: + node.get_logger().info(f'Service call failed: {str(e)}') + else: + node.get_logger().info(f'Result of service : {response.sum}') + break + + # Bei CTRL+C schließen + node.destroy_node() + rclpy.shutdown() + +if __name__ == '__main__': + main() \ No newline at end of file diff --git a/src/ros2_customMsg.py b/src/ros2_customMsg.py new file mode 100755 index 0000000000000000000000000000000000000000..904564afb4cd0615e514a4db4520491dc4b72e1e --- /dev/null +++ b/src/ros2_customMsg.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +""" +ROS2 Beispiel: Publisher und Subscriber +""" +# ------------------------------------------ +# inkludieren der Bibliotheken +import rclpy +from m_ros2py import ros2node +from rospy2_pkg.msg import Num # CHANGE +from datetime import datetime + +rate = 1 # Hz +topic_name = "caller" +counter = 0 +# ------------------------------------------ +# Beispiel-Callback-Funktionen für Publisher +def pub(): + global counter + msg = Num() + msg.txt = "counter_" +str(counter) + msg.num = counter + print(f"Send msg to topic {topic_name} -- data: {msg.num} ({str(datetime.now())})") + counter += 1 + return msg + +# ------------------------------------------ + +def main(args=None): + # Initialisiere Knoten mit Knotennamen + rclpy.init(args=args) + node = ros2node("publisher_node") + + # Publisher mit Timer erstellen + # Parameter: NodeName, MsgType, Funktion, Frequenz zum publishen + node.create_publisher_with_timer(topic_name, Num, pub, rate) + + # Starten + rclpy.spin(node) + + # Bei CTRL+C schließen + node.destroy_node() + rclpy.shutdown() + +if __name__ == '__main__': + main() diff --git a/src/ros2_multiple.py b/src/ros2_multiple.py new file mode 100755 index 0000000000000000000000000000000000000000..171a2a3973b5e2c341717bb0eb298284e8e3089c --- /dev/null +++ b/src/ros2_multiple.py @@ -0,0 +1,63 @@ +#!/usr/bin/env python3 +""" +ROS2 Beispiel: Publisher und Subscriber +""" +# ------------------------------------------ +# inkludieren der Bibliotheken +import rclpy +from std_msgs.msg import String +from m_ros2py import ros2node + +# Farbike Textausgabe +from colorama import init as colorama_init +from colorama import Fore +from colorama import Style +colorama_init() + +# ------------------------------------------ +# Beispiel-Callback-Funktionen für Publisher +def str_pub_1(): + msg = String() + msg.data = 'Hello 1Hz' + print(f"{Fore.RED}str_pub_1 >> Publishing {Style.RESET_ALL} \t {msg.data}") + return msg + +def str_pub_2(): + msg = String() + msg.data = 'Hello 2Hz' + print(f"{Fore.RED}str_pub_2 >> Publishing {Style.RESET_ALL} \t {msg.data}") + return msg + +# Beispiel-Callback-Funktionen für Subscriber +def str_sub_1(msg): + print(f"{Fore.GREEN} Receiving << str_sub_1{Style.RESET_ALL} \t\t {msg.data} ") + +def str_sub_2(msg): + print(f"{Fore.GREEN} Receiving << str_sub_2{Style.RESET_ALL} \t\t {msg.data} ") + +# ------------------------------------------ + + +def main(args=None): + # Initialisiere Knoten mit Knotennamen + rclpy.init(args=args) + node = ros2node("my_ros2_node") + + # Mehrere Publisher mit unterschiedlichen Timern erstellen + # Parameter: NodeName, MsgType, Funktion, Frequenz zum publishen + node.create_publisher_with_timer("str_publisher_1hz", String, str_pub_1, 1) + node.create_publisher_with_timer("str_publisher_2hz", String, str_pub_2, 0.5) + + # Mehrere Subscriber erstellen + node.create_subscriber("str_publisher_1hz",String,str_sub_1) + node.create_subscriber("str_publisher_2hz",String,str_sub_2) + + # Starten + rclpy.spin(node) + + # Bei CTRL+C schließen + node.destroy_node() + rclpy.shutdown() + +if __name__ == '__main__': + main() diff --git a/src/ros2_pub.py b/src/ros2_pub.py new file mode 100755 index 0000000000000000000000000000000000000000..2d9e8abd3cd07c5e66409de19044476dd776832d --- /dev/null +++ b/src/ros2_pub.py @@ -0,0 +1,41 @@ +#!/usr/bin/env python3 +""" +ROS2 Beispiel: Publisher und Subscriber +""" +# ------------------------------------------ +# inkludieren der Bibliotheken +import rclpy +from std_msgs.msg import String +from m_ros2py import ros2node +from datetime import datetime + +rate = 1 # Hz +topic_name = "caller" +# ------------------------------------------ +# Beispiel-Callback-Funktionen für Publisher +def str_pub(): + msg = String() + msg.data = 'Hello World' + print(f"Send msg to topic {topic_name} -- data: {msg.data} ({str(datetime.now())})") + return msg + +# ------------------------------------------ + +def main(args=None): + # Initialisiere Knoten mit Knotennamen + rclpy.init(args=args) + node = ros2node("publisher_node") + + # Publisher mit Timer erstellen + # Parameter: NodeName, MsgType, Funktion, Frequenz zum publishen + node.create_publisher_with_timer(topic_name, String, str_pub, rate) + + # Starten + rclpy.spin(node) + + # Bei CTRL+C schließen + node.destroy_node() + rclpy.shutdown() + +if __name__ == '__main__': + main() diff --git a/src/ros2_service.py b/src/ros2_service.py new file mode 100755 index 0000000000000000000000000000000000000000..667bf067d79fa455de8bf8e01399343db5c5bdd6 --- /dev/null +++ b/src/ros2_service.py @@ -0,0 +1,39 @@ +#!/usr/bin/env python3 +""" +ROS2 Beispiel: Publisher und Subscriber +""" +# ------------------------------------------ +# inkludieren der Bibliotheken +import rclpy +from rospy2_pkg.srv import Num +from m_ros2py import ros2node +from datetime import datetime + +rate = 1 # Hz +topic_name = "addThreeInts" +# ------------------------------------------ +# Beispiel-Callback-Funktionen für Publisher +def service_cb(request, response): + response.sum = request.a + request.b + request.c + print(f"Incoming request {topic_name} -- data: {request.a} {request.b} {request.c} ({str(datetime.now())})") + return response +# ------------------------------------------ + +def main(args=None): + # Initialisiere Knoten mit Knotennamen + rclpy.init(args=args) + node = ros2node("service_node") + + # Publisher mit Timer erstellen + # Parameter: NodeName, MsgType, Funktion, Frequenz zum publishen + node.create_new_service(topic_name,Num,service_cb) + + # Starten + rclpy.spin(node) + + # Bei CTRL+C schließen + node.destroy_node() + rclpy.shutdown() + +if __name__ == '__main__': + main() diff --git a/src/ros2_sub.py b/src/ros2_sub.py new file mode 100755 index 0000000000000000000000000000000000000000..9210fa85954ed0330be693470aef724467ee5dbd --- /dev/null +++ b/src/ros2_sub.py @@ -0,0 +1,36 @@ +#!/usr/bin/env python3 +""" +ROS2 Beispiel: Subscriber +""" +# ------------------------------------------ +# inkludieren der Bibliotheken +import rclpy +from std_msgs.msg import String +from m_ros2py import ros2node +from datetime import datetime + +topic_name = "caller" +# ------------------------------------------ +# Beispiel-Callback-Funktionen für Subscriber +def str_sub(msg): + print(f"Receiving msg from topic {topic_name} -- data: {msg.data} ({str(datetime.now())})") + +# ------------------------------------------ + +def main(args=None): + # Initialisiere Knoten mit Knotennamen + rclpy.init(args=args) + node = ros2node("subscriber_node") + + # Subscriber erstellen + node.create_subscriber(topic_name,String,str_sub) + + # Starten + rclpy.spin(node) + + # Bei CTRL+C schließen + node.destroy_node() + rclpy.shutdown() + +if __name__ == '__main__': + main() diff --git a/srv/Num.srv b/srv/Num.srv new file mode 100644 index 0000000000000000000000000000000000000000..b2e646f49d966594ee41df5a5f6737d72bab436e --- /dev/null +++ b/srv/Num.srv @@ -0,0 +1,5 @@ +int64 a +int64 b +int64 c +--- +int64 sum