├── .github ├── ISSUE_TEMPLATE │ ├── bug_report.md │ ├── config.yml │ └── feature_request.md ├── PULL_REQUEST_TEMPLATE.md └── workflows │ ├── jira-link.yaml │ ├── pre-commit.yaml │ └── stale.yaml ├── .gitignore ├── .pre-commit-config.yaml ├── .yamato ├── sonar.yml └── yamato-config.yml ├── CHANGELOG.md ├── CMakeLists.txt ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── launch └── endpoint.launch ├── package.xml ├── requirements.txt ├── setup.py ├── src └── ros_tcp_endpoint │ ├── __init__.py │ ├── client.py │ ├── communication.py │ ├── default_server_endpoint.py │ ├── exceptions.py │ ├── publisher.py │ ├── server.py │ ├── service.py │ ├── subscriber.py │ ├── tcp_sender.py │ ├── thread_pauser.py │ └── unity_service.py └── test ├── __init__.py ├── test_client.py ├── test_publisher.py ├── test_ros_service.py ├── test_server.py ├── test_subscriber.py ├── test_tcp_sender.py ├── test_thread_pauser.py └── test_unity_service.py /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Create a report to help us improve 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Describe the bug** 11 | A clear and concise description of what the bug is. 12 | 13 | **To Reproduce** 14 | Steps to reproduce the behavior: 15 | 1. Go to '...' 16 | 2. Click on '....' 17 | 3. Scroll down to '....' 18 | 4. See error 19 | 20 | **Console logs / stack traces** 21 | Please wrap in [triple backticks (```)](https://help.github.com/en/articles/creating-and-highlighting-code-blocks) to make it easier to read. 22 | 23 | **Expected behavior** 24 | A clear and concise description of what you expected to happen. 25 | 26 | **Screenshots** 27 | If applicable, add screenshots or videos to help explain your problem. 28 | 29 | **Environment (please complete the following information, where applicable):** 30 | - Unity Version: [e.g. Unity 2020.2.0f1] 31 | - Unity machine OS + version: [e.g. Windows 10] 32 | - ROS machine OS + version: [e.g. Ubuntu 18.04, ROS Noetic] 33 | - ROS–Unity communication: [e.g. Docker] 34 | - Branch or version: [e.g. v0.2.0] 35 | 36 | **Additional context** 37 | Add any other context about the problem here. 38 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/config.yml: -------------------------------------------------------------------------------- 1 | blank_issues_enabled: false 2 | contact_links: 3 | - name: Unity Robotics Forum 4 | url: https://forum.unity.com/forums/robotics.623/ 5 | about: Discussions and questions about Unity Robotics tools, demos, or integrations. -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request 3 | about: Suggest an idea for this project 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Is your feature request related to a problem? Please describe.** 11 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] 12 | 13 | **Describe the solution you'd like** 14 | A clear and concise description of what you want to happen. 15 | 16 | **Describe alternatives you've considered** 17 | A clear and concise description of any alternative solutions or features you've considered. 18 | 19 | **Additional context** 20 | Add any other context or screenshots about the feature request here. 21 | -------------------------------------------------------------------------------- /.github/PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | ## Proposed change(s) 2 | 3 | Describe the changes made in this PR. 4 | 5 | ### Useful links (GitHub issues, JIRA tickets, forum threads, etc.) 6 | 7 | Provide any relevant links here. 8 | 9 | ### Types of change(s) 10 | 11 | - [ ] Bug fix 12 | - [ ] New feature 13 | - [ ] Code refactor 14 | - [ ] Documentation update 15 | - [ ] Other (please describe) 16 | 17 | ## Testing and Verification 18 | 19 | Please describe the tests that you ran to verify your changes. Please also provide instructions, ROS packages, and Unity project files as appropriate so we can reproduce the test environment. 20 | 21 | ### Test Configuration: 22 | - Unity Version: [e.g. Unity 2020.2.0f1] 23 | - Unity machine OS + version: [e.g. Windows 10] 24 | - ROS machine OS + version: [e.g. Ubuntu 18.04, ROS Noetic] 25 | - ROS–Unity communication: [e.g. Docker] 26 | 27 | ## Checklist 28 | - [ ] Ensured this PR is up-to-date with the `dev` branch 29 | - [ ] Created this PR to target the `dev` branch 30 | - [ ] Followed the style guidelines as described in the [Contribution Guidelines](https://github.com/Unity-Technologies/ROS-TCP-Endpoint/blob/main/CONTRIBUTING.md) 31 | - [ ] Added tests that prove my fix is effective or that my feature works 32 | - [ ] Updated the [Changelog](https://github.com/Unity-Technologies/ROS-TCP-Endpoint/blob/dev/CHANGELOG.md) and described changes in the [Unreleased section](https://github.com/Unity-Technologies/ROS-TCP-Endpoint/blob/dev/CHANGELOG.md#unreleased) 33 | - [ ] Updated the documentation as appropriate 34 | 35 | ## Other comments -------------------------------------------------------------------------------- /.github/workflows/jira-link.yaml: -------------------------------------------------------------------------------- 1 | name: jira-link 2 | 3 | on: 4 | pull_request: 5 | types: [opened, edited, reopened, synchronize] 6 | 7 | jobs: 8 | jira-link: 9 | runs-on: ubuntu-20.04 10 | steps: 11 | - name: check pull request title and source branch name 12 | run: | 13 | echo "Checking pull request with title ${{ github.event.pull_request.title }} from source branch ${{ github.event.pull_request.head.ref }}" 14 | if ! [[ "${{ github.event.pull_request.title }}" =~ ^AIRO-[0-9]+[[:space:]].*$ ]] && ! [[ "${{ github.event.pull_request.head.ref }}" =~ ^AIRO-[0-9]+.*$ ]] 15 | then 16 | echo -e "Please make sure one of the following is true:\n \ 17 | 1. the pull request title starts with 'AIRO-xxxx ', e.g. 'AIRO-1024 My Pull Request'\n \ 18 | 2. the source branch starts with 'AIRO-xxx', e.g. 'AIRO-1024-my-branch'" 19 | exit 1 20 | else 21 | echo "Completed checking" 22 | fi 23 | -------------------------------------------------------------------------------- /.github/workflows/pre-commit.yaml: -------------------------------------------------------------------------------- 1 | name: pre-commit 2 | 3 | on: 4 | pull_request: 5 | 6 | jobs: 7 | pre-commit: 8 | runs-on: ubuntu-latest 9 | steps: 10 | - uses: actions/checkout@v2 11 | - uses: actions/setup-python@v2 12 | with: 13 | python-version: 3.7.x 14 | - uses: pre-commit/action@v2.0.0 -------------------------------------------------------------------------------- /.github/workflows/stale.yaml: -------------------------------------------------------------------------------- 1 | name: 'Stale issue handler' 2 | on: 3 | workflow_dispatch: 4 | schedule: 5 | - cron: '0 17 * * *' # 17:00 UTC; 10:00 PDT 6 | 7 | permissions: 8 | issues: write 9 | 10 | jobs: 11 | stale: 12 | runs-on: ubuntu-latest 13 | steps: 14 | - uses: actions/stale@v4.0.0 15 | id: stale 16 | with: 17 | stale-issue-label: 'stale' 18 | stale-issue-message: 'This issue has been marked stale because it has been open for 14 days with no activity. Please remove the stale label or comment on this issue, or the issue will be automatically closed in the next 14 days.' 19 | days-before-stale: 14 20 | days-before-pr-stale: -1 21 | days-before-close: 14 22 | days-before-pr-close: -1 23 | exempt-issue-labels: 'blocked,must,should,keep,pinned,work-in-progress,request,announcement' 24 | close-issue-message: 'This issue has been marked stale for 14 days and will now be closed. If this issue is still valid, please ping a maintainer.' 25 | - name: Print outputs 26 | run: echo ${{ join(steps.stale.outputs.*, ',') }} 27 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | *.pyc 3 | .idea 4 | *~ 5 | build 6 | devel 7 | -------------------------------------------------------------------------------- /.pre-commit-config.yaml: -------------------------------------------------------------------------------- 1 | repos: 2 | - repo: https://github.com/python/black 3 | rev: 19.3b0 4 | hooks: 5 | - id: black 6 | args: [--line-length=100] 7 | - repo: https://github.com/pre-commit/pre-commit-hooks 8 | rev: v3.4.0 9 | hooks: 10 | - id: trailing-whitespace 11 | name: trailing-whitespace-markdown 12 | types: [markdown] -------------------------------------------------------------------------------- /.yamato/sonar.yml: -------------------------------------------------------------------------------- 1 | name: Sonarqube Standard Scan 2 | agent: 3 | type: Unity::metal::macmini 4 | image: package-ci/mac 5 | flavor: m1.mac 6 | variables: 7 | SONARQUBE_PROJECT_KEY: ai-robotics-endpoint-ros 8 | commands: 9 | - curl https://binaries.sonarsource.com/Distribution/sonar-scanner-cli/sonar-scanner-cli-4.6.2.2472-macosx.zip -o sonar-scanner-macosx.zip -L 10 | - unzip sonar-scanner-macosx.zip -d ~/sonar-scanner 11 | - ~/sonar-scanner/sonar-scanner-4.6.2.2472-macosx/bin/sonar-scanner -Dsonar.projectKey=$SONARQUBE_PROJECT_KEY -Dsonar.sources=. -Dsonar.host.url=$SONARQUBE_ENDPOINT_URL_PRD -Dsonar.login=$SONARQUBE_TOKEN_PRD 12 | triggers: 13 | cancel_old_ci: true 14 | expression: | 15 | ((pull_request.target eq "main" OR pull_request.target eq "dev-ros") 16 | AND NOT pull_request.push.changes.all match "**/*.md") OR 17 | (push.branch eq "main" OR push.branch eq "dev-ros") -------------------------------------------------------------------------------- /.yamato/yamato-config.yml: -------------------------------------------------------------------------------- 1 | name: Endpoint Unit Tests 2 | agent: 3 | type: Unity::VM 4 | image: robotics/ci-ubuntu20:v0.1.0-795910 5 | flavor: i1.large 6 | variables: 7 | # Coverage measured as a percentage (out of 100) 8 | COVERAGE_EXPECTED: 30 9 | commands: 10 | # run unit tests and save test results in /home/bokken/build/output/Unity-Technologies/ROS-TCP-Endpoint 11 | - command: | 12 | source /opt/ros/noetic/setup.bash && echo "ROS_DISTRO == $ROS_DISTRO" 13 | cd .. && mkdir -p catkin_ws/src && cp -r ./ROS-TCP-Endpoint catkin_ws/src 14 | cd catkin_ws && catkin_make && source devel/setup.bash 15 | cd src/ROS-TCP-Endpoint 16 | python3 -m pytest --cov=. --cov-report xml:../../../ROS-TCP-Endpoint/test-results/coverage.xml --cov-report html:../../../ROS-TCP-Endpoint/test-results/coverage.html test/ 17 | # check the test coverage 18 | - command: | 19 | linecoverage=$(head -2 test-results/coverage.xml | grep -Eo 'line-rate="[0-9]+([.][0-9]+)?"' | grep -Eo "[0-9]+([.][0-9]+)?") 20 | echo "Line coverage: $linecoverage" 21 | if (( $(echo "$linecoverage * 100.0 < $COVERAGE_EXPECTED" | bc -l) )); 22 | then echo "ERROR: Code Coverage is under threshold of $COVERAGE_EXPECTED%" && exit 1 23 | fi 24 | triggers: 25 | cancel_old_ci: true 26 | expression: | 27 | (pull_request.target eq "main" OR push.branch eq "main" OR pull_request.target eq "dev-ros" OR push.branch eq "dev-ros") 28 | AND NOT pull_request.push.changes.all match "**/*.md" 29 | artifacts: 30 | logs: 31 | paths: 32 | - "test-results/**/*" 33 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | All notable changes to this repository will be documented in this file. 4 | 5 | The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/) and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html). 6 | 7 | ## Unreleased 8 | 9 | ### Upgrade Notes 10 | 11 | ### Known Issues 12 | 13 | ### Added 14 | 15 | ### Changed 16 | 17 | ### Deprecated 18 | 19 | ### Removed 20 | 21 | ### Fixed 22 | 23 | ## [0.7.0] - 2022-02-01 24 | 25 | ### Added 26 | 27 | Added Sonarqube Scanner 28 | 29 | Private ros params 30 | 31 | Send information during hand shaking for ros and package version checks 32 | 33 | Send service response as one queue item 34 | 35 | 36 | ## [0.6.0] - 2021-09-30 37 | 38 | Add the [Close Stale Issues](https://github.com/marketplace/actions/close-stale-issues) action 39 | 40 | ### Upgrade Notes 41 | 42 | ### Known Issues 43 | 44 | ### Added 45 | 46 | Support for queue_size and latch for publishers. (https://github.com/Unity-Technologies/ROS-TCP-Endpoint/issues/82) 47 | 48 | ### Changed 49 | 50 | ### Deprecated 51 | 52 | ### Removed 53 | 54 | ### Fixed 55 | 56 | ## [0.5.0] - 2021-07-15 57 | 58 | ### Upgrade Notes 59 | 60 | Upgrade the ROS communication to support ROS2 with Unity 61 | 62 | ### Known Issues 63 | 64 | ### Added 65 | 66 | ### Changed 67 | 68 | ### Deprecated 69 | 70 | ### Removed 71 | 72 | ### Fixed 73 | 74 | ## [0.4.0] - 2021-05-27 75 | 76 | Note: the logs only reflects the changes from version 0.3.0 77 | 78 | ### Upgrade Notes 79 | 80 | RosConnection 2.0: maintain a single constant connection from Unity to the Endpoint. This is more efficient than opening one connection per message, and it eliminates a whole bunch of user issues caused by ROS being unable to connect to Unity due to firewalls, proxies, etc. 81 | 82 | ### Known Issues 83 | 84 | ### Added 85 | 86 | Add a link to the Robotics forum, and add a config.yml to add a link in the Github Issues page 87 | 88 | Add linter, unit tests, and test coverage reporting 89 | 90 | ### Changed 91 | 92 | Improving the performance of the read_message in client.py, This is done by receiving the entire message all at once instead of reading 1024 byte chunks and stitching them together as you go. 93 | 94 | ### Deprecated 95 | 96 | ### Removed 97 | 98 | Remove outdated handshake references 99 | 100 | ### Fixed -------------------------------------------------------------------------------- /CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 2.8.3) 2 | project(ros_tcp_endpoint) 3 | 4 | find_package(catkin REQUIRED COMPONENTS 5 | rospy 6 | std_msgs 7 | ) 8 | 9 | catkin_python_setup() 10 | 11 | catkin_package(CATKIN_DEPENDS message_runtime ) 12 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as 6 | contributors and maintainers pledge to making participation in our project and 7 | our community a harassment-free experience for everyone, regardless of age, body 8 | size, disability, ethnicity, gender identity and expression, level of experience, 9 | nationality, personal appearance, race, religion, or sexual identity and 10 | orientation. 11 | 12 | ## Our Standards 13 | 14 | Examples of behavior that contributes to creating a positive environment 15 | include: 16 | 17 | * Using welcoming and inclusive language 18 | * Being respectful of differing viewpoints and experiences 19 | * Gracefully accepting constructive criticism 20 | * Focusing on what is best for the community 21 | * Showing empathy towards other community members 22 | 23 | Examples of unacceptable behavior by participants include: 24 | 25 | * The use of sexualized language or imagery and unwelcome sexual attention or 26 | advances 27 | * Trolling, insulting/derogatory comments, and personal or political attacks 28 | * Public or private harassment 29 | * Publishing others' private information, such as a physical or electronic 30 | address, without explicit permission 31 | * Other conduct which could reasonably be considered inappropriate in a 32 | professional setting 33 | 34 | ## Our Responsibilities 35 | 36 | Project maintainers are responsible for clarifying the standards of acceptable 37 | behavior and are expected to take appropriate and fair corrective action in 38 | response to any instances of unacceptable behavior. 39 | 40 | Project maintainers have the right and responsibility to remove, edit, or 41 | reject comments, commits, code, wiki edits, issues, and other contributions 42 | that are not aligned to this Code of Conduct, or to ban temporarily or 43 | permanently any contributor for other behaviors that they deem inappropriate, 44 | threatening, offensive, or harmful. 45 | 46 | ## Scope 47 | 48 | This Code of Conduct applies both within project spaces and in public spaces 49 | when an individual is representing the project or its community. Examples of 50 | representing a project or community include using an official project e-mail 51 | address, posting via an official social media account, or acting as an appointed 52 | representative at an online or offline event. Representation of a project may be 53 | further defined and clarified by project maintainers. 54 | 55 | ## Enforcement 56 | 57 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 58 | reported by contacting the project team at [unity-robotics@unity3d.com](mailto:unity-robotics@unity3d.com). All 59 | complaints will be reviewed and investigated and will result in a response that 60 | is deemed necessary and appropriate to the circumstances. The project team is 61 | obligated to maintain confidentiality with regard to the reporter of an incident. 62 | Further details of specific enforcement policies may be posted separately. 63 | 64 | Project maintainers who do not follow or enforce the Code of Conduct in good 65 | faith may face temporary or permanent repercussions as determined by other 66 | members of the project's leadership. 67 | 68 | ## Attribution 69 | 70 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], 71 | version 1.4, available at 72 | https://www.contributor-covenant.org/version/1/4/code-of-conduct/ 73 | 74 | [homepage]: https://www.contributor-covenant.org -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contribution Guidelines 2 | 3 | Thank you for your interest in contributing to Unity Robotics! To facilitate your 4 | contributions, we've outlined a brief set of guidelines to ensure that your extensions 5 | can be easily integrated. 6 | 7 | ## Communication 8 | 9 | First, please read through our 10 | [code of conduct](CODE_OF_CONDUCT.md), 11 | as we expect all our contributors to follow it. 12 | 13 | Second, before starting on a project that you intend to contribute to any of our 14 | Unity Robotics packages or tutorials, we **strongly** recommend posting on the repository's 15 | [Issues page](https://github.com/Unity-Technologies/ROS-TCP-Endpoint/issues) and 16 | briefly outlining the changes you plan to make. This will enable us to provide 17 | some context that may be helpful for you. This could range from advice and 18 | feedback on how to optimally perform your changes or reasons for not doing it. 19 | 20 | ## Git Branches 21 | 22 | The `main` branch corresponds to the most recent stable version of the project. The `dev` branch 23 | contains changes that are staged to be merged into `main` as the team sees fit. 24 | 25 | When contributing to the project, please make sure that your Pull Request (PR) 26 | does the following: 27 | 28 | - Is up-to-date with and targets the `dev` branch 29 | - Contains a detailed description of the changes performed 30 | - Has corresponding changes to documentation, unit tests and sample environments (if 31 | applicable) 32 | - Contains a summary of the tests performed to validate your changes 33 | - Links to issue numbers that the PR resolves (if any) 34 | 35 | 38 | 39 | ## Code style 40 | 41 | All Python code should follow the [PEP 8 style guidelines](https://pep8.org/). 42 | 43 | All C# code should follow the [Microsoft C# Coding Conventions](https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/inside-a-program/coding-conventions). 44 | Additionally, the [Unity Coding package](https://docs.unity3d.com/Packages/com.unity.coding@0.1/manual/index.html) 45 | can be used to format, encode, and lint your code according to the standard Unity 46 | development conventions. Be aware that these Unity conventions will supersede the 47 | Microsoft C# Coding Conventions where applicable. 48 | 49 | Please note that even if the code you are changing does not adhere to these guidelines, 50 | we expect your submissions to follow these conventions. 51 | 52 | ## Contributor License Agreements 53 | 54 | When you open a pull request, you will be asked to acknowledge our Contributor 55 | License Agreement. We allow both individual contributions and contributions made 56 | on behalf of companies. We use an open source tool called CLA assistant. If you 57 | have any questions on our CLA, please 58 | [submit an issue](https://github.com/Unity-Technologies/ROS-TCP-Endpoint/issues) or 59 | email us at [unity-robotics@unity3d.com](mailto:unity-robotics@unity3d.com). 60 | 61 | ## Contribution review 62 | 63 | Once you have a change ready following the above ground rules, simply make a 64 | pull request in GitHub. -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | Copyright 2020 Unity Technologies 179 | 180 | Licensed under the Apache License, Version 2.0 (the "License"); 181 | you may not use this file except in compliance with the License. 182 | You may obtain a copy of the License at 183 | 184 | http://www.apache.org/licenses/LICENSE-2.0 185 | 186 | Unless required by applicable law or agreed to in writing, software 187 | distributed under the License is distributed on an "AS IS" BASIS, 188 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 189 | See the License for the specific language governing permissions and 190 | limitations under the License. 191 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ROS TCP Endpoint 2 | 3 | [![License](https://img.shields.io/badge/license-Apache--2.0-green.svg)](LICENSE.md) 4 | [![Version](https://img.shields.io/github/v/tag/Unity-Technologies/ROS-TCP-Endpoint)](https://github.com/Unity-Technologies/ROS-TCP-Endpoint/releases) 5 | ![ROS](https://img.shields.io/badge/ros-melodic,noetic-brightgreen) 6 | ![ROS](https://img.shields.io/badge/ros2-foxy,galactic-brightgreen) 7 | 8 | --- 9 | 10 | We're currently working on lots of things! Please take a short moment fill out our [survey](https://unitysoftware.co1.qualtrics.com/jfe/form/SV_0ojVkDVW0nNrHkW) to help us identify what products and packages to build next. 11 | 12 | --- 13 | 14 | ## Introduction 15 | 16 | [ROS](https://www.ros.org/) package used to create an endpoint to accept ROS messages sent from a Unity scene. This ROS package works in tandem with the [ROS TCP Connector](https://github.com/Unity-Technologies/ROS-TCP-Connector) Unity package. 17 | 18 | Instructions and examples on how to use this ROS package can be found on the [Unity Robotics Hub](https://github.com/Unity-Technologies/Unity-Robotics-Hub/blob/master/tutorials/ros_unity_integration/README.md) repository. 19 | 20 | ## Community and Feedback 21 | 22 | The Unity Robotics projects are open-source and we encourage and welcome contributions. 23 | If you wish to contribute, be sure to review our [contribution guidelines](CONTRIBUTING.md) 24 | and [code of conduct](CODE_OF_CONDUCT.md). 25 | 26 | ## Support 27 | For questions or discussions about Unity Robotics package installations or how to best set up and integrate your robotics projects, please create a new thread on the [Unity Robotics forum](https://forum.unity.com/forums/robotics.623/) and make sure to include as much detail as possible. 28 | 29 | For feature requests, bugs, or other issues, please file a [GitHub issue](https://github.com/Unity-Technologies/ROS-TCP-Endpoint/issues) using the provided templates and the Robotics team will investigate as soon as possible. 30 | 31 | For any other questions or feedback, connect directly with the 32 | Robotics team at [unity-robotics@unity3d.com](mailto:unity-robotics@unity3d.com). 33 | 34 | ## License 35 | [Apache License 2.0](LICENSE) -------------------------------------------------------------------------------- /launch/endpoint.launch: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /package.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | ros_tcp_endpoint 4 | 0.7.0 5 | Acts as the bridge between Unity messages sent via Websocket and ROS messages. 6 | 7 | Unity Robotics 8 | 9 | Apache 2.0 10 | catkin 11 | rospy 12 | message_generation 13 | rospy 14 | rospy 15 | message_runtime 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | black 2 | pre-commit 3 | pytest-cov -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | ## ! DO NOT MANUALLY INVOKE THIS setup.py, USE CATKIN INSTEAD 2 | 3 | from setuptools import setup 4 | from catkin_pkg.python_setup import generate_distutils_setup 5 | 6 | # fetch values from package.xml 7 | setup_args = generate_distutils_setup(packages=["ros_tcp_endpoint"], package_dir={"": "src"}) 8 | 9 | setup(**setup_args) 10 | -------------------------------------------------------------------------------- /src/ros_tcp_endpoint/__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright 2020 Unity Technologies 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | from .server import TcpServer 16 | -------------------------------------------------------------------------------- /src/ros_tcp_endpoint/client.py: -------------------------------------------------------------------------------- 1 | # Copyright 2020 Unity Technologies 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | import struct 16 | import socket 17 | import rospy 18 | from io import BytesIO 19 | 20 | import threading 21 | import json 22 | 23 | from .exceptions import TopicOrServiceNameDoesNotExistError 24 | 25 | 26 | class ClientThread(threading.Thread): 27 | """ 28 | Thread class to read all data from a connection and pass along the data to the 29 | desired source. 30 | """ 31 | 32 | def __init__(self, conn, tcp_server, incoming_ip, incoming_port): 33 | """ 34 | Set class variables 35 | Args: 36 | conn: 37 | tcp_server: server object 38 | incoming_ip: connected from this IP address 39 | incoming_port: connected from this port 40 | """ 41 | self.conn = conn 42 | self.tcp_server = tcp_server 43 | self.incoming_ip = incoming_ip 44 | self.incoming_port = incoming_port 45 | threading.Thread.__init__(self) 46 | 47 | @staticmethod 48 | def recvall(conn, size, flags=0): 49 | """ 50 | Receive exactly bufsize bytes from the socket. 51 | """ 52 | buffer = bytearray(size) 53 | view = memoryview(buffer) 54 | pos = 0 55 | while pos < size: 56 | read = conn.recv_into(view[pos:], size - pos, flags) 57 | if not read: 58 | raise IOError("No more data available") 59 | pos += read 60 | return bytes(buffer) 61 | 62 | @staticmethod 63 | def read_int32(conn): 64 | """ 65 | Reads four bytes from socket connection and unpacks them to an int 66 | 67 | Returns: int 68 | 69 | """ 70 | raw_bytes = ClientThread.recvall(conn, 4) 71 | num = struct.unpack(" 0 and not data: 103 | self.tcp_server.logerr( 104 | "No data for a message size of {}, breaking!".format(full_message_size) 105 | ) 106 | return 107 | 108 | destination = destination.rstrip("\x00") 109 | return destination, data 110 | 111 | @staticmethod 112 | def serialize_message(destination, message): 113 | """ 114 | Serialize a destination and message class. 115 | 116 | Args: 117 | destination: name of destination 118 | message: message class to serialize 119 | 120 | Returns: 121 | serialized destination and message as a list of bytes 122 | """ 123 | dest_bytes = destination.encode("utf-8") 124 | length = len(dest_bytes) 125 | dest_info = struct.pack(" 187 | names = (str(type(name))).split(".") 188 | module_name = names[0][8:] 189 | class_name = names[-1].split("_")[-1][:-2] 190 | return "{}/{}".format(module_name, class_name) 191 | except (IndexError, AttributeError, ImportError) as e: 192 | self.tcp_server.logerr("Failed to resolve message name: {}".format(e)) 193 | return None 194 | 195 | 196 | class SysCommand_Log: 197 | def __init__(self): 198 | self.text = "" 199 | 200 | 201 | class SysCommand_Service: 202 | def __init__(self): 203 | self.srv_id = 0 204 | 205 | 206 | class SysCommand_TopicsResponse: 207 | def __init__(self): 208 | self.topics = [] 209 | self.types = [] 210 | 211 | 212 | class SysCommand_Handshake: 213 | def __init__(self, metadata): 214 | self.version = "v0.7.0" 215 | self.metadata = json.dumps(metadata.__dict__) 216 | 217 | 218 | class SysCommand_Handshake_Metadata: 219 | def __init__(self): 220 | self.protocol = "ROS1" 221 | -------------------------------------------------------------------------------- /src/ros_tcp_endpoint/thread_pauser.py: -------------------------------------------------------------------------------- 1 | import threading 2 | 3 | 4 | class ThreadPauser: 5 | def __init__(self): 6 | self.condition = threading.Condition() 7 | self.result = None 8 | 9 | def sleep_until_resumed(self): 10 | with self.condition: 11 | self.condition.wait() 12 | 13 | def resume_with_result(self, result): 14 | self.result = result 15 | with self.condition: 16 | self.condition.notify() 17 | -------------------------------------------------------------------------------- /src/ros_tcp_endpoint/unity_service.py: -------------------------------------------------------------------------------- 1 | # Copyright 2020 Unity Technologies 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | import rospy 16 | import socket 17 | import re 18 | 19 | from .communication import RosReceiver 20 | from .client import ClientThread 21 | 22 | 23 | class UnityService(RosReceiver): 24 | """ 25 | Class to register a ROS service that's implemented in Unity. 26 | """ 27 | 28 | def __init__(self, topic, service_class, tcp_server, queue_size=10): 29 | """ 30 | 31 | Args: 32 | topic: Topic name to publish messages to 33 | service_class: The message class in catkin workspace 34 | queue_size: Max number of entries to maintain in an outgoing queue 35 | """ 36 | strippedTopic = re.sub("[^A-Za-z0-9_]+", "", topic) 37 | self.node_name = "{}_service".format(strippedTopic) 38 | 39 | self.topic = topic 40 | self.service_class = service_class 41 | self.tcp_server = tcp_server 42 | self.queue_size = queue_size 43 | 44 | self.service = rospy.Service(self.topic, self.service_class, self.send) 45 | 46 | def send(self, request): 47 | """ 48 | Connect to TCP endpoint on client, pass along message and get reply 49 | Args: 50 | data: message data to send outside of ROS network 51 | 52 | Returns: 53 | The response message 54 | """ 55 | return self.tcp_server.send_unity_service(self.topic, self.service_class, request) 56 | 57 | def unregister(self): 58 | """ 59 | 60 | Returns: 61 | 62 | """ 63 | self.service.shutdown() 64 | -------------------------------------------------------------------------------- /test/__init__.py: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /test/test_client.py: -------------------------------------------------------------------------------- 1 | from unittest import mock 2 | from unittest.mock import Mock 3 | from ros_tcp_endpoint.client import ClientThread 4 | from ros_tcp_endpoint.server import TcpServer 5 | import sys 6 | import threading 7 | 8 | 9 | def test_client_thread_initialization(): 10 | tcp_server = TcpServer(node_name="test-tcp-server", tcp_ip="127.0.0.1", tcp_port=10000) 11 | mock_conn = mock.Mock() 12 | client_thread = ClientThread(mock_conn, tcp_server, "127.0.0.1", 10000) 13 | assert client_thread.tcp_server.node_name == "test-tcp-server" 14 | assert client_thread.incoming_ip == "127.0.0.1" 15 | assert client_thread.incoming_port == 10000 16 | 17 | 18 | def test_recvall_should_read_bytes_exact_size(): 19 | mock_conn = mock.Mock() 20 | mock_conn.recv_into.return_value = 1 21 | result = ClientThread.recvall(mock_conn, 8) 22 | assert result == b"\x00\x00\x00\x00\x00\x00\x00\x00" 23 | 24 | 25 | @mock.patch.object(ClientThread, "recvall", return_value=b"\x01\x00\x00\x00") 26 | def test_read_int32_should_parse_int(mock_recvall): 27 | mock_conn = mock.Mock() 28 | result = ClientThread.read_int32(mock_conn) 29 | mock_recvall.assert_called_once 30 | assert result == 1 31 | 32 | 33 | @mock.patch.object(ClientThread, "read_int32", return_value=4) 34 | @mock.patch.object(ClientThread, "recvall", return_value=b"Hello world!") 35 | def test_read_string_should_decode(mock_recvall, mock_read_int): 36 | mock_conn = mock.Mock() 37 | result = ClientThread.read_string(mock_conn) 38 | mock_recvall.assert_called_once 39 | mock_read_int.assert_called_once 40 | assert result == "Hello world!" 41 | 42 | 43 | @mock.patch.object(ClientThread, "read_string", return_value="__srv") 44 | @mock.patch.object(ClientThread, "read_int32", return_value=4) 45 | @mock.patch.object(ClientThread, "recvall", return_value=b"Hello world!") 46 | def test_read_message_return_destination_data(mock_recvall, mock_read_int, mock_read_str): 47 | tcp_server = TcpServer(node_name="test-tcp-server", tcp_ip="127.0.0.1", tcp_port=10000) 48 | mock_conn = mock.Mock() 49 | client_thread = ClientThread(mock_conn, tcp_server, "127.0.0.1", 10000) 50 | result = client_thread.read_message(mock_conn) 51 | assert result == ("__srv", b"Hello world!") 52 | -------------------------------------------------------------------------------- /test/test_publisher.py: -------------------------------------------------------------------------------- 1 | from unittest import mock 2 | from ros_tcp_endpoint.publisher import RosPublisher 3 | import rospy 4 | 5 | 6 | @mock.patch.object(rospy, "Publisher") 7 | def test_publisher_send(mock_ros): 8 | mock_tcp_server = mock.Mock() 9 | publisher = RosPublisher("color", mock.Mock(), mock_tcp_server) 10 | publisher.send("test data") 11 | publisher.msg.deserialize.assert_called_once() 12 | publisher.pub.publish.assert_called_once() 13 | 14 | 15 | @mock.patch.object(rospy, "Publisher") 16 | def test_publisher_unregister(mock_ros): 17 | mock_tcp_server = mock.Mock() 18 | publisher = RosPublisher("color", mock.Mock(), mock_tcp_server) 19 | publisher.unregister() 20 | publisher.pub.unregister.assert_called_once() 21 | -------------------------------------------------------------------------------- /test/test_ros_service.py: -------------------------------------------------------------------------------- 1 | from unittest import mock 2 | from ros_tcp_endpoint.service import RosService 3 | import rospy 4 | 5 | 6 | @mock.patch.object(rospy, "ServiceProxy") 7 | def test_subscriber_send(mock_ros): 8 | ros_service = RosService("color", mock.Mock()) 9 | service_response = ros_service.send("test data") 10 | ros_service.srv_class.deserialize.assert_called_once() 11 | assert service_response is not None 12 | 13 | 14 | @mock.patch.object(rospy, "ServiceProxy") 15 | def test_subscriber_unregister(mock_ros): 16 | ros_service = RosService("color", mock.Mock()) 17 | ros_service.unregister() 18 | ros_service.srv.close.assert_called_once() 19 | -------------------------------------------------------------------------------- /test/test_server.py: -------------------------------------------------------------------------------- 1 | from unittest import mock 2 | from ros_tcp_endpoint import TcpServer 3 | from ros_tcp_endpoint.server import SysCommands 4 | import importlib 5 | import rospy 6 | import sys 7 | import ros_tcp_endpoint 8 | 9 | 10 | @mock.patch("socket.socket") 11 | @mock.patch("ros_tcp_endpoint.server.rospy") 12 | def test_server_constructor(mock_ros, mock_socket): 13 | mock_ros.get_param = mock.Mock(return_value="127.0.0.1") 14 | server = TcpServer("test-tcp-server") 15 | assert server.node_name == "test-tcp-server" 16 | assert server.tcp_ip == "127.0.0.1" 17 | assert server.buffer_size == 1024 18 | assert server.connections == 10 19 | 20 | 21 | def test_start_server(): 22 | server = TcpServer(node_name="test-tcp-server", tcp_ip="127.0.0.1", tcp_port=10000) 23 | assert server.tcp_ip == "127.0.0.1" 24 | assert server.tcp_port == 10000 25 | assert server.connections == 10 26 | server.start() 27 | 28 | 29 | def test_unity_service_empty_topic_should_return_none(): 30 | server = TcpServer(node_name="test-tcp-server", tcp_ip="127.0.0.1", tcp_port=10000) 31 | system_cmds = SysCommands(server) 32 | result = system_cmds.unity_service("", "test message") 33 | assert result is None 34 | 35 | 36 | def test_unity_service_resolve_message_name_failure(): 37 | server = TcpServer(node_name="test-tcp-server", tcp_ip="127.0.0.1", tcp_port=10000) 38 | system_cmds = SysCommands(server) 39 | result = system_cmds.unity_service("get_pos", "unresolvable message") 40 | assert result is None 41 | 42 | 43 | @mock.patch.object(rospy, "Service") 44 | @mock.patch.object( 45 | SysCommands, "resolve_message_name", return_value="unity_interfaces.msg/RosUnitySrvMessage" 46 | ) 47 | def test_unity_service_resolve_news_service(mock_resolve_message, mock_ros_service): 48 | server = TcpServer(node_name="test-tcp-server", tcp_ip="127.0.0.1", tcp_port=10000) 49 | assert server.ros_services_table == {} 50 | system_cmds = SysCommands(server) 51 | result = system_cmds.unity_service("get_pos", "unity_interfaces.msg/RosUnitySrvMessage") 52 | mock_ros_service.assert_called_once 53 | assert result is None 54 | 55 | 56 | @mock.patch.object(rospy, "Service") 57 | @mock.patch.object( 58 | SysCommands, "resolve_message_name", return_value="unity_interfaces.msg/RosUnitySrvMessage" 59 | ) 60 | def test_unity_service_resolve_existing_service(mock_resolve_message, mock_ros_service): 61 | server = TcpServer(node_name="test-tcp-server", tcp_ip="127.0.0.1", tcp_port=10000) 62 | server.ros_services = {"get_pos": mock.Mock()} 63 | system_cmds = SysCommands(server) 64 | result = system_cmds.unity_service("get_pos", "unity_interfaces.msg/RosUnitySrvMessage") 65 | mock_ros_service.assert_called_once 66 | assert result is None 67 | 68 | 69 | @mock.patch.object(sys, "modules", return_value="unity_interfaces.msg") 70 | @mock.patch.object(importlib, "import_module") 71 | def test_resolve_message_name(mock_import_module, mock_sys_modules): 72 | server = TcpServer(node_name="test-tcp-server", tcp_ip="127.0.0.1", tcp_port=10000) 73 | msg_name = "unity_interfaces.msg/UnityColor.msg" 74 | result = SysCommands(server).resolve_message_name(msg_name) 75 | mock_import_module.assert_called_once 76 | mock_sys_modules.assert_called_once 77 | assert result is not None 78 | 79 | 80 | @mock.patch.object(rospy, "Publisher") 81 | def test_publish_add_new_topic(mock_ros_publisher): 82 | server = TcpServer(node_name="test-tcp-server", tcp_ip="127.0.0.1", tcp_port=10000) 83 | result = SysCommands(server).publish("object_pos_topic", "std_msgs/Bool") 84 | assert server.publishers_table != {} 85 | mock_ros_publisher.assert_called_once 86 | 87 | 88 | @mock.patch.object(rospy, "Publisher") 89 | def test_publish_existing_topic(mock_ros_publisher): 90 | server = TcpServer(node_name="test-tcp-server", tcp_ip="127.0.0.1", tcp_port=10000) 91 | server.publishers_table = {"object_pos_topic": mock.Mock()} 92 | result = SysCommands(server).publish("object_pos_topic", "std_msgs/Bool") 93 | assert server.publishers_table["object_pos_topic"] is not None 94 | mock_ros_publisher.assert_called_once 95 | 96 | 97 | def test_publish_empty_topic_should_return_none(): 98 | server = TcpServer(node_name="test-tcp-server", tcp_ip="127.0.0.1", tcp_port=10000) 99 | result = SysCommands(server).publish("", "pos") 100 | assert result is None 101 | assert server.publishers_table == {} 102 | 103 | 104 | def test_publish_empty_message_should_return_none(): 105 | server = TcpServer(node_name="test-tcp-server", tcp_ip="127.0.0.1", tcp_port=10000) 106 | result = SysCommands(server).publish("test-topic", "") 107 | assert result is None 108 | assert server.publishers_table == {} 109 | 110 | 111 | @mock.patch.object(rospy, "Subscriber") 112 | @mock.patch.object(SysCommands, "resolve_message_name", return_value="unity_interfaces.msg/Pos") 113 | def test_subscribe_to_new_topic(mock_resolve_msg, mock_ros_subscriber): 114 | server = TcpServer(node_name="test-tcp-server", tcp_ip="127.0.0.1", tcp_port=10000) 115 | result = SysCommands(server).subscribe("object_pos_topic", "pos") 116 | assert server.subscribers_table != {} 117 | mock_ros_subscriber.assert_called_once 118 | 119 | 120 | @mock.patch.object(rospy, "Subscriber") 121 | @mock.patch.object(SysCommands, "resolve_message_name", return_value="unity_interfaces.msg/Pos") 122 | def test_subscribe_to_existing_topic(mock_resolve_msg, mock_ros_subscriber): 123 | server = TcpServer(node_name="test-tcp-server", tcp_ip="127.0.0.1", tcp_port=10000) 124 | server.subscribers_table = {"object_pos_topic": mock.Mock()} 125 | result = SysCommands(server).subscribe("object_pos_topic", "pos") 126 | assert server.subscribers_table["object_pos_topic"] is not None 127 | mock_ros_subscriber.assert_called_once 128 | 129 | 130 | def test_subscribe_to_empty_topic_should_return_none(): 131 | server = TcpServer(node_name="test-tcp-server", tcp_ip="127.0.0.1", tcp_port=10000) 132 | result = SysCommands(server).subscribe("", "pos") 133 | assert result is None 134 | assert server.subscribers_table == {} 135 | 136 | 137 | def test_subscribe_to_empty_message_should_return_none(): 138 | server = TcpServer(node_name="test-tcp-server", tcp_ip="127.0.0.1", tcp_port=10000) 139 | result = SysCommands(server).subscribe("test-topic", "") 140 | assert result is None 141 | assert server.subscribers_table == {} 142 | 143 | 144 | @mock.patch.object(rospy, "ServiceProxy") 145 | @mock.patch.object(SysCommands, "resolve_message_name") 146 | def test_ros_service_new_topic(mock_resolve_msg, mock_ros_service): 147 | server = TcpServer(node_name="test-tcp-server", tcp_ip="127.0.0.1", tcp_port=10000) 148 | result = SysCommands(server).ros_service("object_pos_topic", "pos") 149 | assert server.ros_services_table != {} 150 | mock_ros_service.assert_called_once 151 | 152 | 153 | @mock.patch.object(rospy, "ServiceProxy") 154 | @mock.patch.object(SysCommands, "resolve_message_name") 155 | def test_ros_service_existing_topic(mock_resolve_msg, mock_ros_service): 156 | server = TcpServer(node_name="test-tcp-server", tcp_ip="127.0.0.1", tcp_port=10000) 157 | server.ros_services_table = {"object_pos_topic": mock.Mock()} 158 | result = SysCommands(server).ros_service("object_pos_topic", "pos") 159 | assert server.ros_services_table["object_pos_topic"] is not None 160 | mock_ros_service.assert_called_once 161 | 162 | 163 | def test_ros_service_empty_topic_should_return_none(): 164 | server = TcpServer(node_name="test-tcp-server", tcp_ip="127.0.0.1", tcp_port=10000) 165 | result = SysCommands(server).ros_service("", "pos") 166 | assert result is None 167 | assert server.ros_services_table == {} 168 | 169 | 170 | def test_ros_service_empty_message_should_return_none(): 171 | server = TcpServer(node_name="test-tcp-server", tcp_ip="127.0.0.1", tcp_port=10000) 172 | result = SysCommands(server).ros_service("test-topic", "") 173 | assert result is None 174 | assert server.ros_services_table == {} 175 | -------------------------------------------------------------------------------- /test/test_subscriber.py: -------------------------------------------------------------------------------- 1 | from unittest import mock 2 | from ros_tcp_endpoint.subscriber import RosSubscriber 3 | import rospy 4 | 5 | 6 | @mock.patch.object(rospy, "Subscriber") 7 | def test_subscriber_send(mock_ros): 8 | mock_tcp_server = mock.Mock() 9 | subscriber = RosSubscriber("color", mock.Mock(), mock_tcp_server) 10 | assert subscriber.node_name == "color_RosSubscriber" 11 | subscriber.send("test data") 12 | mock_tcp_server.send_unity_message.assert_called_once() 13 | 14 | 15 | @mock.patch.object(rospy, "Subscriber") 16 | def test_subscriber_unregister(mock_ros): 17 | mock_tcp_server = mock.Mock() 18 | subscriber = RosSubscriber("color", mock.Mock(), mock_tcp_server) 19 | assert subscriber.node_name == "color_RosSubscriber" 20 | subscriber.unregister() 21 | subscriber.sub.unregister.assert_called_once() 22 | -------------------------------------------------------------------------------- /test/test_tcp_sender.py: -------------------------------------------------------------------------------- 1 | import queue 2 | import socket 3 | from unittest import mock 4 | from ros_tcp_endpoint import TcpServer 5 | import ros_tcp_endpoint 6 | 7 | 8 | @mock.patch("ros_tcp_endpoint.tcp_sender.rospy") 9 | def test_tcp_sender_constructor(mock_ros): 10 | server = TcpServer(node_name="test-tcp-server", tcp_ip="127.0.0.1", tcp_port=10000) 11 | tcp_sender = ros_tcp_endpoint.tcp_sender.UnityTcpSender(server) 12 | assert tcp_sender.sender_id == 1 13 | assert tcp_sender.time_between_halt_checks == 5 14 | assert tcp_sender.queue == None 15 | assert tcp_sender.next_srv_id == 1001 16 | assert tcp_sender.srv_lock != None 17 | assert tcp_sender.services_waiting == {} 18 | 19 | 20 | # @mock.patch("socket.socket") 21 | # @mock.patch.object(ros_tcp_endpoint.client.ClientThread, "serialize_message") 22 | # def test_send_unity_error_should_send_msg(mock_serialize_msg, mock_socket): 23 | # sender = ros_tcp_endpoint.tcp_sender.UnityTcpSender() 24 | # sender.queue = queue.Queue() 25 | # sender.send_unity_error("Test error") 26 | # mock_serialize_msg.assert_called_once() 27 | 28 | 29 | @mock.patch.object(ros_tcp_endpoint.client.ClientThread, "serialize_message") 30 | def test_send_message_should_serialize_message(mock_serialize_msg): 31 | server = TcpServer(node_name="test-tcp-server", tcp_ip="127.0.0.1", tcp_port=10000) 32 | sender = ros_tcp_endpoint.tcp_sender.UnityTcpSender(server) 33 | sender.queue = queue.Queue() 34 | sender.send_unity_message("test topic", "test msg") 35 | mock_serialize_msg.assert_called_once() 36 | 37 | 38 | # @mock.patch.object(ros_tcp_endpoint.thread_pauser.ThreadPauser, "sleep_until_resumed") 39 | # @mock.patch.object(ros_tcp_endpoint.client.ClientThread, "serialize_message") 40 | # def test_send_unity_service_should_serialize_ros_unity_srv(mock_serialize_msg, mock_thread_pauser): 41 | # sender = ros_tcp_endpoint.tcp_sender.UnityTcpSender() 42 | # sender.send_unity_service_request(mock.Mock(), mock.Mock(), mock.Mock()) 43 | # mock_serialize_msg.assert_called_once() 44 | # # TODO: Test the scenario when the queue is not None 45 | # assert sender.queue == None 46 | 47 | 48 | @mock.patch("ros_tcp_endpoint.thread_pauser.ThreadPauser") 49 | def test_send_unity_service_response_should_resume(mock_thread_pauser_class): 50 | server = TcpServer(node_name="test-tcp-server", tcp_ip="127.0.0.1", tcp_port=10000) 51 | sender = ros_tcp_endpoint.tcp_sender.UnityTcpSender(server) 52 | thread_pauser = mock_thread_pauser_class() 53 | sender.services_waiting = {"moveit": thread_pauser} 54 | sender.send_unity_service_response("moveit", "test data") 55 | thread_pauser.resume_with_result.assert_called_once() 56 | 57 | 58 | def test_start_sender_should_increase_sender_id(): 59 | server = TcpServer(node_name="test-tcp-server", tcp_ip="127.0.0.1", tcp_port=10000) 60 | sender = ros_tcp_endpoint.tcp_sender.UnityTcpSender(server) 61 | init_sender_id = 1 62 | assert sender.sender_id == init_sender_id 63 | sender.start_sender(mock.Mock(), mock.Mock()) 64 | assert sender.sender_id == init_sender_id + 1 65 | -------------------------------------------------------------------------------- /test/test_thread_pauser.py: -------------------------------------------------------------------------------- 1 | import threading 2 | from unittest import mock 3 | from ros_tcp_endpoint.thread_pauser import ThreadPauser 4 | 5 | 6 | @mock.patch.object(threading.Condition, "wait") 7 | def test_sleep_until_resumed(mock_thread_wait): 8 | thread_pauser = ThreadPauser() 9 | thread_pauser.sleep_until_resumed() 10 | mock_thread_wait.assert_called_once 11 | 12 | 13 | @mock.patch.object(threading.Condition, "notify") 14 | def test_resume(mock_thread_notify): 15 | thread_pauser = ThreadPauser() 16 | thread_pauser.resume_with_result(mock.Mock) 17 | mock_thread_notify.assert_called_once 18 | -------------------------------------------------------------------------------- /test/test_unity_service.py: -------------------------------------------------------------------------------- 1 | from unittest import mock 2 | from ros_tcp_endpoint.unity_service import UnityService 3 | import rospy 4 | 5 | 6 | @mock.patch.object(rospy, "Service") 7 | def test_unity_service_send(mock_ros_service): 8 | mock_tcp_server = mock.Mock() 9 | unity_service = UnityService("color", mock.Mock(), mock_tcp_server) 10 | assert unity_service.node_name == "color_service" 11 | unity_service.send("test data") 12 | mock_tcp_server.send_unity_service.assert_called_once() 13 | 14 | 15 | @mock.patch.object(rospy, "Service") 16 | def test_unity_service_unregister(mock_ros_service): 17 | mock_tcp_server = mock.Mock() 18 | unity_service = UnityService("color", mock.Mock(), mock_tcp_server) 19 | assert unity_service.node_name == "color_service" 20 | unity_service.unregister() 21 | unity_service.service.shutdown.assert_called_once() 22 | --------------------------------------------------------------------------------